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.
- package/.env.example +78 -0
- package/README.md +282 -0
- package/dist/src/active-inference/actions.d.ts +75 -0
- package/dist/src/active-inference/actions.js +250 -0
- package/dist/src/active-inference/autonomous-loop.d.ts +103 -0
- package/dist/src/active-inference/autonomous-loop.js +289 -0
- package/dist/src/active-inference/core.d.ts +85 -0
- package/dist/src/active-inference/core.js +555 -0
- package/dist/src/active-inference/demo-autonomous-loop.d.ts +8 -0
- package/dist/src/active-inference/demo-autonomous-loop.js +338 -0
- package/dist/src/active-inference/demo-value-integration.d.ts +8 -0
- package/dist/src/active-inference/demo-value-integration.js +174 -0
- package/dist/src/active-inference/index.d.ts +32 -0
- package/dist/src/active-inference/index.js +88 -0
- package/dist/src/active-inference/integration.d.ts +114 -0
- package/dist/src/active-inference/integration.js +698 -0
- package/dist/src/active-inference/memory-integration.d.ts +51 -0
- package/dist/src/active-inference/memory-integration.js +232 -0
- package/dist/src/active-inference/observations.d.ts +67 -0
- package/dist/src/active-inference/observations.js +147 -0
- package/dist/src/active-inference/test-active-inference.d.ts +8 -0
- package/dist/src/active-inference/test-active-inference.js +320 -0
- package/dist/src/active-inference/test-value-integration.d.ts +6 -0
- package/dist/src/active-inference/test-value-integration.js +168 -0
- package/dist/src/active-inference/types.d.ts +150 -0
- package/dist/src/active-inference/types.js +59 -0
- package/dist/src/active-inference/value-integration.d.ts +164 -0
- package/dist/src/active-inference/value-integration.js +459 -0
- package/dist/src/agents/base-agent.d.ts +53 -0
- package/dist/src/agents/base-agent.js +178 -0
- package/dist/src/agents/builder.d.ts +67 -0
- package/dist/src/agents/builder.js +537 -0
- package/dist/src/agents/critic.d.ts +35 -0
- package/dist/src/agents/critic.js +322 -0
- package/dist/src/agents/ethicist.d.ts +54 -0
- package/dist/src/agents/ethicist.js +393 -0
- package/dist/src/agents/explorer.d.ts +26 -0
- package/dist/src/agents/explorer.js +216 -0
- package/dist/src/agents/feeling.d.ts +41 -0
- package/dist/src/agents/feeling.js +320 -0
- package/dist/src/agents/index.d.ts +111 -0
- package/dist/src/agents/index.js +222 -0
- package/dist/src/agents/memory.d.ts +69 -0
- package/dist/src/agents/memory.js +404 -0
- package/dist/src/agents/message-bus.d.ts +88 -0
- package/dist/src/agents/message-bus.js +267 -0
- package/dist/src/agents/narrator.d.ts +90 -0
- package/dist/src/agents/narrator.js +473 -0
- package/dist/src/agents/planner.d.ts +38 -0
- package/dist/src/agents/planner.js +341 -0
- package/dist/src/agents/predictor.d.ts +73 -0
- package/dist/src/agents/predictor.js +506 -0
- package/dist/src/agents/sensor.d.ts +88 -0
- package/dist/src/agents/sensor.js +377 -0
- package/dist/src/agents/test-agents.d.ts +6 -0
- package/dist/src/agents/test-agents.js +73 -0
- package/dist/src/agents/types.d.ts +194 -0
- package/dist/src/agents/types.js +7 -0
- package/dist/src/brain/index.d.ts +185 -0
- package/dist/src/brain/index.js +843 -0
- package/dist/src/brain/trace.d.ts +91 -0
- package/dist/src/brain/trace.js +327 -0
- package/dist/src/brain/types.d.ts +165 -0
- package/dist/src/brain/types.js +51 -0
- package/dist/src/cli/chat.d.ts +237 -0
- package/dist/src/cli/chat.js +1959 -0
- package/dist/src/cli/dispatcher.d.ts +182 -0
- package/dist/src/cli/dispatcher.js +718 -0
- package/dist/src/cli/human-loop.d.ts +170 -0
- package/dist/src/cli/human-loop.js +543 -0
- package/dist/src/cli/index.d.ts +12 -0
- package/dist/src/cli/index.js +28 -0
- package/dist/src/cli/interactive.d.ts +141 -0
- package/dist/src/cli/interactive.js +757 -0
- package/dist/src/cli/ui.d.ts +205 -0
- package/dist/src/cli/ui.js +632 -0
- package/dist/src/consciousness/attention-schema.d.ts +154 -0
- package/dist/src/consciousness/attention-schema.js +432 -0
- package/dist/src/consciousness/global-workspace.d.ts +149 -0
- package/dist/src/consciousness/global-workspace.js +422 -0
- package/dist/src/consciousness/index.d.ts +186 -0
- package/dist/src/consciousness/index.js +476 -0
- package/dist/src/consciousness/phi-calculator.d.ts +119 -0
- package/dist/src/consciousness/phi-calculator.js +445 -0
- package/dist/src/consciousness/phi-decisions.d.ts +169 -0
- package/dist/src/consciousness/phi-decisions.js +383 -0
- package/dist/src/consciousness/phi-monitor.d.ts +153 -0
- package/dist/src/consciousness/phi-monitor.js +465 -0
- package/dist/src/consciousness/types.d.ts +260 -0
- package/dist/src/consciousness/types.js +44 -0
- package/dist/src/daemon/dream-mode.d.ts +115 -0
- package/dist/src/daemon/dream-mode.js +470 -0
- package/dist/src/daemon/index.d.ts +162 -0
- package/dist/src/daemon/index.js +542 -0
- package/dist/src/daemon/maintenance.d.ts +139 -0
- package/dist/src/daemon/maintenance.js +549 -0
- package/dist/src/daemon/process.d.ts +82 -0
- package/dist/src/daemon/process.js +442 -0
- package/dist/src/daemon/scheduler.d.ts +90 -0
- package/dist/src/daemon/scheduler.js +494 -0
- package/dist/src/daemon/types.d.ts +213 -0
- package/dist/src/daemon/types.js +50 -0
- package/dist/src/epistemic/index.d.ts +74 -0
- package/dist/src/epistemic/index.js +225 -0
- package/dist/src/grounding/epistemic-stack.d.ts +100 -0
- package/dist/src/grounding/epistemic-stack.js +408 -0
- package/dist/src/grounding/feedback.d.ts +98 -0
- package/dist/src/grounding/feedback.js +276 -0
- package/dist/src/grounding/index.d.ts +123 -0
- package/dist/src/grounding/index.js +224 -0
- package/dist/src/grounding/verifier.d.ts +149 -0
- package/dist/src/grounding/verifier.js +484 -0
- package/dist/src/healing/detector.d.ts +110 -0
- package/dist/src/healing/detector.js +436 -0
- package/dist/src/healing/fixer.d.ts +138 -0
- package/dist/src/healing/fixer.js +572 -0
- package/dist/src/healing/index.d.ts +23 -0
- package/dist/src/healing/index.js +43 -0
- package/dist/src/hooks/index.d.ts +135 -0
- package/dist/src/hooks/index.js +317 -0
- package/dist/src/index.d.ts +23 -0
- package/dist/src/index.js +1266 -0
- package/dist/src/kernel/index.d.ts +155 -0
- package/dist/src/kernel/index.js +795 -0
- package/dist/src/kernel/invariants.d.ts +153 -0
- package/dist/src/kernel/invariants.js +355 -0
- package/dist/src/kernel/test-kernel.d.ts +6 -0
- package/dist/src/kernel/test-kernel.js +108 -0
- package/dist/src/kernel/test-real-mcp.d.ts +10 -0
- package/dist/src/kernel/test-real-mcp.js +295 -0
- package/dist/src/llm/index.d.ts +146 -0
- package/dist/src/llm/index.js +428 -0
- package/dist/src/llm/router.d.ts +136 -0
- package/dist/src/llm/router.js +510 -0
- package/dist/src/mcp/index.d.ts +85 -0
- package/dist/src/mcp/index.js +657 -0
- package/dist/src/mcp/resilient.d.ts +139 -0
- package/dist/src/mcp/resilient.js +417 -0
- package/dist/src/memory/cache.d.ts +118 -0
- package/dist/src/memory/cache.js +356 -0
- package/dist/src/memory/cognitive-workspace.d.ts +231 -0
- package/dist/src/memory/cognitive-workspace.js +521 -0
- package/dist/src/memory/consolidation.d.ts +99 -0
- package/dist/src/memory/consolidation.js +443 -0
- package/dist/src/memory/episodic.d.ts +114 -0
- package/dist/src/memory/episodic.js +394 -0
- package/dist/src/memory/forgetting.d.ts +134 -0
- package/dist/src/memory/forgetting.js +324 -0
- package/dist/src/memory/index.d.ts +211 -0
- package/dist/src/memory/index.js +367 -0
- package/dist/src/memory/indexer.d.ts +123 -0
- package/dist/src/memory/indexer.js +479 -0
- package/dist/src/memory/procedural.d.ts +136 -0
- package/dist/src/memory/procedural.js +479 -0
- package/dist/src/memory/semantic.d.ts +132 -0
- package/dist/src/memory/semantic.js +497 -0
- package/dist/src/memory/types.d.ts +193 -0
- package/dist/src/memory/types.js +15 -0
- package/dist/src/orchestrator.d.ts +65 -0
- package/dist/src/orchestrator.js +317 -0
- package/dist/src/persistence/index.d.ts +257 -0
- package/dist/src/persistence/index.js +763 -0
- package/dist/src/pipeline/executor.d.ts +51 -0
- package/dist/src/pipeline/executor.js +695 -0
- package/dist/src/pipeline/index.d.ts +7 -0
- package/dist/src/pipeline/index.js +11 -0
- package/dist/src/self-production.d.ts +67 -0
- package/dist/src/self-production.js +205 -0
- package/dist/src/subagents/executor.d.ts +58 -0
- package/dist/src/subagents/executor.js +283 -0
- package/dist/src/subagents/index.d.ts +37 -0
- package/dist/src/subagents/index.js +53 -0
- package/dist/src/subagents/registry.d.ts +23 -0
- package/dist/src/subagents/registry.js +167 -0
- package/dist/src/subagents/types.d.ts +79 -0
- package/dist/src/subagents/types.js +14 -0
- package/dist/src/tools/bash.d.ts +139 -0
- package/dist/src/tools/bash.js +583 -0
- package/dist/src/tools/edit.d.ts +125 -0
- package/dist/src/tools/edit.js +424 -0
- package/dist/src/tools/git.d.ts +179 -0
- package/dist/src/tools/git.js +504 -0
- package/dist/src/tools/index.d.ts +21 -0
- package/dist/src/tools/index.js +163 -0
- package/dist/src/types.d.ts +145 -0
- package/dist/src/types.js +7 -0
- package/dist/src/world-model/decoder.d.ts +163 -0
- package/dist/src/world-model/decoder.js +517 -0
- package/dist/src/world-model/digital-twin.d.ts +219 -0
- package/dist/src/world-model/digital-twin.js +695 -0
- package/dist/src/world-model/encoder.d.ts +141 -0
- package/dist/src/world-model/encoder.js +564 -0
- package/dist/src/world-model/index.d.ts +221 -0
- package/dist/src/world-model/index.js +772 -0
- package/dist/src/world-model/predictor.d.ts +161 -0
- package/dist/src/world-model/predictor.js +681 -0
- package/dist/src/world-model/test-value-jepa.d.ts +8 -0
- package/dist/src/world-model/test-value-jepa.js +430 -0
- package/dist/src/world-model/types.d.ts +341 -0
- package/dist/src/world-model/types.js +69 -0
- package/dist/src/world-model/value-jepa.d.ts +247 -0
- package/dist/src/world-model/value-jepa.js +622 -0
- package/dist/test/brain.test.d.ts +11 -0
- package/dist/test/brain.test.js +358 -0
- package/dist/test/cli/dispatcher.test.d.ts +4 -0
- package/dist/test/cli/dispatcher.test.js +332 -0
- package/dist/test/cli/human-loop.test.d.ts +4 -0
- package/dist/test/cli/human-loop.test.js +270 -0
- package/dist/test/grounding/feedback.test.d.ts +4 -0
- package/dist/test/grounding/feedback.test.js +462 -0
- package/dist/test/grounding/verifier.test.d.ts +4 -0
- package/dist/test/grounding/verifier.test.js +442 -0
- package/dist/test/grounding.test.d.ts +6 -0
- package/dist/test/grounding.test.js +246 -0
- package/dist/test/healing/detector.test.d.ts +4 -0
- package/dist/test/healing/detector.test.js +266 -0
- package/dist/test/healing/fixer.test.d.ts +4 -0
- package/dist/test/healing/fixer.test.js +369 -0
- package/dist/test/integration.test.d.ts +5 -0
- package/dist/test/integration.test.js +290 -0
- package/dist/test/tools/bash.test.d.ts +4 -0
- package/dist/test/tools/bash.test.js +348 -0
- package/dist/test/tools/edit.test.d.ts +4 -0
- package/dist/test/tools/edit.test.js +350 -0
- package/dist/test/tools/git.test.d.ts +4 -0
- package/dist/test/tools/git.test.js +350 -0
- package/package.json +60 -0
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Genesis 6.0 - Latent State Decoder
|
|
4
|
+
*
|
|
5
|
+
* Decodes latent states back to interpretable representations.
|
|
6
|
+
*
|
|
7
|
+
* Capabilities:
|
|
8
|
+
* - Decode to text descriptions
|
|
9
|
+
* - Decode to structured state
|
|
10
|
+
* - Decode to feature maps
|
|
11
|
+
* - Interpolate between states
|
|
12
|
+
*
|
|
13
|
+
* The decoder is the inverse of the encoder, allowing the system
|
|
14
|
+
* to generate human-readable outputs from internal representations.
|
|
15
|
+
*
|
|
16
|
+
* Architecture:
|
|
17
|
+
* - Modality-specific decoders
|
|
18
|
+
* - Feature extraction
|
|
19
|
+
* - Narrative generation
|
|
20
|
+
*
|
|
21
|
+
* References:
|
|
22
|
+
* - VAE Decoders (Kingma & Welling, 2014)
|
|
23
|
+
* - VQ-VAE (van den Oord et al., 2017)
|
|
24
|
+
*
|
|
25
|
+
* Usage:
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { createLatentDecoder } from './world-model/decoder.js';
|
|
28
|
+
*
|
|
29
|
+
* const decoder = createLatentDecoder();
|
|
30
|
+
*
|
|
31
|
+
* // Decode to text
|
|
32
|
+
* const description = decoder.decodeToText(latentState);
|
|
33
|
+
*
|
|
34
|
+
* // Decode to structured state
|
|
35
|
+
* const state = decoder.decodeToState(latentState);
|
|
36
|
+
*
|
|
37
|
+
* // Interpolate between states
|
|
38
|
+
* const interpolated = decoder.interpolate(stateA, stateB, 0.5);
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
+
exports.LatentDecoder = exports.DEFAULT_DECODER_CONFIG = void 0;
|
|
43
|
+
exports.createLatentDecoder = createLatentDecoder;
|
|
44
|
+
const crypto_1 = require("crypto");
|
|
45
|
+
exports.DEFAULT_DECODER_CONFIG = {
|
|
46
|
+
outputDim: 512,
|
|
47
|
+
vocabularySize: 10000,
|
|
48
|
+
maxTextLength: 500,
|
|
49
|
+
featureThreshold: 0.1,
|
|
50
|
+
interpolationSteps: 10,
|
|
51
|
+
};
|
|
52
|
+
// ============================================================================
|
|
53
|
+
// Vocabulary for text generation
|
|
54
|
+
// ============================================================================
|
|
55
|
+
const VOCABULARY = {
|
|
56
|
+
concepts: [
|
|
57
|
+
'system', 'state', 'action', 'process', 'entity', 'relation',
|
|
58
|
+
'input', 'output', 'result', 'change', 'update', 'transform',
|
|
59
|
+
'data', 'information', 'knowledge', 'pattern', 'structure',
|
|
60
|
+
'active', 'passive', 'stable', 'changing', 'growing', 'declining',
|
|
61
|
+
],
|
|
62
|
+
descriptors: [
|
|
63
|
+
'high', 'low', 'moderate', 'significant', 'minimal', 'optimal',
|
|
64
|
+
'increasing', 'decreasing', 'stable', 'fluctuating', 'converging',
|
|
65
|
+
'strong', 'weak', 'balanced', 'unbalanced', 'coherent', 'fragmented',
|
|
66
|
+
],
|
|
67
|
+
relations: [
|
|
68
|
+
'connected to', 'dependent on', 'influences', 'causes', 'prevents',
|
|
69
|
+
'enables', 'contains', 'similar to', 'different from', 'related to',
|
|
70
|
+
],
|
|
71
|
+
sentiment: [
|
|
72
|
+
'positive', 'negative', 'neutral', 'uncertain', 'confident',
|
|
73
|
+
'stable', 'volatile', 'improving', 'declining', 'transitioning',
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
class LatentDecoder {
|
|
77
|
+
config;
|
|
78
|
+
eventHandlers = new Set();
|
|
79
|
+
// Statistics
|
|
80
|
+
decodingCount = 0;
|
|
81
|
+
interpolationCount = 0;
|
|
82
|
+
constructor(config = {}) {
|
|
83
|
+
this.config = { ...exports.DEFAULT_DECODER_CONFIG, ...config };
|
|
84
|
+
}
|
|
85
|
+
// ============================================================================
|
|
86
|
+
// Text Decoding
|
|
87
|
+
// ============================================================================
|
|
88
|
+
/**
|
|
89
|
+
* Decode latent state to text description
|
|
90
|
+
*/
|
|
91
|
+
decodeToText(state) {
|
|
92
|
+
const vector = state.vector;
|
|
93
|
+
// Extract dominant features
|
|
94
|
+
const dominantIndices = this.getDominantIndices(vector, 10);
|
|
95
|
+
// Generate keywords from features
|
|
96
|
+
const keywords = this.vectorToKeywords(vector, dominantIndices);
|
|
97
|
+
// Calculate sentiment from vector
|
|
98
|
+
const sentiment = this.calculateSentiment(vector);
|
|
99
|
+
// Generate description
|
|
100
|
+
const description = this.generateDescription(keywords, sentiment, state);
|
|
101
|
+
const decoding = {
|
|
102
|
+
id: (0, crypto_1.randomUUID)(),
|
|
103
|
+
sourceState: state.sourceId,
|
|
104
|
+
modality: 'text',
|
|
105
|
+
output: description,
|
|
106
|
+
keywords,
|
|
107
|
+
sentiment,
|
|
108
|
+
confidence: state.confidence,
|
|
109
|
+
timestamp: new Date(),
|
|
110
|
+
};
|
|
111
|
+
this.decodingCount++;
|
|
112
|
+
this.emit({ type: 'decoded_text', data: { length: description.length, keywords } });
|
|
113
|
+
return decoding;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Extract keywords from vector
|
|
117
|
+
*/
|
|
118
|
+
vectorToKeywords(vector, dominantIndices) {
|
|
119
|
+
const keywords = [];
|
|
120
|
+
// Map indices to concept words
|
|
121
|
+
for (const idx of dominantIndices.slice(0, 5)) {
|
|
122
|
+
const conceptIdx = idx % VOCABULARY.concepts.length;
|
|
123
|
+
keywords.push(VOCABULARY.concepts[conceptIdx]);
|
|
124
|
+
}
|
|
125
|
+
// Add descriptors based on vector statistics
|
|
126
|
+
const mean = vector.reduce((a, b) => a + b, 0) / vector.length;
|
|
127
|
+
const variance = vector.reduce((a, b) => a + (b - mean) ** 2, 0) / vector.length;
|
|
128
|
+
if (mean > 0.1) {
|
|
129
|
+
keywords.push('active');
|
|
130
|
+
}
|
|
131
|
+
else if (mean < -0.1) {
|
|
132
|
+
keywords.push('passive');
|
|
133
|
+
}
|
|
134
|
+
if (variance > 0.3) {
|
|
135
|
+
keywords.push('dynamic');
|
|
136
|
+
}
|
|
137
|
+
else {
|
|
138
|
+
keywords.push('stable');
|
|
139
|
+
}
|
|
140
|
+
return [...new Set(keywords)]; // Remove duplicates
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Calculate sentiment from vector
|
|
144
|
+
*/
|
|
145
|
+
calculateSentiment(vector) {
|
|
146
|
+
// Use first few dimensions as sentiment indicators
|
|
147
|
+
const sentimentDims = vector.slice(0, 10);
|
|
148
|
+
const sentiment = sentimentDims.reduce((a, b) => a + b, 0) / sentimentDims.length;
|
|
149
|
+
return Math.max(-1, Math.min(1, sentiment));
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Generate natural language description
|
|
153
|
+
*/
|
|
154
|
+
generateDescription(keywords, sentiment, state) {
|
|
155
|
+
const parts = [];
|
|
156
|
+
// Opening based on modality
|
|
157
|
+
const modalityOpening = {
|
|
158
|
+
text: 'Text content',
|
|
159
|
+
image: 'Visual representation',
|
|
160
|
+
code: 'Code structure',
|
|
161
|
+
state: 'System state',
|
|
162
|
+
audio: 'Audio signal',
|
|
163
|
+
sensor: 'Sensor reading',
|
|
164
|
+
};
|
|
165
|
+
parts.push(modalityOpening[state.sourceModality] || 'Content');
|
|
166
|
+
// Add keywords
|
|
167
|
+
if (keywords.length > 0) {
|
|
168
|
+
parts.push(`involving ${keywords.slice(0, 3).join(', ')}`);
|
|
169
|
+
}
|
|
170
|
+
// Add sentiment description
|
|
171
|
+
const sentimentWord = sentiment > 0.3 ? 'positive'
|
|
172
|
+
: sentiment < -0.3 ? 'negative'
|
|
173
|
+
: 'neutral';
|
|
174
|
+
parts.push(`with ${sentimentWord} indicators`);
|
|
175
|
+
// Add confidence
|
|
176
|
+
const confidenceWord = state.confidence > 0.7 ? 'high'
|
|
177
|
+
: state.confidence > 0.4 ? 'moderate'
|
|
178
|
+
: 'low';
|
|
179
|
+
parts.push(`(${confidenceWord} confidence)`);
|
|
180
|
+
// Add entropy information
|
|
181
|
+
if (state.entropy !== undefined) {
|
|
182
|
+
const entropyWord = state.entropy > 0.7 ? 'high information density'
|
|
183
|
+
: state.entropy > 0.4 ? 'moderate complexity'
|
|
184
|
+
: 'simple structure';
|
|
185
|
+
parts.push(`showing ${entropyWord}`);
|
|
186
|
+
}
|
|
187
|
+
return parts.join(' ') + '.';
|
|
188
|
+
}
|
|
189
|
+
// ============================================================================
|
|
190
|
+
// State Decoding
|
|
191
|
+
// ============================================================================
|
|
192
|
+
/**
|
|
193
|
+
* Decode latent state to structured state
|
|
194
|
+
*/
|
|
195
|
+
decodeToState(state) {
|
|
196
|
+
const vector = state.vector;
|
|
197
|
+
const output = {};
|
|
198
|
+
const numericFields = [];
|
|
199
|
+
const categoricalFields = [];
|
|
200
|
+
// Decode numerical properties
|
|
201
|
+
output['energy'] = this.sigmoidToRange(vector[0], 0, 1);
|
|
202
|
+
numericFields.push('energy');
|
|
203
|
+
output['stability'] = this.sigmoidToRange(vector[1], 0, 1);
|
|
204
|
+
numericFields.push('stability');
|
|
205
|
+
output['activity'] = this.sigmoidToRange(vector[2], 0, 1);
|
|
206
|
+
numericFields.push('activity');
|
|
207
|
+
output['complexity'] = state.entropy || 0.5;
|
|
208
|
+
numericFields.push('complexity');
|
|
209
|
+
// Decode categorical properties
|
|
210
|
+
const stateIdx = Math.abs(Math.floor(vector[10] * 5)) % 5;
|
|
211
|
+
const states = ['idle', 'active', 'processing', 'waiting', 'error'];
|
|
212
|
+
output['status'] = states[stateIdx];
|
|
213
|
+
categoricalFields.push('status');
|
|
214
|
+
const modeIdx = Math.abs(Math.floor(vector[11] * 4)) % 4;
|
|
215
|
+
const modes = ['normal', 'degraded', 'recovering', 'optimal'];
|
|
216
|
+
output['mode'] = modes[modeIdx];
|
|
217
|
+
categoricalFields.push('mode');
|
|
218
|
+
// Decode array properties
|
|
219
|
+
output['features'] = this.getDominantIndices(vector, 5).map((i) => `feature_${i}`);
|
|
220
|
+
// Add metadata
|
|
221
|
+
output['confidence'] = state.confidence;
|
|
222
|
+
output['timestamp'] = state.timestamp.toISOString();
|
|
223
|
+
output['sourceModality'] = state.sourceModality;
|
|
224
|
+
const decoding = {
|
|
225
|
+
id: (0, crypto_1.randomUUID)(),
|
|
226
|
+
sourceState: state.sourceId,
|
|
227
|
+
modality: 'state',
|
|
228
|
+
output,
|
|
229
|
+
numericFields,
|
|
230
|
+
categoricalFields,
|
|
231
|
+
confidence: state.confidence,
|
|
232
|
+
timestamp: new Date(),
|
|
233
|
+
};
|
|
234
|
+
this.decodingCount++;
|
|
235
|
+
this.emit({ type: 'decoded_state', data: { fields: Object.keys(output).length } });
|
|
236
|
+
return decoding;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Convert sigmoid value to range
|
|
240
|
+
*/
|
|
241
|
+
sigmoidToRange(value, min, max) {
|
|
242
|
+
const sigmoid = 1 / (1 + Math.exp(-value * 5));
|
|
243
|
+
return min + sigmoid * (max - min);
|
|
244
|
+
}
|
|
245
|
+
// ============================================================================
|
|
246
|
+
// Feature Decoding
|
|
247
|
+
// ============================================================================
|
|
248
|
+
/**
|
|
249
|
+
* Decode to feature representation
|
|
250
|
+
*/
|
|
251
|
+
decodeToFeatures(state) {
|
|
252
|
+
const vector = state.vector;
|
|
253
|
+
const features = [];
|
|
254
|
+
// Extract top activations
|
|
255
|
+
const indexed = vector.map((v, i) => ({ value: v, index: i }));
|
|
256
|
+
indexed.sort((a, b) => Math.abs(b.value) - Math.abs(a.value));
|
|
257
|
+
const topActivations = indexed.slice(0, 20).map((item) => item.index);
|
|
258
|
+
// Group into features
|
|
259
|
+
const featureGroups = this.groupFeatures(indexed.slice(0, 50));
|
|
260
|
+
for (let i = 0; i < featureGroups.length; i++) {
|
|
261
|
+
const group = featureGroups[i];
|
|
262
|
+
const avgActivation = group.reduce((sum, item) => sum + Math.abs(item.value), 0) / group.length;
|
|
263
|
+
if (avgActivation >= this.config.featureThreshold) {
|
|
264
|
+
features.push({
|
|
265
|
+
name: `feature_group_${i}`,
|
|
266
|
+
indices: group.map((item) => item.index),
|
|
267
|
+
activation: avgActivation,
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
// Add existing features from state
|
|
272
|
+
if (state.features) {
|
|
273
|
+
features.push(...state.features);
|
|
274
|
+
}
|
|
275
|
+
const decoding = {
|
|
276
|
+
id: (0, crypto_1.randomUUID)(),
|
|
277
|
+
sourceState: state.sourceId,
|
|
278
|
+
modality: 'state',
|
|
279
|
+
output: features,
|
|
280
|
+
topActivations,
|
|
281
|
+
confidence: state.confidence,
|
|
282
|
+
timestamp: new Date(),
|
|
283
|
+
};
|
|
284
|
+
this.emit({ type: 'decoded_features', data: { featureCount: features.length } });
|
|
285
|
+
return decoding;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Group related features
|
|
289
|
+
*/
|
|
290
|
+
groupFeatures(indexed) {
|
|
291
|
+
const groups = [];
|
|
292
|
+
const used = new Set();
|
|
293
|
+
for (const item of indexed) {
|
|
294
|
+
if (used.has(item.index))
|
|
295
|
+
continue;
|
|
296
|
+
const group = [item];
|
|
297
|
+
used.add(item.index);
|
|
298
|
+
// Find nearby indices with similar values
|
|
299
|
+
for (const other of indexed) {
|
|
300
|
+
if (used.has(other.index))
|
|
301
|
+
continue;
|
|
302
|
+
const indexDistance = Math.abs(item.index - other.index);
|
|
303
|
+
const valueDistance = Math.abs(item.value - other.value);
|
|
304
|
+
if (indexDistance < 10 && valueDistance < 0.2) {
|
|
305
|
+
group.push(other);
|
|
306
|
+
used.add(other.index);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (group.length >= 2) {
|
|
310
|
+
groups.push(group);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return groups;
|
|
314
|
+
}
|
|
315
|
+
// ============================================================================
|
|
316
|
+
// Interpolation
|
|
317
|
+
// ============================================================================
|
|
318
|
+
/**
|
|
319
|
+
* Interpolate between two latent states
|
|
320
|
+
*/
|
|
321
|
+
interpolate(stateA, stateB, t) {
|
|
322
|
+
const minLen = Math.min(stateA.vector.length, stateB.vector.length);
|
|
323
|
+
const interpolatedVector = new Array(minLen);
|
|
324
|
+
for (let i = 0; i < minLen; i++) {
|
|
325
|
+
interpolatedVector[i] = stateA.vector[i] * (1 - t) + stateB.vector[i] * t;
|
|
326
|
+
}
|
|
327
|
+
const interpolated = {
|
|
328
|
+
vector: this.normalize(interpolatedVector),
|
|
329
|
+
dimensions: minLen,
|
|
330
|
+
sourceModality: stateA.sourceModality,
|
|
331
|
+
sourceId: `interp-${stateA.sourceId}-${stateB.sourceId}-${t.toFixed(2)}`,
|
|
332
|
+
timestamp: new Date(),
|
|
333
|
+
confidence: Math.min(stateA.confidence, stateB.confidence) * (1 - Math.abs(t - 0.5) * 0.2),
|
|
334
|
+
entropy: stateA.entropy * (1 - t) + (stateB.entropy || 0.5) * t,
|
|
335
|
+
};
|
|
336
|
+
this.interpolationCount++;
|
|
337
|
+
this.emit({ type: 'interpolated', data: { t } });
|
|
338
|
+
return interpolated;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Generate interpolation sequence
|
|
342
|
+
*/
|
|
343
|
+
interpolateSequence(stateA, stateB, steps = this.config.interpolationSteps) {
|
|
344
|
+
const sequence = [];
|
|
345
|
+
for (let i = 0; i <= steps; i++) {
|
|
346
|
+
const t = i / steps;
|
|
347
|
+
sequence.push(this.interpolate(stateA, stateB, t));
|
|
348
|
+
}
|
|
349
|
+
return sequence;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Spherical interpolation (SLERP) for better interpolation on unit sphere
|
|
353
|
+
*/
|
|
354
|
+
slerp(stateA, stateB, t) {
|
|
355
|
+
const a = this.normalize(stateA.vector);
|
|
356
|
+
const b = this.normalize(stateB.vector);
|
|
357
|
+
// Calculate angle
|
|
358
|
+
const dot = a.reduce((sum, v, i) => sum + v * b[i], 0);
|
|
359
|
+
const theta = Math.acos(Math.max(-1, Math.min(1, dot)));
|
|
360
|
+
if (theta < 0.001) {
|
|
361
|
+
// Vectors are nearly parallel, use linear interpolation
|
|
362
|
+
return this.interpolate(stateA, stateB, t);
|
|
363
|
+
}
|
|
364
|
+
const sinTheta = Math.sin(theta);
|
|
365
|
+
const weightA = Math.sin((1 - t) * theta) / sinTheta;
|
|
366
|
+
const weightB = Math.sin(t * theta) / sinTheta;
|
|
367
|
+
const slerpVector = a.map((v, i) => v * weightA + b[i] * weightB);
|
|
368
|
+
return {
|
|
369
|
+
vector: slerpVector,
|
|
370
|
+
dimensions: slerpVector.length,
|
|
371
|
+
sourceModality: stateA.sourceModality,
|
|
372
|
+
sourceId: `slerp-${stateA.sourceId}-${stateB.sourceId}-${t.toFixed(2)}`,
|
|
373
|
+
timestamp: new Date(),
|
|
374
|
+
confidence: Math.min(stateA.confidence, stateB.confidence),
|
|
375
|
+
entropy: stateA.entropy * (1 - t) + (stateB.entropy || 0.5) * t,
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
// ============================================================================
|
|
379
|
+
// Utilities
|
|
380
|
+
// ============================================================================
|
|
381
|
+
/**
|
|
382
|
+
* Get indices of dominant (highest absolute) values
|
|
383
|
+
*/
|
|
384
|
+
getDominantIndices(vector, count) {
|
|
385
|
+
const indexed = vector.map((v, i) => ({ value: Math.abs(v), index: i }));
|
|
386
|
+
indexed.sort((a, b) => b.value - a.value);
|
|
387
|
+
return indexed.slice(0, count).map((item) => item.index);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Normalize vector
|
|
391
|
+
*/
|
|
392
|
+
normalize(vector) {
|
|
393
|
+
const magnitude = Math.sqrt(vector.reduce((sum, v) => sum + v * v, 0));
|
|
394
|
+
if (magnitude === 0)
|
|
395
|
+
return vector;
|
|
396
|
+
return vector.map((v) => v / magnitude);
|
|
397
|
+
}
|
|
398
|
+
// ============================================================================
|
|
399
|
+
// Analysis
|
|
400
|
+
// ============================================================================
|
|
401
|
+
/**
|
|
402
|
+
* Compare two latent states
|
|
403
|
+
*/
|
|
404
|
+
compare(stateA, stateB) {
|
|
405
|
+
// Cosine similarity
|
|
406
|
+
const minLen = Math.min(stateA.vector.length, stateB.vector.length);
|
|
407
|
+
let dotProduct = 0;
|
|
408
|
+
let magA = 0;
|
|
409
|
+
let magB = 0;
|
|
410
|
+
const divergent = [];
|
|
411
|
+
for (let i = 0; i < minLen; i++) {
|
|
412
|
+
dotProduct += stateA.vector[i] * stateB.vector[i];
|
|
413
|
+
magA += stateA.vector[i] * stateA.vector[i];
|
|
414
|
+
magB += stateB.vector[i] * stateB.vector[i];
|
|
415
|
+
// Track divergent dimensions
|
|
416
|
+
const diff = Math.abs(stateA.vector[i] - stateB.vector[i]);
|
|
417
|
+
if (diff > 0.5) {
|
|
418
|
+
divergent.push(i);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const similarity = magA > 0 && magB > 0
|
|
422
|
+
? dotProduct / (Math.sqrt(magA) * Math.sqrt(magB))
|
|
423
|
+
: 0;
|
|
424
|
+
// Euclidean distance
|
|
425
|
+
let sumSq = 0;
|
|
426
|
+
for (let i = 0; i < minLen; i++) {
|
|
427
|
+
sumSq += (stateA.vector[i] - stateB.vector[i]) ** 2;
|
|
428
|
+
}
|
|
429
|
+
const distance = Math.sqrt(sumSq);
|
|
430
|
+
// Common features
|
|
431
|
+
const commonFeatures = [];
|
|
432
|
+
if (stateA.features && stateB.features) {
|
|
433
|
+
const aNames = new Set(stateA.features.map((f) => f.name));
|
|
434
|
+
for (const f of stateB.features) {
|
|
435
|
+
if (aNames.has(f.name)) {
|
|
436
|
+
commonFeatures.push(f.name);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return {
|
|
441
|
+
similarity,
|
|
442
|
+
distance,
|
|
443
|
+
divergentDimensions: divergent.slice(0, 10),
|
|
444
|
+
commonFeatures,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Analyze latent state structure
|
|
449
|
+
*/
|
|
450
|
+
analyze(state) {
|
|
451
|
+
const vector = state.vector;
|
|
452
|
+
// Sparsity (fraction of near-zero values)
|
|
453
|
+
const nearZeroCount = vector.filter((v) => Math.abs(v) < 0.01).length;
|
|
454
|
+
const sparsity = nearZeroCount / vector.length;
|
|
455
|
+
// Dominant region
|
|
456
|
+
const regionSize = Math.floor(vector.length / 4);
|
|
457
|
+
const regionSums = [0, 0, 0, 0];
|
|
458
|
+
for (let r = 0; r < 4; r++) {
|
|
459
|
+
for (let i = r * regionSize; i < (r + 1) * regionSize; i++) {
|
|
460
|
+
regionSums[r] += Math.abs(vector[i] || 0);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const dominantRegionIdx = regionSums.indexOf(Math.max(...regionSums));
|
|
464
|
+
const regions = ['semantic', 'structural', 'temporal', 'relational'];
|
|
465
|
+
const dominantRegion = regions[dominantRegionIdx];
|
|
466
|
+
// Simple cluster assignment based on dominant dimensions
|
|
467
|
+
const dominant = this.getDominantIndices(vector, 3);
|
|
468
|
+
const clusterAssignment = (dominant[0] % 10);
|
|
469
|
+
// Anomaly score (deviation from expected distribution)
|
|
470
|
+
const mean = vector.reduce((a, b) => a + b, 0) / vector.length;
|
|
471
|
+
const variance = vector.reduce((a, b) => a + (b - mean) ** 2, 0) / vector.length;
|
|
472
|
+
const expectedVariance = 0.1;
|
|
473
|
+
const anomalyScore = Math.abs(variance - expectedVariance) / expectedVariance;
|
|
474
|
+
return {
|
|
475
|
+
sparsity,
|
|
476
|
+
dominantRegion,
|
|
477
|
+
clusterAssignment,
|
|
478
|
+
anomalyScore: Math.min(1, anomalyScore),
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
// ============================================================================
|
|
482
|
+
// Events
|
|
483
|
+
// ============================================================================
|
|
484
|
+
on(handler) {
|
|
485
|
+
this.eventHandlers.add(handler);
|
|
486
|
+
return () => this.eventHandlers.delete(handler);
|
|
487
|
+
}
|
|
488
|
+
emit(event) {
|
|
489
|
+
for (const handler of this.eventHandlers) {
|
|
490
|
+
try {
|
|
491
|
+
handler(event);
|
|
492
|
+
}
|
|
493
|
+
catch (err) {
|
|
494
|
+
console.error('Decoder event handler error:', err);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
// ============================================================================
|
|
499
|
+
// Stats
|
|
500
|
+
// ============================================================================
|
|
501
|
+
stats() {
|
|
502
|
+
return {
|
|
503
|
+
decodingCount: this.decodingCount,
|
|
504
|
+
interpolationCount: this.interpolationCount,
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
getConfig() {
|
|
508
|
+
return { ...this.config };
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
exports.LatentDecoder = LatentDecoder;
|
|
512
|
+
// ============================================================================
|
|
513
|
+
// Factory
|
|
514
|
+
// ============================================================================
|
|
515
|
+
function createLatentDecoder(config) {
|
|
516
|
+
return new LatentDecoder(config);
|
|
517
|
+
}
|