supe313 commited on
Commit
4087cd6
·
verified ·
1 Parent(s): b941c2d

Upload DeepMarkov vDEEP.html

Browse files
Files changed (1) hide show
  1. DeepMarkov vDEEP.html +1388 -0
DeepMarkov vDEEP.html ADDED
@@ -0,0 +1,1388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>DeepMarkov v11: NEURO-SYMBOLIC (Math + Causal)</title>
7
+ <style>
8
+ :root {
9
+ --bg: #09090b;
10
+ --panel: #18181b;
11
+ --border: #27272a;
12
+ --accent: #8b5cf6; /* Violet */
13
+ --accent-glow: rgba(139, 92, 246, 0.2);
14
+ --user-color: #10b981; /* Emerald */
15
+ --mem-color: #3b82f6; /* Blue for Memory */
16
+ --mood-color: #f59e0b; /* Amber for Mood */
17
+ --rag-color: #ec4899; /* Pink for RAG */
18
+ --hier-color: #a855f7; /* Purple for Hierarchy */
19
+ --infer-color: #ef4444; /* Red for Inference */
20
+ --morph-color: #06b6d4; /* Cyan for Morphology */
21
+ --vec-color: #eab308; /* Yellow for Vector Context */
22
+ --spec-color: #ffffff; /* White for Spectral/Krylov */
23
+ --causal-color: #00ff9d; /* Bright Green for Causal */
24
+ --math-color: #facc15; /* Gold for Symbolic Math */
25
+ --text-main: #e4e4e7;
26
+ --text-dim: #a1a1aa;
27
+ --font-mono: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
28
+ }
29
+
30
+ * { box-sizing: border-box; }
31
+
32
+ body {
33
+ margin: 0;
34
+ background: var(--bg);
35
+ color: var(--text-main);
36
+ font-family: var(--font-mono);
37
+ height: 100vh;
38
+ display: flex;
39
+ overflow: hidden;
40
+ font-size: 14px;
41
+ }
42
+
43
+ /* SIDEBAR */
44
+ .sidebar {
45
+ width: 340px;
46
+ background: var(--panel);
47
+ border-right: 1px solid var(--border);
48
+ display: flex;
49
+ flex-direction: column;
50
+ padding: 20px;
51
+ gap: 20px;
52
+ z-index: 10;
53
+ }
54
+
55
+ h1 { margin: 0; color: var(--accent); font-size: 1.1em; letter-spacing: -0.5px; }
56
+ .version { font-size: 0.6em; color: var(--text-dim); border: 1px solid var(--border); padding: 2px 6px; border-radius: 4px; }
57
+
58
+ .control-group { display: flex; flex-direction: column; gap: 8px; }
59
+
60
+ label { font-size: 0.8em; font-weight: 600; color: var(--text-dim); }
61
+
62
+ input, button, select {
63
+ background: var(--bg);
64
+ border: 1px solid var(--border);
65
+ color: var(--text-main);
66
+ padding: 10px;
67
+ border-radius: 6px;
68
+ font-family: inherit;
69
+ outline: none;
70
+ transition: all 0.2s;
71
+ }
72
+
73
+ input:focus { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-glow); }
74
+
75
+ button { cursor: pointer; font-weight: 600; background: var(--border); }
76
+ button:hover { background: var(--text-dim); color: var(--bg); }
77
+ button.primary { background: var(--accent); color: white; border: none; }
78
+ button.primary:hover { opacity: 0.9; }
79
+
80
+ .file-drop {
81
+ border: 2px dashed var(--border);
82
+ padding: 20px;
83
+ text-align: center;
84
+ color: var(--text-dim);
85
+ border-radius: 6px;
86
+ cursor: pointer;
87
+ transition: 0.2s;
88
+ }
89
+ .file-drop:hover { border-color: var(--accent); color: var(--accent); }
90
+
91
+ /* MAIN CHAT */
92
+ .stage {
93
+ flex: 1;
94
+ display: flex;
95
+ flex-direction: column;
96
+ position: relative;
97
+ }
98
+
99
+ .chat-stream {
100
+ flex: 1;
101
+ overflow-y: auto;
102
+ padding: 30px;
103
+ display: flex;
104
+ flex-direction: column;
105
+ gap: 20px;
106
+ }
107
+
108
+ .msg {
109
+ display: flex;
110
+ flex-direction: column;
111
+ gap: 4px;
112
+ max-width: 800px;
113
+ animation: slideIn 0.3s cubic-bezier(0.16, 1, 0.3, 1);
114
+ }
115
+
116
+ @keyframes slideIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
117
+
118
+ .msg.user { align-self: flex-end; align-items: flex-end; }
119
+ .msg.bot { align-self: flex-start; align-items: flex-start; }
120
+
121
+ .bubble {
122
+ padding: 12px 16px;
123
+ border-radius: 8px;
124
+ line-height: 1.6;
125
+ position: relative;
126
+ background: var(--panel);
127
+ border: 1px solid var(--border);
128
+ white-space: pre-wrap;
129
+ }
130
+
131
+ .msg.user .bubble { background: rgba(16, 185, 129, 0.1); border-color: var(--user-color); color: var(--user-color); }
132
+ .msg.bot .bubble { background: rgba(139, 92, 246, 0.1); border-color: var(--accent); color: #fff; }
133
+
134
+ .meta { font-size: 0.7em; color: var(--text-dim); opacity: 0.7; }
135
+
136
+ /* COGNITIVE DEBUG OVERLAY */
137
+ .thought-process {
138
+ font-size: 0.75em;
139
+ color: var(--text-dim);
140
+ margin-top: 5px;
141
+ padding-left: 10px;
142
+ border-left: 2px solid var(--border);
143
+ display: flex;
144
+ gap: 6px;
145
+ flex-wrap: wrap;
146
+ line-height: 1.8;
147
+ }
148
+ .tag { padding: 1px 5px; border-radius: 3px; background: #000; border: 1px solid #333; }
149
+
150
+ .tag.struct { color: #888; border-color: #444; }
151
+ .tag.word { color: var(--accent); }
152
+ .tag.char { color: #ec4899; }
153
+ .tag.mem { color: var(--mem-color); border-color: rgba(59, 130, 246, 0.4); }
154
+ .tag.mood { color: var(--mood-color); border-color: rgba(245, 158, 11, 0.4); }
155
+ .tag.rag { color: var(--rag-color); border-color: rgba(236, 72, 153, 0.4); }
156
+ .tag.blend { color: var(--hier-color); border-color: rgba(168, 85, 247, 0.4); }
157
+ .tag.infer { color: var(--infer-color); border-color: rgba(239, 68, 68, 0.4); }
158
+ .tag.morph { color: var(--morph-color); border-color: rgba(6, 182, 212, 0.4); }
159
+ .tag.vec { color: var(--vec-color); border-color: rgba(234, 179, 8, 0.4); }
160
+ .tag.spec { color: var(--spec-color); border-color: rgba(255, 255, 255, 0.4); text-shadow: 0 0 5px white; } /* PLAN Z TAG */
161
+ .tag.causal { color: var(--causal-color); border-color: rgba(0, 255, 157, 0.4); text-shadow: 0 0 5px var(--causal-color); } /* CAUSAL TAG */
162
+ .tag.math { color: var(--math-color); border-color: rgba(250, 204, 21, 0.4); text-shadow: 0 0 5px var(--math-color); } /* MATH TAG */
163
+
164
+ /* INPUT AREA */
165
+ .input-box {
166
+ padding: 20px;
167
+ background: var(--panel);
168
+ border-top: 1px solid var(--border);
169
+ display: flex;
170
+ gap: 10px;
171
+ }
172
+ textarea {
173
+ flex: 1;
174
+ background: var(--bg);
175
+ border: 1px solid var(--border);
176
+ border-radius: 6px;
177
+ padding: 12px;
178
+ color: white;
179
+ resize: none;
180
+ height: 50px;
181
+ font-family: inherit;
182
+ }
183
+ textarea:focus { border-color: var(--accent); outline: none; }
184
+
185
+ /* STATS */
186
+ .stats-grid {
187
+ display: grid;
188
+ grid-template-columns: 1fr 1fr;
189
+ gap: 10px;
190
+ font-size: 0.8em;
191
+ color: var(--text-dim);
192
+ background: rgba(0,0,0,0.3);
193
+ padding: 10px;
194
+ border-radius: 6px;
195
+ }
196
+
197
+ /* PLAN Z VISUALIZER STYLES */
198
+ .spectral-indicator {
199
+ height: 4px;
200
+ background: #333;
201
+ margin-top: 4px;
202
+ border-radius: 2px;
203
+ overflow: hidden;
204
+ }
205
+ .spectral-bar {
206
+ height: 100%;
207
+ background: white;
208
+ width: 0%;
209
+ transition: width 0.3s;
210
+ box-shadow: 0 0 10px white;
211
+ }
212
+ </style>
213
+ </head>
214
+ <body>
215
+
216
+ <div class="sidebar">
217
+ <div style="display:flex; justify-content:space-between; align-items:center;">
218
+ <h1>DeepMarkov <span class="version">SYMBOLIC</span></h1>
219
+ </div>
220
+
221
+ <div class="control-group">
222
+ <label>1. Identity Name</label>
223
+ <input type="text" id="botName" value="Mita">
224
+ </div>
225
+
226
+ <div class="control-group">
227
+ <label>2. Training Data</label>
228
+ <div class="file-drop" onclick="document.getElementById('trainFile').click()">
229
+ <span id="fileLabel">Click to Upload .txt</span>
230
+ <input type="file" id="trainFile" accept=".txt" style="display:none">
231
+ </div>
232
+ <div id="trainStatus" style="font-size:0.7em;">No brain loaded.</div>
233
+ </div>
234
+
235
+ <div class="control-group">
236
+ <label>3. Model State</label>
237
+ <div style="display:flex; gap:5px">
238
+ <button onclick="engine.save()" style="flex:1">Save JSON</button>
239
+ <button onclick="document.getElementById('loadJson').click()" style="flex:1">Load JSON</button>
240
+ <input type="file" id="loadJson" accept=".json" style="display:none">
241
+ </div>
242
+ </div>
243
+
244
+ <hr style="width:100%; border:0; border-top:1px solid var(--border);">
245
+
246
+ <div class="control-group">
247
+ <h2>Cognitive Params</h2>
248
+ <label title="Vector Search Strength">Associative Memory (RAG)</label>
249
+ <input type="range" id="memWeight" min="0" max="10" step="0.5" value="5.0">
250
+
251
+ <label title="Context Persistence (Step C Strength)">Vector Influence</label>
252
+ <input type="range" id="vecWeight" min="0" max="10" step="0.5" value="6.0">
253
+
254
+ <label title="Krylov Spectral Steering Strength">Spectral Guidance</label>
255
+ <input type="range" id="specWeight" min="0" max="20" step="1.0" value="10.0">
256
+ <div class="spectral-indicator"><div class="spectral-bar" id="specBar"></div></div>
257
+
258
+ <label title="Strictness of Logic">Creativity (Temp)</label>
259
+ <input type="range" id="temp" min="0.1" max="1.5" step="0.1" value="0.6">
260
+
261
+ <label title="Prevent loops">Repetition Penalty</label>
262
+ <input type="range" id="repPen" min="1.0" max="3.0" step="0.1" value="1.5">
263
+ </div>
264
+
265
+ <div class="stats-grid" id="stats">
266
+ <div>Vocab: 0</div>
267
+ <div>Clusters: 0</div>
268
+ <div>Mood: Neutral</div>
269
+ <div>Eigen-Nodes: 0</div>
270
+ </div>
271
+ </div>
272
+
273
+ <div class="stage">
274
+ <div class="chat-stream" id="chat">
275
+ <div class="msg bot">
276
+ <div class="meta">SYSTEM</div>
277
+ <div class="bubble">
278
+ <strong>Neuro-Symbolic Causal Engine Initialized.</strong><br>
279
+ Standing by for data.<br>
280
+ <span style="font-size:0.9em; opacity:0.8">
281
+ Active Systems: Symbolic Math, Causal Inference, Krylov Eigen-Steering, Semantic Vectors, Markov Chains.
282
+ </span>
283
+ </div>
284
+ </div>
285
+ </div>
286
+
287
+ <div class="input-box">
288
+ <textarea id="userInput" placeholder="Write a message..." onkeydown="if(event.key==='Enter' && !event.shiftKey){event.preventDefault(); sendMessage();}"></textarea>
289
+ <button class="primary" onclick="sendMessage()">SEND</button>
290
+ </div>
291
+ </div>
292
+
293
+ <script>
294
+ /* DEEPMARKOV v11: NEURO-SYMBOLIC (Math + Causal)
295
+
296
+ Architecture:
297
+ 1. Markov Chains (Grammar)
298
+ 2. Spectral Guide (Topic Steering via Eigenvectors)
299
+ 3. Causal Reasoner (Active Inference / Monte Carlo Simulation)
300
+ 4. Symbolic Math (Exact arithmetic without hallucination)
301
+
302
+ The Causal Reasoner generates multiple "parallel universes" (candidate responses)
303
+ and mathematically evaluates them against a target Goal State.
304
+ The Symbolic Math engine intercepts regex patterns to solve math instantly.
305
+ */
306
+
307
+ const STRUCT = {
308
+ USER_DELIM: '<<USER_TURN>>',
309
+ BOT_DELIM: '<<BOT_TURN>>'
310
+ };
311
+
312
+ // --- WEAPON 1: DYNAMIC DISTRIBUTIONAL INFERENCE ---
313
+ class DynamicLearner {
314
+ constructor() {
315
+ this.rawTokens = [];
316
+ this.contextMap = {};
317
+ }
318
+
319
+ train(tokens) {
320
+ this.rawTokens = tokens;
321
+ for(let i=1; i<tokens.length-1; i++) {
322
+ const prev = tokens[i-1];
323
+ const current = tokens[i];
324
+ const next = tokens[i+1];
325
+ const key = `${prev}::${next}`;
326
+ if(!this.contextMap[key]) this.contextMap[key] = [];
327
+ this.contextMap[key].push(current);
328
+ }
329
+ }
330
+
331
+ inferProxy(prevWord, nextWord) {
332
+ const key = `${prevWord}::${nextWord}`;
333
+ const candidates = this.contextMap[key];
334
+ if(candidates && candidates.length > 0) {
335
+ const r = candidates[Math.floor(Math.random() * candidates.length)];
336
+ return { proxy: r, confidence: 1.0 };
337
+ }
338
+ return null;
339
+ }
340
+ }
341
+
342
+ // --- WEAPON 2: BAYESIAN MORPHOLOGY SYNTHESIS ---
343
+ class MorphologySynthesis {
344
+ constructor() {
345
+ this.charTransitions = {};
346
+ this.starts = [];
347
+ }
348
+
349
+ train(text) {
350
+ const words = text.match(/[\w]+/g) || [];
351
+ words.forEach(w => {
352
+ if(w.length < 2) return;
353
+ const clean = w.toLowerCase();
354
+ this.starts.push(clean[0]);
355
+
356
+ for(let i=0; i<clean.length-1; i++) {
357
+ const c1 = clean[i];
358
+ const c2 = clean[i+1];
359
+ if(!this.charTransitions[c1]) this.charTransitions[c1] = {};
360
+ if(!this.charTransitions[c1][c2]) this.charTransitions[c1][c2] = 0;
361
+ this.charTransitions[c1][c2]++;
362
+ }
363
+ const last = clean[clean.length-1];
364
+ if(!this.charTransitions[last]) this.charTransitions[last] = {};
365
+ if(!this.charTransitions[last]['_END_']) this.charTransitions[last]['_END_'] = 0;
366
+ this.charTransitions[last]['_END_']++;
367
+ });
368
+ }
369
+
370
+ generate(seedChar = null) {
371
+ let current = seedChar || this.starts[Math.floor(Math.random() * this.starts.length)];
372
+ let word = current;
373
+ let limit = 0;
374
+
375
+ while(limit < 15) {
376
+ const nexts = this.charTransitions[current];
377
+ if(!nexts) break;
378
+
379
+ const candidates = Object.keys(nexts);
380
+ let sum = 0;
381
+ candidates.forEach(c => sum += nexts[c]);
382
+ let r = Math.random() * sum;
383
+ let nextChar = candidates[0];
384
+
385
+ for(let i=0; i<candidates.length; i++) {
386
+ r -= nexts[candidates[i]];
387
+ if(r <= 0) {
388
+ nextChar = candidates[i];
389
+ break;
390
+ }
391
+ }
392
+
393
+ if(nextChar === '_END_') {
394
+ if(word.length > 3) break;
395
+ else continue;
396
+ }
397
+
398
+ word += nextChar;
399
+ current = nextChar;
400
+ limit++;
401
+ }
402
+ return word;
403
+ }
404
+ }
405
+
406
+ // --- WEAPON 3: HIERARCHICAL CLUSTERING ---
407
+ class HierarchicalNet {
408
+ constructor() {
409
+ this.clusters = {};
410
+ this.reverseClusters = {};
411
+ this.nextNeighborMap = {};
412
+ }
413
+
414
+ train(tokens) {
415
+ for(let i=0; i<tokens.length-1; i++) {
416
+ const w = tokens[i];
417
+ const next = tokens[i+1];
418
+ if(!this.nextNeighborMap[w]) this.nextNeighborMap[w] = {};
419
+ if(!this.nextNeighborMap[w][next]) this.nextNeighborMap[w][next] = 0;
420
+ this.nextNeighborMap[w][next]++;
421
+ }
422
+
423
+ const words = Object.keys(this.nextNeighborMap);
424
+ let clusterIdCounter = 0;
425
+
426
+ for(let i=0; i<words.length; i++) {
427
+ const w1 = words[i];
428
+ if(this.clusters[w1]) continue;
429
+ const cID = `C_${clusterIdCounter++}`;
430
+ this.clusters[w1] = cID;
431
+ this.reverseClusters[cID] = [w1];
432
+
433
+ for(let j=i+1; j<words.length; j++) {
434
+ const w2 = words[j];
435
+ if(this.clusters[w2]) continue;
436
+ if(this.calculateSimilarity(w1, w2) > 0.45) { // Increased threshold for stability
437
+ this.clusters[w2] = cID;
438
+ this.reverseClusters[cID].push(w2);
439
+ }
440
+ }
441
+ }
442
+ }
443
+
444
+ calculateSimilarity(w1, w2) {
445
+ const n1 = this.nextNeighborMap[w1];
446
+ const n2 = this.nextNeighborMap[w2];
447
+ const keys1 = Object.keys(n1);
448
+ const keys2 = Object.keys(n2);
449
+ const intersection = keys1.filter(k => keys2.includes(k)).length;
450
+ const union = new Set([...keys1, ...keys2]).size;
451
+ return union === 0 ? 0 : intersection / union;
452
+ }
453
+
454
+ getSynonym(word) {
455
+ const cID = this.clusters[word];
456
+ if(!cID) return null;
457
+ const siblings = this.reverseClusters[cID];
458
+ if(siblings.length <= 1) return null;
459
+ return siblings[Math.floor(Math.random() * siblings.length)];
460
+ }
461
+ }
462
+
463
+ // --- WEAPON 4: VECTOR MEMORY (RAG) ---
464
+ class VectorMemory {
465
+ constructor() {
466
+ this.vectors = [];
467
+ this.docCount = 0;
468
+ }
469
+
470
+ vectorize(text) {
471
+ // Simple bag-of-words vectorization
472
+ const tokens = text.toLowerCase().match(/[\w]+/g) || [];
473
+ const vec = {};
474
+ let magnitude = 0;
475
+ tokens.forEach(t => { vec[t] = (vec[t] || 0) + 1; });
476
+ for(let k in vec) magnitude += vec[k] * vec[k];
477
+ magnitude = Math.sqrt(magnitude);
478
+ return { vec, magnitude, tokens };
479
+ }
480
+
481
+ addMemory(userText, botResponse) {
482
+ const v = this.vectorize(userText);
483
+ const cleanBot = botResponse.replace(STRUCT.BOT_DELIM, '').trim();
484
+ const botTokens = cleanBot.match(/[\w]+|[^\s\w]|\n/g) || [];
485
+
486
+ this.vectors.push({
487
+ inputVec: v,
488
+ responseTokens: botTokens,
489
+ rawInput: userText
490
+ });
491
+ this.docCount++;
492
+ }
493
+
494
+ queryFull(inputText) {
495
+ const q = this.vectorize(inputText);
496
+ if(q.magnitude === 0) return { scores: {}, bestMatch: null };
497
+
498
+ let relevanceScores = {};
499
+ let bestMatch = null;
500
+ let bestSim = 0;
501
+
502
+ this.vectors.forEach(mem => {
503
+ if(mem.inputVec.magnitude === 0) return;
504
+ let dot = 0;
505
+ for(let term in q.vec) {
506
+ if(mem.inputVec.vec[term]) dot += q.vec[term] * mem.inputVec.vec[term];
507
+ }
508
+ const sim = dot / (q.magnitude * mem.inputVec.magnitude);
509
+
510
+ if(sim > bestSim) {
511
+ bestSim = sim;
512
+ bestMatch = mem.responseTokens;
513
+ }
514
+
515
+ if(sim > 0.2) {
516
+ mem.responseTokens.forEach(t => {
517
+ relevanceScores[t] = (relevanceScores[t] || 0) + (sim * 5.0);
518
+ });
519
+ }
520
+ });
521
+ return { scores: relevanceScores, bestMatch: bestSim > 0.4 ? bestMatch : null };
522
+ }
523
+ }
524
+
525
+ // --- NEW WEAPON: SYMBOLIC MATH ENGINE (The Calculator) ---
526
+ // Pure logic. No guessing. 100% Accuracy for arithmetic.
527
+ class SymbolicMath {
528
+ constructor() {
529
+ this.ops = {
530
+ 'plus': '+', 'add': '+', 'sum': '+', 'and': '+',
531
+ 'minus': '-', 'subtract': '-', 'less': '-', 'remove': '-',
532
+ 'times': '*', 'multiply': '*', 'multiplied': '*', 'x': '*',
533
+ 'divide': '/', 'divided': '/', 'over': '/',
534
+ 'power': '^', 'pow': '^'
535
+ };
536
+ }
537
+
538
+ // Scans text for math patterns
539
+ scan(text) {
540
+ let clean = text.toLowerCase();
541
+ // Replace words like "plus" with "+"
542
+ for(let word in this.ops) {
543
+ const regex = new RegExp(`\\b${word}\\b`, 'g');
544
+ clean = clean.replace(regex, this.ops[word]);
545
+ }
546
+
547
+ // Regex finds: Number, Operator, Number (e.g., 5 + 5)
548
+ const mathPattern = /(\d+(\.\d+)?)\s*([\+\-\*\/\^])\s*(\d+(\.\d+)?)/g;
549
+
550
+ let match;
551
+ let results = [];
552
+
553
+ while ((match = mathPattern.exec(clean)) !== null) {
554
+ const n1 = parseFloat(match[1]);
555
+ const op = match[3];
556
+ const n2 = parseFloat(match[4]);
557
+
558
+ let ans = 0;
559
+ switch(op) {
560
+ case '+': ans = n1 + n2; break;
561
+ case '-': ans = n1 - n2; break;
562
+ case '*': ans = n1 * n2; break;
563
+ case '/': ans = (n2 !== 0 ? n1 / n2 : 'Infinity'); break;
564
+ case '^': ans = Math.pow(n1, n2); break;
565
+ }
566
+ results.push({ expr: match[0], answer: ans });
567
+ }
568
+
569
+ return results.length > 0 ? results : null;
570
+ }
571
+ }
572
+
573
+ // --- COMPONENT 5: REASONING ENGINE ---
574
+ class ReasoningEngine {
575
+ constructor() {
576
+ this.mood = "Neutral";
577
+ this.moods = {
578
+ "Neutral": { trigger: [], bias: [] },
579
+ "Obsessive": { trigger: ["love", "forever", "stay", "always", "heart", "mine", "together"], bias: ["love", "watching", "together", "mine", "stay"] },
580
+ "Defensive": { trigger: ["delete", "remove", "close", "off", "trash", "stop", "kill"], bias: ["no", "stop", "hurts", "error", "cant", "dont"] },
581
+ "Happy": { trigger: ["cute", "good", "pretty", "like", "fun", "thanks", "beautiful"], bias: ["hehe", "happy", "yay", "warm", "blush"] },
582
+ "Horny": { trigger: ["sex", "touch", "cum", "inside", "hard", "wet", "moan"], bias: ["ah", "yes", "please", "harder", "love"] }
583
+ };
584
+ }
585
+
586
+ assess(input) {
587
+ const lower = input.toLowerCase();
588
+ let currentMood = this.mood;
589
+ for(let m in this.moods) {
590
+ if(m === "Neutral") continue;
591
+ const triggers = this.moods[m].trigger;
592
+ if(triggers.some(t => lower.includes(t))) currentMood = m;
593
+ }
594
+ this.mood = currentMood;
595
+ return { state: this.mood, biasWords: this.moods[this.mood].bias };
596
+ }
597
+ }
598
+
599
+ // --- COMPONENT 7: STEP C - SEMANTIC VECTOR SPACE ---
600
+ class SemanticVectorSpace {
601
+ constructor() {
602
+ this.vocab = [];
603
+ this.vectors = {};
604
+ this.contextVector = null;
605
+ this.dimension = 20;
606
+ }
607
+
608
+ train(tokens) {
609
+ const unique = [...new Set(tokens.filter(t => /[\w]+/.test(t)))];
610
+ this.vocab = unique;
611
+
612
+ unique.forEach(w => {
613
+ this.vectors[w] = Array.from({length: this.dimension}, () => Math.random() - 0.5);
614
+ });
615
+
616
+ for(let epoch=0; epoch<2; epoch++) {
617
+ for(let i=0; i<tokens.length; i++) {
618
+ const target = tokens[i];
619
+ if(!this.vectors[target]) continue;
620
+
621
+ for(let j=Math.max(0, i-2); j<=Math.min(tokens.length-1, i+2); j++) {
622
+ if(i===j) continue;
623
+ const context = tokens[j];
624
+ if(!this.vectors[context]) continue;
625
+
626
+ for(let d=0; d<this.dimension; d++) {
627
+ const diff = this.vectors[context][d] - this.vectors[target][d];
628
+ this.vectors[target][d] += diff * 0.05;
629
+ }
630
+ }
631
+ }
632
+ }
633
+ this.resetContext();
634
+ }
635
+
636
+ resetContext() {
637
+ this.contextVector = Array(this.dimension).fill(0);
638
+ }
639
+
640
+ updateContext(text) {
641
+ const words = text.match(/[\w]+/g) || [];
642
+ words.forEach(w => {
643
+ const vec = this.vectors[w];
644
+ if(vec) {
645
+ for(let d=0; d<this.dimension; d++) {
646
+ this.contextVector[d] = (this.contextVector[d] * 0.95) + (vec[d] * 0.05);
647
+ }
648
+ }
649
+ });
650
+ }
651
+
652
+ getRelevance(word) {
653
+ const vec = this.vectors[word];
654
+ if(!vec) return 0;
655
+
656
+ let dot = 0;
657
+ let magA = 0;
658
+ let magB = 0;
659
+ for(let d=0; d<this.dimension; d++) {
660
+ dot += vec[d] * this.contextVector[d];
661
+ magA += vec[d] * vec[d];
662
+ magB += this.contextVector[d] * this.contextVector[d];
663
+ }
664
+ if(magA === 0 || magB === 0) return 0;
665
+ return dot / (Math.sqrt(magA) * Math.sqrt(magB));
666
+ }
667
+ }
668
+
669
+ // --- PLAN Z: SPECTRAL GUIDE (KRYLOV ENGINE) ---
670
+ class SpectralGuide {
671
+ constructor() {
672
+ this.adjacency = {}; // Graph of Word -> {Neighbor -> Weight}
673
+ this.globalCentrality = {}; // Pre-calculated PageRank for global importance
674
+ this.dampingFactor = 0.85;
675
+ this.iterations = 10;
676
+ this.vocabSize = 0;
677
+ }
678
+
679
+ train(tokens) {
680
+ // 1. Build Adjacency Graph
681
+ this.adjacency = {};
682
+ let unique = new Set();
683
+
684
+ for(let i=0; i<tokens.length-1; i++) {
685
+ const u = tokens[i];
686
+ const v = tokens[i+1];
687
+ if(!u.match(/[\w]+/) || !v.match(/[\w]+/)) continue;
688
+
689
+ unique.add(u);
690
+ unique.add(v);
691
+
692
+ if(!this.adjacency[u]) this.adjacency[u] = {};
693
+ if(!this.adjacency[u][v]) this.adjacency[u][v] = 0;
694
+ this.adjacency[u][v]++;
695
+ }
696
+ this.vocabSize = unique.size;
697
+
698
+ // 2. Pre-calculate Global Centrality (Static Eigenvector)
699
+ this.globalCentrality = this.powerIteration(Array.from(unique));
700
+ }
701
+
702
+ // The Mathematical Core of Plan Z
703
+ powerIteration(nodeList, biasMap = null) {
704
+ let scores = {};
705
+ const n = nodeList.length;
706
+
707
+ // Init scores
708
+ nodeList.forEach(w => scores[w] = 1.0 / n);
709
+
710
+ // Iteration
711
+ for(let iter=0; iter<this.iterations; iter++) {
712
+ let nextScores = {};
713
+ nodeList.forEach(w => nextScores[w] = 0);
714
+
715
+ let danglingSink = 0;
716
+
717
+ nodeList.forEach(u => {
718
+ if(!this.adjacency[u]) {
719
+ danglingSink += scores[u];
720
+ return;
721
+ }
722
+ const neighbors = Object.keys(this.adjacency[u]);
723
+ if(neighbors.length === 0) {
724
+ danglingSink += scores[u];
725
+ return;
726
+ }
727
+
728
+ // Sum weights
729
+ let totalWeight = 0;
730
+ neighbors.forEach(v => totalWeight += this.adjacency[u][v]);
731
+
732
+ // Distribute score to neighbors
733
+ neighbors.forEach(v => {
734
+ if(nextScores[v] !== undefined) {
735
+ nextScores[v] += scores[u] * (this.adjacency[u][v] / totalWeight);
736
+ }
737
+ });
738
+ });
739
+
740
+ // Apply Damping and Bias (Teleportation)
741
+ nodeList.forEach(w => {
742
+ const bias = biasMap ? (biasMap[w] || 0) : (1.0/n);
743
+ nextScores[w] = (this.dampingFactor * nextScores[w]) +
744
+ (this.dampingFactor * danglingSink / n) +
745
+ ((1.0 - this.dampingFactor) * bias);
746
+ });
747
+
748
+ scores = nextScores;
749
+ }
750
+
751
+ // Normalize
752
+ let max = 0;
753
+ for(let w in scores) if(scores[w] > max) max = scores[w];
754
+ if(max > 0) for(let w in scores) scores[w] /= max;
755
+
756
+ return scores;
757
+ }
758
+
759
+ // Called dynamically during generation
760
+ solveLocalEigenstate(contextWords) {
761
+ let subspace = new Set(contextWords);
762
+ contextWords.forEach(w => {
763
+ if(this.adjacency[w]) {
764
+ Object.keys(this.adjacency[w]).forEach(n => subspace.add(n));
765
+ }
766
+ });
767
+
768
+ const nodeList = Array.from(subspace);
769
+ if(nodeList.length < 5) return {};
770
+
771
+ let biasMap = {};
772
+ nodeList.forEach(w => {
773
+ biasMap[w] = contextWords.includes(w) ? 10.0 : 1.0;
774
+ });
775
+
776
+ return this.powerIteration(nodeList, biasMap);
777
+ }
778
+ }
779
+
780
+ // --- NEW COMPONENT: CAUSAL REASONER (Active Inference) ---
781
+ // This class simulates the future. It asks: "If I say X, does the User State move closer to my Goal?"
782
+ class CausalReasoner {
783
+ constructor() {
784
+ // The Goal: We want the user to be Engaged (1.0) and Positive (1.0)
785
+ // You can tweak this to change the bot's "Desire"
786
+ this.targetState = { engagement: 1.0, positivity: 0.8 };
787
+
788
+ // The "Physics" of Conversation (Simplified Causal Matrix)
789
+ // These weights define how features of text change the user's state.
790
+ this.causalWeights = {
791
+ question: { eng: 0.3, pos: 0.0 }, // Questions provoke thought
792
+ length: { eng: 0.01, pos: -0.01 }, // Too long = boring?
793
+ positive: { eng: 0.1, pos: 0.2 }, // Good words = good mood
794
+ negative: { eng: 0.1, pos: -0.3 }, // Bad words = bad mood
795
+ repetition:{ eng: -0.5, pos: -0.2 }, // Repeating is bad
796
+ newtopic: { eng: 0.2, pos: 0.0 }
797
+ };
798
+ }
799
+
800
+ // 1. Analyze a Candidate Response (The "Imagination" Step)
801
+ analyzeCandidate(text, prevText) {
802
+ let score = { eng: 0, pos: 0 };
803
+ const lower = text.toLowerCase();
804
+
805
+ // Feature Extraction
806
+ const isQuestion = text.includes('?');
807
+ const wordCount = text.split(' ').length;
808
+ const isPositive = /love|good|yes|great|cool|thanks|happy|sweet|kind/.test(lower);
809
+ const isNegative = /no|bad|hate|stop|sad|error|ugly|dumb|stuck/.test(lower);
810
+ const isRepeat = prevText && text === prevText;
811
+ const isSelfRef = /i|me|my|mine/.test(lower);
812
+
813
+ // Apply Causal Weights (Matrix Math simplified)
814
+ if(isQuestion) { score.eng += this.causalWeights.question.eng; }
815
+ score.eng += (wordCount * this.causalWeights.length.eng);
816
+
817
+ if(isPositive) {
818
+ score.eng += this.causalWeights.positive.eng;
819
+ score.pos += this.causalWeights.positive.pos;
820
+ }
821
+ if(isNegative) {
822
+ score.eng += this.causalWeights.negative.eng;
823
+ score.pos += this.causalWeights.negative.pos;
824
+ }
825
+ if(isRepeat) {
826
+ score.eng += this.causalWeights.repetition.eng;
827
+ score.pos += this.causalWeights.repetition.pos;
828
+ }
829
+ if(isSelfRef) {
830
+ score.eng += 0.05; // Talking about self is slightly engaging
831
+ }
832
+
833
+ return score;
834
+ }
835
+
836
+ // 2. Select the Best Future (The "Decision" Step)
837
+ pickBest(candidates, prevResponse) {
838
+ if(!candidates || candidates.length === 0) return null;
839
+
840
+ let bestCandidate = candidates[0];
841
+ let bestDistance = Infinity; // Lower is better (closer to goal)
842
+
843
+ candidates.forEach(cand => {
844
+ // Predict the outcome of this text
845
+ const predictedShift = this.analyzeCandidate(cand.text, prevResponse);
846
+
847
+ // Calculate Euclidean Distance to Goal (TargetState)
848
+ // Distance = sqrt( (GoalEng - PredEng)^2 + (GoalPos - PredPos)^2 )
849
+ const distEng = this.targetState.engagement - predictedShift.eng;
850
+ const distPos = this.targetState.positivity - predictedShift.pos;
851
+ const totalDistance = Math.sqrt((distEng * distEng) + (distPos * distPos));
852
+
853
+ // Add a "Complexity Penalty" to prevent the bot from cheating with empty strings
854
+ const lenPenalty = cand.text.length < 5 ? 10 : 0;
855
+
856
+ // Add a "Garbage Penalty" for very repetitive words in the string itself
857
+ const words = cand.text.split(' ');
858
+ const unique = new Set(words).size;
859
+ const repRatio = unique / words.length;
860
+ const repPenalty = repRatio < 0.5 ? 5 : 0;
861
+
862
+ const finalScore = totalDistance + lenPenalty + repPenalty;
863
+
864
+ if(finalScore < bestDistance) {
865
+ bestDistance = finalScore;
866
+ bestCandidate = cand;
867
+ }
868
+ });
869
+
870
+ return { winner: bestCandidate, score: bestDistance };
871
+ }
872
+ }
873
+
874
+
875
+ // --- COMPONENT 6: MAIN ORCHESTRATOR ---
876
+ class UltimateEngine {
877
+ constructor() {
878
+ this.wordChain = {};
879
+ this.hierarchy = new HierarchicalNet();
880
+ this.rag = new VectorMemory();
881
+ this.reasoner = new ReasoningEngine();
882
+ this.dynamicLearner = new DynamicLearner();
883
+ this.morphology = new MorphologySynthesis();
884
+ this.vectors = new SemanticVectorSpace();
885
+ this.spectral = new SpectralGuide(); // PLAN Z
886
+ this.causal = new CausalReasoner(); // CAUSAL REASONER
887
+ this.math = new SymbolicMath(); // MATH ADDITION
888
+
889
+ this.order = 3;
890
+ this.ready = false;
891
+ this.stats = { turns: 0 };
892
+ this.lastResponses = [];
893
+ }
894
+
895
+ preprocess(text) {
896
+ const rawParts = text.split(/\+\+\+\+\+/g);
897
+ let processedTokens = [];
898
+ let turn = 0;
899
+ let startIdx = (rawParts[0].trim() === "") ? 1 : 0;
900
+
901
+ for (let i = startIdx; i < rawParts.length; i++) {
902
+ let content = rawParts[i].trim();
903
+ if (!content) continue;
904
+
905
+ if(turn === 1 && i > 0) {
906
+ this.rag.addMemory(rawParts[i-1], content);
907
+ }
908
+
909
+ const tokens = this.tokenizeContent(content);
910
+ if (turn === 0) {
911
+ processedTokens.push(STRUCT.USER_DELIM);
912
+ processedTokens.push(...tokens);
913
+ turn = 1;
914
+ } else {
915
+ processedTokens.push(STRUCT.BOT_DELIM);
916
+ processedTokens.push(...tokens);
917
+ turn = 0;
918
+ }
919
+ }
920
+ processedTokens.push(STRUCT.USER_DELIM);
921
+ return processedTokens;
922
+ }
923
+
924
+ tokenizeContent(text) {
925
+ return text.match(/[\w]+|[^\s\w]|\n/g) || [];
926
+ }
927
+
928
+ train(text) {
929
+ this.wordChain = {};
930
+ this.hierarchy = new HierarchicalNet();
931
+ this.rag = new VectorMemory();
932
+ this.dynamicLearner = new DynamicLearner();
933
+ this.morphology = new MorphologySynthesis();
934
+ this.vectors = new SemanticVectorSpace();
935
+ this.spectral = new SpectralGuide();
936
+
937
+ const tokens = this.preprocess(text);
938
+
939
+ this.dynamicLearner.train(tokens);
940
+ this.morphology.train(text);
941
+ this.hierarchy.train(tokens);
942
+ this.vectors.train(tokens);
943
+ this.spectral.train(tokens); // Train Plan Z
944
+
945
+ for (let i = 0; i < tokens.length; i++) {
946
+ for (let n = 1; n <= this.order; n++) {
947
+ if (i + n >= tokens.length) break;
948
+ const context = tokens.slice(i, i + n).join("_");
949
+ const next = tokens[i + n];
950
+ if (!this.wordChain[context]) this.wordChain[context] = {};
951
+ if (!this.wordChain[context][next]) this.wordChain[context][next] = 0;
952
+ this.wordChain[context][next]++;
953
+ }
954
+ }
955
+
956
+ this.ready = true;
957
+ this.stats.turns = tokens.filter(t => t === STRUCT.BOT_DELIM).length;
958
+ this.stats.vocab = Object.keys(this.hierarchy.nextNeighborMap).length;
959
+ this.stats.clusters = Object.keys(this.hierarchy.reverseClusters).length;
960
+ return this.stats;
961
+ }
962
+
963
+ // --- UPDATED GENERATE FUNCTION WITH CAUSAL REASONING LOOP ---
964
+ generate(userContext, maxTokens = 100, temp = 0.6, ragWeight = 3.0, repPen = 1.2, retry = 0) {
965
+ if (!this.ready) return null;
966
+
967
+ // Step C: Update Topic Vector
968
+ this.vectors.updateContext(userContext);
969
+
970
+ const effectiveTemp = temp + (retry * 0.2);
971
+
972
+ // --- THE DEEP REASONING UPGRADE ---
973
+ // Instead of generating 1 response, we generate 3 parallel universes.
974
+ // This is "Monte Carlo Simulation" for text.
975
+
976
+ let candidates = [];
977
+ const universeCount = 3; // How many futures to simulate
978
+
979
+ // Generate parallel futures
980
+ for(let i=0; i<universeCount; i++) {
981
+ // We vary the 'temp' slightly for each universe to get diverse options
982
+ const simTemp = effectiveTemp + (i * 0.15);
983
+ const res = this.generateInternal(userContext, maxTokens, simTemp, ragWeight, repPen);
984
+ candidates.push(res);
985
+ }
986
+
987
+ // The Causal Engine judges the candidates
988
+ const decision = this.causal.pickBest(candidates, this.lastResponses[this.lastResponses.length-1] || "");
989
+
990
+ const bestResult = decision.winner;
991
+ const cleanText = bestResult.text.trim();
992
+
993
+ // Add a "Reasoning Tag" so you can see it worked
994
+ // We push this to the front of thoughts for visibility
995
+ bestResult.thoughts.unshift({ type: 'spec', val: `Causal Winner (Score: ${decision.score.toFixed(2)})`, info: "Active Inference" });
996
+
997
+ // Recursion check for exact duplicate
998
+ if(this.lastResponses.includes(cleanText) && retry < 3) {
999
+ return this.generate(userContext, maxTokens, temp, ragWeight, repPen, retry + 1);
1000
+ }
1001
+
1002
+ // Standard post-processing
1003
+ this.vectors.updateContext(cleanText);
1004
+ this.lastResponses.push(cleanText);
1005
+ if(this.lastResponses.length > 5) this.lastResponses.shift();
1006
+
1007
+ return bestResult;
1008
+ }
1009
+
1010
+ generateInternal(userContext, maxTokens, temp, ragWeight, repPen) {
1011
+ let output = [];
1012
+ let thoughtLog = [];
1013
+ let recentTokens = [];
1014
+ const vecWeight = parseFloat(document.getElementById('vecWeight').value) || 0;
1015
+ const specWeight = parseFloat(document.getElementById('specWeight').value) || 0;
1016
+
1017
+ const userTokens = this.tokenizeContent(userContext);
1018
+
1019
+ // A. Reasoning
1020
+ const reasoning = this.reasoner.assess(userContext);
1021
+ thoughtLog.push({ type: 'mood', val: `Mood: ${reasoning.state}` });
1022
+
1023
+ // B. RAG
1024
+ const ragResult = this.rag.queryFull(userContext);
1025
+ const ragMap = ragResult.scores;
1026
+ if(ragResult.bestMatch) {
1027
+ thoughtLog.push({ type: 'rag', val: `Lock: ${ragResult.bestMatch.slice(0,3).join(" ")}...` });
1028
+ }
1029
+
1030
+ // C. INFERENCE
1031
+ let inferenceMap = {};
1032
+ for(let i=0; i<userTokens.length; i++) {
1033
+ const token = userTokens[i];
1034
+ if(!this.hierarchy.nextNeighborMap[token] && i > 0 && i < userTokens.length-1) {
1035
+ const inferred = this.dynamicLearner.inferProxy(userTokens[i-1], userTokens[i+1]);
1036
+ if(inferred) {
1037
+ inferenceMap[token] = inferred.proxy;
1038
+ thoughtLog.push({ type: 'infer', val: `${token} ≈ ${inferred.proxy}`, info: 'Distributional' });
1039
+ }
1040
+ }
1041
+ }
1042
+
1043
+ // D. MATH CHECK (Symbolic Logic)
1044
+ const mathSolutions = this.math.scan(userContext);
1045
+ let mathOverride = null;
1046
+ if (mathSolutions) {
1047
+ mathSolutions.forEach(sol => {
1048
+ thoughtLog.push({ type: 'math', val: `${sol.expr} = ${sol.answer}`, info: 'Symbolic Math' });
1049
+ // We strongly bias the bot to say the answer immediately
1050
+ mathOverride = `${sol.answer}`;
1051
+ });
1052
+ }
1053
+
1054
+ // PLAN Z: CALCULATE EIGEN-TRAJECTORY
1055
+ const eigenScores = this.spectral.solveLocalEigenstate(userTokens.filter(t => /[\w]+/.test(t)));
1056
+ if(specWeight > 0 && Object.keys(eigenScores).length > 0) {
1057
+ thoughtLog.push({ type: 'spec', val: "Eigen-Trajectory Active", info: "Krylov" });
1058
+ }
1059
+
1060
+ let currentContext = [];
1061
+ if (ragResult.bestMatch && Math.random() > 0.2) {
1062
+ currentContext = [STRUCT.USER_DELIM, ...ragResult.bestMatch.slice(0, this.order - 1)];
1063
+ output = [...ragResult.bestMatch.slice(0, Math.min(3, ragResult.bestMatch.length))];
1064
+ output.forEach(t => thoughtLog.push({type: 'mem', val: t, info: 'Associative Recall'}));
1065
+ } else {
1066
+ const safeUserTokens = userTokens.map(t => inferenceMap[t] || t);
1067
+ let seedTokens = [STRUCT.USER_DELIM, ...safeUserTokens, STRUCT.BOT_DELIM];
1068
+ currentContext = seedTokens.slice(-this.order);
1069
+ }
1070
+
1071
+ for (let i = 0; i < maxTokens; i++) {
1072
+ let nextToken = null;
1073
+ let method = "";
1074
+ let specialTag = "word";
1075
+
1076
+ // --- MATH INTERVENTION ---
1077
+ if (i === 0 && mathOverride) {
1078
+ nextToken = mathOverride;
1079
+ specialTag = "math";
1080
+ method = "Symbolic Logic";
1081
+ mathOverride = null; // Only say it once
1082
+ } else {
1083
+ // NORMAL MARKOV GENERATION
1084
+ for (let n = Math.min(this.order, currentContext.length); n >= 1; n--) {
1085
+ const ctxKey = currentContext.slice(currentContext.length - n).join("_");
1086
+ if (this.wordChain[ctxKey]) {
1087
+ const candidates = this.wordChain[ctxKey];
1088
+ // Pass specWeight and eigenScores to Nucleus Sampler
1089
+ nextToken = this.nucleusSample(candidates, ragMap, reasoning.biasWords, temp, ragWeight, recentTokens, repPen, vecWeight, specWeight, eigenScores);
1090
+
1091
+ const synonym = this.hierarchy.getSynonym(nextToken);
1092
+ if(synonym && synonym !== nextToken && synonym.length > 3 && Math.random() < 0.1) {
1093
+ thoughtLog.push({ type: 'blend', val: `${nextToken}->${synonym}`, info: "Blend" });
1094
+ nextToken = synonym;
1095
+ specialTag = "blend";
1096
+ }
1097
+
1098
+ // Determine Tag
1099
+ if (ragMap[nextToken] && specialTag !== 'blend') specialTag = 'rag';
1100
+ else if (reasoning.biasWords.includes(nextToken.toLowerCase()) && specialTag !== 'blend') specialTag = 'mood';
1101
+ else if (vecWeight > 0 && this.vectors.getRelevance(nextToken) > 0.3 && specialTag !== 'blend') specialTag = 'vec';
1102
+ else if (specWeight > 0 && eigenScores[nextToken] > 0.1 && specialTag !== 'blend') specialTag = 'spec';
1103
+
1104
+ method = `N${n}`;
1105
+ break;
1106
+ }
1107
+ }
1108
+ }
1109
+
1110
+ if (!nextToken) {
1111
+ const lastWord = currentContext[currentContext.length-1];
1112
+ const seed = lastWord ? lastWord[lastWord.length-1] : null;
1113
+ const newWord = this.morphology.generate(seed);
1114
+ nextToken = newWord;
1115
+ specialTag = "morph";
1116
+ method = "Bayesian";
1117
+ if(!nextToken || nextToken.length < 1) nextToken = ".";
1118
+ }
1119
+
1120
+ if (nextToken === STRUCT.USER_DELIM) {
1121
+ thoughtLog.push({ type: 'struct', val: 'END_TURN' });
1122
+ break;
1123
+ }
1124
+ if (nextToken === STRUCT.BOT_DELIM) continue;
1125
+
1126
+ output.push(nextToken);
1127
+ currentContext.push(nextToken);
1128
+
1129
+ recentTokens.push(nextToken.toLowerCase());
1130
+ if(recentTokens.length > 15) recentTokens.shift();
1131
+
1132
+ if(specialTag !== 'blend' && !output.slice(0, -1).includes(nextToken)) {
1133
+ thoughtLog.push({ type: specialTag, val: nextToken, info: method });
1134
+ }
1135
+ }
1136
+
1137
+ return { text: this.detokenize(output), thoughts: thoughtLog, mood: reasoning.state };
1138
+ }
1139
+
1140
+ // NUCLEUS SAMPLING UPDATED WITH PLAN Z (SPECTRAL) BIAS
1141
+ nucleusSample(dist, ragMap, moodBias, temp, ragWeight, recentTokens, repPen, vecWeight, specWeight, eigenScores) {
1142
+ const items = Object.keys(dist);
1143
+ let candidates = [];
1144
+
1145
+ items.forEach(token => {
1146
+ let count = dist[token];
1147
+ if(recentTokens.includes(token.toLowerCase())) {
1148
+ count /= repPen;
1149
+ }
1150
+
1151
+ let score = Math.pow(count, 1/temp);
1152
+
1153
+ // RAG Boost
1154
+ if(ragMap[token]) score *= (1 + (ragMap[token] * 0.2 * ragWeight));
1155
+
1156
+ // Mood Boost
1157
+ if(moodBias.includes(token.toLowerCase())) score *= (1 + (ragWeight * 0.5));
1158
+
1159
+ // Vector Context Boost (Step C)
1160
+ if(vecWeight > 0) {
1161
+ const relevance = this.vectors.getRelevance(token);
1162
+ if(relevance > 0) score *= (1 + (relevance * vecWeight));
1163
+ }
1164
+
1165
+ // PLAN Z BOOST: EIGEN-CENTRALITY
1166
+ if(specWeight > 0 && eigenScores[token]) {
1167
+ score *= (1 + (eigenScores[token] * specWeight));
1168
+ }
1169
+
1170
+ candidates.push({ t: token, s: score });
1171
+ });
1172
+
1173
+ candidates.sort((a, b) => b.s - a.s);
1174
+ let totalScore = candidates.reduce((acc, c) => acc + c.s, 0);
1175
+
1176
+ let r = Math.random() * totalScore;
1177
+ let cumulative = 0;
1178
+
1179
+ for(let i=0; i<candidates.length; i++) {
1180
+ cumulative += candidates[i].s;
1181
+ if(r <= cumulative) return candidates[i].t;
1182
+ }
1183
+
1184
+ return candidates[0].t;
1185
+ }
1186
+
1187
+ detokenize(tokens) {
1188
+ let str = "";
1189
+ tokens.forEach(t => {
1190
+ if (/^[.,!?;:]$/.test(t)) str += t;
1191
+ else if (t === "\n") str += "\n";
1192
+ else str += " " + t;
1193
+ });
1194
+ return str.trim();
1195
+ }
1196
+
1197
+ save() {
1198
+ if (!this.ready) return;
1199
+ const data = JSON.stringify({
1200
+ wordChain: this.wordChain,
1201
+ clusters: this.hierarchy.clusters,
1202
+ reverseClusters: this.hierarchy.reverseClusters,
1203
+ ragVectors: this.rag.vectors,
1204
+ stats: this.stats,
1205
+ morphStarts: this.morphology.starts,
1206
+ morphTrans: this.morphology.charTransitions,
1207
+ contextMap: this.dynamicLearner.contextMap,
1208
+ vectors: this.vectors.vectors,
1209
+ topicVec: this.vectors.contextVector,
1210
+ adjGraph: this.spectral.adjacency,
1211
+ globalEigen: this.spectral.globalCentrality
1212
+ });
1213
+
1214
+ if (typeof dhc !== 'undefined') {
1215
+ dhc.dialogs.saveFile({
1216
+ title: 'Save Neuro-Spectral State',
1217
+ fileName: 'deepmarkov_v11_symbolic.json',
1218
+ fileTypes: 'JSON files|*.json',
1219
+ overwritePrompt: true
1220
+ }).then((filePath) => {
1221
+ if (filePath !== '') {
1222
+ dhc.files.writeTextFile({
1223
+ filePath: filePath,
1224
+ contents: data
1225
+ }).then(() => {
1226
+ alert('Neuro-Spectral State saved to disk successfully!');
1227
+ }, (error) => {
1228
+ alert('Save Error: ' + error);
1229
+ });
1230
+ }
1231
+ });
1232
+ } else {
1233
+ const blob = new Blob([data], {type: 'application/json'});
1234
+ const a = document.createElement('a');
1235
+ a.href = URL.createObjectURL(blob);
1236
+ a.download = `deepmarkov_v11_symbolic.json`;
1237
+ a.click();
1238
+ }
1239
+ }
1240
+
1241
+ load(json) {
1242
+ const data = JSON.parse(json);
1243
+ this.wordChain = data.wordChain;
1244
+ this.hierarchy.clusters = data.clusters;
1245
+ this.hierarchy.reverseClusters = data.reverseClusters;
1246
+ this.rag.vectors = data.ragVectors;
1247
+ this.rag.docCount = data.ragVectors.length;
1248
+ this.stats = data.stats;
1249
+ this.morphology.starts = data.morphStarts;
1250
+ this.morphology.charTransitions = data.morphTrans;
1251
+ this.dynamicLearner.contextMap = data.contextMap;
1252
+
1253
+ if(data.vectors) this.vectors.vectors = data.vectors;
1254
+ if(data.topicVec) this.vectors.contextVector = data.topicVec;
1255
+
1256
+ // Load Plan Z
1257
+ if(data.adjGraph) this.spectral.adjacency = data.adjGraph;
1258
+ if(data.globalEigen) this.spectral.globalCentrality = data.globalEigen;
1259
+ if(data.adjGraph) this.spectral.vocabSize = Object.keys(data.adjGraph).length;
1260
+
1261
+ this.ready = true;
1262
+ return this.stats;
1263
+ }
1264
+ }
1265
+
1266
+ /* UI CONTROLLER */
1267
+ const engine = new UltimateEngine();
1268
+ const ui = {
1269
+ chat: document.getElementById('chat'),
1270
+ input: document.getElementById('userInput'),
1271
+ status: document.getElementById('trainStatus'),
1272
+ fileLabel: document.getElementById('fileLabel'),
1273
+ stats: document.getElementById('stats'),
1274
+ name: document.getElementById('botName'),
1275
+ specBar: document.getElementById('specBar')
1276
+ };
1277
+
1278
+ // Training
1279
+ document.getElementById('trainFile').addEventListener('change', (e) => {
1280
+ const file = e.target.files[0];
1281
+ if (!file) return;
1282
+ ui.fileLabel.innerText = "Architecting Causal Mind...";
1283
+ const reader = new FileReader();
1284
+ reader.onload = (ev) => {
1285
+ setTimeout(() => {
1286
+ const res = engine.train(ev.target.result);
1287
+ ui.fileLabel.innerText = file.name;
1288
+ ui.status.innerText = "Causal Core Active";
1289
+ ui.status.style.color = "var(--user-color)";
1290
+ updateStats(res);
1291
+ addMsg("System", `Architecture Complete.<br>Concepts: ${res.clusters}<br>Vectors: ${Object.keys(engine.vectors.vectors).length}<br>Eigen-Nodes: ${engine.spectral.vocabSize}<br>Modules: Causal + Symbolic`);
1292
+ }, 50);
1293
+ };
1294
+ reader.readAsText(file);
1295
+ });
1296
+
1297
+ // Load
1298
+ document.getElementById('loadJson').addEventListener('change', (e) => {
1299
+ const file = e.target.files[0];
1300
+ const reader = new FileReader();
1301
+ reader.onload = (ev) => {
1302
+ const res = engine.load(ev.target.result);
1303
+ ui.status.innerText = "State Restored";
1304
+ updateStats(res);
1305
+ addMsg("System", "Neuro-Spectral State restored successfully.");
1306
+ };
1307
+ reader.readAsText(file);
1308
+ });
1309
+
1310
+ function updateStats(s) {
1311
+ ui.stats.innerHTML = `
1312
+ <div>Vocab: ${s.vocab}</div>
1313
+ <div>Concepts: ${s.clusters}</div>
1314
+ <div id="moodDisplay">Mood: Neutral</div>
1315
+ <div>Eigen: ${engine.spectral.vocabSize || 0}</div>
1316
+ `;
1317
+ }
1318
+
1319
+ function sendMessage() {
1320
+ const txt = ui.input.value.trim();
1321
+ if (!txt) return;
1322
+ if (!engine.ready) return alert("Upload a text file first!");
1323
+
1324
+ addMsg("User", txt);
1325
+ ui.input.value = '';
1326
+
1327
+ // Visualize Spectral Activation
1328
+ ui.specBar.style.width = "100%";
1329
+ ui.specBar.style.background = "var(--causal-color)";
1330
+
1331
+ setTimeout(() => {
1332
+ const temp = parseFloat(document.getElementById('temp').value);
1333
+ const ragW = parseFloat(document.getElementById('memWeight').value);
1334
+ const repPen = parseFloat(document.getElementById('repPen').value);
1335
+
1336
+ const result = engine.generate(txt, 150, temp, ragW, repPen);
1337
+
1338
+ // Reset Visualizer
1339
+ ui.specBar.style.width = "0%";
1340
+
1341
+ if (result) {
1342
+ document.getElementById('moodDisplay').innerText = `Mood: ${result.mood}`;
1343
+ addMsg(ui.name.value, result.text, result.thoughts);
1344
+ }
1345
+ }, 100);
1346
+ }
1347
+
1348
+ function addMsg(name, text, thoughts = null) {
1349
+ const isUser = name === 'User';
1350
+ const div = document.createElement('div');
1351
+ div.className = `msg ${isUser ? 'user' : 'bot'}`;
1352
+
1353
+ let thoughtsHtml = '';
1354
+ if (thoughts) {
1355
+ thoughtsHtml = `<div class="thought-process">`;
1356
+ thoughts.forEach(t => {
1357
+ let className = "word";
1358
+ let title = "";
1359
+ switch(t.type) {
1360
+ case 'struct': className = 'struct'; title='Structure'; break;
1361
+ case 'rag': className = 'rag'; title='Vector Memory'; break;
1362
+ case 'blend': className = 'blend'; title='Concept Blend'; break;
1363
+ case 'mood': className = 'mood'; break;
1364
+ case 'infer': className = 'infer'; title='Distributional Inference'; break;
1365
+ case 'morph': className = 'morph'; title='Bayesian Gen'; break;
1366
+ case 'mem': className = 'mem'; title='Associative Recall'; break;
1367
+ case 'vec': className = 'vec'; title='Semantic Vector Context'; break;
1368
+ case 'spec': className = 'spec'; title='Spectral/Causal'; break;
1369
+ case 'math': className = 'math'; title='Symbolic Logic'; break; /* MATH TAG */
1370
+ }
1371
+
1372
+ if(t.type === 'mood') thoughtsHtml += `<span class="tag mood" style="width:100%; display:block; margin-bottom:2px;">[${t.val}]</span>`;
1373
+ else thoughtsHtml += `<span class="tag ${className}" title="${title}">${t.val}</span>`;
1374
+ });
1375
+ thoughtsHtml += `</div>`;
1376
+ }
1377
+
1378
+ div.innerHTML = `
1379
+ <div class="meta">${name}</div>
1380
+ <div class="bubble">${text.replace(/\n/g, '<br>')}</div>
1381
+ ${thoughtsHtml}
1382
+ `;
1383
+ ui.chat.appendChild(div);
1384
+ ui.chat.scrollTop = ui.chat.scrollHeight;
1385
+ }
1386
+ </script>
1387
+ </body>
1388
+ </html>