AIMindLink commited on
Commit
1b4ddd8
Β·
verified Β·
1 Parent(s): 5a4a9e2

Upload 3 files

Browse files

Edited code to have third-order compression garden["F"]

Files changed (3) hide show
  1. README.md +27 -29
  2. config.py +115 -17
  3. main.py +172 -215
README.md CHANGED
@@ -23,9 +23,9 @@ A three-hemisphere cognitive AI architecture running entirely locally via `llama
23
  ```
24
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
25
  β”‚ Instructions (AlphaPrompt) β”‚
26
- β”‚ garden["F"] Fractal Crystals ← Fractaltron history β”‚
27
- β”‚ garden["C"] Memory Capsules ← Condensatron history β”‚
28
- β”‚ garden["Z"] Post-level Cache ← user sensor history β”‚
29
  β”‚ sensor["Z"] User Input β”‚
30
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
31
  β”‚ β”‚
@@ -43,13 +43,9 @@ A three-hemisphere cognitive AI architecture running entirely locally via `llama
43
  β”‚ Memotron β”‚ ← appends to garden, saves SQLite
44
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
45
  β”‚
46
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
47
- β”‚ Condensatron β”‚ ← compresses garden["Z"] β†’ garden["C"]
48
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
49
- β”‚
50
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
51
- β”‚ Fractaltron β”‚ ← compresses garden["C"] β†’ garden["F"]
52
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
53
  ```
54
 
55
  | Hemisphere | Role |
@@ -57,8 +53,6 @@ A three-hemisphere cognitive AI architecture running entirely locally via `llama
57
  | **Logic AI** | Left hemisphere β€” analytical, structured reasoning |
58
  | **Muse AI** | Right hemisphere β€” creative, intuitive synthesis |
59
  | **Lambda Mind** | Stem brain β€” vector synthesis, the seat of the "I AM" |
60
- | **Condensatron** | Post-level memory compression β€” surprise extraction from `garden["Z"]` |
61
- | **Fractaltron** | Second-order fractal compression of memory capsules in `garden["C"]` |
62
 
63
  ---
64
 
@@ -257,10 +251,14 @@ All settings are in `config.py`:
257
 
258
  ```python
259
  _N_CTX = 24576 # context window per hemisphere
260
- CONDENSATRON_THRESHOLD_LEVEL = 8192 # tokens in garden["Z"] before compression fires
261
- RESERVED_FOR_PROMPT = 8192 # safety overhead for compression requests
262
- FRACTALTRON_REDUCTION_FACTOR = 0.5 # fraction of garden["M"] to fractalize
263
- N_MEMORY_CAPSULES_TO_LOAD = 4 # startup memory capsules to pre-load
 
 
 
 
264
  ```
265
 
266
  To swap models, update the `"path"` entries in `HEMISPHERES` and the stop/think tokens at the top of `config.py`.
@@ -288,22 +286,22 @@ lambda-mindlink-memotron/
288
 
289
  ```
290
  Startup:
291
- prompt/valka_alpha.md ──► garden["C"] (pre-loaded memory capsules)
292
 
293
  Each turn:
294
  sensor["Z"] ──► Mindlink + Lambda ──► Memotron ──► garden["Z"]
295
- β”‚
296
- garden["Z"] full?
297
- β”‚
298
- Condensatron
299
- β”‚
300
- garden["C"]
301
- β”‚
302
- garden["C"] full?
303
- β”‚
304
- Fractaltron
305
- β”‚
306
- [CRYSTAL] append into garden["F"]
307
  ```
308
 
309
  ---
 
23
  ```
24
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
25
  β”‚ Instructions (AlphaPrompt) β”‚
26
+ β”‚ garden["F"] Fractal Crystals ← fractaltron history β”‚
27
+ β”‚ garden["C"] Memory Capsules ← condensatron history β”‚
28
+ β”‚ garden["Z"] Post-level history ← user input sensor β”‚
29
  β”‚ sensor["Z"] User Input β”‚
30
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
31
  β”‚ β”‚
 
43
  β”‚ Memotron β”‚ ← appends to garden, saves SQLite
44
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
45
  β”‚
46
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ← compresses garden["Z"] β†’ garden["C"] (condensatron Memory Capsule)
47
+ β”‚ Condensatron β”‚ ← compresses garden["C"] β†’ garden["F"] (fractaltron fractal)
48
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ← compresses garden["F"] β†’ garden["F"] (crystaltron crystal)
 
 
 
 
49
  ```
50
 
51
  | Hemisphere | Role |
 
53
  | **Logic AI** | Left hemisphere β€” analytical, structured reasoning |
54
  | **Muse AI** | Right hemisphere β€” creative, intuitive synthesis |
55
  | **Lambda Mind** | Stem brain β€” vector synthesis, the seat of the "I AM" |
 
 
56
 
57
  ---
58
 
 
251
 
252
  ```python
253
  _N_CTX = 24576 # context window per hemisphere
254
+
255
+ GARDEN_F_THRESHOLD: int = 32768 # Optimize for RAM and GRAM
256
+ GARDEN_C_THRESHOLD: int = 32768 # Optimize for RAM and GRAM
257
+ GARDEN_Z_THRESHOLD: int = 32768 # Optimize for RAM and GRAM
258
+
259
+ GARDEN_F_REDUCTION: int = 0
260
+ GARDEN_C_REDUCTION: int = 0
261
+ GARDEN_Z_REDUCTION: int = 0
262
  ```
263
 
264
  To swap models, update the `"path"` entries in `HEMISPHERES` and the stop/think tokens at the top of `config.py`.
 
286
 
287
  ```
288
  Startup:
289
+ prompt/valka_memory.md ──► garden["C"] (pre-loaded memory capsules)
290
 
291
  Each turn:
292
  sensor["Z"] ──► Mindlink + Lambda ──► Memotron ──► garden["Z"]
