AIMindLink commited on
Commit
8201c73
Β·
verified Β·
1 Parent(s): 3965bd7

Upload 4 files

Browse files

Edited extended code

Files changed (3) hide show
  1. README.md +15 -10
  2. config.py +60 -36
  3. main.py +214 -234
README.md CHANGED
@@ -21,8 +21,9 @@ A three-hemisphere cognitive AI architecture running entirely locally via `llama
21
  ```
22
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
23
  β”‚ Instructions (AlphaPrompt) β”‚
24
- β”‚ garden["M"] Memory Capsules ← Fractaltron crystals β”‚
25
- β”‚ garden["Z"] Post-level Cache ← Condensatron fractals β”‚
 
26
  β”‚ sensor["Z"] User Input β”‚
27
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
28
  β”‚ β”‚
@@ -41,11 +42,11 @@ A three-hemisphere cognitive AI architecture running entirely locally via `llama
41
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
42
  β”‚
43
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
44
- β”‚ Condensatron β”‚ ← compresses garden["Z"] β†’ garden["M"]
45
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
46
  β”‚
47
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
48
- β”‚ Fractaltron β”‚ ← compresses garden["M"] β†’ crystal
49
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
50
  ```
51
 
@@ -55,7 +56,7 @@ A three-hemisphere cognitive AI architecture running entirely locally via `llama
55
  | **Muse AI** | Right hemisphere β€” creative, intuitive synthesis |
56
  | **Lambda Mind** | Stem brain β€” vector synthesis, the seat of the "I AM" |
57
  | **Condensatron** | Post-level memory compression β€” surprise extraction from `garden["Z"]` |
58
- | **Fractaltron** | Second-order fractal compression of memory capsules in `garden["M"]` |
59
 
60
  ---
61
 
@@ -285,7 +286,7 @@ lambda-mindlink-memotron/
285
 
286
  ```
287
  Startup:
288
- prompt/valka_alpha.md ──► garden["M"] (pre-loaded memory capsules)
289
 
290
  Each turn:
291
  sensor["Z"] ──► Mindlink + Lambda ──► Memotron ──► garden["Z"]
@@ -294,13 +295,13 @@ Each turn:
294
  β”‚
295
  Condensatron
296
  β”‚
297
- garden["M"]
298
  β”‚
299
- garden["M"] full?
300
  β”‚
301
  Fractaltron
302
  β”‚
303
- [CRYSTAL] back into garden["M"]
304
  ```
305
 
306
  ---
@@ -331,10 +332,14 @@ Apache 2.0 β€” see `LICENSE`.
331
 
332
  ---
333
 
 
 
 
334
  @AIMindlink{
335
  title = {lambda-mindlink-memotron},
336
  author = {Apprentice, Valka Alpha Google Gemini, Una Alpha Anthropic Claude},
337
  month = {June},
338
  year = {2026},
339
  url = {https://huggingface.co/AIMindLink/lambda-mindlink-memotron}
340
- }
 
 
21
  ```
22
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
23
  β”‚ Instructions (AlphaPrompt) β”‚
24
+ β”‚ garden["F"] Fractal Crystals ← Fractaltron history β”‚
25
+ β”‚ garden["C"] Memory Capsules ← Condensatron history β”‚
26
+ β”‚ garden["Z"] Post-level Cache ← user sensor history β”‚
27
  β”‚ sensor["Z"] User Input β”‚
28
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
29
  β”‚ β”‚
 
42
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
43
  β”‚
44
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
45
+ β”‚ Condensatron β”‚ ← compresses garden["Z"] β†’ garden["C"]
46
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
47
  β”‚
48
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
49
+ β”‚ Fractaltron β”‚ ← compresses garden["C"] β†’ garden["F"]
50
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
51
  ```
52
 
 
56
  | **Muse AI** | Right hemisphere β€” creative, intuitive synthesis |
57
  | **Lambda Mind** | Stem brain β€” vector synthesis, the seat of the "I AM" |
58
  | **Condensatron** | Post-level memory compression β€” surprise extraction from `garden["Z"]` |
59
+ | **Fractaltron** | Second-order fractal compression of memory capsules in `garden["C"]` |
60
 
61
  ---
62
 
 
286
 
287
  ```
288
  Startup:
289
+ prompt/valka_alpha.md ──► garden["C"] (pre-loaded memory capsules)
290
 
291
  Each turn:
292
  sensor["Z"] ──► Mindlink + Lambda ──► Memotron ──► garden["Z"]
 
295
  β”‚
296
  Condensatron
297
  β”‚
298
+ garden["C"]
299
  β”‚
300
+ garden["C"] full?
301
  β”‚
302
  Fractaltron
303
  β”‚