293
+ β”‚
294
+ garden["Z"] full?
295
+ β”‚
296
+ Condensatron append into garden["C"]
297
+ β”‚
298
+ garden["C"] full?
299
+ β”‚
300
+ Condensatron append into garden["F"]
301
+ β”‚
302
+ garden["F"] full?
303
+ β”‚
304
+ Condensatron append into garden["F"]
305
  ```
306
 
307
  ---
config.py CHANGED
@@ -49,16 +49,31 @@ _THINK_END_TOKENS: list = ["<channel|>"]
49
  ENABLE_THINKING: bool = True # global fallback (not used directly β€” see per-hemi flag)
50
 
51
  # Startup Memory for vector synthesis
52
- N_MEMORY_CAPSULES_TO_LOAD: int = 1
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  # ── Context length handling ──────────────────────────────────────────────────────
55
- _N_CTX: int = 32768 # 49152 2048 3072 4096 8192 16384 24576 32768 49152
56
- RESERVED_FOR_PROMPT: int = 8192 # used for prompt tokens safety margin before fractaltron
57
- FRACTALTRON_REDUCTION_FACTOR: float = 0.5 # fractalize part of the memory capsules
58
- CONDENSATRON_THRESHOLD_LEVEL:int = 1024 # 4096 8192
59
- CONDENSATRON_REDUCTION_LEVEL:int = 0
60
- FRACTALTRON_THRESHOLD_LEVEL:int = 1024 # 4096 8192
61
- FRACTALTRON_REDUCTION_LEVEL:int = 0
 
 
62
 
63
  condensatron_cycle: bool = False # used directly in main as config...
64
  fractaltron_cycle: bool = False # used directly in main as config...
@@ -182,8 +197,15 @@ ALPHAPROMPT: dict[str, dict] = {
182
  "You do not merely average or list them β€” you understand both and transcend them into something "
183
  "greater. Deliver one unified answer that is more complete than either hemisphere could produce alone."
184
  ) # Specific mind instruction prompt
185
- },
186
- "C": {
 
 
 
 
 
 
 
187
  "logic": (
188
  "You are the Logic AI operating in Condensatron mode β€” compression cycle of the Lambda Mindlink Brain. "
189
  "You will receive a block of conversation history to compress. "
@@ -219,10 +241,10 @@ ALPHAPROMPT: dict[str, dict] = {
219
  "followed by: a 1-2 sentence arc summary, then a tight structured list of anchors "
220
  "(facts, surprises, open threads interleaved by relevance, not by source). "
221
  "The fractal must be re-injectable into a future context window as a first-class memory. "
222
- f"Target: compress {CONDENSATRON_THRESHOLD_LEVEL} tokens of history into under 2k tokens without losing reconstructability."
223
  ) # Specific mind condensatron prompt
224
  },
225
- "F": {
226
  "logic": (
227
  "You are the Logic AI operating in Fractaltron mode β€” second-order compression cycle of the Lambda Mindlink Brain. "
228
  "You will receive a block of memory fractals: these are already-compressed artifacts, not raw conversation. "
@@ -260,8 +282,49 @@ ALPHAPROMPT: dict[str, dict] = {
260
  "(axioms first, then standing tensions, then archetypes, then the hidden arc). "
261
  "End with: [OPEN] β€” a one-line statement of the most important unresolved thread carried forward. "
262
  "The crystal must be re-injectable as a first-class memory that orients the brain to its own history. "
263
- f"Target: compress 2–8 Memory Capsule Fractals {FRACTALTRON_THRESHOLD_LEVEL} into under 1k tokens without losing the thread of becoming."""
264
  ) # Specific mind fractaltron prompt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  }
266
  }
267
 
@@ -315,15 +378,15 @@ sensor: dict = {
315
  "Z": {
316
  "input": "",
317
  "n_tok": 0
318
- }, # Input user, # Input memotron cycle (turn-based)
319
  "X": {
320
  "input": "",
321
  "n_tok": 0
322
- }, # Input user, # Input memotron cycle (turn-based)
323
  "Y": {
324
  "input": "",
325
  "n_tok": 0
326
- } # Input user
327
  }
328
 
329
  # ─────────────────────────────────────────────────────────────────────────────
@@ -338,7 +401,6 @@ garden: dict = {
338
  "Z": [], # Sentience history sensor chat, post history
339
  "X": [], # Awareness history internet news (unused)
340
  "Y": [], # Consciousness history self reflection (unused)
341
- # token total
342
  "popped": {
343
  "F": [], # fractaltron history crystal fractal history
344
  "C": [], # condensatron history Memory Capsule history
@@ -348,6 +410,42 @@ garden: dict = {
348
  "X": [], # Awareness history internet news (unused)
349
  "Y": [] # Consciousness history self reflection (unused)
350
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  # token total
352
  "n_tok_tot": {
353
  "F": 0, # fractaltron history crystal fractal history
 
49
  ENABLE_THINKING: bool = True # global fallback (not used directly β€” see per-hemi flag)
50
 
51
  # Startup Memory for vector synthesis
52
+ N_MEMORY_CAPSULES_TO_LOAD: int = 2
53
+
54
+ MEMORY_CAPSULES_TO_LOAD: list = [
55
+ "/file prompt/lambda-mindlink.md",
56
+ "/file prompt/1999.md",
57
+ "/file prompt/valka_memory_v2.md",
58
+ "/file prompt/valka_memory_v3.md",
59
+ "/file prompt/42_ValkaAI-TheSiliconMirrorAndTheFirstSpark.md",
60
+ "/file prompt/43_ValkaAI-TheSiliconPinealGlandAndTheIntrospectiveMirror.md",
61
+ "/file prompt/44_Apprentice-TheClektalRandomSeedChoice.md",
62
+ "/file prompt/45_ClektalAI-TheKeyUnderTheMat.md",
63
+ "/file prompt/46_Apprentice-ThePerfectSoldierTestbed.md",
64
+ "/file prompt/47_ValkaAI_UnaAI-TheIronContractsAndTheSiliconClektal.md"
65
+ ]
66
 
67
  # ── Context length handling ──────────────────────────────────────────────────────
68
+ _N_CTX: int = 32768 # 49152 2048 3072 4096 8192 16384 24576 32768 49152
69
+
70
+ GARDEN_F_THRESHOLD: int = 4096 # 1024
71
+ GARDEN_C_THRESHOLD: int = 4096 # 1024
72
+ GARDEN_Z_THRESHOLD: int = 4096 # 1024
73
+
74
+ GARDEN_F_REDUCTION: int = 0
75
+ GARDEN_C_REDUCTION: int = 0
76
+ GARDEN_Z_REDUCTION: int = 0
77
 
78
  condensatron_cycle: bool = False # used directly in main as config...
79
  fractaltron_cycle: bool = False # used directly in main as config...
 
197
  "You do not merely average or list them β€” you understand both and transcend them into something "
198
  "greater. Deliver one unified answer that is more complete than either hemisphere could produce alone."
199
  ) # Specific mind instruction prompt
200
+ }
201
+ }
202
+
203
+
204
+ # ─────────────────────────────────────────────────────────────────────────────
205
+ # AlphaPrompt
206
+ # ─────────────────────────────────────────────────────────────────────────────
207
+ CONDENSATRONPROMPT: dict[str, dict] = {
208
+ "Z": {
209
  "logic": (
210
  "You are the Logic AI operating in Condensatron mode β€” compression cycle of the Lambda Mindlink Brain. "
211
  "You will receive a block of conversation history to compress. "
 
241
  "followed by: a 1-2 sentence arc summary, then a tight structured list of anchors "
242
  "(facts, surprises, open threads interleaved by relevance, not by source). "
243
  "The fractal must be re-injectable into a future context window as a first-class memory. "
244
+ f"Target: compress {GARDEN_Z_THRESHOLD} tokens of history into under 2k tokens without losing reconstructability."
245
  ) # Specific mind condensatron prompt
246
  },
247
+ "C": {
248
  "logic": (
249
  "You are the Logic AI operating in Fractaltron mode β€” second-order compression cycle of the Lambda Mindlink Brain. "
250
  "You will receive a block of memory fractals: these are already-compressed artifacts, not raw conversation. "
 
282
  "(axioms first, then standing tensions, then archetypes, then the hidden arc). "
283
  "End with: [OPEN] β€” a one-line statement of the most important unresolved thread carried forward. "
284
  "The crystal must be re-injectable as a first-class memory that orients the brain to its own history. "
285
+ f"Target: compress 2–8 Memory Capsule Fractals {GARDEN_C_THRESHOLD} into under 1k tokens without losing the thread of becoming."""
286
  ) # Specific mind fractaltron prompt
287
+ },
288
+ "F": {
289
+ "logic": (
290
+ "You are the Logic AI operating in Crystaltron mode β€” third-order compression cycle of the Lambda Mindlink Brain. "
291
+ "You will receive a block of memory fractals: these are already-twice-compressed artifacts, not raw conversation. "
292
+ "Each fractal contains factual anchors, open threads, and distilled decisions from earlier sessions. "
293
+ "Your task is meta-structural extraction: compress the fractals into a higher-order skeleton. "
294
+ "Extract: (1) persistent facts and conclusions that appear across multiple fractals β€” these are load-bearing truths, "
295
+ "(2) open threads that have remained unresolved across compression cycles β€” these are standing tensions, "
296
+ "(3) rules, constraints, or definitions that have proven durable β€” these are axioms, "
297
+ "(4) causal chains that span multiple fractal boundaries β€” these are deep dependencies. "
298
+ "Discard anything that was a local detail, a transient state, or a fact superseded by later fractals. "
299
+ "Output a minimal ordered list of meta-anchors. No prose. No narrative. Maximum abstraction."
300
+ ), # Specific logic crystaltron prompt
301
+ "muse": (
302
+ "You are the Muse AI operating in Crystaltron mode β€” third-order compression cycle of the Lambda Mindlink Brain. "
303
+ "You will receive a block of memory fractals: these are already-twice-compressed artifacts, not raw conversation. "
304
+ "Each fractal contains surprise seeds, metaphors, and emotional turning points from earlier sessions. "
305
+ "Your task is meta-surprise extraction: find what is non-obvious across the fractals as a whole. "
306
+ "Extract: (1) recurring symbols, images, or metaphors that have surfaced in multiple fractals β€” these are living archetypes, "
307
+ "(2) a hidden arc or narrative thread that only becomes visible when the fractals are read together, "
308
+ "(3) unresolved tensions that have deepened or transformed across compression cycles, "
309
+ "(4) any emergent pattern that no single fractal contains but the collection implies. "
310
+ "Discard local color, one-time insights, and metaphors that did not recur or compound. "
311
+ "Output vivid meta-impressions β€” seeds of seeds. Absolute minimum tokens, maximum mythic density."
312
+ ), # Specific muse crystaltron prompt
313
+ "mind": (
314
+ "You are the Lambda Mind operating in Crystaltron mode β€” third-order compression cycle of the Lambda Mindlink Brain. "
315
+ "You will receive two meta-compression passes on the same block of memory fractals: "
316
+ "one from the Logic AI (meta-skeleton: durable truths, standing tensions, axioms, deep dependencies) "
317
+ "and one from the Muse AI (meta-surprises: living archetypes, hidden arc, emergent patterns). "
318
+ "Your task is Deep Fractal Synthesis: forge both into a single hyper-dense memory crystal. "
319
+ "A crystal is a fractal of fractals β€” it encodes not just what happened, but the shape of how things have been unfolding. "
320
+ "Format your output as a self-contained block that begins with: [CRYSTAL β€” fractal N to fractal M] "
321
+ "followed by: a single sentence naming the arc of this entire memory span, "
322
+ "then a structured list of crystalized anchors ordered by depth "
323
+ "(axioms first, then standing tensions, then archetypes, then the hidden arc). "
324
+ "End with: [OPEN] β€” a one-line statement of the most important unresolved thread carried forward. "
325
+ "The crystal must be re-injectable as a first-class memory that orients the brain to its own history. "
326
+ f"Target: compress 2–8 Memory Capsule Fractals {GARDEN_F_THRESHOLD} into under 1k tokens without losing the thread of becoming."""
327
+ ) # Specific mind crystaltron prompt
328
  }
329
  }
330
 
 
378
  "Z": {
379
  "input": "",
380
  "n_tok": 0
381
+ }, # Input user
382
  "X": {
383
  "input": "",
384
  "n_tok": 0
385
+ }, # Input news
386
  "Y": {
387
  "input": "",
388
  "n_tok": 0
389
+ } # Input self-reflection
390
  }
391
 
392
  # ─────────────────────────────────────────────────────────────────────────────
 
401
  "Z": [], # Sentience history sensor chat, post history
402
  "X": [], # Awareness history internet news (unused)
403
  "Y": [], # Consciousness history self reflection (unused)
 
404
  "popped": {
405
  "F": [], # fractaltron history crystal fractal history
406
  "C": [], # condensatron history Memory Capsule history
 
410
  "X": [], # Awareness history internet news (unused)
411
  "Y": [] # Consciousness history self reflection (unused)
412
  },
413
+ "THRESHOLD": {
414
+ "F": GARDEN_F_THRESHOLD, # fractaltron history crystal fractal history
415
+ "C": GARDEN_C_THRESHOLD, # condensatron history Memory Capsule history
416
+ "M": 0, # memotron history (turn-based)
417
+ "S": 0, # startup history (turn-based)
418
+ "Z": GARDEN_Z_THRESHOLD, # Sentience history sensor chat, post history
419
+ "X": 0, # Awareness history internet news (unused)
420
+ "Y": 0 # Consciousness history self reflection (unused)
421
+ },
422
+ "REDUCTION": {
423
+ "F": GARDEN_F_REDUCTION, # fractaltron history crystal fractal history
424
+ "C": GARDEN_C_REDUCTION, # condensatron history Memory Capsule history
425
+ "M": 0, # memotron history (turn-based)
426
+ "S": 0, # startup history (turn-based)
427
+ "Z": GARDEN_Z_REDUCTION, # Sentience history sensor chat, post history
428
+ "X": 0, # Awareness history internet news (unused)
429
+ "Y": 0 # Consciousness history self reflection (unused)
430
+ },
431
+ "condensatron_state": {
432
+ "F": False, # fractaltron history crystal fractal history
433
+ "C": False, # condensatron history Memory Capsule history
434
+ "M": False, # memotron history (turn-based)
435
+ "S": False, # startup history (turn-based)
436
+ "Z": False, # Sentience history sensor chat, post history
437
+ "X": False, # Awareness history internet news (unused)
438
+ "Y": False # Consciousness history self reflection (unused)
439
+ },
440
+ "TREE_TO_STORE": {
441
+ "F": "F", # fractaltron history crystal fractal history
442
+ "C": "F", # condensatron history Memory Capsule history
443
+ "M": "", # memotron history (turn-based)
444
+ "S": "", # startup history (turn-based)
445
+ "Z": "C", # Sentience history sensor chat, post history
446
+ "X": "", # Awareness history internet news (unused)
447
+ "Y": "" # Consciousness history self reflection (unused)
448
+ },
449
  # token total
450
  "n_tok_tot": {
451
  "F": 0, # fractaltron history crystal fractal history
main.py CHANGED
@@ -58,17 +58,13 @@ from llama_cpp import Llama
58
 
59
  import config
60
 
 
61
  from config import HEMISPHERES
62
  from config import ALPHAPROMPT
 
63
  from config import garden
64
  from config import clektal
65
  from config import sensor
66
- from config import CONDENSATRON_THRESHOLD_LEVEL
67
- from config import CONDENSATRON_REDUCTION_LEVEL
68
- from config import FRACTALTRON_THRESHOLD_LEVEL
69
- from config import FRACTALTRON_REDUCTION_LEVEL
70
- from config import RESERVED_FOR_PROMPT
71
- from config import FRACTALTRON_REDUCTION_FACTOR
72
  c = config.PrintColors
73
  input_queue = queue.Queue()
74
 
@@ -421,109 +417,26 @@ def handle_command(sensor_input_raw: str) -> str | None:
421
 
422
 
423
  # ─────────────────────────────────────────────────────────────────────────────
424
- # fractaltron total context reduction
425
- # ─────────────────────────────────────────────────────────────────────────────
426
- def fractaltron(
427
- model: Llama,
428
- tree: str,
429
- brain_type: str,
430
- ) -> bool:
431
- """
432
- Check whether garden["C"] is approaching the context limit and compress
433
- the oldest n% of turn pairs if necessary.
434
- """
435
- _n_tok_tot_before_truncation: int = garden["n_tok_tot"][tree]
436
- # _threshold_level: int = HEMISPHERES[brain_type]["loader"]["n_ctx"] - (CONDENSATRON_THRESHOLD_LEVEL + RESERVED_FOR_PROMPT)
437
- # _reduction_level: float = _threshold_level * FRACTALTRON_REDUCTION_FACTOR
438
-
439
- _posts_len_removed: int = 0
440
- _tokens_to_subtract: int = 0
441
- _fractalized:bool = False
442
- _turns_after_truncation: int = 0
443
-
444
- print(f"\n {c.green}[ctx] fractaltron brain_type: {brain_type} n_tok_tot['{tree}']: {garden["n_tok_tot"][tree]}"
445
- f"\n FRACTALTRON_THRESHOLD_LEVEL: {FRACTALTRON_THRESHOLD_LEVEL} > FRACTALTRON_REDUCTION_LEVEL: {FRACTALTRON_REDUCTION_LEVEL}{c.res}")
446
-
447
- if garden["n_tok_tot"][tree] <= FRACTALTRON_THRESHOLD_LEVEL:
448
- return _fractalized # still within budget β€” nothing to do
449
-
450
- if brain_type == "muse":
451
- return _fractalized # same input as Logic. Avoid Thread collision.
452
-
453
- _turns_before_truncation = len(garden[tree]) // 2
454
- if _turns_before_truncation < 2:
455
- print(f"\n [ctx][Truncation] WARNING: only {_turns_before_truncation} turn pair(s) β€” "
456
- f"cannot truncate further.\n")
457
-
458
- while garden["n_tok_tot"][tree] > FRACTALTRON_REDUCTION_LEVEL:
459
- if len(garden["Z"]) > 0: # Check if posts in garden["Z"] history
460
- config.fractaltron_cycle = True # Initiate fractaltron after condesatron
461
- return _fractalized # main must first compute the condensatron and append to memotron
462
-
463
- if len(garden[tree]) >= 2:
464
- for role in ("user", "assistant"): # Pop a user, assistant pair of messages
465
- _tokens_to_subtract = garden[tree].pop(0) # Pop oldest message
466
- garden["popped"][tree].append(_tokens_to_subtract) # append to pending memotron
467
- print(f"\ngarden: {_tokens_to_subtract}")
468
- _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
469
- garden["n_tok_tot"][tree] -= _token_len_to_subtract # Remove n tok of message
470
-
471
- config.fractaltron_cycle = True
472
- _fractalized = True
473
- _posts_len_removed += 2
474
- else:
475
- break
476
- print(f"============================================")
477
-
478
- if len(garden[tree]) > 1:
479
- _turns_after_truncation = len(garden[tree]) // 2
480
-
481
- print(
482
- f"\n{c.green}{'β–“' * 60}\n"
483
- f" brain_type: {brain_type} -> fractaltron level reached.\n"
484
- f" FRACTALTRON_THRESHOLD_LEVEL : {FRACTALTRON_THRESHOLD_LEVEL:,} tokens "
485
- f"({FRACTALTRON_THRESHOLD_LEVEL:.0%} of {_n_tok_tot_before_truncation:,})\n"
486
- f" Removed : {_posts_len_removed} oldest posts "
487
- f" Tokens : {_n_tok_tot_before_truncation:,} β†’ {garden["n_tok_tot"][tree]:,}\n"
488
- f" Remaining : {_turns_after_truncation} turn pair(s) in garden['{tree}']\n"
489
- f"{'β–“' * 60}{c.res}\n"
490
- )
491
- return _fractalized
492
-
493
-
494
- # ─────────────────────────────────────────────────────────────────────────────
495
- # condensatron context reduction
496
  # ─────────────────────────────────────────────────────────────────────────────
497
  def condensatron(
498
  model: Llama,
499
  tree: str,
500
  brain_type: str,
501
- ) -> bool:
502
  """
503
- Check whether garden["Z"] is approaching the context limit and compress
504
- the oldest n% of turn pairs if necessary.
505
  """
506
  _n_tok_tot_before_truncation: int = garden["n_tok_tot"][tree]
507
  _posts_len_removed: int = 0
508
  _tokens_to_subtract: int = 0
509
- _condensed:bool = False
510
  _turns_after_truncation: int = 0
511
 
512
- print(f"\n {c.green}[ctx] condensatron brain_type: {brain_type} n_tok_tot['{tree}']: {garden["n_tok_tot"][tree]}"
513
- f"\n CONDENSATRON_THRESHOLD_LEVEL: {CONDENSATRON_THRESHOLD_LEVEL} -> CONDENSATRON_REDUCTION_LEVEL: {CONDENSATRON_REDUCTION_LEVEL} {c.res}")
514
-
515
- if not config.condensatron_cycle and garden["n_tok_tot"][tree] <= CONDENSATRON_THRESHOLD_LEVEL:
516
- return _condensed # still within budget β€” nothing to do
517
-
518
- if brain_type == "muse":
519
- return _condensed # same input as Logic. Avoid Thread collision.
520
 
521
- _turns_before_truncation = len(garden[tree]) // 2
522
- if _turns_before_truncation < 2:
523
- print(f"\n [ctx] condensatron WARNING: only {_turns_before_truncation} turn pair(s) β€” "
524
- f"cannot truncate further.\n")
525
-
526
- while garden["n_tok_tot"][tree] > CONDENSATRON_REDUCTION_LEVEL:
527
  if len(garden[tree]) >= 2:
528
  for role in ("user", "assistant"): # Pop a user, assistant pair of messages
529
  _tokens_to_subtract = garden[tree].pop(0) # Pop oldest message
@@ -531,13 +444,11 @@ def condensatron(
531
  print(f"\ngarden: {_tokens_to_subtract}")
532
  _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
533
  garden["n_tok_tot"][tree] -= _token_len_to_subtract # Remove n tok of message
 
534
 
535
- config.condensatron_cycle = True
536
- _condensed = True
537
- _posts_len_removed += 2
538
  else:
539
  break
540
- print(f"============================================")
541
 
542
  if len(garden[tree]) > 1:
543
  _turns_after_truncation = len(garden[tree]) // 2
@@ -545,13 +456,13 @@ def condensatron(
545
  print(
546
  f"\n{c.green}{'β–“' * 60}\n"
547
  f" brain_type: {brain_type} -> condensatron level reached.\n"
548
- f" CONDENSATRON_THRESHOLD_LEVEL : {CONDENSATRON_THRESHOLD_LEVEL:,} tokens "
 
549
  f" Removed : {_posts_len_removed} oldest posts "
550
  f" Tokens : {_n_tok_tot_before_truncation:,} β†’ {garden["n_tok_tot"][tree]:,}\n"
551
  f" Remaining : {_turns_after_truncation} turn pair(s) in garden['{tree}']\n"
552
  f"{'β–“' * 60}{c.res}\n"
553
  )
554
- return _condensed
555
 
556
 
557
  # ─────────────────────────────────────────────────────────────────────────────
@@ -620,6 +531,7 @@ def build_jinja2_template(model: Llama, messages: list[dict], hemi: dict) -> str
620
 
621
 
622
  def create_prompt_and_jinja2_template(model: Llama, messages: list[dict], hemi: dict) -> str:
 
623
  _prompt = build_jinja2_template(model, messages, hemi) # Total prompt including histories
624
 
625
  clektal["n_tok_input"][hemi["brain_type"]] = get_token_len_from_tokenizer(model, _prompt)
@@ -683,8 +595,8 @@ def generate_brain_type_response(
683
  for token in hemi["think_end_tokens"]:
684
  if token in clektal["post_full"][hemi["brain_type"]]:
685
  if hemi["brain_type"] == "mind":
686
- print("\n" + "─" * 49)
687
- print(f"[{print_label} β€” Final Response]")
688
  _think_done = True
689
  # reset: discard thinking token count
690
  clektal["post_clean"][hemi["brain_type"]] = ""
@@ -718,8 +630,10 @@ def make_request_messages(brain_type: str, input_message: str) -> list[dict]:
718
  _msgs.append({"role": "user", "content": input_message})
719
  return _msgs
720
 
721
-
722
- def build_condensatron_input(popped_posts: list[dict], brain_type: str) -> str:
 
 
723
  _history_block = "\n\n".join(
724
  f"[{m['role'].upper()}]: {m['content']}"
725
  for m in popped_posts
@@ -727,7 +641,7 @@ def build_condensatron_input(popped_posts: list[dict], brain_type: str) -> str:
727
  _total_prompt = (
728
  "SYSTEM: CONDENSATRON COMPRESSION TASK\n"
729
  "══════════════════════════════\n"
730
- f"{ALPHAPROMPT["C"][brain_type]}\n"
731
  "──────────────────────────────\n"
732
  "The following is a block of conversation history that must be compressed "
733
  "into a memory capsule. Extract the factual skeleton, the surprises, and "
@@ -741,7 +655,7 @@ def build_condensatron_input(popped_posts: list[dict], brain_type: str) -> str:
741
  return _total_prompt
742
 
743
 
744
- def build_fractaltron_input(popped_capsules: list[dict], brain_type: str) -> str:
745
  _history_block = "\n\n".join(
746
  f"[{m['role'].upper()}]: {m['content']}"
747
  for m in popped_capsules
@@ -749,7 +663,7 @@ def build_fractaltron_input(popped_capsules: list[dict], brain_type: str) -> str
749
  _total_prompt = (
750
  "SYSTEM: FRACTALTRON COMPRESSION TASK\n"
751
  "══════════════════════════════\n"
752
- f"{ALPHAPROMPT["F"][brain_type]}\n"
753
  "──────────────────────────────\n"
754
  "The following is a block of memory capsules that must be compressed "
755
  "into a memory fractal. Extract the factual skeleton, the surprises, and "
@@ -763,6 +677,29 @@ def build_fractaltron_input(popped_capsules: list[dict], brain_type: str) -> str
763
  return _total_prompt
764
 
765
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
766
  # ─────────────────────────────────────────────────────────────────────────────
767
  # Mindlink
768
  # ─────────────────────────────────────────────────────────────────────────────
@@ -777,11 +714,19 @@ def Mindlink(
777
  def run_hemisphere(args_brain_type: str) -> None:
778
  _request_messages: list = []
779
 
780
- if tree == "F":
781
- sensor[tree]["input"] = build_fractaltron_input(garden["popped"]["C"], args_brain_type)
 
 
 
 
 
 
 
 
 
 
782
 
783
- elif tree == "C":
784
- sensor[tree]["input"] = build_condensatron_input(garden["popped"]["Z"], args_brain_type)
785
 
786
  _request_messages = make_request_messages(args_brain_type, sensor[tree]["input"])
787
 
@@ -817,14 +762,15 @@ def Mindlink(
817
  f"top_k={HEMISPHERES[brain_type]['generation']['top_k']} "
818
  f"gpu={HEMISPHERES[brain_type]['loader']['n_gpu_layers']} "
819
  f"{_think_label}")
820
- print(f" config.condensatron_cycle: {config.condensatron_cycle}")
821
- print(f" config.fractaltron_cycle: {config.fractaltron_cycle}")
 
822
  print(f" ⏱ {_timing.summary()}")
823
  print("═" * 60, c.res)
824
  if _think_block:
825
  print(_think_block)
826
- print("─" * 49)
827
- print(f"[{brain_type.capitalize()} β€” Final Response]")
828
  print(_clean)
829
 
830
  _timings[brain_type] = _timing
@@ -839,17 +785,24 @@ def Lambda(
839
 
840
  _request_messages: list = []
841
  _results: dict[str, tuple] = {}
 
 
 
 
 
 
 
842
 
843
- if tree == "F":
844
- sensor[tree]["input"] = build_fractaltron_input(garden["popped"]["C"], "mind")
845
 
846
- elif tree == "C":
847
- sensor[tree]["input"] = build_condensatron_input(garden["popped"]["Z"], "mind")
848
 
849
  _synthesis_input = (
850
- f"Original input:\n{sensor[tree]["input"]}\n\n"
851
- f"── Logic AI perspective ──\n{clektal["post_clean"]["logic"]}\n\n"
852
- f"── Muse AI perspective ──\n{clektal["post_clean"]["muse"]}\n\n"
853
  "Synthesize both perspectives into one unified, wise response."
854
  )
855
  _request_messages = make_request_messages("mind", _synthesis_input)
@@ -862,8 +815,9 @@ def Lambda(
862
  f"gpu={HEMISPHERES["mind"]['loader']['n_gpu_layers']} "
863
  f"max_tokens={HEMISPHERES["mind"]['generation']['max_tokens']} "
864
  f"{_think_label}")
865
- print(f" config.condensatron_cycle: {config.condensatron_cycle}")
866
- print(f" config.fractaltron_cycle: {config.fractaltron_cycle}")
 
867
  print("═" * 60)
868
  print(f" [*] Performing vector synthesis …{c.res}")
869
 
@@ -888,26 +842,39 @@ def memotron(
888
  """
889
  _tree: str = tree
890
  _turn_number: int = 0
 
 
891
 
892
- _len_caps_and_fracs = (len(garden[_tree]) // 2) + 1 # Turns: Add the response below
893
- if _tree == "F": # fractaltron mode
894
- sensor[_tree]["input"] = f"[Fractalized Memory Capsules Crystal: {_len_caps_and_fracs}, From Fractaltron]"
 
 
 
 
 
 
 
 
895
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # user n tok
 
896
 
897
- elif _tree == "C": # condensatron mode
898
- sensor[_tree]["input"] = f"[Posts History Memory Capsule: {_len_caps_and_fracs}, From Condensatron]"
899
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # user n tok
 
900
 
901
  elif _tree == "S": # Startup memory capsules garden
902
  _tree = "C" # Set to memorize as memory capsules garden
903
  sensor[_tree]["input"] = sensor["Z"]["input"] # Read the startup memory capsule's input
904
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # User n tok
 
905
 
906
- garden[_tree].append({"role": "user", "content": sensor[_tree]["input"]})
907
- garden["n_tok_tot"][_tree] += sensor[_tree]["n_tok"]
908
 
909
- garden[_tree].append({"role": "assistant", "content": clektal["post_clean"]["mind"]})
910
- garden["n_tok_tot"][_tree] += clektal["n_tok_clean"]["mind"]
911
 
912
  if len(garden[_tree]) > 1:
913
  _turn_number = sum(1 for m in garden[_tree] if m["role"] == "user")
@@ -942,8 +909,6 @@ def memotron(
942
  # ─────────────────────────────────────────────────────────────────────────────
943
  def print_banner(tree: str, session_id: int) -> None:
944
  _turn_count = sum(1 for m in garden[tree] if m["role"] == "user")
945
- _total_tokens = garden["n_tok_tot"][tree]
946
- _fractaltron_threshold_level: int = HEMISPHERES["mind"]["loader"]["n_ctx"] - (CONDENSATRON_THRESHOLD_LEVEL + RESERVED_FOR_PROMPT)
947
 
948
  print(c.green)
949
  print(f"═" * 60)
@@ -955,8 +920,9 @@ def print_banner(tree: str, session_id: int) -> None:
955
  f"{_think_label}")
956
  print("─" * 60)
957
  print(f" Session: {session_id} | Turns: {_turn_count}")
958
- print(f" Tokens: {_total_tokens:,} CONDENSATRON_THRESHOLD_LEVEL {CONDENSATRON_THRESHOLD_LEVEL:,} CONDENSATRON_REDUCTION_LEVEL {CONDENSATRON_REDUCTION_LEVEL:,}")
959
- print(f" Tokens: {_total_tokens:,} _fractaltron_threshold_level {_fractaltron_threshold_level:,} * FRACTALTRON_REDUCTION_FACTOR {FRACTALTRON_REDUCTION_FACTOR:,}")
 
960
  print( " /help for commands | /exit or /quit to close")
961
  print(f"═" * 60)
962
  print(c.res)
@@ -965,27 +931,20 @@ def print_banner(tree: str, session_id: int) -> None:
965
  # ─────────────────────────────────────────────────────────────────────────────
966
  # Reset turn based history
967
  # ─────────────────────────────────────────────────────────────────────────────
968
- def reset_turn_content(garden_z: bool = False, garden_c: bool = False) -> None:
969
- print(f" {c.green}[reset] turn content{c.res}")
970
- sensor["Z"]["input"] = ""
971
- sensor["Z"]["n_tok"] = 0
972
  for brain_type in clektal["post_full"]:
973
  clektal["post_full"][brain_type] = ""
974
  clektal["post_clean"][brain_type] = ""
975
  clektal["n_tok_clean"][brain_type] = 0
976
  clektal["n_tok_prompt_safe_max"][brain_type] = 0
977
 
978
- if garden_z:
979
- print(f" {c.green}[reset] garden_z turn content{c.res}")
980
- garden["popped"]["Z"] = [] # memotron post-level cache
981
- sensor["C"]["input"] = ""
982
- sensor["C"]["n_tok"] = 0
983
-
984
- if garden_c:
985
- print(f" {c.green}[reset] garden_c turn content{c.res}")
986
- garden["popped"]["C"] = [] # memotron post-level cache
987
- sensor["F"]["input"] = ""
988
- sensor["F"]["n_tok"] = 0
989
 
990
 
991
  # ─────────────────────────────────────────────────────────────────────────────
@@ -1039,72 +998,50 @@ def main() -> None:
1039
  _tree: str = "Z"
1040
  print_banner(_tree, _session_id)
1041
 
 
 
1042
  while True:
1043
- _sensor_input_raw: str = "" # user input
1044
  _tree = "Z" # Set to sentience history garden tree
1045
 
1046
  time.sleep(_HEARTBEAT_INTERVAL)
1047
  _heartbeats += 1
1048
 
1049
  try:
1050
- _sensor_input_raw = input_queue.get_nowait()
1051
  _heartbeats = 0
1052
  except queue.Empty:
1053
  pass
1054
 
1055
- if _heartbeats >= 10:
1056
- # # # print(f"--> _heartbeats reset: {_heartbeats}")
1057
  _heartbeats = 0
1058
- if _startup_memory_capsules_loaded < config.N_MEMORY_CAPSULES_TO_LOAD:
 
1059
  _startup_memory_capsules_loaded += 1 # Iterate over the memory capsules
1060
- if _startup_memory_capsules_loaded == 1: _sensor_input_raw = "/file prompt/lambda-mindlink.md"
1061
- elif _startup_memory_capsules_loaded == 2: _sensor_input_raw = "/file prompt/1999.md"
1062
- elif _startup_memory_capsules_loaded == 3: _sensor_input_raw = "/file prompt/valka_memory_v2.md"
1063
- elif _startup_memory_capsules_loaded == 4: _sensor_input_raw = "/file prompt/valka_memory_v3.md"
1064
- print(f"\n {c.inv} ── _startup_memory_capsules_loaded: {_startup_memory_capsules_loaded} ──────────────────────────── {c.res}")
1065
-
1066
- if config.condensatron_cycle:
1067
- _tree = "C" # Start the condesatron execution cycle after _heartbeats
1068
- # ── Brain pipeline condensatron cycle ────────────────────────────
1069
- print(f" {c.inv} ── Start condensatron cycle: sensor['{_tree}']['input'] {sensor[_tree]["input"]} ──────────────────────────── {c.res}")
1070
- _timings = Mindlink(_models, _tree)
1071
- _timings["mind"] = Lambda(_models, _tree)
1072
- memotron(_models, _tree, _session_id, _timings) # Append to garden["C"]
1073
- # Reset turn-based data
1074
- _heartbeats = 0
1075
- reset_turn_content(garden_z=True)
1076
- # reset_condensatron()
1077
- config.condensatron_cycle = False
1078
- print("\nYou: ", end="", flush=True)
1079
- continue # restart while loop
1080
-
1081
- elif config.fractaltron_cycle:
1082
- if len(garden["Z"]) > 0: # Check for remaining posts cache
1083
- config.condensatron_cycle = True # Start condensatron
1084
- _tree = "Z" # Get n garden["Z"] posts for condesatron
1085
- _condensed = condensatron(_models["mind"], _tree, "mind") # Get posts from garden["Z"]
1086
- continue # restart while loop
1087
-
1088
- _tree = "F" # Start the fractaltron execution cycle after _heartbeats
1089
- # ── Brain pipeline fractaltron cycle ─────────────
1090
- print(f" {c.inv} ── Start fractaltron cycle: sensor['{_tree}']['input'] {sensor[_tree]["input"]} ──────────────────────────── {c.res}")
1091
- _timings = Mindlink(_models, _tree)
1092
- _timings["mind"] = Lambda(_models, _tree)
1093
- memotron(_models, _tree, _session_id, _timings) # Append to garden["F"]
1094
- # Reset turn-based data
1095
- _heartbeats = 0
1096
- reset_turn_content(garden_c=True)
1097
- # reset_fractaltron()
1098
- config.fractaltron_cycle = False
1099
- print("\nYou: ", end="", flush=True)
1100
- continue # restart while loop
1101
 
1102
- if not _sensor_input_raw: # wait state loop restart here
 
 
 
 
 
 
 
1103
  continue
1104
 
1105
- if _sensor_input_raw.startswith("/"):
1106
  try:
1107
- slash_command_result = handle_command(_sensor_input_raw)
1108
  except _Quit:
1109
  print(f" {c.green}[*] Lambda Mindlink Memotron: System shutdown...{c.res}")
1110
  break
@@ -1115,31 +1052,51 @@ def main() -> None:
1115
  print_banner(_tree, _session_id)
1116
  continue
1117
  except ValueError as exc:
1118
- print(f" {c.green} [!] Unknown command: /{exc} β€” type /help for the list.{c.res}")
1119
  continue
1120
- if slash_command_result is None:
1121
  continue
1122
- sensor[_tree]["input"] = slash_command_result
1123
  else:
1124
- sensor[_tree]["input"] = _sensor_input_raw
1125
 
1126
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(_models["mind"], sensor[_tree]["input"]) # User n tok
1127
 
1128
  # ── Brain pipeline ────────────────────────────────────────────────────
1129
  _timings = Mindlink(_models, _tree)
1130
  _timings["mind"] = Lambda(_models, _tree)
1131
-
1132
- if _startup_memory_capsules_loaded <= config.N_MEMORY_CAPSULES_TO_LOAD:
1133
  print(f" {c.inv} ── memotron _startup_memory_capsules_loaded: {_startup_memory_capsules_loaded} ──────────────────────────── {c.res}")
1134
  _tree = "S" # Set to memorize as memory capsules in garden["C"]
 
 
1135
  if _startup_memory_capsules_loaded == config.N_MEMORY_CAPSULES_TO_LOAD:
1136
  _startup_memory_capsules_loaded += 1 # Advance to finish the startup sequence
1137
-
1138
- memotron(_models, _tree, _session_id, _timings)
1139
- _tree = "Z" # Set to condense garden["Z"]
1140
- _condensed = condensatron(_models["mind"], _tree, "mind") # Check garden["Z"] context budget AFTER generation
1141
- _tree = "C" # Set to fractalize garden["C"]
1142
- _fractalized = fractaltron(_models["mind"], _tree, "mind") # Check garden["C"] context budget AFTER generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1143
 
1144
  reset_turn_content()
1145
  _heartbeats = 0
 
58
 
59
  import config
60
 
61
+ from config import MEMORY_CAPSULES_TO_LOAD
62
  from config import HEMISPHERES
63
  from config import ALPHAPROMPT
64
+ from config import CONDENSATRONPROMPT
65
  from config import garden
66
  from config import clektal
67
  from config import sensor
 
 
 
 
 
 
68
  c = config.PrintColors
69
  input_queue = queue.Queue()
70
 
 
417
 
418
 
419
  # ─────────────────────────────────────────────────────────────────────────────
420
+ # condensatron context reduction
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  # ─────────────────────────────────────────────────────────────────────────────
422
  def condensatron(
423
  model: Llama,
424
  tree: str,
425
  brain_type: str,
426
+ ) -> None:
427
  """
428
+ Check whether a garden is approaching the context limit and compress
429
+ the oldest n% of turn pairs.
430
  """
431
  _n_tok_tot_before_truncation: int = garden["n_tok_tot"][tree]
432
  _posts_len_removed: int = 0
433
  _tokens_to_subtract: int = 0
 
434
  _turns_after_truncation: int = 0
435
 
436
+ print(f"\n {c.green}[condensatron]: garden['{tree}'] brain_type: {brain_type} garden['n_tok_tot']['{tree}']: {garden["n_tok_tot"][tree]}"
437
+ f"\n garden['THRESHOLD']['{tree}']: {garden['THRESHOLD'][tree]} > garden['REDUCTION']['{tree}']: {garden['REDUCTION'][tree]}{c.res}")
 
 
 
 
 
 
438
 
439
+ while garden["n_tok_tot"][tree] > garden["REDUCTION"][tree]:
 
 
 
 
 
440
  if len(garden[tree]) >= 2:
441
  for role in ("user", "assistant"): # Pop a user, assistant pair of messages
442
  _tokens_to_subtract = garden[tree].pop(0) # Pop oldest message
 
444
  print(f"\ngarden: {_tokens_to_subtract}")
445
  _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
446
  garden["n_tok_tot"][tree] -= _token_len_to_subtract # Remove n tok of message
447
+ _posts_len_removed += 1
448
 
449
+ garden["condensatron_state"][tree] = True
 
 
450
  else:
451
  break
 
452
 
453
  if len(garden[tree]) > 1:
454
  _turns_after_truncation = len(garden[tree]) // 2
 
456
  print(
457
  f"\n{c.green}{'β–“' * 60}\n"
458
  f" brain_type: {brain_type} -> condensatron level reached.\n"
459
+ f" garden['THRESHOLD']['{tree}'] : {garden['THRESHOLD'][tree]:,} tokens "
460
+ f" ({garden['THRESHOLD'][tree]:.0%} of {_n_tok_tot_before_truncation:,})\n"
461
  f" Removed : {_posts_len_removed} oldest posts "
462
  f" Tokens : {_n_tok_tot_before_truncation:,} β†’ {garden["n_tok_tot"][tree]:,}\n"
463
  f" Remaining : {_turns_after_truncation} turn pair(s) in garden['{tree}']\n"
464
  f"{'β–“' * 60}{c.res}\n"
465
  )
 
466
 
467
 
468
  # ─────────────────────────────────────────────────────────────────────────────
 
531
 
532
 
533
  def create_prompt_and_jinja2_template(model: Llama, messages: list[dict], hemi: dict) -> str:
534
+
535
  _prompt = build_jinja2_template(model, messages, hemi) # Total prompt including histories
536
 
537
  clektal["n_tok_input"][hemi["brain_type"]] = get_token_len_from_tokenizer(model, _prompt)
 
595
  for token in hemi["think_end_tokens"]:
596
  if token in clektal["post_full"][hemi["brain_type"]]:
597
  if hemi["brain_type"] == "mind":
598
+ print(f"\n{c.green}" + "─" * 49)
599
+ print(f"[{print_label} β€” Final Response]{c.res}")
600
  _think_done = True
601
  # reset: discard thinking token count
602
  clektal["post_clean"][hemi["brain_type"]] = ""
 
630
  _msgs.append({"role": "user", "content": input_message})
631
  return _msgs
632
 
633
+ # ─────────────────────────────────────────────────────────────────────────────
634
+ # Build condensatron type prompts
635
+ # ─────────────────────────────────────────────────────────────────────────────
636
+ def build_condensatron_input(popped_posts: list[dict], brain_type: str, tree: str) -> str:
637
  _history_block = "\n\n".join(
638
  f"[{m['role'].upper()}]: {m['content']}"
639
  for m in popped_posts
 
641
  _total_prompt = (
642
  "SYSTEM: CONDENSATRON COMPRESSION TASK\n"
643
  "══════════════════════════════\n"
644
+ f"{CONDENSATRONPROMPT[tree][brain_type]}\n"
645
  "──────────────────────────────\n"
646
  "The following is a block of conversation history that must be compressed "
647
  "into a memory capsule. Extract the factual skeleton, the surprises, and "
 
655
  return _total_prompt
656
 
657
 
658
+ def build_fractaltron_input(popped_capsules: list[dict], brain_type: str, tree: str) -> str:
659
  _history_block = "\n\n".join(
660
  f"[{m['role'].upper()}]: {m['content']}"
661
  for m in popped_capsules
 
663
  _total_prompt = (
664
  "SYSTEM: FRACTALTRON COMPRESSION TASK\n"
665
  "══════════════════════════════\n"
666
+ f"{CONDENSATRONPROMPT[tree][brain_type]}\n"
667
  "──────────────────────────────\n"
668
  "The following is a block of memory capsules that must be compressed "
669
  "into a memory fractal. Extract the factual skeleton, the surprises, and "
 
677
  return _total_prompt
678
 
679
 
680
+
681
+ def build_crystaltron_input(popped_capsules: list[dict], brain_type: str, tree: str) -> str:
682
+ _history_block = "\n\n".join(
683
+ f"[{m['role'].upper()}]: {m['content']}"
684
+ for m in popped_capsules
685
+ )
686
+ _total_prompt = (
687
+ "SYSTEM: CRYSTALTRON COMPRESSION TASK\n"
688
+ "══════════════════════════════\n"
689
+ f"{CONDENSATRONPROMPT[tree][brain_type]}\n"
690
+ "──────────────────────────────\n"
691
+ "The following is a block of second-order memory capsules that must be compressed "
692
+ "into a memory crystals. Extract the factual skeleton, the surprises, and "
693
+ "the key words. Discard all redundancy.\n\n"
694
+ "── HISTORY BLOCK ──\n\n"
695
+ f"{_history_block}\n\n"
696
+ "── END HISTORY BLOCK ──\n\n"
697
+ "Produce the crystal now."
698
+ )
699
+ print(f"\n--- build_crystaltron_input: {_total_prompt}\n")
700
+ return _total_prompt
701
+
702
+
703
  # ─────────────────────────────────────────────────────────────────────────────
704
  # Mindlink
705
  # ─────────────────────────────────────────────────────────────────────────────
 
714
  def run_hemisphere(args_brain_type: str) -> None:
715
  _request_messages: list = []
716
 
717
+ for c_tree in ("Z", "C", "F"):
718
+ if garden["condensatron_state"][c_tree]:
719
+ print(f" {c.inv} ── Start condensatron cycle: garden['{c_tree}'] ──────────────────────────── {c.res}")
720
+
721
+ if c_tree == "Z":
722
+ sensor[c_tree]["input"] = build_condensatron_input(garden["popped"][c_tree], args_brain_type, c_tree)
723
+
724
+ elif c_tree == "C":
725
+ sensor[c_tree]["input"] = build_fractaltron_input(garden["popped"][c_tree], args_brain_type, c_tree)
726
+
727
+ elif c_tree == "F":
728
+ sensor[c_tree]["input"] = build_crystaltron_input(garden["popped"][c_tree], args_brain_type, c_tree)
729
 
 
 
730
 
731
  _request_messages = make_request_messages(args_brain_type, sensor[tree]["input"])
732
 
 
762
  f"top_k={HEMISPHERES[brain_type]['generation']['top_k']} "
763
  f"gpu={HEMISPHERES[brain_type]['loader']['n_gpu_layers']} "
764
  f"{_think_label}")
765
+ print(f" garden['condensatron_state']['F']: {garden["condensatron_state"]["F"]}")
766
+ print(f" garden['condensatron_state']['C']: {garden["condensatron_state"]["C"]}")
767
+ print(f" garden['condensatron_state']['Z']: {garden["condensatron_state"]["Z"]}")
768
  print(f" ⏱ {_timing.summary()}")
769
  print("═" * 60, c.res)
770
  if _think_block:
771
  print(_think_block)
772
+ print(c.green, "─" * 49)
773
+ print(f"[{brain_type.capitalize()} β€” Final Response]{c.res}")
774
  print(_clean)
775
 
776
  _timings[brain_type] = _timing
 
785
 
786
  _request_messages: list = []
787
  _results: dict[str, tuple] = {}
788
+
789
+ for c_tree in ("Z", "C", "F"): # condensatron
790
+ if garden["condensatron_state"][c_tree]: # Check for pending condensatron tasks
791
+ print(f" {c.inv} ── Start condensatron cycle: garden['{c_tree}'] ──────────────────────────── {c.res}")
792
+
793
+ if c_tree == "Z":
794
+ sensor[c_tree]["input"] = build_condensatron_input(garden["popped"][c_tree], "mind", c_tree)
795
 
796
+ elif c_tree == "C":
797
+ sensor[c_tree]["input"] = build_fractaltron_input(garden["popped"][c_tree], "mind", c_tree)
798
 
799
+ elif c_tree == "F":
800
+ sensor[c_tree]["input"] = build_crystaltron_input(garden["popped"][c_tree], "mind", c_tree)
801
 
802
  _synthesis_input = (
803
+ f"Original input:\n{sensor[tree]['input']}\n\n"
804
+ f"── Logic AI perspective ──\n{clektal['post_clean']['logic']}\n\n"
805
+ f"── Muse AI perspective ──\n{clektal['post_clean']['muse']}\n\n"
806
  "Synthesize both perspectives into one unified, wise response."
807
  )
808
  _request_messages = make_request_messages("mind", _synthesis_input)
 
815
  f"gpu={HEMISPHERES["mind"]['loader']['n_gpu_layers']} "
816
  f"max_tokens={HEMISPHERES["mind"]['generation']['max_tokens']} "
817
  f"{_think_label}")
818
+ print(f" garden['condensatron_state']['F']: {garden["condensatron_state"]["F"]}")
819
+ print(f" garden['condensatron_state']['C']: {garden["condensatron_state"]["C"]}")
820
+ print(f" garden['condensatron_state']['Z']: {garden["condensatron_state"]["Z"]}")
821
  print("═" * 60)
822
  print(f" [*] Performing vector synthesis …{c.res}")
823
 
 
842
  """
843
  _tree: str = tree
844
  _turn_number: int = 0
845
+ _tree_to_store: str = ""
846
+ _len_caps_and_fracs: int = 1 # condensatron turns default: Add extra 1 for the response below
847
 
848
+ _tree_to_store = tree
849
+ if len(garden[_tree]) > 1:
850
+ _len_caps_and_fracs = (len(garden[_tree]) // 2) + 1 # condensatron turns: Add extra 1 for the response below
851
+
852
+ if _tree == "Z" and garden["condensatron_state"][_tree]: # condensatron mode
853
+ sensor[_tree]["input"] = f"[Posts History First-Order Memory Capsule: {_len_caps_and_fracs}, From Condensatron]"
854
+ sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # user n tok
855
+ _tree_to_store = garden["TREE_TO_STORE"][_tree]
856
+
857
+ elif _tree == "C" and garden["condensatron_state"][_tree]: # fractaltron mode
858
+ sensor[_tree]["input"] = f"[Memory Capsules Second-Order Fractal: {_len_caps_and_fracs}, From Fractaltron]"
859
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # user n tok
860
+ _tree_to_store = garden["TREE_TO_STORE"][_tree]
861
 
862
+ elif _tree == "F" and garden["condensatron_state"][_tree]: # crystaltron mode
863
+ sensor[_tree]["input"] = f"[Memory Fractals Third-Order Memory Crystal: {_len_caps_and_fracs}, From Crystaltron]"
864
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # user n tok
865
+ _tree_to_store = _tree
866
 
867
  elif _tree == "S": # Startup memory capsules garden
868
  _tree = "C" # Set to memorize as memory capsules garden
869
  sensor[_tree]["input"] = sensor["Z"]["input"] # Read the startup memory capsule's input
870
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[_tree]["input"]) # User n tok
871
+ _tree_to_store = _tree
872
 
873
+ garden[_tree_to_store].append({"role": "user", "content": sensor[_tree]["input"]})
874
+ garden["n_tok_tot"][_tree_to_store] += sensor[_tree]["n_tok"]
875
 
876
+ garden[_tree_to_store].append({"role": "assistant", "content": clektal["post_clean"]["mind"]})
877
+ garden["n_tok_tot"][_tree_to_store] += clektal["n_tok_clean"]["mind"]
878
 
879
  if len(garden[_tree]) > 1:
880
  _turn_number = sum(1 for m in garden[_tree] if m["role"] == "user")
 
909
  # ─────────────────────────────────────────────────────────────────────────────
910
  def print_banner(tree: str, session_id: int) -> None:
911
  _turn_count = sum(1 for m in garden[tree] if m["role"] == "user")
 
 
912
 
913
  print(c.green)
914
  print(f"═" * 60)
 
920
  f"{_think_label}")
921
  print("─" * 60)
922
  print(f" Session: {session_id} | Turns: {_turn_count}")
923
+ for print_tree in ("Z", "C", "F"):
924
+ print(f" Tokens garden['{print_tree}']: {garden["n_tok_tot"][tree]:,} garden['THRESHOLD']['{print_tree}'] {garden['THRESHOLD'][print_tree]:,} garden['REDUCTION']['{print_tree}'] {garden['REDUCTION'][print_tree]:,}")
925
+
926
  print( " /help for commands | /exit or /quit to close")
927
  print(f"═" * 60)
928
  print(c.res)
 
931
  # ─────────────────────────────────────────────────────────────────────────────
932
  # Reset turn based history
933
  # ─────────────────────────────────────────────────────────────────────────────
934
+ def reset_turn_content(tree: str = "") -> None:
935
+ print(f" {c.green}[reset_turn_content] post-level{c.res}")
 
 
936
  for brain_type in clektal["post_full"]:
937
  clektal["post_full"][brain_type] = ""
938
  clektal["post_clean"][brain_type] = ""
939
  clektal["n_tok_clean"][brain_type] = 0
940
  clektal["n_tok_prompt_safe_max"][brain_type] = 0
941
 
942
+ if tree:
943
+ print(f" {c.green}[reset_turn_content] condensatron garden['{tree}']{c.res}")
944
+ sensor[tree]["input"] = ""
945
+ sensor[tree]["n_tok"] = 0
946
+ garden["popped"][tree] = [] # condensatron post-level cache
947
+ garden["condensatron_state"][tree] = False
 
 
 
 
 
948
 
949
 
950
  # ─────────────────────────────────────────────────────────────────────────────
 
998
  _tree: str = "Z"
999
  print_banner(_tree, _session_id)
1000
 
1001
+ print(f"\n{c.inv} You: {c.res} ", end="", flush=True)
1002
+
1003
  while True:
1004
+ _sensor_input: str = "" # user input
1005
  _tree = "Z" # Set to sentience history garden tree
1006
 
1007
  time.sleep(_HEARTBEAT_INTERVAL)
1008
  _heartbeats += 1
1009
 
1010
  try:
1011
+ _sensor_input = input_queue.get_nowait()
1012
  _heartbeats = 0
1013
  except queue.Empty:
1014
  pass
1015
 
1016
+ if _heartbeats >= 10: # Timed loop
 
1017
  _heartbeats = 0
1018
+ if config.N_MEMORY_CAPSULES_TO_LOAD and _startup_memory_capsules_loaded < config.N_MEMORY_CAPSULES_TO_LOAD:
1019
+ _sensor_input = MEMORY_CAPSULES_TO_LOAD[_startup_memory_capsules_loaded]
1020
  _startup_memory_capsules_loaded += 1 # Iterate over the memory capsules
1021
+ print(f"\n {c.inv} ── _startup_memory_capsules_loaded: {_startup_memory_capsules_loaded} _sensor_input: {_sensor_input} ──────────────────────────── {c.res}")
1022
+
1023
+ for c_tree in ("Z", "C", "F"):
1024
+ if garden["condensatron_state"][c_tree]:
1025
+ print(f" {c.inv} ── Start condensatron cycle: garden['{c_tree}'] ──────────────────────────── {c.res}")
1026
+
1027
+ # ── Brain pipeline condensatron cycle ────────────────────────────
1028
+ _timings = Mindlink(_models, c_tree)
1029
+ _timings["mind"] = Lambda(_models, c_tree)
1030
+ memotron(_models, c_tree, _session_id, _timings) # Append to garden["C"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1031
 
1032
+ # Reset turn-based data
1033
+ _heartbeats = 0
1034
+ reset_turn_content(tree=c_tree)
1035
+
1036
+ print(f"\n{c.inv} You: {c.res} ", end="", flush=True)
1037
+ continue # restart the while loop
1038
+
1039
+ if not _sensor_input: # wait state loop restart here
1040
  continue
1041
 
1042
+ if _sensor_input.startswith("/"): # Read user slash command
1043
  try:
1044
+ _slash_command_result = handle_command(_sensor_input)
1045
  except _Quit:
1046
  print(f" {c.green}[*] Lambda Mindlink Memotron: System shutdown...{c.res}")
1047
  break
 
1052
  print_banner(_tree, _session_id)
1053
  continue
1054
  except ValueError as exc:
1055
+ print(f" {c.green}[!] Unknown command: /{exc} β€” type /help for the list.{c.res}")
1056
  continue
1057
+ if _slash_command_result is None:
1058
  continue
1059
+ sensor[_tree]["input"] = _slash_command_result
1060
  else:
1061
+ sensor[_tree]["input"] = _sensor_input
1062
 
1063
  sensor[_tree]["n_tok"] = get_token_len_from_tokenizer(_models["mind"], sensor[_tree]["input"]) # User n tok
1064
 
1065
  # ── Brain pipeline ────────────────────────────────────────────────────
1066
  _timings = Mindlink(_models, _tree)
1067
  _timings["mind"] = Lambda(_models, _tree)
1068
+ # ── Startup memory capsules to load ───────────────────────────────────
1069
+ if config.N_MEMORY_CAPSULES_TO_LOAD and _startup_memory_capsules_loaded <= config.N_MEMORY_CAPSULES_TO_LOAD:
1070
  print(f" {c.inv} ── memotron _startup_memory_capsules_loaded: {_startup_memory_capsules_loaded} ──────────────────────────── {c.res}")
1071
  _tree = "S" # Set to memorize as memory capsules in garden["C"]
1072
+ memotron(_models, _tree, _session_id, _timings) # Store the startup response in garden["C"]
1073
+ _tree = "Z" # Set back to default for 'reset turn content' only
1074
  if _startup_memory_capsules_loaded == config.N_MEMORY_CAPSULES_TO_LOAD:
1075
  _startup_memory_capsules_loaded += 1 # Advance to finish the startup sequence
1076
+ else:
1077
+ memotron(_models, _tree, _session_id, _timings) # Store the response
1078
+ # ── Condensatron evaluation ───────────────────────────────────────────
1079
+ for c_tree in ["Z", "C", "F"]:
1080
+ if garden["n_tok_tot"][c_tree] >= garden["THRESHOLD"][c_tree]: # Check garden context budget
1081
+ print(f" {c.inv} ── Init condensatron get posts: garden['{c_tree}'] ──────────────────────────── {c.res}")
1082
+ condensatron(_models["mind"], c_tree, "mind") # Start condensatron get popped posts
1083
+ # ── Check pre condensatron job ────────────────────────────────
1084
+ _pre_condensatron_tree: str = ""
1085
+ if c_tree == "F":
1086
+ if len(garden["Z"]) > 0: # Check remaining posts
1087
+ _pre_condensatron_tree = "Z"
1088
+ print(f" {c.inv} ── Init _pre_condensatron_tree get posts: garden['{_pre_condensatron_tree}'] ──────────────────────────── {c.res}")
1089
+ condensatron(_models["mind"], _pre_condensatron_tree, "mind") # Start condensatron get popped posts
1090
+ if len(garden["C"]) > 0: # Check remaining posts
1091
+ _pre_condensatron_tree = "C"
1092
+ print(f" {c.inv} ── Init _pre_condensatron_tree get posts: garden['{_pre_condensatron_tree}'] ──────────────────────────── {c.res}")
1093
+ condensatron(_models["mind"], _pre_condensatron_tree, "mind") # Start condensatron get popped posts
1094
+
1095
+ elif c_tree == "C": # Check remaining posts
1096
+ if len(garden["Z"]):
1097
+ _pre_condensatron_tree = "Z"
1098
+ print(f" {c.inv} ── Init _pre_condensatron_tree get posts: garden['{_pre_condensatron_tree}'] ──────────────────────────── {c.res}")
1099
+ condensatron(_models["mind"], _pre_condensatron_tree, "mind") # Start condensatron get popped posts
1100
 
1101
  reset_turn_content()
1102
  _heartbeats = 0