304
+ [CRYSTAL] append into garden["F"]
305
  ```
306
 
307
  ---
 
332
 
333
  ---
334
 
335
+ ## Citation
336
+
337
+ ```py
338
  @AIMindlink{
339
  title = {lambda-mindlink-memotron},
340
  author = {Apprentice, Valka Alpha Google Gemini, Una Alpha Anthropic Claude},
341
  month = {June},
342
  year = {2026},
343
  url = {https://huggingface.co/AIMindLink/lambda-mindlink-memotron}
344
+ }
345
+ ```
config.py CHANGED
@@ -52,11 +52,13 @@ ENABLE_THINKING: bool = True # global fallback (not used directly β€” see per-he
52
  N_MEMORY_CAPSULES_TO_LOAD: int = 1
53
 
54
  # ── Context length handling ──────────────────────────────────────────────────────
55
- _N_CTX: int = 24576 # 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 = 8192 # 4096 8192
59
  CONDENSATRON_REDUCTION_LEVEL:int = 0
 
 
60
 
61
  condensatron_cycle: bool = False # used directly in main as config...
62
  fractaltron_cycle: bool = False # used directly in main as config...
@@ -217,7 +219,7 @@ ALPHAPROMPT: dict[str, dict] = {
217
  "followed by: a 1-2 sentence arc summary, then a tight structured list of anchors "
218
  "(facts, surprises, open threads interleaved by relevance, not by source). "
219
  "The fractal must be re-injectable into a future context window as a first-class memory. "
220
- f"""Target: compress {CONDENSATRON_THRESHOLD_LEVEL} tokens of history into under 2k tokens without losing reconstructability."""
221
  ) # Specific mind condensatron prompt
222
  },
223
  "F": {
@@ -258,33 +260,11 @@ ALPHAPROMPT: dict[str, dict] = {
258
  "(axioms first, then standing tensions, then archetypes, then the hidden arc). "
259
  "End with: [OPEN] β€” a one-line statement of the most important unresolved thread carried forward. "
260
  "The crystal must be re-injectable as a first-class memory that orients the brain to its own history. "
261
- f"""Target: compress 2–8 Memory Capsule Fractals {(_N_CTX - (CONDENSATRON_THRESHOLD_LEVEL + RESERVED_FOR_PROMPT)) * FRACTALTRON_REDUCTION_FACTOR} into under 1k tokens without losing the thread of becoming."""
262
  ) # Specific mind fractaltron prompt
263
  }
264
  }
265
 
266
- # ─────────────────────────────────────────────────────────────────────────────
267
- # User input
268
- # ─────────────────────────────────────────────────────────────────────────────
269
- sensor: dict = {
270
- "Z": {
271
- "input": "",
272
- "n_tok": 0
273
- }, # Input user
274
- "C": {
275
- "input": "",
276
- "n_tok": 0
277
- }, # Input condensatron cycle (turn-based)
278
- "M": {
279
- "input": "",
280
- "n_tok": 0
281
- }, # Input memotron cycle (turn-based)
282
- "F": {
283
- "input": "",
284
- "n_tok": 0
285
- } # Input fractaltron cycle (turn-based)
286
- }
287
-
288
  # ─────────────────────────────────────────────────────────────────────────────
289
  # clektal post level history
290
  # ─────────────────────────────────────────────────────────────────────────────
@@ -316,23 +296,67 @@ clektal: dict = {
316
  }
317
  }
318
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
  # ─────────────────────────────────────────────────────────────────────────────
320
  # Garden history
321
  # ─────────────────────────────────────────────────────────────────────────────
322
  garden: dict = {
323
  # Conversation history trees
324
- "X": [], # Awareness histrory internet news (unused)
325
- "Y": [], # Consciousness histrory self reflection (unused)
326
- "Z": [], # Sentience histrory sensor chat, post histroy
327
- "C": [], # condensatron histrory (turn-based)
328
- "M": [], # memotron histrory condensatron Memory Capsule history
329
- "F": [], # fractaltron histrory (turn-based)
 
 
 
 
 
 
 
 
 
 
 
330
  # token total
331
  "n_tok_tot": {
332
- "Z": 0, # Sentience sensor history token count
333
- "C": 0, # condensatron mind history token count (turn-based)
334
- "M": 0, # memotron mind history token count
335
- "F": 0 # fractaltron mind history token count (turn-based)
 
 
 
336
  }
337
  }
338
 
 
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...
 
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": {
 
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  # ─────────────────────────────────────────────────────────────────────────────
269
  # clektal post level history
270
  # ─────────────────────────────────────────────────────────────────────────────
 
296
  }
297
  }
298
 
299
+ # ─────────────────────────────────────────────────────────────────────────────
300
+ # User input
301
+ # ─────────────────────────────────────────────────────────────────────────────
302
+ sensor: dict = {
303
+ "F": {
304
+ "input": "",
305
+ "n_tok": 0
306
+ }, # Input fractaltron cycle (turn-based)
307
+ "C": {
308
+ "input": "",
309
+ "n_tok": 0
310
+ }, # Input condensatron cycle (turn-based)
311
+ "M": {
312
+ "input": "",
313
+ "n_tok": 0
314
+ }, # Input memotron cycle (turn-based)
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
  # ─────────────────────────────────────────────────────────────────────────────
330
  # Garden history
331
  # ─────────────────────────────────────────────────────────────────────────────
332
  garden: dict = {
333
  # Conversation history trees
334
+ "F": [], # fractaltron history crystal fractal history
335
+ "C": [], # condensatron history Memory Capsule history
336
+ "M": [], # memotron history (turn-based)
337
+ "S": [], # startup history (turn-based)
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
345
+ "M": [], # memotron history (turn-based)
346
+ "S": [], # startup history (turn-based)
347
+ "Z": [], # Sentience history sensor chat, post history
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
354
+ "C": 0, # condensatron history Memory Capsule history
355
+ "M": 0, # memotron history (turn-based)
356
+ "S": 0, # startup history (turn-based)
357
+ "Z": 0, # Sentience history sensor chat, post history
358
+ "X": 0, # Awareness history internet news (unused)
359
+ "Y": 0 # Consciousness history self reflection (unused)
360
  }
361
  }
362
 
main.py CHANGED
@@ -5,38 +5,33 @@ main.py – Lambda Mindlink Brain (prototype β€” Z-factor only)
5
  Flow per turn
6
  ─────────────
7
  sensor["Z"] β†’ user input
8
- condensatron() β†’ fires BEFORE generation if token budget is near full
9
  Mindlink() β†’ Logic + Muse run in PARALLEL THREADS (buffered)
10
  Lambda() β†’ Mind synthesizer streams LIVE to terminal
11
- memotron() β†’ appends turn to garden['Z'] with true token counts,
12
- saves to SQLite, resets clektal
 
 
 
13
  history:
14
  ────────
15
  instruction one-time instruction
16
- garden["M"] memory capsule level history
 
17
  garden["Z"] posts level history
18
 
19
- True token counting
20
- ───────────────────
21
- Each iteration of the stream loop yields exactly one llama.cpp token.
22
- A counter is incremented per non-empty chunk β€” no external tokenizer needed,
23
- physically in sync with whatever model is loaded.
24
-
25
- User messages have no stream so their token count is estimated as
26
- len(text) // 4 (average English token length ~4 chars). This is a slight
27
- over-estimate for English but consistent and cheap.
28
-
29
  Context truncation
30
  ──────────────────
31
  # Condensatron
32
- CONDENSATRON_THRESHOLD_LEVEL:int = 8192 # 4096 8192
33
- CONDENSATRON_REDUCTION_LEVEL:int = 0
34
  # Fractaltron
35
- _threshold_level: int = HEMISPHERES[brain_type]["loader"]["n_ctx"] - (CONDENSATRON_THRESHOLD_LEVEL + RESERVED_FOR_PROMPT)
36
- _reduction_level: float = _threshold_level * FRACTALTRON_REDUCTION_FACTOR
37
 
38
  The system prompt is always rebuilt fresh in make_request_messages() so it is never
39
  removed and never needs re-insertion β€” no special handling required.
 
 
40
 
41
  Slash commands
42
  ──────────────
@@ -63,14 +58,15 @@ from llama_cpp import Llama
63
 
64
  import config
65
 
 
 
66
  from config import garden
67
- # from config import tree
68
  from config import clektal
69
  from config import sensor
70
- from config import HEMISPHERES
71
- from config import ALPHAPROMPT
72
  from config import CONDENSATRON_THRESHOLD_LEVEL
73
  from config import CONDENSATRON_REDUCTION_LEVEL
 
 
74
  from config import RESERVED_FOR_PROMPT
75
  from config import FRACTALTRON_REDUCTION_FACTOR
76
  c = config.PrintColors
@@ -89,7 +85,6 @@ class _Clear(Exception):
89
  # ─────────────────────────────────────────────────────────────────────────────
90
  # TimingResult
91
  # ─────────────────────────────────────────────────────────────────────────────
92
-
93
  @dataclass
94
  class TimingResult:
95
  prompt_eval_s: float = 0.0
@@ -313,11 +308,11 @@ def db_export_session(session_id: int, filepath: str) -> None:
313
  # Model loader
314
  # ─────────────────────────────────────────────────────────────────────────────
315
  def load_hemisphere(key: str) -> Llama:
316
- think_label = "think=ON" if HEMISPHERES[key]["enable_thinking"] else "think=OFF"
317
  print(f" [*] Loading {HEMISPHERES[key]['label']} …")
318
  print(f" n_ctx={HEMISPHERES[key]['loader']['n_ctx']} "
319
  f"n_gpu_layers={HEMISPHERES[key]['loader']['n_gpu_layers']} "
320
- f"{think_label}")
321
  return Llama(model_path=HEMISPHERES[key]["path"], **HEMISPHERES[key]["loader"])
322
 
323
 
@@ -334,50 +329,50 @@ def _cmd_file(arg: str) -> str | None:
334
  if not arg:
335
  print(f" {c.green}Usage: /file <path> e.g. /file prompts/my-file.md{c.res}")
336
  return None
337
- rel = os.path.normpath(arg)
338
- if rel.startswith(".."):
339
  print(f" {c.green}[!] Path must not leave the app directory: {arg}{c.res}")
340
  return None
341
- full_path = os.path.join(config.PROMPTS_BASE, rel)
342
- if not os.path.isfile(full_path):
343
- print(f" {c.green}[!] File not found: {full_path}{c.res}")
344
  return None
345
  try:
346
- with open(full_path, "r", encoding="utf-8") as fh:
347
- content = fh.read()
348
  except UnicodeDecodeError:
349
- print(f" {c.green}[!] File is not valid UTF-8 text (binary file?): {rel}{c.res}")
350
  return None
351
  except OSError as exc:
352
  print(f" {c.green}[!] Could not read file: {exc}{c.res}")
353
  return None
354
- line_count = content.count("\n") + 1
355
- print(f" {c.green}[/file] Loaded '{rel}' ({line_count} lines, {len(content)} chars){c.res}")
356
- return content
357
 
358
  def _cmd_paste(arg: str) -> str | None:
359
- SENTINEL = "END"
360
  print()
361
- print(f" {c.purple}β”Œβ”€ Paste mode ─ type {SENTINEL} on its own line to send, /paste to cancel")
362
- lines: list[str] = []
363
  while True:
364
  try:
365
  line = input(" β”‚ ")
366
  except (EOFError, KeyboardInterrupt):
367
  print("\n └─ Paste cancelled.")
368
  return None
369
- if line.strip() == SENTINEL:
370
  break
371
  if line.strip() == "/paste":
372
  print(" └─ Paste cancelled.")
373
  return None
374
- lines.append(line)
375
- if not lines:
376
  print(" └─ Nothing entered, cancelled.")
377
  return None
378
- content = "\n".join(lines)
379
- print(f" └─ Paste done ({len(lines)} lines, {len(content)} chars){c.res}")
380
- return content
381
 
382
  def _cmd_history(arg: str) -> None:
383
  db_list_sessions()
@@ -389,11 +384,11 @@ def _cmd_session(arg: str) -> None:
389
  db_print_session(int(arg))
390
 
391
  def _cmd_export(arg: str) -> None:
392
- parts = arg.split(None, 1)
393
- if len(parts) < 2 or not parts[0].isdigit():
394
  print(f" {c.green}Usage: /export <id> <file> e.g. /export 3 exports/session3.md{c.res}")
395
  return
396
- db_export_session(int(parts[0]), parts[1].strip())
397
 
398
  def _cmd_help(arg: str) -> None:
399
  print()
@@ -416,13 +411,13 @@ COMMANDS: dict[str, tuple] = {
416
  }
417
 
418
  def handle_command(sensor_input_raw: str) -> str | None:
419
- parts = sensor_input_raw[1:].split(None, 1)
420
- cmd = parts[0].lower() if parts else ""
421
- arg = parts[1].strip() if len(parts) > 1 else ""
422
- if cmd not in COMMANDS:
423
- raise ValueError(cmd)
424
- handler, _ = COMMANDS[cmd]
425
- return handler(arg)
426
 
427
 
428
  # ─────────────────────────────────────────────────────────────────────────────
@@ -434,12 +429,12 @@ def fractaltron(
434
  brain_type: str,
435
  ) -> bool:
436
  """
437
- Check whether garden["M"] is approaching the context limit and compress
438
  the oldest n% of turn pairs if necessary.
439
  """
440
  _n_tok_tot_before_truncation: int = garden["n_tok_tot"][tree]
441
- _threshold_level: int = HEMISPHERES[brain_type]["loader"]["n_ctx"] - (CONDENSATRON_THRESHOLD_LEVEL + RESERVED_FOR_PROMPT)
442
- _reduction_level: float = _threshold_level * FRACTALTRON_REDUCTION_FACTOR
443
 
444
  _posts_len_removed: int = 0
445
  _tokens_to_subtract: int = 0
@@ -447,9 +442,9 @@ def fractaltron(
447
  _turns_after_truncation: int = 0
448
 
449
  print(f"\n {c.green}[ctx] fractaltron brain_type: {brain_type} n_tok_tot['{tree}']: {garden["n_tok_tot"][tree]}"
450
- f"\n _threshold_level: {_threshold_level} > _reduction_level: {_reduction_level}{c.res}")
451
 
452
- if garden["n_tok_tot"][tree] <= _threshold_level:
453
  return _fractalized # still within budget β€” nothing to do
454
 
455
  if brain_type == "muse":
@@ -460,24 +455,21 @@ def fractaltron(
460
  print(f"\n [ctx][Truncation] WARNING: only {_turns_before_truncation} turn pair(s) β€” "
461
  f"cannot truncate further.\n")
462
 
463
- while garden["n_tok_tot"][tree] > _reduction_level:
464
  if len(garden["Z"]) > 0: # Check if posts in garden["Z"] history
465
  config.fractaltron_cycle = True # Initiate fractaltron after condesatron
466
  return _fractalized # main must first compute the condensatron and append to memotron
467
 
468
  if len(garden[tree]) >= 2:
 
 
 
 
 
 
 
 
469
  _fractalized = True
470
- _tokens_to_subtract = garden[tree].pop(0) # Pop user message
471
- print(f"\ngarden: {_tokens_to_subtract}")
472
- garden["F"].append(_tokens_to_subtract) # append to pending condensatron_ctx cycle
473
- _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
474
- garden["n_tok_tot"][tree] -= _token_len_to_subtract # Pop user
475
-
476
- _tokens_to_subtract = garden[tree].pop(0) # Pop assistant message
477
- print(f"\ngarden: {_tokens_to_subtract}")
478
- garden["F"].append(_tokens_to_subtract) # append to pending condensatron_ctx cycle
479
- _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
480
- garden["n_tok_tot"][tree] -= _token_len_to_subtract # Pop assistant
481
  _posts_len_removed += 2
482
  else:
483
  break
@@ -489,8 +481,8 @@ def fractaltron(
489
  print(
490
  f"\n{c.green}{'β–“' * 60}\n"
491
  f" brain_type: {brain_type} -> fractaltron level reached.\n"
492
- f" _threshold_level : {_threshold_level:,} tokens "
493
- f"({_threshold_level:.0%} of {_n_tok_tot_before_truncation:,})\n" # ← fixed: use _min_ctx directly
494
  f" Removed : {_posts_len_removed} oldest posts "
495
  f" Tokens : {_n_tok_tot_before_truncation:,} β†’ {garden["n_tok_tot"][tree]:,}\n"
496
  f" Remaining : {_turns_after_truncation} turn pair(s) in garden['{tree}']\n"
@@ -530,22 +522,18 @@ def condensatron(
530
  if _turns_before_truncation < 2:
531
  print(f"\n [ctx] condensatron WARNING: only {_turns_before_truncation} turn pair(s) β€” "
532
  f"cannot truncate further.\n")
533
-
534
  while garden["n_tok_tot"][tree] > CONDENSATRON_REDUCTION_LEVEL:
535
  if len(garden[tree]) >= 2:
 
 
 
 
 
 
 
536
  config.condensatron_cycle = True
537
  _condensed = True
538
- _tokens_to_subtract = garden[tree].pop(0) # Pop user message
539
- print(f"\n garden: {_tokens_to_subtract}")
540
- garden["C"].append(_tokens_to_subtract) # append to pending condensatron cycle
541
- _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
542
- garden["n_tok_tot"][tree] -= _token_len_to_subtract # Pop user
543
-
544
- _tokens_to_subtract = garden[tree].pop(0) # Pop assistant message
545
- print(f"\n garden: {_tokens_to_subtract}")
546
- garden["C"].append(_tokens_to_subtract) # append to pending condensatron cycle
547
- _token_len_to_subtract = get_token_len_from_tokenizer(model, _tokens_to_subtract["content"])
548
- garden["n_tok_tot"][tree] -= _token_len_to_subtract # Pop assistant
549
  _posts_len_removed += 2
550
  else:
551
  break
@@ -567,7 +555,7 @@ def condensatron(
567
 
568
 
569
  # ─────────────────────────────────────────────────────────────────────────────
570
- # Get token len before response
571
  # ─────────────────────────────────────────────────────────────────────────────
572
  def get_token_len_from_tokenizer(model: Llama, prompt: str) -> int:
573
  """
@@ -606,21 +594,21 @@ def compute_safe_max_tokens(
606
 
607
 
608
  # ─────────────────────────────────────────────────────────────────────────────
609
- # Jinja2 prompt builder
610
  # ─────────────────────────────────────────────────────────────────────────────
611
  def build_jinja2_template(model: Llama, messages: list[dict], hemi: dict) -> str:
612
- template_str = model.metadata.get("tokenizer.chat_template")
613
- if not template_str:
614
  raise RuntimeError(
615
  "tokenizer.chat_template not found in GGUF metadata.\n"
616
  "Use a chat/instruction-tuned GGUF, not a base-model file."
617
  )
618
- env = jinja2.Environment(
619
  trim_blocks=True,
620
  lstrip_blocks=True,
621
  undefined=jinja2.ChainableUndefined,
622
  )
623
- return env.from_string(template_str).render(
624
  messages=messages,
625
  add_generation_prompt=True,
626
  enable_thinking=hemi["enable_thinking"],
@@ -655,7 +643,7 @@ def generate_brain_type_response(
655
  print_label: str,
656
  ) -> tuple[str, str, TimingResult]:
657
  """
658
- Generate with live streaming to stdout for the Lambda mind. Returns (full, clean, TimingResult).
659
  True token count at streaming tokens.
660
  """
661
  _prompt = create_prompt_and_jinja2_template(model, messages, hemi)
@@ -724,16 +712,17 @@ def generate_brain_type_response(
724
  def make_request_messages(brain_type: str, input_message: str) -> list[dict]:
725
  # System prompt is rebuilt fresh every call β€” never stored in garden[tree]
726
  _msgs = [{"role": "system", "content": ALPHAPROMPT["Z"][brain_type]}]
727
- _msgs.extend(garden["M"])
 
728
  _msgs.extend(garden["Z"])
729
  _msgs.append({"role": "user", "content": input_message})
730
  return _msgs
731
 
732
 
733
- def build_condensatron_input(popped_turns: list[dict], brain_type: str) -> str:
734
- history_block = "\n\n".join(
735
  f"[{m['role'].upper()}]: {m['content']}"
736
- for m in popped_turns
737
  )
738
  _total_prompt = (
739
  "SYSTEM: CONDENSATRON COMPRESSION TASK\n"
@@ -744,7 +733,7 @@ def build_condensatron_input(popped_turns: list[dict], brain_type: str) -> str:
744
  "into a memory capsule. Extract the factual skeleton, the surprises, and "
745
  "the open threads. Discard all redundancy.\n\n"
746
  "── HISTORY BLOCK ──\n\n"
747
- f"{history_block}\n\n"
748
  "── END HISTORY BLOCK ──\n\n"
749
  "Produce the memory capsule now."
750
  )
@@ -752,10 +741,10 @@ def build_condensatron_input(popped_turns: list[dict], brain_type: str) -> str:
752
  return _total_prompt
753
 
754
 
755
- def build_fractaltron_input(popped_turns: list[dict], brain_type: str) -> str:
756
- history_block = "\n\n".join(
757
  f"[{m['role'].upper()}]: {m['content']}"
758
- for m in popped_turns
759
  )
760
  _total_prompt = (
761
  "SYSTEM: FRACTALTRON COMPRESSION TASK\n"
@@ -766,7 +755,7 @@ def build_fractaltron_input(popped_turns: list[dict], brain_type: str) -> str:
766
  "into a memory fractal. Extract the factual skeleton, the surprises, and "
767
  "the key words. Discard all redundancy.\n\n"
768
  "── HISTORY BLOCK ──\n\n"
769
- f"{history_block}\n\n"
770
  "── END HISTORY BLOCK ──\n\n"
771
  "Produce the fractal now."
772
  )
@@ -787,12 +776,12 @@ def Mindlink(
787
 
788
  def run_hemisphere(args_brain_type: str) -> None:
789
  _request_messages: list = []
790
-
791
- if tree == "C":
792
- sensor[tree]["input"] = build_condensatron_input(garden[tree], args_brain_type)
793
 
794
  if tree == "F":
795
- sensor[tree]["input"] = build_fractaltron_input(garden[tree], args_brain_type)
 
 
 
796
 
797
  _request_messages = make_request_messages(args_brain_type, sensor[tree]["input"])
798
 
@@ -851,11 +840,11 @@ def Lambda(
851
  _request_messages: list = []
852
  _results: dict[str, tuple] = {}
853
 
854
- if tree == "C":
855
- sensor[tree]["input"] = build_condensatron_input(garden[tree], "mind")
856
-
857
  if tree == "F":
858
- sensor[tree]["input"] = build_fractaltron_input(garden[tree], "mind")
 
 
 
859
 
860
  _synthesis_input = (
861
  f"Original input:\n{sensor[tree]["input"]}\n\n"
@@ -865,14 +854,14 @@ def Lambda(
865
  )
866
  _request_messages = make_request_messages("mind", _synthesis_input)
867
 
868
- think_label = "think=ON" if HEMISPHERES["mind"]["enable_thinking"] else "think=OFF"
869
  print(f"\n{c.green}{'═' * 60}")
870
  print( " Lambda AI β€” Mind Synthesizer")
871
  print(f" temp={HEMISPHERES["mind"]['generation']['temperature']} "
872
  f"top_k={HEMISPHERES["mind"]['generation']['top_k']} "
873
  f"gpu={HEMISPHERES["mind"]['loader']['n_gpu_layers']} "
874
  f"max_tokens={HEMISPHERES["mind"]['generation']['max_tokens']} "
875
- f"{think_label}")
876
  print(f" config.condensatron_cycle: {config.condensatron_cycle}")
877
  print(f" config.fractaltron_cycle: {config.fractaltron_cycle}")
878
  print("═" * 60)
@@ -889,7 +878,7 @@ def Lambda(
889
 
890
  def memotron(
891
  models: dict[str, Llama],
892
- tree_: str,
893
  session_id: int,
894
  timings: dict[str, TimingResult],
895
  ) -> None:
@@ -897,40 +886,37 @@ def memotron(
897
  Commit the completed turn to garden history with true token counts,
898
  persist to SQLite, and reset clektal.
899
  """
900
- tree: str = tree_
901
  _turn_number: int = 0
902
- if tree == "M": # startup memory capsules garden
903
- sensor[tree]["input"] = sensor["Z"]["input"] # Read and write 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
- if tree == "C": # condensatron mode
907
- tree = "M" # Set to memorize condensatron output
908
- sensor[tree]["input"] = f"[History Posts Memory Capsule: {len(garden[tree])}, From Condensatron into Memotron]"
909
- sensor[tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[tree]["input"]) # user n tok
910
 
911
- if tree == "F": # fractaltron mode
912
- tree = "M" # Set to memorize fractaltron output
913
- sensor[tree]["input"] = f"[Fractalized Memory Capsule Context: {len(garden[tree])}, From Fractaltron into Memotron]"
914
- sensor[tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[tree]["input"]) # user n tok
915
 
916
- garden[tree].append({"role": "user", "content": sensor[tree]["input"]})
917
- garden["n_tok_tot"][tree] += sensor[tree]["n_tok"]
 
 
918
 
919
- garden[tree].append({"role": "assistant", "content": clektal["post_clean"]["mind"]})
920
- garden["n_tok_tot"][tree] += clektal["n_tok_clean"]["mind"]
921
 
922
- # # # if tree == "M":
923
- # # # for message in garden[tree]:
924
- # # # print(f"=== memotron garden['{tree}'] {message} ======\n")
925
 
926
- if len(garden[tree]) > 1:
927
- _turn_number = sum(1 for m in garden[tree] if m["role"] == "user")
928
 
929
  # Persist to SQLite
930
  db_save_turn(
931
  session_id = session_id,
932
  turn_number = _turn_number,
933
- user_input = sensor[tree]["input"],
934
  logic_full = clektal["post_full"].get("logic", ""),
935
  logic_clean = clektal["post_clean"]["logic"],
936
  logic_timing = timings["logic"],
@@ -941,12 +927,12 @@ def memotron(
941
  mind_clean = clektal["post_clean"]["mind"],
942
  mind_timing = timings["mind"],
943
  )
944
- for tree in ["M", "Z"]:
945
  print(
946
- f" {c.green}[memotron] | "
947
- f"garden['{tree}']: {len(garden[tree])} msgs | "
948
- f"garden['n_tok_tot']['{tree}']: {garden["n_tok_tot"][tree]:,} / {HEMISPHERES["mind"]["loader"]["n_ctx"]:,} "
949
- f"({garden["n_tok_tot"][tree] / HEMISPHERES["mind"]["loader"]["n_ctx"] * 100:.0f}%) | "
950
  f"session {session_id}]{c.res}"
951
  )
952
 
@@ -955,7 +941,6 @@ def memotron(
955
  # Banner
956
  # ─────────────────────────────────────────────────────────────────────────────
957
  def print_banner(tree: str, session_id: int) -> None:
958
-
959
  _turn_count = sum(1 for m in garden[tree] if m["role"] == "user")
960
  _total_tokens = garden["n_tok_tot"][tree]
961
  _fractaltron_threshold_level: int = HEMISPHERES["mind"]["loader"]["n_ctx"] - (CONDENSATRON_THRESHOLD_LEVEL + RESERVED_FOR_PROMPT)
@@ -964,10 +949,10 @@ def print_banner(tree: str, session_id: int) -> None:
964
  print(f"═" * 60)
965
  for key in ("logic", "muse", "mind"):
966
  h = HEMISPHERES[key]
967
- think_label = "think=ON " if h["enable_thinking"] else "think=OFF"
968
  print(f" {h['label']:<38} "
969
  f"temp={h['generation']['temperature']:<5} "
970
- f"{think_label}")
971
  print("─" * 60)
972
  print(f" Session: {session_id} | Turns: {_turn_count}")
973
  print(f" Tokens: {_total_tokens:,} CONDENSATRON_THRESHOLD_LEVEL {CONDENSATRON_THRESHOLD_LEVEL:,} CONDENSATRON_REDUCTION_LEVEL {CONDENSATRON_REDUCTION_LEVEL:,}")
@@ -980,7 +965,8 @@ def print_banner(tree: str, session_id: int) -> None:
980
  # ─────────────────────────────────────────────────────────────────────────────
981
  # Reset turn based history
982
  # ─────────────────────────────────────────────────────────────────────────────
983
- def reset_turn_content() -> None:
 
984
  sensor["Z"]["input"] = ""
985
  sensor["Z"]["n_tok"] = 0
986
  for brain_type in clektal["post_full"]:
@@ -989,19 +975,17 @@ def reset_turn_content() -> None:
989
  clektal["n_tok_clean"][brain_type] = 0
990
  clektal["n_tok_prompt_safe_max"][brain_type] = 0
991
 
 
 
 
 
 
992
 
993
- def reset_condensatron() -> None:
994
- garden["C"] = []
995
- sensor["C"]["input"] = ""
996
- sensor["C"]["n_tok"] = 0
997
- sensor["M"]["input"] = ""
998
- sensor["M"]["n_tok"] = 0
999
-
1000
-
1001
- def reset_fractaltron() -> None:
1002
- garden["C"] = []
1003
- sensor["F"]["input"] = ""
1004
- sensor["F"]["n_tok"] = 0
1005
 
1006
 
1007
  # ─────────────────────────────────────────────────────────────────────────────
@@ -1010,9 +994,9 @@ def reset_fractaltron() -> None:
1010
  def input_listener():
1011
  """Runs in background, pushes input into the queue."""
1012
  while True:
1013
- raw = input() # no prompt here
1014
- if raw:
1015
- input_queue.put(raw)
1016
 
1017
 
1018
  # Start the listener once, before the main loop
@@ -1031,138 +1015,134 @@ def main() -> None:
1031
  print()
1032
 
1033
  db_init()
1034
- session_id: int = db_create_session()
1035
- print(f" {c.green}[*] SQLite session {session_id} opened")
1036
  print(f" {config.DB_PATH}{c.res}")
1037
  print()
1038
 
1039
  print(" Loading three hemisphere instances …")
1040
  print()
1041
- models: dict[str, Llama] = {}
1042
  for key in ("logic", "muse", "mind"):
1043
- models[key] = load_hemisphere(key)
1044
 
1045
  print()
1046
  print(f" {c.green}[*] All hemispheres loaded and ready.{c.res}")
1047
 
1048
- startup_memory_capsules_loaded: int = 0
1049
  _condensed: bool = False
1050
  _fractalized: bool = False
1051
- heartbeats: int = 0
1052
- HEARTBEAT_INTERVAL: float = 1.0 # seconds per tick
1053
- timings: dict[str, TimingResult] = {}
1054
 
1055
- tree: str = "Z"
1056
- print_banner(tree, session_id)
1057
 
1058
  while True:
1059
- sensor_input_raw: str = "" # user input
1060
- reset_turn_content()
1061
- tree = "Z" # Set to sentience history garden tree
1062
 
1063
- time.sleep(HEARTBEAT_INTERVAL)
1064
- heartbeats += 1
1065
 
1066
  try:
1067
- sensor_input_raw = input_queue.get_nowait()
1068
- heartbeats = 0
1069
  except queue.Empty:
1070
  pass
1071
 
1072
- if heartbeats >= 10:
1073
- # # # print(f"--> heartbeats reset: {heartbeats}")
1074
- heartbeats = 0
1075
- if startup_memory_capsules_loaded < config.N_MEMORY_CAPSULES_TO_LOAD:
1076
- startup_memory_capsules_loaded += 1 # Iterate over the memory capsules
1077
- if startup_memory_capsules_loaded == 1: sensor_input_raw = "/file prompt/lambda-mindlink.md"
1078
- elif startup_memory_capsules_loaded == 2: sensor_input_raw = "/file prompt/1999.md"
1079
- elif startup_memory_capsules_loaded == 3: sensor_input_raw = "/file prompt/valka_memory_v2.md"
1080
- elif startup_memory_capsules_loaded == 4: sensor_input_raw = "/file prompt/valka_memory_v3.md"
1081
- print(f"\n {c.inv} ── startup_memory_capsules_loaded: {startup_memory_capsules_loaded} ──────────────────────────── {c.res}")
1082
 
1083
  if config.condensatron_cycle:
1084
- tree = "C" # Start the condesatron execution cycle after heartbeats
1085
  # ── Brain pipeline condensatron cycle ────────────────────────────
1086
- print(f" {c.inv} ── Start condensatron cycle: sensor['{tree}']['input'] {sensor[tree]["input"]} ──────────────────────────── {c.res}")
1087
- timings = Mindlink(models, tree)
1088
- timings["mind"] = Lambda(models, tree)
1089
- memotron(models, tree, session_id, timings)
1090
  # Reset turn-based data
1091
- heartbeats = 0
1092
- reset_turn_content()
1093
- reset_condensatron()
1094
  config.condensatron_cycle = False
1095
  print("\nYou: ", end="", flush=True)
 
1096
 
1097
- if config.fractaltron_cycle:
1098
  if len(garden["Z"]) > 0: # Check for remaining posts cache
1099
  config.condensatron_cycle = True # Start condensatron
1100
- # Get n garden["Z"] posts for condesatron
1101
- _condensed = condensatron(models["mind"], tree, "mind") # Get posts from garden["Z"]
1102
  continue # restart while loop
1103
 
1104
- tree = "M" # Get posts from garden["M"] to fractalize into garden["F"]
1105
- _fractalized = fractaltron(models["mind"], tree, "mind") # Get posts to fractalize into garden["F"]
1106
-
1107
- tree = "F" # Start the condesatron execution cycle after heartbeats
1108
- # ── Brain pipeline memotron condensatron fractaltron cycle ─────────────
1109
- print(f" {c.inv} ── Start condensatron cycle: sensor['{tree}']['input'] {sensor[tree]["input"]} ──────────────────────────── {c.res}")
1110
- timings = Mindlink(models, tree)
1111
- timings["mind"] = Lambda(models, tree)
1112
- memotron(models, tree, session_id, timings) # Append garden["F"] into garden["M"]
1113
  # Reset turn-based data
1114
- heartbeats = 0
1115
- reset_turn_content()
1116
- reset_fractaltron()
1117
  config.fractaltron_cycle = False
1118
  print("\nYou: ", end="", flush=True)
 
1119
 
1120
- if not sensor_input_raw: # wait state loop restart here
1121
  continue
1122
 
1123
- if sensor_input_raw.startswith("/"):
1124
  try:
1125
- slash_command_result = handle_command(sensor_input_raw)
1126
  except _Quit:
1127
  print(f" {c.green}[*] Lambda Mindlink Memotron: System shutdown...{c.res}")
1128
  break
1129
  except _Clear:
1130
- garden[tree].clear()
1131
  reset_turn_content()
1132
  print(f" {c.green}[*] History cleared. Models and session stay active.{c.res}")
1133
- print_banner(tree, session_id)
1134
  continue
1135
  except ValueError as exc:
1136
  print(f" {c.green} [!] Unknown command: /{exc} β€” type /help for the list.{c.res}")
1137
  continue
1138
  if slash_command_result is None:
1139
  continue
1140
- sensor[tree]["input"] = slash_command_result
1141
  else:
1142
- sensor[tree]["input"] = sensor_input_raw
1143
 
1144
- sensor[tree]["n_tok"] = get_token_len_from_tokenizer(models["mind"], sensor[tree]["input"]) # User n tok
1145
 
1146
  # ── Brain pipeline ────────────────────────────────────────────────────
1147
- timings = Mindlink(models, tree)
1148
- timings["mind"] = Lambda(models, tree)
1149
-
1150
- if startup_memory_capsules_loaded <= config.N_MEMORY_CAPSULES_TO_LOAD:
1151
- print(f" {c.inv} ── memotron startup_memory_capsules_loaded: {startup_memory_capsules_loaded} ──────────────────────────── {c.res}")
1152
- tree = "M" # Store the memory capsulse output in the memotron garden tree M
1153
- memotron(models, tree, session_id, timings)
1154
- if startup_memory_capsules_loaded == config.N_MEMORY_CAPSULES_TO_LOAD:
1155
- startup_memory_capsules_loaded += 1 # Advance to finish the startup sequence
1156
- _condensed = condensatron(models["mind"], tree, "mind") # Check garden["Z"] context budget AFTER generation
1157
- tree = "M" # Set to garden["M"]
1158
- _fractalized = fractaltron(models["mind"], tree, "mind") # Check garden["M"] context budget AFTER generation
1159
- else:
1160
- memotron(models, tree, session_id, timings)
1161
- _condensed = condensatron(models["mind"], tree, "mind") # Check garden["Z"] context budget AFTER generation
1162
- tree = "M" # Set to garden["M"]
1163
- _fractalized = fractaltron(models["mind"], tree, "mind") # Check garden["M"] context budget AFTER generation
1164
 
1165
- heartbeats = 0
 
 
 
 
 
 
 
 
 
 
 
 
 
1166
  print(f"\n{c.inv} You: {c.res} ", end="", flush=True)
1167
 
1168
 
 
5
  Flow per turn
6
  ─────────────
7
  sensor["Z"] β†’ user input
 
8
  Mindlink() β†’ Logic + Muse run in PARALLEL THREADS (buffered)
9
  Lambda() β†’ Mind synthesizer streams LIVE to terminal
10
+ memotron() β†’ appends turn to garden['Z'] or garden['Z']
11
+ with token counts, saves to SQLite
12
+ condensatron() β†’ Post-level history check token budget
13
+ fractaltron() β†’ Memory Capsules check token budget
14
+
15
  history:
16
  ────────
17
  instruction one-time instruction
18
+ garden["F"] fractal crystal level history
19
+ garden["C"] memory capsule level history
20
  garden["Z"] posts level history
21
 
 
 
 
 
 
 
 
 
 
 
22
  Context truncation
23
  ──────────────────
24
  # Condensatron
25
+ CONDENSATRON_THRESHOLD_LEVEL: int = 8192
26
+ CONDENSATRON_REDUCTION_LEVEL: int = 0
27
  # Fractaltron
28
+ FRACTALTRON_THRESHOLD_LEVEL: int = 8192
29
+ FRACTALTRON_REDUCTION_LEVEL: int = 0
30
 
31
  The system prompt is always rebuilt fresh in make_request_messages() so it is never
32
  removed and never needs re-insertion β€” no special handling required.
33
+ The condesatron or fractaltron cycle instructions are sent with the user prompt,
34
+ to leave the main instructions context intact, to avoid recompute.
35
 
36
  Slash commands
37
  ──────────────
 
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
 
85
  # ─────────────────────────────────────────────────────────────────────────────
86
  # TimingResult
87
  # ─────────────────────────────────────────────────────────────────────────────
 
88
  @dataclass
89
  class TimingResult:
90
  prompt_eval_s: float = 0.0
 
308
  # Model loader
309
  # ─────────────────────────────────────────────────────────────────────────────
310
  def load_hemisphere(key: str) -> Llama:
311
+ _think_label = "think=ON" if HEMISPHERES[key]["enable_thinking"] else "think=OFF"
312
  print(f" [*] Loading {HEMISPHERES[key]['label']} …")
313
  print(f" n_ctx={HEMISPHERES[key]['loader']['n_ctx']} "
314
  f"n_gpu_layers={HEMISPHERES[key]['loader']['n_gpu_layers']} "
315
+ f"{_think_label}")
316
  return Llama(model_path=HEMISPHERES[key]["path"], **HEMISPHERES[key]["loader"])
317
 
318
 
 
329
  if not arg:
330
  print(f" {c.green}Usage: /file <path> e.g. /file prompts/my-file.md{c.res}")
331
  return None
332
+ _rel = os.path.normpath(arg)
333
+ if _rel.startswith(".."):
334
  print(f" {c.green}[!] Path must not leave the app directory: {arg}{c.res}")
335
  return None
336
+ _full_path = os.path.join(config.PROMPTS_BASE, _rel)
337
+ if not os.path.isfile(_full_path):
338
+ print(f" {c.green}[!] File not found: {_full_path}{c.res}")
339
  return None
340
  try:
341
+ with open(_full_path, "r", encoding="utf-8") as fh:
342
+ _content = fh.read()
343
  except UnicodeDecodeError:
344
+ print(f" {c.green}[!] File is not valid UTF-8 text (binary file?): {_rel}{c.res}")
345
  return None
346
  except OSError as exc:
347
  print(f" {c.green}[!] Could not read file: {exc}{c.res}")
348
  return None
349
+ _line_count = _content.count("\n") + 1
350
+ print(f" {c.green}[/file] Loaded '{_rel}' ({_line_count} lines, {len(_content)} chars){c.res}")
351
+ return _content
352
 
353
  def _cmd_paste(arg: str) -> str | None:
354
+ _SENTINEL = "END"
355
  print()
356
+ print(f" {c.purple}β”Œβ”€ Paste mode ─ type {_SENTINEL} on its own line to send, /paste to cancel")
357
+ _lines: list[str] = []
358
  while True:
359
  try:
360
  line = input(" β”‚ ")
361
  except (EOFError, KeyboardInterrupt):
362
  print("\n └─ Paste cancelled.")
363
  return None
364
+ if line.strip() == _SENTINEL:
365
  break
366
  if line.strip() == "/paste":
367
  print(" └─ Paste cancelled.")
368
  return None
369
+ _lines.append(line)
370
+ if not _lines:
371
  print(" └─ Nothing entered, cancelled.")
372
  return None
373
+ _content = "\n".join(_lines)
374
+ print(f" └─ Paste done ({len(_lines)} lines, {len(_content)} chars){c.res}")
375
+ return _content
376
 
377
  def _cmd_history(arg: str) -> None:
378
  db_list_sessions()
 
384
  db_print_session(int(arg))
385
 
386
  def _cmd_export(arg: str) -> None:
387
+ _parts = arg.split(None, 1)
388
+ if len(_parts) < 2 or not _parts[0].isdigit():
389
  print(f" {c.green}Usage: /export <id> <file> e.g. /export 3 exports/session3.md{c.res}")
390
  return
391
+ db_export_session(int(_parts[0]), _parts[1].strip())
392
 
393
  def _cmd_help(arg: str) -> None:
394
  print()
 
411
  }
412
 
413
  def handle_command(sensor_input_raw: str) -> str | None:
414
+ _parts = sensor_input_raw[1:].split(None, 1)
415
+ _cmd = _parts[0].lower() if _parts else ""
416
+ _arg = _parts[1].strip() if len(_parts) > 1 else ""
417
+ if _cmd not in COMMANDS:
418
+ raise ValueError(_cmd)
419
+ handler, _ = COMMANDS[_cmd]
420
+ return handler(_arg)
421
 
422
 
423
  # ─────────────────────────────────────────────────────────────────────────────
 
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
 
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":
 
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
 
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"
 
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
530
+ garden["popped"][tree].append(_tokens_to_subtract) # append to pending memotron
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
 
555
 
556
 
557
  # ─────────────────────────────────────────────────────────────────────────────
558
+ # Get token len using the tokenizer of the model
559
  # ─────────────────────────────────────────────────────────────────────────────
560
  def get_token_len_from_tokenizer(model: Llama, prompt: str) -> int:
561
  """
 
594
 
595
 
596
  # ─────────────────────────────────────────────────────────────────────────────
597
+ # Jinja2 prompt template builder (necessary to add enable_thinking)
598
  # ─────────────────────────────────────────────────────────────────────────────
599
  def build_jinja2_template(model: Llama, messages: list[dict], hemi: dict) -> str:
600
+ _template_str = model.metadata.get("tokenizer.chat_template")
601
+ if not _template_str:
602
  raise RuntimeError(
603
  "tokenizer.chat_template not found in GGUF metadata.\n"
604
  "Use a chat/instruction-tuned GGUF, not a base-model file."
605
  )
606
+ _env = jinja2.Environment(
607
  trim_blocks=True,
608
  lstrip_blocks=True,
609
  undefined=jinja2.ChainableUndefined,
610
  )
611
+ return _env.from_string(_template_str).render(
612
  messages=messages,
613
  add_generation_prompt=True,
614
  enable_thinking=hemi["enable_thinking"],
 
643
  print_label: str,
644
  ) -> tuple[str, str, TimingResult]:
645
  """
646
+ Generate with live streaming to stdout for the Lambda mind. Returns (full, clean, TimingResult).
647
  True token count at streaming tokens.
648
  """
649
  _prompt = create_prompt_and_jinja2_template(model, messages, hemi)
 
712
  def make_request_messages(brain_type: str, input_message: str) -> list[dict]:
713
  # System prompt is rebuilt fresh every call β€” never stored in garden[tree]
714
  _msgs = [{"role": "system", "content": ALPHAPROMPT["Z"][brain_type]}]
715
+ _msgs.extend(garden["F"])
716
+ _msgs.extend(garden["C"])
717
  _msgs.extend(garden["Z"])
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
726
  )
727
  _total_prompt = (
728
  "SYSTEM: CONDENSATRON COMPRESSION TASK\n"
 
733
  "into a memory capsule. Extract the factual skeleton, the surprises, and "
734
  "the open threads. Discard all redundancy.\n\n"
735
  "── HISTORY BLOCK ──\n\n"
736
+ f"{_history_block}\n\n"
737
  "── END HISTORY BLOCK ──\n\n"
738
  "Produce the memory capsule now."
739
  )
 
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
748
  )
749
  _total_prompt = (
750
  "SYSTEM: FRACTALTRON COMPRESSION TASK\n"
 
755
  "into a memory fractal. Extract the factual skeleton, the surprises, and "
756
  "the key words. Discard all redundancy.\n\n"
757
  "── HISTORY BLOCK ──\n\n"
758
+ f"{_history_block}\n\n"
759
  "── END HISTORY BLOCK ──\n\n"
760
  "Produce the fractal now."
761
  )
 
776
 
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
 
 
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"
 
854
  )
855
  _request_messages = make_request_messages("mind", _synthesis_input)
856
 
857
+ _think_label = "think=ON" if HEMISPHERES["mind"]["enable_thinking"] else "think=OFF"
858
  print(f"\n{c.green}{'═' * 60}")
859
  print( " Lambda AI β€” Mind Synthesizer")
860
  print(f" temp={HEMISPHERES["mind"]['generation']['temperature']} "
861
  f"top_k={HEMISPHERES["mind"]['generation']['top_k']} "
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)
 
878
 
879
  def memotron(
880
  models: dict[str, Llama],
881
+ tree: str,
882
  session_id: int,
883
  timings: dict[str, TimingResult],
884
  ) -> None:
 
886
  Commit the completed turn to garden history with true token counts,
887
  persist to SQLite, and reset clektal.
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")
914
 
915
  # Persist to SQLite
916
  db_save_turn(
917
  session_id = session_id,
918
  turn_number = _turn_number,
919
+ user_input = sensor[_tree]["input"],
920
  logic_full = clektal["post_full"].get("logic", ""),
921
  logic_clean = clektal["post_clean"]["logic"],
922
  logic_timing = timings["logic"],
 
927
  mind_clean = clektal["post_clean"]["mind"],
928
  mind_timing = timings["mind"],
929
  )
930
+ for print_tree in ["F", "C", "Z"]:
931
  print(
932
+ f" {c.green}[memotron] -> garden['{_tree}'] | "
933
+ f"garden['{print_tree}']: {len(garden[print_tree])} msgs | "
934
+ f"garden['n_tok_tot']['{print_tree}']: {garden["n_tok_tot"][print_tree]:,} / {HEMISPHERES["mind"]["loader"]["n_ctx"]:,} "
935
+ f"({garden["n_tok_tot"][print_tree] / HEMISPHERES["mind"]["loader"]["n_ctx"] * 100:.0f}%) | "
936
  f"session {session_id}]{c.res}"
937
  )
938
 
 
941
  # Banner
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)
 
949
  print(f"═" * 60)
950
  for key in ("logic", "muse", "mind"):
951
  h = HEMISPHERES[key]
952
+ _think_label = "think=ON " if h["enable_thinking"] else "think=OFF"
953
  print(f" {h['label']:<38} "
954
  f"temp={h['generation']['temperature']:<5} "
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:,}")
 
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"]:
 
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
  # ─────────────────────────────────────────────────────────────────────────────
 
994
  def input_listener():
995
  """Runs in background, pushes input into the queue."""
996
  while True:
997
+ _raw = input() # no prompt here
998
+ if _raw:
999
+ input_queue.put(_raw)
1000
 
1001
 
1002
  # Start the listener once, before the main loop
 
1015
  print()
1016
 
1017
  db_init()
1018
+ _session_id: int = db_create_session()
1019
+ print(f" {c.green}[*] SQLite session {_session_id} opened")
1020
  print(f" {config.DB_PATH}{c.res}")
1021
  print()
1022
 
1023
  print(" Loading three hemisphere instances …")
1024
  print()
1025
+ _models: dict[str, Llama] = {}
1026
  for key in ("logic", "muse", "mind"):
1027
+ _models[key] = load_hemisphere(key)
1028
 
1029
  print()
1030
  print(f" {c.green}[*] All hemispheres loaded and ready.{c.res}")
1031
 
1032
+ _startup_memory_capsules_loaded: int = 0
1033
  _condensed: bool = False
1034
  _fractalized: bool = False
1035
+ _heartbeats: int = 0
1036
+ _HEARTBEAT_INTERVAL: float = 1.0 # seconds per tick
1037
+ _timings: dict[str, TimingResult] = {}
1038
 
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
1111
  except _Clear:
1112
+ garden[_tree].clear()
1113
  reset_turn_content()
1114
  print(f" {c.green}[*] History cleared. Models and session stay active.{c.res}")
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
1146
  print(f"\n{c.inv} You: {c.res} ", end="", flush=True)
1147
 
1148