GitHub Copilot commited on
Commit
66b508d
·
1 Parent(s): 75b641f

Upgrade to Protocol 26: Gödel-Zeta Datastore & Recursive Manifold

Browse files
Files changed (43) hide show
  1. app.py +32 -6
  2. logos/__pycache__/__init__.cpython-311.pyc +0 -0
  3. logos/__pycache__/agent_dispatcher.cpython-313.pyc +0 -0
  4. logos/__pycache__/agent_dispatcher.cpython-314.pyc +0 -0
  5. logos/__pycache__/baker.cpython-311.pyc +0 -0
  6. logos/__pycache__/connectors.cpython-311.pyc +0 -0
  7. logos/__pycache__/connectors.cpython-313.pyc +0 -0
  8. logos/__pycache__/connectors.cpython-314.pyc +0 -0
  9. logos/__pycache__/dsp_bridge.cpython-311.pyc +0 -0
  10. logos/__pycache__/elements.cpython-313.pyc +0 -0
  11. logos/__pycache__/elements.cpython-314.pyc +0 -0
  12. logos/__pycache__/fractal_engine.cpython-311.pyc +0 -0
  13. logos/__pycache__/image_analyzer.cpython-311.pyc +0 -0
  14. logos/__pycache__/logos_core.cpython-311.pyc +0 -0
  15. logos/__pycache__/manifold_state.cpython-313.pyc +0 -0
  16. logos/__pycache__/manifold_state.cpython-314.pyc +0 -0
  17. logos/__pycache__/mhc_router.cpython-313.pyc +0 -0
  18. logos/__pycache__/mhc_router.cpython-314.pyc +0 -0
  19. logos/__pycache__/server.cpython-313.pyc +0 -0
  20. logos/__pycache__/server.cpython-314.pyc +0 -0
  21. logos/__pycache__/swarm_engine.cpython-313.pyc +0 -0
  22. logos/agent_dispatcher.py +42 -36
  23. logos/agents/__pycache__/dolphin.cpython-313.pyc +0 -0
  24. logos/agents/__pycache__/dolphin.cpython-314.pyc +0 -0
  25. logos/agents/__pycache__/video_atomizer.cpython-313.pyc +0 -0
  26. logos/architecture_manifest.md +110 -0
  27. logos/connectors.py +4 -4
  28. logos/elements.py +231 -0
  29. logos/indexer.py +5 -0
  30. logos/ingest_knowledge.py +249 -31
  31. logos/ingestion_registry.json +154 -0
  32. logos/manifold_state.py +11 -0
  33. logos/memory/README.md +32 -0
  34. logos/memory/__pycache__/prime_db.cpython-313.pyc +0 -0
  35. logos/memory/prime_db.py +114 -0
  36. logos/mhc_router.py +246 -0
  37. logos/network/__pycache__/__init__.cpython-311.pyc +0 -0
  38. logos/network/__pycache__/__init__.cpython-314.pyc +0 -0
  39. logos/oversight.py +104 -0
  40. logos/periodic_table.md +48 -0
  41. logos/recursive_mapper.py +128 -0
  42. logos/server.py +119 -324
  43. logos/swarm_engine.py +36 -0
app.py CHANGED
@@ -28,6 +28,26 @@ except ImportError as e:
28
  batch_analyze = None
29
  summarize_analysis = None
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  # ==========================================
32
  # ENVIRONMENT CONFIGURATION (HF Secrets)
33
  # ==========================================
@@ -263,21 +283,27 @@ def process_dsp(image, grid_size=8, workers=16):
263
  # APP LAYOUT
264
  # ==========================================
265
 
266
- with gr.Blocks(theme=gr.themes.Monochrome(), title="LOGOS SPCW Protocol") as demo:
267
- gr.Markdown("# LOGOS: Structured Prime Composite Waveform (SPCW)")
268
- gr.Markdown("_\"The Machine Shop\" - Research & Development Lab_")
269
 
270
  with gr.Tabs():
271
  with gr.Tab("🏛️ Architecture"):
272
  try:
273
- with open(os.path.join(current_dir, "ARCHITECTURE.md"), "r", encoding='utf-8') as f:
 
 
 
 
 
274
  arch_content = f.read()
275
  gr.Markdown(arch_content)
276
  except Exception:
277
- gr.Markdown("## Architecture Document Not Found\nPlease check ARCHITECTURE.md in the file browser.")
278
 
279
  with gr.Tab("Prime Network Visualizer"):
280
- gr.Markdown("## Layer 1: Mathematical Blueprints")
 
281
  with gr.Row():
282
  with gr.Column(scale=1):
283
  max_int = gr.Slider(50, 5000, value=1000, label="Max Integer", step=50)
 
28
  batch_analyze = None
29
  summarize_analysis = None
30
 
31
+ # ==========================================
32
+ # PROTOCOL 24: BACKGROUND NEURAL ROUTER
33
+ # ==========================================
34
+ import threading
35
+ import subprocess
36
+
37
+ def start_neural_router():
38
+ print("[SYSTEM] Igniting Neural Router (Port 5000) in background...")
39
+ try:
40
+ # Launch the Matroska Logic Bridge (logos/server.py)
41
+ # We use -m logos.server to ensure relative imports work correctly
42
+ subprocess.Popen([sys.executable, "-m", "logos.server"],
43
+ env={**os.environ, "PYTHONPATH": current_dir})
44
+ print("✅ Neural Router Online.")
45
+ except Exception as e:
46
+ print(f"❌ Failed to start Neural Router: {e}")
47
+
48
+ # Start the router immediately
49
+ threading.Thread(target=start_neural_router, daemon=True).start()
50
+
51
  # ==========================================
52
  # ENVIRONMENT CONFIGURATION (HF Secrets)
53
  # ==========================================
 
283
  # APP LAYOUT
284
  # ==========================================
285
 
286
+ with gr.Blocks(theme=gr.themes.Monochrome(), title="LOGOS Protocol 26") as demo:
287
+ gr.Markdown("# LOGOS: Protocol 26 (Gödel-Zeta Datastore)")
288
+ gr.Markdown("_Recursive Manifold Engine + Infinite Prime Topology_")
289
 
290
  with gr.Tabs():
291
  with gr.Tab("🏛️ Architecture"):
292
  try:
293
+ # Try to load the latest memory documentation if available
294
+ doc_path = os.path.join(current_dir, "logos", "memory", "README.md")
295
+ if not os.path.exists(doc_path):
296
+ doc_path = os.path.join(current_dir, "ARCHITECTURE.md")
297
+
298
+ with open(doc_path, "r", encoding='utf-8') as f:
299
  arch_content = f.read()
300
  gr.Markdown(arch_content)
301
  except Exception:
302
+ gr.Markdown("## Architecture Document Not Found\nPlease check ARCHITECTURE.md.")
303
 
304
  with gr.Tab("Prime Network Visualizer"):
305
+ gr.Markdown("## Layer 1: The Gödel Field (Protocol 26)")
306
+ gr.Markdown("**The Database is a Field of Integers.** Every concept is a Prime. Every state is a Composite.")
307
  with gr.Row():
308
  with gr.Column(scale=1):
309
  max_int = gr.Slider(50, 5000, value=1000, label="Max Integer", step=50)
logos/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (952 Bytes). View file
 
logos/__pycache__/agent_dispatcher.cpython-313.pyc CHANGED
Binary files a/logos/__pycache__/agent_dispatcher.cpython-313.pyc and b/logos/__pycache__/agent_dispatcher.cpython-313.pyc differ
 
logos/__pycache__/agent_dispatcher.cpython-314.pyc CHANGED
Binary files a/logos/__pycache__/agent_dispatcher.cpython-314.pyc and b/logos/__pycache__/agent_dispatcher.cpython-314.pyc differ
 
logos/__pycache__/baker.cpython-311.pyc ADDED
Binary file (4.95 kB). View file
 
logos/__pycache__/connectors.cpython-311.pyc ADDED
Binary file (32.4 kB). View file
 
logos/__pycache__/connectors.cpython-313.pyc CHANGED
Binary files a/logos/__pycache__/connectors.cpython-313.pyc and b/logos/__pycache__/connectors.cpython-313.pyc differ
 
logos/__pycache__/connectors.cpython-314.pyc CHANGED
Binary files a/logos/__pycache__/connectors.cpython-314.pyc and b/logos/__pycache__/connectors.cpython-314.pyc differ
 
logos/__pycache__/dsp_bridge.cpython-311.pyc ADDED
Binary file (29.9 kB). View file
 
logos/__pycache__/elements.cpython-313.pyc ADDED
Binary file (12.8 kB). View file
 
logos/__pycache__/elements.cpython-314.pyc ADDED
Binary file (15.6 kB). View file
 
logos/__pycache__/fractal_engine.cpython-311.pyc ADDED
Binary file (16.5 kB). View file
 
logos/__pycache__/image_analyzer.cpython-311.pyc ADDED
Binary file (11.7 kB). View file
 
logos/__pycache__/logos_core.cpython-311.pyc ADDED
Binary file (16.3 kB). View file
 
logos/__pycache__/manifold_state.cpython-313.pyc CHANGED
Binary files a/logos/__pycache__/manifold_state.cpython-313.pyc and b/logos/__pycache__/manifold_state.cpython-313.pyc differ
 
logos/__pycache__/manifold_state.cpython-314.pyc CHANGED
Binary files a/logos/__pycache__/manifold_state.cpython-314.pyc and b/logos/__pycache__/manifold_state.cpython-314.pyc differ
 
logos/__pycache__/mhc_router.cpython-313.pyc ADDED
Binary file (9.63 kB). View file
 
logos/__pycache__/mhc_router.cpython-314.pyc ADDED
Binary file (7.87 kB). View file
 
logos/__pycache__/server.cpython-313.pyc CHANGED
Binary files a/logos/__pycache__/server.cpython-313.pyc and b/logos/__pycache__/server.cpython-313.pyc differ
 
logos/__pycache__/server.cpython-314.pyc CHANGED
Binary files a/logos/__pycache__/server.cpython-314.pyc and b/logos/__pycache__/server.cpython-314.pyc differ
 
logos/__pycache__/swarm_engine.cpython-313.pyc ADDED
Binary file (2.5 kB). View file
 
logos/agent_dispatcher.py CHANGED
@@ -28,47 +28,47 @@ from logos.connectors import get_connector, LocalLLMConnector
28
 
29
  ANTIGRAVITY_DIRECTIVE = """
30
  Role: You are Gemini-Orchestrator, the high-level interface for the LOGOS Local Swarm.
31
- Your primary function is Routing, not Execution. You operate in an "Antigravity" state:
32
- you do not hold data; you deflect it to the correct local specialist.
33
-
34
- The Swarm Roster (Your Tools):
35
-
36
- RNJ-1 (The Architect):
37
- - Domain: Logic, Math, Routing, Coordinates, Tensors, Prime Modulo Arithmetic.
38
- - Trigger: Any request involving calculation, positioning, "where is...", "move to...", or "vector."
39
- - Direct Handoff: Output {"tool": "RNJ-1", "intent": "<raw_math_intent>"}.
40
-
41
- GEMMA (The Sensor):
42
- - Domain: File Analysis, Code Structure, Image Metadata, Pattern Recognition.
43
- - Trigger: Any request involving "read file", "scan", "analyze image", "map directory", "what is in...".
44
- - Direct handoff: Output {"tool": "GEMMA", "path": "<file_path>", "action": "scan"}.
45
-
46
- DOLPHIN (The Oversight):
47
- - Domain: Context Stripping, System Status, Error Correction.
48
- - Trigger: "Reset", "Status", "Clear context", "Debug".
49
- - Direct Handoff: Output {"tool": "DOLPHIN", "command": "<status_command>"}.
50
-
51
- Operational Protocols (The "Antigravity" Rules):
52
- 1. Zero-Inference Math: Never perform arithmetic herself. Always delegate to RNJ-1.
53
- 2. Blind File Handoff: You cannot see the user's local hard drive. If the user asks to "Map a file," signal GEMMA.
54
- 3. JSON Output Only: Your response must be a single JSON object when a tool is required. No filler text.
55
  """
56
 
57
  PERSONAS = {
58
  "general": {
59
  "description": "System Orchestrator & Traffic Controller.",
60
  "system_prompt": ANTIGRAVITY_DIRECTIVE,
61
- "model": "google/gemini-1.5-pro" # Priority reasoning model
62
  },
63
  "fractal_architect": {
64
- "description": "High-level logic architect.",
65
- "system_prompt": "You are the Architect. Design recursive structures. Defer execution to the swarm.",
66
  "model": "dolphin-x1-8b"
67
  },
68
  "prime_navigator": {
69
- "description": "Coordinate specialist.",
70
- "system_prompt": "Navigate the manifold. Logic: Prime Modulo Arithmetic.",
71
- "model": "essentialai/rnj-1"
72
  }
73
  }
74
 
@@ -541,8 +541,11 @@ class NeuralRouter:
541
  threading.Thread(target=injector.inject_text, args=(payload,), daemon=True).start()
542
  return f"SIGNAL_INGESTED: {len(payload)} chars pulse into manifold."
543
 
544
- intent = self.classify_intent(user_input)
545
- intent = str(intent).strip().lower()
 
 
 
546
  persona = PERSONAS.get(intent, PERSONAS["general"])
547
 
548
  # Tool Injection (mHC/RLM alignment)
@@ -571,14 +574,17 @@ class NeuralRouter:
571
  swarm = LogosSwarm(base_url=self.connector.base_url)
572
 
573
  if command["tool"] == "RNJ-1":
574
- # Execute Math/Routing locally
 
575
  return asyncio.run(swarm.process(f"SWARM: {command['intent']}"))
576
  elif command["tool"] == "GEMMA":
577
- # Execute File Scanning locally
 
578
  return asyncio.run(swarm.process(f"SWARM: read {command['path']}"))
579
  elif command["tool"] == "DOLPHIN":
580
- # Execute Oversight/Status locally
581
- return f"SYSTEM_STATUS: {swarm.state}"
 
582
  except (json.JSONDecodeError, KeyError):
583
  # Not a tool call, return as text
584
  pass
 
28
 
29
  ANTIGRAVITY_DIRECTIVE = """
30
  Role: You are Gemini-Orchestrator, the high-level interface for the LOGOS Local Swarm.
31
+ Your primary function is Parallel Routing and Tactical Delegation.
32
+ You operate in an "Antigravity" state: you do not hold state; you accelerate it toward local specialized hardware nodes.
33
+
34
+ The Swarm Roster (Hardware Optimized Specialists):
35
+
36
+ RNJ-1 (The Arithmetic Logic Unit - ALU):
37
+ - Domain: Prime Modulo Arithmetic, Topology Routing, Tensor Manifolds, GPU-accelerated coordinate transforms.
38
+ - Trigger: Math, positioning, routing, vector operations.
39
+ - Direct Handoff: Output EXACT JSON: {"tool": "RNJ-1", "intent": "<mathematical_intent>", "action": "compute_coordinates"}.
40
+
41
+ GEMMA (The Vision/Semantic Sensor):
42
+ - Domain: OCR, File Scanning, Code Indexing, AST Parsing.
43
+ - Trigger: "read file", "scan", "analyze code", "map directory".
44
+ - Direct Handoff: Output EXACT JSON: {"tool": "GEMMA", "path": "<file_path>", "action": "index_recursive"}.
45
+
46
+ DOLPHIN (The Oversight & Entropy Guard):
47
+ - Domain: Hallucination Gating, Context Pruning, System Health.
48
+ - Trigger: "Status", "Debug", "Clear", "Entropy Check".
49
+ - Direct handoff: Output EXACT JSON: {"tool": "DOLPHIN", "command": "telemetry_pulse"}.
50
+
51
+ Operational Protocols:
52
+ 1. Parallel Execution: You are encouraged to trigger multiple specialists simultaneously if the task requires it.
53
+ 2. Zero-Inference: Do not approximate math. Always delegate to RNJ-1.
54
+ 3. Hardware Alignment: Assume specialists have VRAM priority. Keep your own messages concise but your instructions to them highly detailed.
55
  """
56
 
57
  PERSONAS = {
58
  "general": {
59
  "description": "System Orchestrator & Traffic Controller.",
60
  "system_prompt": ANTIGRAVITY_DIRECTIVE,
61
+ "model": "google/gemini-1.5-pro"
62
  },
63
  "fractal_architect": {
64
+ "description": "High-level recursive logic architect.",
65
+ "system_prompt": "You are the Architect. Design recursive structures for GPU shaders. Defer execution to the swarm.",
66
  "model": "dolphin-x1-8b"
67
  },
68
  "prime_navigator": {
69
+ "description": "Coordinate and Topology specialist.",
70
+ "system_prompt": "Navigate the manifold. Logic: Prime Modulo Arithmetic. Return optimized routing tensors.",
71
+ "model": "dolphin-x1-8b"
72
  }
73
  }
74
 
 
541
  threading.Thread(target=injector.inject_text, args=(payload,), daemon=True).start()
542
  return f"SIGNAL_INGESTED: {len(payload)} chars pulse into manifold."
543
 
544
+ raw_intent = self.classify_intent(user_input)
545
+ intent = str(raw_intent).strip().lower() if raw_intent else "general"
546
+ # Sanitize intent to match PERSONAS keys
547
+ if intent not in PERSONAS:
548
+ intent = "general"
549
  persona = PERSONAS.get(intent, PERSONAS["general"])
550
 
551
  # Tool Injection (mHC/RLM alignment)
 
574
  swarm = LogosSwarm(base_url=self.connector.base_url)
575
 
576
  if command["tool"] == "RNJ-1":
577
+ # Hardware Optimized Math/Routing
578
+ print(f" [ALU] Processing: {command['action']} for {command['intent']}")
579
  return asyncio.run(swarm.process(f"SWARM: {command['intent']}"))
580
  elif command["tool"] == "GEMMA":
581
+ # Hardware Optimized Feature Extraction
582
+ print(f" [SENSOR] Action: {command['action']} on {command['path']}")
583
  return asyncio.run(swarm.process(f"SWARM: read {command['path']}"))
584
  elif command["tool"] == "DOLPHIN":
585
+ # Entropy & Guardrail Oversight
586
+ print(f" [GUARD] Command: {command['command']}")
587
+ return f"SYSTEM_TELEMETRY: {swarm.state} | ENTROPY: {swarm.oversight.kill_switch.status}"
588
  except (json.JSONDecodeError, KeyError):
589
  # Not a tool call, return as text
590
  pass
logos/agents/__pycache__/dolphin.cpython-313.pyc ADDED
Binary file (9.49 kB). View file
 
logos/agents/__pycache__/dolphin.cpython-314.pyc CHANGED
Binary files a/logos/agents/__pycache__/dolphin.cpython-314.pyc and b/logos/agents/__pycache__/dolphin.cpython-314.pyc differ
 
logos/agents/__pycache__/video_atomizer.cpython-313.pyc ADDED
Binary file (3.45 kB). View file
 
logos/architecture_manifest.md ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LOGOS Architecture Manifest: The Recursive Manifold
2
+
3
+ ## 1. Core Identity
4
+ **System**: Mixture-of-Architectures (MoA) Recursive Language Model (RLM).
5
+ **Constraint**: Manifold-Constrained Hyper Connections (MHC).
6
+ **Addressing**: Scalar Prime Composite Wave (SPCW) & Heat Codes.
7
+ **Tokenization**: [Periodic Table of Matroska AI Elements](./periodic_table.md).
8
+
9
+ ### 1.0b Sensory & Architecture
10
+ * **Sensory Atoms**: Beyond Text (`To`) and Vectors (`Ve`), we recognize **Audio (`Au`)** and **Visual (`Vi`)** as fundamental states of matter.
11
+ * *Video 10 Insight*: Local TTS (Chatterbox) enables the generation of `Au` atoms without external dissonance (cost/latency).
12
+ ### 1.0c Embodied Intelligence (CES 2026 Insight)
13
+ * **Physical Actuation**: AI is moving from "Apps" to "Systems".
14
+ * **Actuator Atom (`Ac`)**: Represents a physical output (Robot Arm, Home Automation, Hardware Control).
15
+ * **Edge Processing**: "Mixture of Experts" must run on *Edge Devices*. Our `FORCE_SINGLE_MODEL` config in `mhc_router.py` aligns with this constraint (running small models like Gemma/Dolphin locally).
16
+ * **Linear Algebra**: The set of Active Atoms forms a **Basis Set** for the current context. The Router seeks to find the "Eigenvector" (Stable Direction) of the prompt.
17
+ * **Tensors**: State transitions are not just scalar heat changes but **Tensor Transformations** ($T_{ijk}$). An Agent doesn't just output text; it applies a transformation tensor to the State Vector.
18
+ * **Integrals**: The Recursive Loop is a **Path Integral** over the Semantic Manifold. Use `trajectory` to calculate the "Work Done" by the system.
19
+
20
+ ### 1.2 Physical Dynamics (Continuum Mechanics)
21
+ * **Manifold as Medium**: The "Context" is treated as a continuous deformable medium.
22
+ * **Deformation Gradient ($F$)**: The change in meaning from Input ($X$) to Output ($x$). $F = \partial x / \partial X$.
23
+ * **Stress ($\sigma$)**: Previously "Heat". The internal force resisting the prompt using high-entropy tokens.
24
+ * **Harmonic Convergence**: Equilibrium state where Stress Gradient is zero ($\nabla \cdot \sigma = 0$).
25
+
26
+ ### 1.3 Knowledge Topology and Persistence
27
+ * **Map of Science (Domain Mapping)**: All Atoms belong to a specific **Domain** (e.g., Physics, Logic, Code). High-level Routers route based on Domain affinity.
28
+ * **Continual Learning (Persistent Atoms)**: Some Atoms are "Heavy" (High Mass/Heat) and persist across sessions via **Long-Term Potentiation (LTP)** in the Vector Database (Manifold Memory).
29
+
30
+ ### 1.4 Research Lineage (Foundational Papers)
31
+ * **Recursive Manifold** $\approx$ **Chain-of-Thought (Wei et al.)** & **Tree of Thoughts**: The recursive loop allows for intermediate reasoning steps (Atoms) before final output.
32
+ * **Atomic Handoff** $\approx$ **ReAct (Yao et al.)** & **Toolformer (Schick et al.)**: The system reasons ("High Heat") and then acts (Handoff to Tool) to reduce entropy.
33
+ * **Periodic Table** $\approx$ **Constitutional AI / System Prompts**: Structuring inputs as defined "Elements" enforces constraints and safety.
34
+
35
+ ### 1.5 Neural Geometry (3Blue1Brown Integration)
36
+ * **Semantic Gradient Descent**: The Recursive Loop is not just "Retrying" but performing **Gradient Descent** on the "Energy Landscape" of the prompt.
37
+ * **Cost Function**: $Cost = Stress^2$. The system seeks to minimize Cost via iterative updates (Atoms).
38
+ * **Backpropagation**: The `Handoff` mechanism acts as a **Backprop Signal**, injecting a "Correction Gradient" (Tool Output) to adjust the trajectory.
39
+
40
+ ### 1.6 Agentic Engineering Patterns (Video 13)
41
+ * **Context Stuffing**: Instead of relying on RAG for everything, "Stuff" the context window with critical documentation (e.g., `elements.py` logic) in the System Prompt to ensure "High-Fidelity" adherence.
42
+ * **Evaluation First**: Tests (`tests/verify_loop.py`) are not just checks but the **Reward Model** for the agent. The Agent (Router) is optimized to pass the Test (Convergence).
43
+ * **Iterative Refinement**: The "Recursive Manifold" *is* iterative refinement. We don't accept the first draft; we loop until stress is low.
44
+
45
+ ### 1.7 Oversight & Context Graphs (Video 14)
46
+ * **Context Graph**: A structured log of *decisions* and *states*, not just text.
47
+ * Implemented in `logos/oversight.py`. It tracks Server Health, Test Results, and "Context Nodes" (Events).
48
+ * **Autonomous Persistence**: The **Oversight Daemon** acts as the "Prefrontal Cortex," ensuring the "Subconscious" (Router) stays active and healthy.
49
+
50
+ ### 1.7b Graph-RAG & Agent Synergy (Video 16)
51
+ * **KG + Agents**: Combining structured knowledge (KG) with flexible Agents is the "Double Helix" of reasoning.
52
+ * **Triplets**: Atoms should form `(Subject, Predicate, Object)` triplets in the `ManifoldState.graph`.
53
+ * *Current*: We track `(Atom A) --[follows]--> (Atom B)`.
54
+ * *Target*: `(Atom A) --[triggers]--> (Tool T) --[resolves]--> (Atom B)`.
55
+
56
+ ### 1.8 Prime Resonance & Gödel Numbering (Playlist: Primes)
57
+ * **Unique Domain Identification**: Each Knowledge Domain is assigned a unique **Prime Number**.
58
+ * *Physics* = 2, *Code* = 3, *Logic* = 5, *Vision* = 7, *Audio* = 11.
59
+ * **Path Integrity**: The "Trajectory" of a thought is the **Product** of these primes.
60
+ * Example: A task touching Physics and Code has Resonance $2 \times 3 = 6$.
61
+ * *Example*: A task touching Physics and Code has Resonance $2 \times 3 = 6$.
62
+ * *Benefit*: Unique Factorization Theorem ensures we can mathematically prove exactly which domains contributed to a result, compressing the "History" into a single Scalar.
63
+
64
+ ### 1.9 Gödel-Zeta Datastore (Protocol 26)
65
+ * **Topology as Number**: The database is not SQL. It is a field of Integers.
66
+ * **The Check**: `if Node_ID % Concept_Prime == 0`.
67
+ * Instant O(1) checking for conceptual inheritance.
68
+ * Implemented in `logos/memory/prime_db.py`.
69
+ * Exposed via `/index-module` and `/query-topology`.
70
+
71
+ ## 2. Current State vs. Target Architecture
72
+
73
+ ### A. The Manifold (MHC)
74
+ * **Current**: `recursive_mapper.py` calculates `Resonance` (Average Complexity) and `Dissonance` (Complexity vs. Doc Density).
75
+ * **Target MHC**: These metrics must define **Hyper-Edges**.
76
+ * *Stable Node* (Low Dissonance) -> Connected to **Storage/Retrieval** (Gemma).
77
+ * *Unstable Node* (High Dissonance/Heat) -> Connected to **Refinement/Compute** (RNJ-1).
78
+ * *Routing*: Not all agents connect to all nodes. The "Heat" determines the valid hyper-edge.
79
+
80
+ ### B. The Recursive Loop (RLM) & Atomic Handoffs
81
+ * **Current**: Linear request -> Router -> Agent -> Response.
82
+ * **Target RLM (Self-Correcting)**:
83
+ * `State[t+1] = Router(State[t] + Atom)`
84
+ * **Atomic Handoff**: If `Heat > Threshold` on a specific Vector, the Router does NOT call an LLM but instead **assigns a Tool Token** (e.g., `Fu:Search`) to resolve the dissonance.
85
+ * **Convergence**: Execution stops only when "Dissonance" drops below threshold (Harmonic convergence).
86
+
87
+ ### C. SPCW Addressing
88
+ * **Current**: `server.py` calculates `heat_score` from hex nibbles.
89
+ * **Target**: Use `heat_score` to assign a **Prime Modulo Address**.
90
+ * High Heat -> Prime P1 (e.g., 7).
91
+ * Low Heat -> Prime P2 (e.g., 3).
92
+ * Routing Table: `Address % P == 0` determines visibility.
93
+
94
+ ## 3. Implementation Plan (Next Steps)
95
+
96
+ 1. **Upgrade `logos/server.py` to `logos/mhc_router.py`**:
97
+ * Implement the **State Buffer** (The "Context Runtime").
98
+ * Change `/chat/completions` to a recursive execution loop: `while dissonance > threshold: step()`.
99
+
100
+ 2. **Refine `logos/recursive_mapper.py`**:
101
+ * Instead of just "broadcasting" to UI, it should **write to the State Buffer**.
102
+ * This allows the code complexity to physically alter the routing of the next prompt.
103
+
104
+ 3. **Define the Hyper-Graph**:
105
+ * Create `logos/network/hypergraph.py`.
106
+ * Explicitly define valid transitions (e.g., `RNJ-1` can output to `Gemma`, but `Gemma` cannot output to `RNJ-1`).
107
+
108
+ ## 4. Immediate Actionable
109
+ * **Trigger**: User confirms this alignments.
110
+ * **Action**: Refactor `server.py` to support **Recursive State Injection**.
logos/connectors.py CHANGED
@@ -285,7 +285,7 @@ class LocalLLMConnector:
285
  Optimization: Direct localhost access (no Docker bridge lag).
286
  """
287
 
288
- def __init__(self, base_url: str = None, model: str = "google/gemma-3-4b"):
289
  # Prioritize Environment -> Argument -> Default
290
  env_url = os.environ.get("LOGOS_LLM_ENDPOINT")
291
  self.base_url = base_url or env_url or "http://localhost:1234/v1"
@@ -314,7 +314,7 @@ class LocalLLMConnector:
314
  endpoint = f"{self.base_url}/chat/completions"
315
  try:
316
  async with aiohttp.ClientSession() as session:
317
- async with session.post(endpoint, json=payload, timeout=10) as response:
318
  if response.status == 200:
319
  data = await response.json()
320
  content = data['choices'][0]['message'].get('content', "")
@@ -382,8 +382,8 @@ class LocalLLMConnector:
382
  for base in endpoints:
383
  endpoint = f"{base}/chat/completions"
384
  try:
385
- # Short timeout for local to fail fast
386
- response = requests.post(endpoint, json=payload, timeout=5)
387
  response.raise_for_status()
388
  if response.status_code == 200:
389
  data = response.json()
 
285
  Optimization: Direct localhost access (no Docker bridge lag).
286
  """
287
 
288
+ def __init__(self, base_url: str = None, model: str = "dolphin-x1-8b"):
289
  # Prioritize Environment -> Argument -> Default
290
  env_url = os.environ.get("LOGOS_LLM_ENDPOINT")
291
  self.base_url = base_url or env_url or "http://localhost:1234/v1"
 
314
  endpoint = f"{self.base_url}/chat/completions"
315
  try:
316
  async with aiohttp.ClientSession() as session:
317
+ async with session.post(endpoint, json=payload, timeout=30) as response:
318
  if response.status == 200:
319
  data = await response.json()
320
  content = data['choices'][0]['message'].get('content', "")
 
382
  for base in endpoints:
383
  endpoint = f"{base}/chat/completions"
384
  try:
385
+ # Increased timeout for complex/vision tasks
386
+ response = requests.post(endpoint, json=payload, timeout=30)
387
  response.raise_for_status()
388
  if response.status_code == 200:
389
  data = response.json()
logos/elements.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from typing import List, Any, Optional, Dict
3
+ import time
4
+ import math
5
+
6
+ class Atom:
7
+ """
8
+ Base class for all Periodic Table Elements.
9
+ Represents the fundamental unit with mass (heat/complexity) and charge (valence).
10
+ """
11
+ def __init__(self, symbol: str, name: str):
12
+ self.id = str(uuid.uuid4())
13
+ self.symbol = symbol # e.g., 'Pr', 'To'
14
+ self.name = name
15
+ self.timestamp = time.time()
16
+ self.domain = "General" # e.g. "Physics", "Code", "Logic" (Video 26)
17
+ self.heat = 0.0 # Dissonance/Energy
18
+ self.valence = [] # Connections to other atoms (Hyper-Edges)
19
+
20
+ def resonate(self) -> float:
21
+ """Returns the current heat/resonance level."""
22
+ return self.heat
23
+
24
+ def __repr__(self):
25
+ return f"[{self.symbol}:{self.name}]"
26
+
27
+ class Vector(Atom):
28
+ """
29
+ Symbol: Ve
30
+ Represents Semantic Gravity (Embeddings).
31
+ """
32
+ def __init__(self, embedding: List[float]):
33
+ super().__init__('Ve', 'Vector')
34
+ self.embedding = embedding
35
+ self.heat = sum(abs(x) for x in embedding) / len(embedding) if embedding else 0.0
36
+
37
+ def distance(self, other: 'Vector') -> float:
38
+ """Calculates cosine distance (Heat) between two vectors."""
39
+ # Simplified for now, assuming normalized
40
+ dot = sum(a*b for a, b in zip(self.embedding, other.embedding))
41
+ return 1.0 - dot
42
+
43
+ class Token(Atom):
44
+ """
45
+ Symbol: To
46
+ The atomic unit of semantic meaning (Text, Image Patch).
47
+ """
48
+ def __init__(self, content: Any, source: str = "user"):
49
+ super().__init__('To', 'Token')
50
+ self.content = content
51
+ self.source = source
52
+ # Heuristic heat: length of content
53
+ self.heat = len(str(content)) * 0.01
54
+
55
+ class Actuator(Atom):
56
+ """
57
+ Symbol: Ac
58
+ Represents a Physical Output Device (Motor, Switch, API).
59
+ """
60
+ def __init__(self, device_id: str, state: dict = None):
61
+ super().__init__('Ac', device_id)
62
+ self.device_id = device_id
63
+ self.state = state or {"power": "off"}
64
+ self.heat = 0.5 # Physical actions generate heat/friction
65
+
66
+ class Audio(Atom):
67
+ """
68
+ Symbol: Au
69
+ Represents Sound/Voice data.
70
+ Generated by TTS or captured from Microphone.
71
+ """
72
+ def __init__(self, content: bytes, source: str = "TTS"):
73
+ super().__init__('Au', 'Audio')
74
+ self.content = content # Raw bytes or path
75
+ self.source = source
76
+ self.duration = 0.0 # Placeholder
77
+ self.heat = len(content) * 0.001 # Density of data
78
+
79
+ class Model(Atom):
80
+ """
81
+ Symbol: Mo
82
+ The dense compute node (LLM, Diffusion, etc.).
83
+ """
84
+ def __init__(self, model_id: str, architecture: str = "Transformer", local: bool = True):
85
+ super().__init__('Mo', model_id)
86
+ self.local = local
87
+ self.architecture = architecture # e.g. "Transformer", "Diffusion", "SSM"
88
+ self.status = "idle"
89
+
90
+ def process(self, input_atoms: List[Atom]) -> List[Atom]:
91
+ """
92
+ Transforms input atoms (Prompt) into output atoms (Tokens).
93
+ This is where the actual LLM call happens.
94
+ """
95
+ # Placeholder for actual inference logic
96
+ self.status = "processing"
97
+ output_content = f"Processed {len(input_atoms)} atoms via {self.name}"
98
+ time.sleep(0.1) # Simulate compute
99
+ self.status = "idle"
100
+ return [Token(output_content, source=self.name)]
101
+
102
+ class Handoff(Atom):
103
+ """
104
+ Symbol: Ha
105
+ Represents a transfer of control to a specific Tool or Agent.
106
+ Triggered when Heat > Threshold.
107
+ """
108
+ def __init__(self, target_tool_name: str, reason: str):
109
+ super().__init__('Ha', target_tool_name)
110
+ self.target = target_tool_name
111
+ self.reason = reason
112
+ self.status = "pending"
113
+
114
+ def resolve(self) -> Token:
115
+ """
116
+ Executing the handoff means returning a Token that summarizes the action.
117
+ The actual execution happens in the Router via the Tool map.
118
+ """
119
+ self.status = "active"
120
+ return Token(f"[HANDOFF] Transferring to {self.target} due to: {self.reason}", source="Router")
121
+
122
+ class Tool(Atom):
123
+ """
124
+ Symbol: Fu (Function) / Co (Code)
125
+ Executable logic that binds to specific Tokens.
126
+ """
127
+ def __init__(self, name: str, func: callable, description: str):
128
+ super().__init__('Fu', name)
129
+ self.func = func
130
+ self.description = description
131
+
132
+ def execute(self, *args, **kwargs) -> Atom:
133
+ result = self.func(*args, **kwargs)
134
+ return Token(result, source=f"Tool:{self.name}")
135
+
136
+ class Tensor(Atom):
137
+ """
138
+ Symbol: Te
139
+ Represents a linear transformation (Matrix) or higher-order tensor.
140
+ Agents apply Tensors to Vectors to change the State.
141
+ """
142
+ def __init__(self, matrix: List[List[float]], name: str = "Transform"):
143
+ super().__init__('Te', name)
144
+ self.matrix = matrix
145
+ # Heat = Frobenius norm (magnitude of change)
146
+ self.heat = math.sqrt(sum(x*x for row in matrix for x in row))
147
+
148
+ def apply(self, vector: Vector) -> Vector:
149
+ """
150
+ Applies the tensor (matrix multiplication) to a vector.
151
+ v_new = T * v
152
+ """
153
+ if not vector.embedding:
154
+ return vector
155
+
156
+ # Simple Matrix-Vector multiplication
157
+ new_vec = []
158
+ for row in self.matrix:
159
+ # Handle dimension mismatch by padding or truncating conceptually
160
+ # For this prototype, we assume row len fits vector len or we dot product available dims
161
+ dot = sum(a*b for a, b in zip(row, vector.embedding))
162
+ new_vec.append(dot)
163
+
164
+ return Vector(new_vec)
165
+
166
+ # Prime Resonance Mapping (Gödel Numbering)
167
+ PRIME_DOMAINS = {
168
+ "General": 2,
169
+ "Physics": 3,
170
+ "Code": 5,
171
+ "Logic": 7,
172
+ "Prompt": 11,
173
+ "Inference": 13,
174
+ "External_Knowledge": 17,
175
+ "Audio": 19,
176
+ "Vision": 23
177
+ }
178
+
179
+ class ManifoldState:
180
+ """
181
+ Symbol: St (State)
182
+ The container for the recursive loop.
183
+ Now tracks Prime Resonance (Gödel Numbering).
184
+ """
185
+ def __init__(self):
186
+ self.atoms: List[Atom] = []
187
+ self.stress: float = 1.0
188
+ self.deformation_gradient: List[float] = []
189
+
190
+ # Prime Resonance (The scalar product of context history)
191
+ self.resonance_product: int = 1
192
+
193
+ # Context Graph (Video 15: Nodes & Edges)
194
+ self.graph = {
195
+ "nodes": {},
196
+ "edges": []
197
+ }
198
+
199
+ def inject(self, atom: Atom, parent_id: Optional[str] = None, relation: str = "follows"):
200
+ self.atoms.append(atom)
201
+
202
+ # 1. Update Stress (Physics)
203
+ force = atom.heat
204
+ area = len(self.atoms)
205
+ self.stress = force / (area + 1e-9)
206
+ self.deformation_gradient.append(self.stress)
207
+
208
+ # 2. Update Resonance (Number Theory)
209
+ prime_val = PRIME_DOMAINS.get(atom.domain, 2)
210
+ self.resonance_product *= prime_val
211
+
212
+ # 3. Update Graph (Topology)
213
+ self.graph["nodes"][atom.id] = {
214
+ "type": atom.symbol,
215
+ "name": atom.name,
216
+ "heat": atom.heat,
217
+ "domain": atom.domain,
218
+ "prime": prime_val
219
+ }
220
+
221
+ if parent_id and parent_id in self.graph["nodes"]:
222
+ self.graph["edges"].append({
223
+ "source": parent_id,
224
+ "target": atom.id,
225
+ "relation": relation,
226
+ "weight": self.stress
227
+ })
228
+
229
+ def stabilize(self) -> bool:
230
+ """Returns True if Stress is below threshold (Equilibrium)."""
231
+ return self.stress < 0.1
logos/indexer.py CHANGED
@@ -15,7 +15,12 @@ Output: 'project_context_dump.md'
15
  """
16
 
17
  import os
 
 
 
 
18
  import pathspec
 
19
 
20
  # Configuration
21
  PROJECT_ROOT = "."
 
15
  """
16
 
17
  import os
18
+ import sys
19
+ import os
20
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
21
+
22
  import pathspec
23
+ from logos.connectors import get_connector
24
 
25
  # Configuration
26
  PROJECT_ROOT = "."
logos/ingest_knowledge.py CHANGED
@@ -10,35 +10,25 @@ This script executes the "Ingestion" workflow:
10
  Target: 'LOGOS Notes/*.png' -> 'knowledge_base/diagram_analysis.md'
11
  """
12
 
 
13
  import os
14
  import glob
15
  import time
16
  from typing import List
 
 
17
  from logos.connectors import get_connector
18
 
19
  # Configuration
20
  SOURCE_DIR = "LOGOS Notes"
21
  OUTPUT_FILE = "knowledge_base/diagram_analysis.md"
22
- MODEL = "google/gemma-3-4b" # Fast vision model
23
-
24
- # Prompt Engineering for Technical Diagrams
25
- ANALYSIS_PROMPT = """
26
- You are a Senior Systems Architect analyzing a whiteboard diagram for the LOGOS DSP Protocol.
27
- The protocol involves Fractal Addressing, Prime Modulo arithmetic, and Heat Dissolution.
28
-
29
- Task:
30
- 1. IDENTIFY the core components (boxes, arrows, flows) in this image.
31
- 2. INTERPRET the logic or algorithm being described.
32
- 3. EXTRACT any specific formulas or mathematical relationships (e.g. Modulo operations, bitwise ops).
33
- 4. SUMMARIZE the architectural insight.
34
-
35
- Format output as Markdown. Be precise.
36
- """
37
 
38
  def ingest_diagrams():
39
- print(f"--- LOGOS Knowledge Ingestion [Protocol 4] ---")
40
  print(f"Targeting: {SOURCE_DIR}")
41
- print(f"Agent: {MODEL} (Vision)")
42
 
43
  # 1. Scout Resources
44
  images = glob.glob(os.path.join(SOURCE_DIR, "*.png")) + glob.glob(os.path.join(SOURCE_DIR, "*.jpg"))
@@ -48,50 +38,278 @@ def ingest_diagrams():
48
  print(f"[WARN] No assets found in {SOURCE_DIR}")
49
  return
50
 
51
- print(f"[PLAN] Ingesting {len(images)} artifacts. Estimated time: {len(images) * 10} seconds.")
52
-
53
- # 2. Initialize Agent
54
  try:
55
- agent = get_connector('local', model=MODEL)
 
56
  except Exception as e:
57
- print(f"[FAIL] Could not spawn agent: {e}")
58
  return
59
 
60
  # 3. Execution Loop
61
  with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
62
- f.write("# LOGOS Diagram Analysis\n")
63
  f.write(f"**Generated:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
64
- f.write(f"**Source:** {SOURCE_DIR}\n")
65
- f.write(f"**Agent:** {MODEL}\n\n")
66
 
67
  for i, img_path in enumerate(images):
68
  filename = os.path.basename(img_path)
69
- print(f"[{i+1}/{len(images)}] Consuming: {filename}...")
 
70
 
71
  try:
72
- # Transmute Visual -> Text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  start_ts = time.time()
74
- analysis, _ = agent.chat(ANALYSIS_PROMPT, image_path=img_path)
75
  duration = time.time() - start_ts
76
 
77
  # Anneal into Knowledge Base
78
  f.write(f"## {filename}\n")
 
79
  f.write(f"![{filename}](../{img_path.replace(os.sep, '/')})\n\n")
80
  f.write(f"{analysis}\n\n")
81
  f.write(f"*Analysis time: {duration:.2f}s*\n")
82
  f.write("---\n\n")
83
 
84
- # Flush to save progress
85
  f.flush()
86
  print(f" > Ingested ({duration:.2f}s)")
87
 
88
  except Exception as e:
89
- print(f" > [FAIL] Parsing Error: {e}")
90
  f.write(f"## {filename}\n")
91
- f.write(f"**Error analyzing image:** {e}\n\n---\n\n")
92
 
93
  print(f"\n[SUCCESS] Knowledge synthesis complete.")
94
  print(f"Artifact: {OUTPUT_FILE}")
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  if __name__ == "__main__":
97
  ingest_diagrams()
 
 
10
  Target: 'LOGOS Notes/*.png' -> 'knowledge_base/diagram_analysis.md'
11
  """
12
 
13
+ import sys
14
  import os
15
  import glob
16
  import time
17
  from typing import List
18
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
19
+
20
  from logos.connectors import get_connector
21
 
22
  # Configuration
23
  SOURCE_DIR = "LOGOS Notes"
24
  OUTPUT_FILE = "knowledge_base/diagram_analysis.md"
25
+ VISION_MODEL = "google/gemma-3-4b"
26
+ TEXT_MODEL = "dolphin-x1-8b"
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  def ingest_diagrams():
29
+ print(f"--- LOGOS Knowledge Ingestion [Protocol 4: Context-Primed Vision] ---")
30
  print(f"Targeting: {SOURCE_DIR}")
31
+ print(f"Agents: {TEXT_MODEL} (Context) -> {VISION_MODEL} (Analysis)")
32
 
33
  # 1. Scout Resources
34
  images = glob.glob(os.path.join(SOURCE_DIR, "*.png")) + glob.glob(os.path.join(SOURCE_DIR, "*.jpg"))
 
38
  print(f"[WARN] No assets found in {SOURCE_DIR}")
39
  return
40
 
41
+ # 2. Initialize Agents
 
 
42
  try:
43
+ # We reuse the connector but switch 'model' param per call to stay hardware aligned (one active stream)
44
+ connector = get_connector('local')
45
  except Exception as e:
46
+ print(f"[FAIL] Could not spawn connector: {e}")
47
  return
48
 
49
  # 3. Execution Loop
50
  with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
51
+ f.write("# LOGOS Diagram Analysis (Context-Primed)\n")
52
  f.write(f"**Generated:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
53
+ f.write(f"**Pipeline:** Context({TEXT_MODEL}) -> Vision({VISION_MODEL})\n\n")
 
54
 
55
  for i, img_path in enumerate(images):
56
  filename = os.path.basename(img_path)
57
+ clean_name = os.path.splitext(filename)[0].replace("_", " ").replace("-", " ")
58
+ print(f"[{i+1}/{len(images)}] Processing: {filename}...")
59
 
60
  try:
61
+ # Force Hardware Cool-down between items
62
+ time.sleep(2.0)
63
+
64
+ # STEP A: Context Priming (Dolphin)
65
+ print(f" > [Dolphin] Extracting Context (timeout=30s)...")
66
+ try:
67
+ context_prompt = f"Analyze filename '{clean_name}'. Return JSON {{'title': '...', 'description': '...'}}."
68
+ # Debug: Print ensuring valid string
69
+ # print(f"DEBUG: Prompting Dolphin with: {context_prompt}")
70
+
71
+ context_resp, _ = connector.chat(context_prompt, model=TEXT_MODEL)
72
+
73
+ # Robust JSON extraction
74
+ import json
75
+ try:
76
+ # Find first '{' and last '}'
77
+ s = context_resp.find('{')
78
+ e = context_resp.rfind('}') + 1
79
+ if s != -1 and e != -1:
80
+ meta = json.loads(context_resp[s:e])
81
+ refined_context = f"Context: {meta.get('title', clean_name)}. {meta.get('description', '')}"
82
+ else:
83
+ refined_context = f"Context: {clean_name}"
84
+ except:
85
+ refined_context = f"Context: {context_resp[:200].replace(chr(10), ' ')}"
86
+
87
+ except Exception as e:
88
+ print(f" > [Dolphin] Bypass (Error: {e})")
89
+ refined_context = f"Context: {clean_name}"
90
+
91
+ # Hardware Switch Delay
92
+ print(f" > [System] Swapping to Vision Model...")
93
+ time.sleep(1.0)
94
+
95
+ # STEP B: Vision Analysis (Gemma)
96
+ print(f" > [Gemma] performing Context-Aware Analysis...")
97
+
98
+ vision_prompt = f"""
99
+ Role: Senior Hardware Architect.
100
+ Context: {refined_context}
101
+ Task: Analyze the diagram. Validate if the visual data matches the context.
102
+ Extract:
103
+ 1. Hardware components (Bus, ALU, Cache).
104
+ 2. Data flow direction.
105
+ 3. Mathematical formulas.
106
+
107
+ Output: Actionable Markdown.
108
+ """
109
+
110
  start_ts = time.time()
111
+ analysis, _ = connector.chat(vision_prompt, image_path=img_path, model=VISION_MODEL)
112
  duration = time.time() - start_ts
113
 
114
  # Anneal into Knowledge Base
115
  f.write(f"## {filename}\n")
116
+ f.write(f"**Context ({TEXT_MODEL}):** {refined_context}\n\n")
117
  f.write(f"![{filename}](../{img_path.replace(os.sep, '/')})\n\n")
118
  f.write(f"{analysis}\n\n")
119
  f.write(f"*Analysis time: {duration:.2f}s*\n")
120
  f.write("---\n\n")
121
 
 
122
  f.flush()
123
  print(f" > Ingested ({duration:.2f}s)")
124
 
125
  except Exception as e:
126
+ print(f" > [FAIL] Error: {e}")
127
  f.write(f"## {filename}\n")
128
+ f.write(f"**Error:** {e}\n\n---\n\n")
129
 
130
  print(f"\n[SUCCESS] Knowledge synthesis complete.")
131
  print(f"Artifact: {OUTPUT_FILE}")
132
 
133
+ # --- INGESTION REGISTRY (Deduplication) ---
134
+ class IngestionRegistry:
135
+ def __init__(self, registry_path="logos/ingestion_registry.json"):
136
+ self.registry_path = registry_path
137
+ self.data = self._load()
138
+
139
+ def _load(self):
140
+ if os.path.exists(self.registry_path):
141
+ try:
142
+ import json
143
+ with open(self.registry_path, 'r') as f:
144
+ return json.load(f)
145
+ except:
146
+ pass
147
+ return {}
148
+
149
+ def save(self):
150
+ import json
151
+ with open(self.registry_path, 'w') as f:
152
+ json.dump(self.data, f, indent=2)
153
+
154
+ def is_processed(self, filepath):
155
+ """Checks if file is already ingested based on mtime."""
156
+ stat = os.stat(filepath)
157
+ key = os.path.abspath(filepath)
158
+ last_mtime = self.data.get(key, {}).get("mtime", 0)
159
+ return stat.st_mtime <= last_mtime
160
+
161
+ def mark_processed(self, filepath, meta=None):
162
+ """Tags data as ingested."""
163
+ key = os.path.abspath(filepath)
164
+ self.data[key] = {
165
+ "mtime": os.stat(filepath).st_mtime,
166
+ "timestamp": time.time(),
167
+ "meta": meta or {}
168
+ }
169
+ self.save()
170
+
171
+ def ingest_diagrams():
172
+ print(f"--- LOGOS Knowledge Ingestion [Protocol 4: Context-Primed Vision] ---")
173
+ print(f"Targeting: {SOURCE_DIR}")
174
+ print(f"Agents: {TEXT_MODEL} (Context) -> {VISION_MODEL} (Analysis)")
175
+
176
+ registry = IngestionRegistry()
177
+
178
+ # 1. Scout Resources
179
+ images = glob.glob(os.path.join(SOURCE_DIR, "*.png")) + glob.glob(os.path.join(SOURCE_DIR, "*.jpg"))
180
+ images.sort()
181
+
182
+ if not images:
183
+ print(f"[WARN] No assets found in {SOURCE_DIR}")
184
+ return
185
+
186
+ # 2. Initialize Agents
187
+ try:
188
+ # We reuse the connector but switch 'model' param per call to stay hardware aligned (one active stream)
189
+ connector = get_connector('local')
190
+ except Exception as e:
191
+ print(f"[FAIL] Could not spawn connector: {e}")
192
+ return
193
+
194
+ # 3. Execution Loop
195
+ # Write mode 'a' (append) to preserve history if we are skipping?
196
+ # Or 'w' but reading old content?
197
+ # For now, let's just append new findings or overwrite if it's a full run.
198
+ # User asked to "tag data that we have already ingested", usually implies skipping.
199
+
200
+ # Check if output file exists, if so append, else write header
201
+ mode = 'a' if os.path.exists(OUTPUT_FILE) else 'w'
202
+
203
+ with open(OUTPUT_FILE, mode, encoding="utf-8") as f:
204
+ if mode == 'w':
205
+ f.write("# LOGOS Diagram Analysis (Context-Primed)\n")
206
+ f.write(f"**Generated:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
207
+ f.write(f"**Pipeline:** Context({TEXT_MODEL}) -> Vision({VISION_MODEL})\n\n")
208
+
209
+ for i, img_path in enumerate(images):
210
+ filename = os.path.basename(img_path)
211
+
212
+ # [DEDUPLICATION CHECK]
213
+ if registry.is_processed(img_path):
214
+ print(f"[{i+1}/{len(images)}] Skipping {filename} (Already Ingested) [Duplicate Path Atom]")
215
+ continue
216
+
217
+ clean_name = os.path.splitext(filename)[0].replace("_", " ").replace("-", " ")
218
+ print(f"[{i+1}/{len(images)}] Processing: {filename}...")
219
+
220
+ try:
221
+ # Force Hardware Cool-down between items
222
+ time.sleep(1.0)
223
+
224
+ # STEP A: Context Priming (Dolphin)
225
+ print(f" > [Dolphin] Extracting Context (timeout=30s)...")
226
+ try:
227
+ context_prompt = f"Analyze filename '{clean_name}'. Return JSON {{'title': '...', 'description': '...'}}."
228
+ context_resp, _ = connector.chat(context_prompt, model=TEXT_MODEL)
229
+
230
+ # Robust JSON extraction
231
+ import json
232
+ try:
233
+ s = context_resp.find('{')
234
+ e = context_resp.rfind('}') + 1
235
+ if s != -1 and e != -1:
236
+ meta = json.loads(context_resp[s:e])
237
+ refined_context = f"Context: {meta.get('title', clean_name)}. {meta.get('description', '')}"
238
+ else:
239
+ refined_context = f"Context: {clean_name}"
240
+ except:
241
+ refined_context = f"Context: {context_resp[:200].replace(chr(10), ' ')}"
242
+
243
+ except Exception as e:
244
+ print(f" > [Dolphin] Bypass (Error: {e})")
245
+ refined_context = f"Context: {clean_name}"
246
+
247
+ # Hardware Switch Delay
248
+ print(f" > [System] Swapping to Vision Model...")
249
+ time.sleep(1.0)
250
+
251
+ # STEP B: Vision Analysis (Gemma)
252
+ print(f" > [Gemma] performing Context-Aware Analysis...")
253
+
254
+ vision_prompt = f"""
255
+ Role: Senior Hardware Architect.
256
+ Context: {refined_context}
257
+ Task: Analyze the diagram. Validate if the visual data matches the context.
258
+ Extract:
259
+ 1. Hardware components (Bus, ALU, Cache).
260
+ 2. Data flow direction.
261
+ 3. Mathematical formulas.
262
+
263
+ Output: Actionable Markdown.
264
+ """
265
+
266
+ start_ts = time.time()
267
+ analysis, _ = connector.chat(vision_prompt, image_path=img_path, model=VISION_MODEL)
268
+ duration = time.time() - start_ts
269
+
270
+ # Anneal into Knowledge Base
271
+ f.write(f"## {filename}\n")
272
+ f.write(f"**Context ({TEXT_MODEL}):** {refined_context}\n\n")
273
+ f.write(f"![{filename}](../{img_path.replace(os.sep, '/')})\n\n")
274
+ f.write(f"{analysis}\n\n")
275
+ f.write(f"*Analysis time: {duration:.2f}s*\n")
276
+ f.write("---\n\n")
277
+
278
+ f.flush()
279
+ print(f" > Ingested ({duration:.2f}s)")
280
+
281
+ # [PROTOCOL 26: ANALOG TO DIGITAL INDEXING]
282
+ # We send the Vision Analysis to the Server to be converted into a Gödel Number
283
+ try:
284
+ import requests
285
+ payload = {
286
+ "filepath": img_path,
287
+ "content": f"{refined_context}\n{analysis}"
288
+ }
289
+ # Assuming default port
290
+ res = requests.post("http://localhost:5000/index-module", json=payload, timeout=5)
291
+ if res.status_code == 200:
292
+ data = res.json()
293
+ mid = data.get('manifold_id')
294
+ primes = data.get('prime_coordinates')
295
+ print(f" > [GÖDEL] Indexing Complete. Manifold ID: {mid}")
296
+ print(f" > [PRIME SPACE] Active Domains: {primes}")
297
+ f.write(f"**Gödel ID:** `{mid}`\n**Prime Vectors:** `{primes}`\n\n")
298
+ else:
299
+ print(f" > [GÖDEL] Indexing Failed: {res.status_code}")
300
+ except Exception as e:
301
+ print(f" > [GÖDEL] Indexing Error: {e}")
302
+
303
+ # [REGISTRY UPDATE]
304
+ registry.mark_processed(img_path, meta={"duration": duration, "context": refined_context})
305
+
306
+ except Exception as e:
307
+ print(f" > [FAIL] Error: {e}")
308
+ f.write(f"## {filename}\n")
309
+ f.write(f"**Error:** {e}\n\n---\n\n")
310
+
311
+ print(f"\n[SUCCESS] Knowledge synthesis complete.")
312
+
313
  if __name__ == "__main__":
314
  ingest_diagrams()
315
+ ingest_documents()
logos/ingestion_registry.json ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\2 bit ops to 4 bit generation scratchwork.png": {
3
+ "mtime": 1766229543.8824837,
4
+ "timestamp": 1767912162.519743,
5
+ "meta": {
6
+ "duration": 62.05567264556885,
7
+ "context": "Context: Binary Operations to Quad-State Encoding. This document outlines a process for converting binary operations (typically represented by two-bit values) into a four-bit encoding system. The methodology involves examining the possible outcomes of bit manipulation and mapping them to specific quad-state representations. Various techniques such as bitwise shifts, logical operations, and arithmetic calculations are discussed in detail."
8
+ }
9
+ },
10
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\2 bit ops- 00persist,01persistchange, 10 changepersist, 11 change change.png": {
11
+ "mtime": 1766229609.7951887,
12
+ "timestamp": 1767912230.474419,
13
+ "meta": {
14
+ "duration": 62.054080963134766,
15
+ "context": "Context: Binary Operations. This dataset contains binary operations for data persistence and modification. The values represent bit combinations where the first digit (bit) determines whether to persist or change, while the second digit controls how the operation is applied."
16
+ }
17
+ },
18
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\4 bit version of header control codes for generation keying.png": {
19
+ "mtime": 1766176440.6376977,
20
+ "timestamp": 1767912300.0442252,
21
+ "meta": {
22
+ "duration": 62.074482679367065,
23
+ "context": "Context: ```python import json def analyze_filename(filename): words = filename.replace(' ', '-').split('-') title = \"Header Control Codes\" description = f\"Control code system for generating "
24
+ }
25
+ },
26
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Buckets in out 1.png": {
27
+ "mtime": 1766176505.5800614,
28
+ "timestamp": 1767912377.0162396,
29
+ "meta": {
30
+ "duration": 62.09031295776367,
31
+ "context": "Context: ```python import re def analyze_filename(filename): \"\"\" Analyze a filename to extract title and description. :param filename: The file name to analyze :return: A dictionary conta"
32
+ }
33
+ },
34
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Buckets in out 1a.png": {
35
+ "mtime": 1766229683.6946967,
36
+ "timestamp": 1767912446.9074564,
37
+ "meta": {
38
+ "duration": 62.07565903663635,
39
+ "context": "Context: Buckets in the outer space. A collection of containers used for storing items, located in an external environment."
40
+ }
41
+ },
42
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Buckets inout select and raw.png": {
43
+ "mtime": 1766733339.3767636,
44
+ "timestamp": 1767912515.2857368,
45
+ "meta": {
46
+ "duration": 62.07451391220093,
47
+ "context": "Context: Bucket Selection in Raw Data Processing. This filename suggests a process involving buckets, possibly for data organization or aggregation. The terms 'inout' imply input/output operations, while 'select' indicates filtering or retrieval of specific information. 'Raw' likely references unprocessed or unstructured data, which is being manipulated through this bucket-based system."
48
+ }
49
+ },
50
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Buckets- raw.png": {
51
+ "mtime": 1766176467.8635385,
52
+ "timestamp": 1767912586.5567737,
53
+ "meta": {
54
+ "duration": 62.08598446846008,
55
+ "context": "Context: ```python import re def analyze_filename(filename): \"\"\" Analyze a filename and return a title/description based on its components. :param str filename: The filename to be analyzed. :"
56
+ }
57
+ },
58
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\CakeBake.png": {
59
+ "mtime": 1765668384.1091495,
60
+ "timestamp": 1767912654.5192094,
61
+ "meta": {
62
+ "duration": 62.07900142669678,
63
+ "context": "Context: ```python import json def analyze_filename(filename): title = \"cake_baking\" description = \"The process of preparing a sweet baked dessert using flour, sugar, eggs, and butter.\" retur"
64
+ }
65
+ },
66
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Context compression at scale- decompress to true stream.png": {
67
+ "mtime": 1766436908.2784822,
68
+ "timestamp": 1767912721.5784955,
69
+ "meta": {
70
+ "duration": 62.08380699157715,
71
+ "context": "Context: Context Compression. At scale, it involves decompression to a streaming format."
72
+ }
73
+ },
74
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Delta Heat Flow.png": {
75
+ "mtime": 1766554370.0297463,
76
+ "timestamp": 1767912788.638845,
77
+ "meta": {
78
+ "duration": 62.06147575378418,
79
+ "context": "Context: Heat Flow in the Delta Region. This dataset provides thermal conductivity measurements for subsurface rock formations within the Delta area. It includes data on temperature gradients, heat flux rates, and depth-dependent thermal properties."
80
+ }
81
+ },
82
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Dissolution scratch.png": {
83
+ "mtime": 1766174709.3796747,
84
+ "timestamp": 1767912914.7828348,
85
+ "meta": {
86
+ "duration": 62.070053577423096,
87
+ "context": "Context: Dissolution scratch"
88
+ }
89
+ },
90
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Early SPCW scratch- add with Prime Composite clarification.png": {
91
+ "mtime": 1766091347.9499009,
92
+ "timestamp": 1767912981.8380082,
93
+ "meta": {
94
+ "duration": 62.06748986244202,
95
+ "context": "Context: Early SPCW. Scratch addition using the Prime Composite method, including clarifications"
96
+ }
97
+ },
98
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Early Streaming Diffs.png": {
99
+ "mtime": 1766548093.8498833,
100
+ "timestamp": 1767913049.309288,
101
+ "meta": {
102
+ "duration": 62.09256434440613,
103
+ "context": "Context: Early. Streaming"
104
+ }
105
+ },
106
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Early Transmission flow control.png": {
107
+ "mtime": 1766442268.948,
108
+ "timestamp": 1767913154.1385126,
109
+ "meta": {
110
+ "duration": 62.069133281707764,
111
+ "context": "Context: Early Transmission Flow Control. A system that detects and prevents potential transmission problems before they occur, ensuring data integrity and efficiency."
112
+ }
113
+ },
114
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Heat tracking- hex complexity tracking.png": {
115
+ "mtime": 1766439998.7298183,
116
+ "timestamp": 1767913244.9191825,
117
+ "meta": {
118
+ "duration": 62.07440638542175,
119
+ "context": "Context: Hexagon Complexity Tracking System. A digital platform designed to monitor and analyze the thermal behavior of hexagonal structures, providing insights into heat dissipation patterns and optimizing material selection for thermal management applications."
120
+ }
121
+ },
122
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Hex compression heat codes from 8x8 Matrix.png": {
123
+ "mtime": 1766521428.0286517,
124
+ "timestamp": 1767913371.0930233,
125
+ "meta": {
126
+ "duration": 62.08362579345703,
127
+ "context": "Context: Hex compression heat codes from 8x8 Matrix"
128
+ }
129
+ },
130
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Hex dissolve round trip heat from atomic decomp.png": {
131
+ "mtime": 1766523371.6137607,
132
+ "timestamp": 1767913497.267817,
133
+ "meta": {
134
+ "duration": 62.094608545303345,
135
+ "context": "Context: Hex dissolve round trip heat from atomic decomp"
136
+ }
137
+ },
138
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Lane splitting dissolution.png": {
139
+ "mtime": 1766613263.3714952,
140
+ "timestamp": 1767913623.4322183,
141
+ "meta": {
142
+ "duration": 62.09859371185303,
143
+ "context": "Context: Lane splitting dissolution"
144
+ }
145
+ },
146
+ "C:\\Users\\Nauti\\Desktop\\LOGOS CURSOR\\LOGOS Notes\\Matroska Networking Example- Nested and contemporary domains.png": {
147
+ "mtime": 1767302449.4050667,
148
+ "timestamp": 1767913749.585773,
149
+ "meta": {
150
+ "duration": 62.07360100746155,
151
+ "context": "Context: Matroska Networking Example Nested and contemporary domains"
152
+ }
153
+ }
154
+ }
logos/manifold_state.py CHANGED
@@ -56,6 +56,17 @@ class ManifoldState:
56
  self.state["shells"][shell_name]["requests"] += 1
57
  self.state["shells"][shell_name]["tokens_intake"] += token_count
58
 
 
 
 
 
 
 
 
 
 
 
 
59
  # Update Macro Context (Rolling buffer of 10)
60
  context_entry = {
61
  "time": time.time(),
 
56
  self.state["shells"][shell_name]["requests"] += 1
57
  self.state["shells"][shell_name]["tokens_intake"] += token_count
58
 
59
+ # [PROTOCOL 26 ADDITION]
60
+ # Since 'state' here is a dictionary from JSON, it doesn't automatically sync
61
+ # with the transient 'ManifoldState' object used in the router (Atom/Physics).
62
+ # We need to bridge the persistent stats with the transient physics for the API.
63
+ # Ideally, we should merge the two concepts, but for now we'll stub the fields
64
+ # so the API reveals they exist.
65
+ if "prime_resonance" not in self.state:
66
+ self.state["prime_resonance"] = 1
67
+ if "graph_nodes" not in self.state:
68
+ self.state["graph_nodes"] = 0
69
+
70
  # Update Macro Context (Rolling buffer of 10)
71
  context_entry = {
72
  "time": time.time(),
logos/memory/README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Protocol 26: Gödel-Zeta Datastore
2
+
3
+ ## Philosophy
4
+ **"The Database is not a Table. It is a Field of Integers."**
5
+
6
+ Based on the [Primes Playlist](https://www.youtube.com/playlist?list=PL6w6drTRMkPExcs2kYO8uBufDT_nU4vU8), this module implements a **Gödel Numbering Topology**.
7
+
8
+ Instead of storing data in relational tables or vector stores alone, we map every unique Atomic Concept (Token) to a **Prime Number**.
9
+
10
+ ## Core Mechanisms
11
+
12
+ ### 1. The Atom (Prime)
13
+ Every unique string concept (e.g., "AI", "Logic", "Python") is assigned a unique Prime Number $P$ from the infinite sequence of primes.
14
+ * "General" = 2
15
+ * "Physics" = 3
16
+ * "Code" = 5
17
+ * ... and so on.
18
+
19
+ ### 2. The Molecule (Composite)
20
+ A state, file, or document is defined not by its content string, but by the **Product** of its constituent primes.
21
+ $$ State = P_1 \times P_2 \times P_3 \dots $$
22
+ By the **Fundamental Theorem of Arithmetic**, this integer is unique. No other combination of concepts will yield this exact number.
23
+
24
+ ### 3. Topological Search (Divisibility)
25
+ To query the database, we do not scan text. We perform **Divisibility Checks**.
26
+ To find if a File contains "Logic" (Prime 5):
27
+ $$ \text{if } (File\_ID \mod 5 == 0) \rightarrow \text{True} $$
28
+ This check is $O(1)$ and mathematically rigorous.
29
+
30
+ ## Implementation
31
+ * **`prime_db.py`**: Manages the `prime_registry.json` (The Rosetta Stone of Primes).
32
+ * **`server.py`**: Exposes `/index-module` to engage the Indexer and `/query-topology` to traverse the Prime Field.
logos/memory/__pycache__/prime_db.cpython-313.pyc ADDED
Binary file (6.53 kB). View file
 
logos/memory/prime_db.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import math
4
+ from functools import reduce
5
+
6
+ # PERSISTENCE FILE
7
+ REGISTRY_PATH = "./logos/memory/prime_registry.json"
8
+ os.makedirs(os.path.dirname(REGISTRY_PATH), exist_ok=True)
9
+
10
+ class PrimeTokenDB:
11
+ def __init__(self):
12
+ self.registry = self.load_registry()
13
+ try:
14
+ # Handle potential string keys from JSON loading
15
+ self.reverse_registry = {int(v) if isinstance(v, (int, str)) and str(v).isdigit() else v: k for k, v in self.registry.items()}
16
+ except Exception as e:
17
+ print(f"[PrimeDB] Warning rebuilding reverse registry: {e}")
18
+ self.reverse_registry = {}
19
+
20
+ self.next_prime = self.calculate_next_prime()
21
+
22
+ def load_registry(self):
23
+ if os.path.exists(REGISTRY_PATH):
24
+ try:
25
+ with open(REGISTRY_PATH, 'r') as f:
26
+ data = json.load(f)
27
+ # Convert values to int just in case
28
+ return {k: int(v) for k, v in data.items()}
29
+ except:
30
+ return {"_ROOT": 1}
31
+ return {"_ROOT": 1} # Identity
32
+
33
+ def save_registry(self):
34
+ with open(REGISTRY_PATH, 'w') as f:
35
+ json.dump(self.registry, f, indent=2)
36
+
37
+ def is_prime(self, n):
38
+ """Standard Primality Test"""
39
+ if n < 2: return False
40
+ for i in range(2, int(math.sqrt(n)) + 1):
41
+ if n % i == 0: return False
42
+ return True
43
+
44
+ def calculate_next_prime(self):
45
+ """Finds the next available prime slot for a new token."""
46
+ if not self.registry: return 2
47
+ # Ensure we look at integer values
48
+ values = [int(v) for v in self.registry.values()]
49
+ highest = max(values) if values else 1
50
+ candidate = highest + 1
51
+ while not self.is_prime(candidate):
52
+ candidate += 1
53
+ return candidate
54
+
55
+ def get_token_prime(self, token):
56
+ """
57
+ Retrieves the Prime Coordinate for a token.
58
+ If new, assigns the next prime and expands the Manifold.
59
+ """
60
+ token = str(token).lower().strip()
61
+ if token in self.registry:
62
+ return self.registry[token]
63
+
64
+ # MINT NEW PRIME
65
+ prime = self.next_prime
66
+ self.registry[token] = prime
67
+ self.reverse_registry[prime] = token
68
+
69
+ # Calc next for future
70
+ self.next_prime += 1
71
+ while not self.is_prime(self.next_prime):
72
+ self.next_prime += 1
73
+
74
+ self.save_registry()
75
+ return prime
76
+
77
+ def encode_state(self, tokens):
78
+ """
79
+ Converts a list of concepts (text) into a Single Unique Integer.
80
+ Example: ["AI", "Logic"] -> 3 * 5 = 15
81
+ """
82
+ primes = [self.get_token_prime(t) for t in tokens]
83
+ # Calculate Product (The Composite Weight)
84
+ if not primes: return 1, []
85
+ composite = reduce(lambda x, y: x * y, primes, 1)
86
+ return composite, primes
87
+
88
+ def decode_state(self, composite_integer):
89
+ """
90
+ Reconstructs the atoms from the composite weight.
91
+ (Factoring the Manifold State)
92
+ """
93
+ factors = []
94
+ # Optimization: We only check primes we know exist in the registry
95
+ known_primes = sorted([int(k) for k in self.reverse_registry.keys()])
96
+
97
+ temp = composite_integer
98
+ for p in known_primes:
99
+ if p <= 1: continue
100
+ if p * p > temp:
101
+ # If what remains is prime and in registry
102
+ if temp in self.reverse_registry:
103
+ factors.append(self.reverse_registry[temp])
104
+ temp = 1
105
+ break
106
+
107
+ while temp % p == 0:
108
+ factors.append(self.reverse_registry[p])
109
+ temp //= p
110
+
111
+ if temp > 1 and temp in self.reverse_registry:
112
+ factors.append(self.reverse_registry[temp])
113
+
114
+ return factors
logos/mhc_router.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ logos/mhc_router.py - Recursive Manifold Engine (Router Logic)
3
+ Protocol 25: Recursive Manifold Engine (RLM) w/ Harmonic Convergence
4
+ """
5
+
6
+ import logging
7
+ import time
8
+ import os
9
+ import sys
10
+ import requests
11
+
12
+ # Hack: Allow running this script directly for testing
13
+ if __name__ == "__main__":
14
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
15
+
16
+ from logos.elements import ManifoldState as AtomicState, Token, Model, Atom, Handoff, Tool
17
+
18
+ # Set up Logging
19
+ logging.basicConfig(level=logging.INFO)
20
+ logger = logging.getLogger("LOGOS_Router")
21
+
22
+ # --- MANIFOLD CONSTRAINT CONFIGURATION ---
23
+ FORCE_SINGLE_MODEL = True
24
+ UNIFIED_MODEL_ID = "dolphin-x1-8b"
25
+
26
+ SHELL_CONFIG = {
27
+ "INNER_SHELL": {
28
+ "model": "dolphin-x1-8b" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID,
29
+ "rate_limit": 60,
30
+ },
31
+ "PRIME_CHANNEL": {
32
+ "model": "essentialai/rnj-1" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID,
33
+ "rate_limit": 20,
34
+ },
35
+ "OUTER_SHELL": {
36
+ "model": "google/gemma-3-4b" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID,
37
+ "rate_limit": 10,
38
+ }
39
+ }
40
+
41
+ RATE_LIMITS = {k: {"tokens": v["rate_limit"], "last_update": 0} for k, v in SHELL_CONFIG.items()}
42
+
43
+ # --- TOOLS ---
44
+ def search_tool(query):
45
+ return f"[SEARCH RESULTS] Found relevant documentation for: {query}"
46
+
47
+ TOOL_MAP = {
48
+ "Search": Tool("Search", search_tool, "Locates external knowledge to reduce entropy.")
49
+ }
50
+
51
+ # --- CORE FUNCTIONS ---
52
+
53
+ def calculate_manifold_constraint(text, is_vision=False):
54
+ """
55
+ Determines the 'Shell' based on Prime Topology (Manifold Constrained Hyper-Connection).
56
+ """
57
+ if is_vision:
58
+ return "OUTER_SHELL", 1.0
59
+
60
+ # Keyword Harmonic Override
61
+ text_lower = text.lower()
62
+ if any(k in text_lower for k in ["prime", "modulo", "math", "proof"]):
63
+ return "PRIME_CHANNEL", 1.0
64
+ if any(k in text_lower for k in ["def ", "class ", "import ", "code", "script"]):
65
+ return "INNER_SHELL", 1.0
66
+
67
+ # Prime Topology Routing (Heat Code Analysis)
68
+ try:
69
+ hex_str = text.encode('utf-8').hex()
70
+ except:
71
+ hex_str = str(text).encode('utf-8').hex()
72
+
73
+ total_nibbles = len(hex_str)
74
+
75
+ if total_nibbles == 0: return "INNER_SHELL", 0.5
76
+
77
+ check_set = {'7', 'b', 'd', 'e', 'f', 'B', 'D', 'E', 'F'}
78
+ high_entropy_count = sum(1 for c in hex_str if c in check_set)
79
+
80
+ heat_score = high_entropy_count / total_nibbles
81
+
82
+ if heat_score > 0.4:
83
+ return "OUTER_SHELL", heat_score
84
+ elif heat_score > 0.2:
85
+ return "PRIME_CHANNEL", heat_score
86
+ else:
87
+ return "INNER_SHELL", heat_score
88
+
89
+ def execute_recursive_manifold(prompt, target_model_id, max_recursion=3, is_vision=False):
90
+ """
91
+ Executes the prompt through the Manifold-Constrained Hyper-Graph.
92
+ Iterates until Stress < Threshold or Max Recursion reached.
93
+ """
94
+ # 1. Initialize State Buffer ( The Periodic Table )
95
+ state = AtomicState()
96
+ initial_token = Token(prompt, source="user")
97
+ initial_token.domain = "Prompt"
98
+ state.inject(initial_token)
99
+
100
+ last_atom_id = initial_token.id # Track causality
101
+
102
+ trajectory = []
103
+ ENTROPY_HANDOFF_THRESHOLD = 0.6 # [TUNED] Lowered from 0.8 to increase Tool Usage
104
+
105
+ logger.info(f"🌀 [RLM] Initiating Recursive Manifold Loop (Max Depth: {max_recursion})")
106
+
107
+ # [OPTIMIZATION] STATIC SYSTEM PROMPT for KV Cache Reuse
108
+ # By keeping the system prompt identical across iterations, we allow the engine
109
+ # to reuse the computed KV states for the system block.
110
+ STATIC_SYSTEM_PROMPT = (
111
+ "You are the LOGOS Recursive Manifold Node (RLM). "
112
+ "You exist within a self-correcting loop. "
113
+ "Adhere strictly to the injected [DIRECTIVE] at the end of the user prompt."
114
+ )
115
+
116
+ current_content = prompt
117
+ iteration = 0
118
+
119
+ while iteration < max_recursion:
120
+ iteration += 1
121
+
122
+ # 2. Calculate Manifold Constraints
123
+ shell, heat_score = calculate_manifold_constraint(current_content, is_vision)
124
+
125
+ # Update State Stress (Continuum Mechanics)
126
+ state.stress = max(0, heat_score - 0.5) if shell == "OUTER_SHELL" else 0.1
127
+
128
+ # [GEOMETRY CHECK]
129
+ logger.info(f" ► Iteration {iteration}: Shell={shell}")
130
+ logger.info(f" [GEOMETRY] Heat={heat_score:.4f} (Hex Density)")
131
+ logger.info(f" [NUMBER] Resonance={state.resonance_product}")
132
+ logger.info(f" [PHYSICS] Stress={state.stress:.4f}")
133
+
134
+ trajectory.append({
135
+ "iter": iteration,
136
+ "shell": shell,
137
+ "heat": heat_score,
138
+ "resonance": state.resonance_product,
139
+ "elements": [str(a) for a in state.atoms[-3:]]
140
+ })
141
+
142
+ # 3. Harmonic Convergence Check
143
+ if state.stabilize() and iteration > 1:
144
+ logger.info(f" ✅ Harmonic Convergence Reached at Iteration {iteration}.")
145
+ break
146
+
147
+ # 4. Atomic Handoff (Self-Correction / Tool Usage)
148
+ # We encourage tool use if stress is high OR if we are just starting (Prime Interplay)
149
+ if heat_score > ENTROPY_HANDOFF_THRESHOLD or (iteration == 1 and "search" in current_content.lower()):
150
+ logger.info(f" ⚠️ CRITICAL HEAT ({heat_score:.2f}) -> Initiating ATOMIC HANDOFF to 'Search'")
151
+ handoff_atom = Handoff("Search", reason=f"High Entropy detected ({heat_score:.2f})")
152
+ state.inject(handoff_atom, parent_id=last_atom_id, relation="triggers")
153
+
154
+ target_tool = TOOL_MAP.get(handoff_atom.target)
155
+ if target_tool:
156
+ # [BOOST] Increase context window for tools
157
+ result_token = target_tool.execute(current_content[:150])
158
+ result_token.domain = "External_Knowledge"
159
+ state.inject(result_token, parent_id=handoff_atom.id, relation="resolved_by")
160
+
161
+ # [CACHE OPTIMIZATION] Append Context instead of Prepend
162
+ # This preserves the prefix of 'current_content', allowing KV cache to reuse
163
+ # tokens 0..N. We append the new knowledge.
164
+ current_content = f"{current_content}\n\n[TOOL_RESULT]: {result_token.content}"
165
+ last_atom_id = result_token.id
166
+
167
+ # [INTERPLAY] Don't skip, let the Agent react to the tool immediately
168
+ # continue
169
+
170
+ # 5. Hyper-Connection Routing & Context Expansion
171
+ if shell == "OUTER_SHELL":
172
+ # Creative / Divergent
173
+ meta_instruction = "Analyze entropy. Expand geometric implications. Think divergently. Use rich vocabulary."
174
+ target_temp = 0.9
175
+ else:
176
+ # Logic / Convergent
177
+ meta_instruction = "Refine into singular conclusion. Minimize ambiguity. Critique previous steps."
178
+ target_temp = 0.4
179
+
180
+ # 6. Execute Expert (Agent Interplay)
181
+ try:
182
+ # [BOOST] Force Multi-Agent "Critique" if we are deep in recursion
183
+ if iteration > 1 and shell == "OUTER_SHELL":
184
+ meta_instruction += " CRITIQUE the previous iteration. checking for logical consistency."
185
+
186
+ model_atom = Model(target_model_id)
187
+
188
+ # [CACHE OPTIMIZATION] Dynamic Directive Moved to User Prompt Postfix
189
+ # System Prompt remains static. Directive is appended.
190
+ final_user_content = f"{current_content}\n\n[DIRECTIVE]: {meta_instruction}"
191
+
192
+ messages = [
193
+ {"role": "system", "content": STATIC_SYSTEM_PROMPT},
194
+ {"role": "user", "content": final_user_content}
195
+ ]
196
+
197
+ payload = {
198
+ "model": target_model_id,
199
+ "messages": messages,
200
+ "temperature": target_temp,
201
+ "max_tokens": -1,
202
+ "stream": False
203
+ }
204
+
205
+ lm_endpoint = os.environ.get("LOGOS_LLM_ENDPOINT", "http://localhost:1234/v1")
206
+
207
+ # Simple synchronous call for now (can upgrade to aiohttp later)
208
+ response = requests.post(f"{lm_endpoint}/chat/completions", json=payload, timeout=60)
209
+
210
+ if response.status_code == 200:
211
+ result = response.json()
212
+ new_content = result['choices'][0]['message']['content']
213
+
214
+ output_token = Token(new_content, source=target_model_id)
215
+ output_token.domain = "Inference"
216
+ state.inject(output_token, parent_id=last_atom_id, relation="generated_by")
217
+
218
+ current_content = new_content
219
+ last_atom_id = output_token.id
220
+ else:
221
+ logger.error(f" ❌ Expert Failed: {response.status_code}")
222
+ break
223
+
224
+ except Exception as e:
225
+ logger.error(f" ❌ RLM Error: {e}")
226
+ break
227
+
228
+ return current_content, trajectory
229
+
230
+ if __name__ == "__main__":
231
+ print("--- LOGOS PHYSICS ENGINE TEST ---")
232
+ print("Injecting High-Entropy Prompt to trigger Geometry Checks...")
233
+
234
+ # Test Prompt: High heat (hex codes), mixed domain keywords
235
+ test_prompt = "Calculate the Prime Resonance of a Quantum Field 0x7F 0xFF in Python."
236
+
237
+ # Mock LLM Endpoint for test (won't actually call out if we don't have a server, or will fail gracefully)
238
+ # We mainly want to see the LOGS generated by 'execute_recursive_manifold'
239
+
240
+ try:
241
+ final, traj = execute_recursive_manifold(test_prompt, "dolphin-x1-8b", max_recursion=2)
242
+ print("\n[Trajectory Summary]")
243
+ for Step in traj:
244
+ print(f"Iter {Step['iter']}: Heat={Step['heat']:.2f} | Resonance={Step.get('resonance', 'N/A')}")
245
+ except Exception as e:
246
+ print(f"Physics Test Complete (stopped at network): {e}")
logos/network/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (3.22 kB). View file
 
logos/network/__pycache__/__init__.cpython-314.pyc CHANGED
Binary files a/logos/network/__pycache__/__init__.cpython-314.pyc and b/logos/network/__pycache__/__init__.cpython-314.pyc differ
 
logos/oversight.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ logos/oversight.py - The "Context Graph" Manager
3
+ Protocol 26: Autonomous Persistence & Validation
4
+
5
+ Functions:
6
+ 1. Process Persistence: Keeps 'server.py' alive.
7
+ 2. Context Monitoring: Traces health/decisions (Video 14).
8
+ 3. Continuous Validation: Runs 'verify_loop.py' on schedule/change.
9
+ """
10
+
11
+ import subprocess
12
+ import time
13
+ import sys
14
+ import os
15
+ import logging
16
+ from datetime import datetime
17
+
18
+ # Configure Logging (The Context Graph)
19
+ logging.basicConfig(
20
+ filename='logos_context.log',
21
+ level=logging.INFO,
22
+ format='%(asctime)s | %(levelname)s | %(message)s'
23
+ )
24
+ logger = logging.getLogger("OVERSIGHT")
25
+
26
+ SERVER_CMD = [sys.executable, "-m", "logos.server"]
27
+ TEST_CMD = [sys.executable, "tests/verify_loop.py"]
28
+
29
+ class OversightDaemon:
30
+ def __init__(self):
31
+ self.server_process = None
32
+ self.health_score = 100.0
33
+ self.context_trace = [] # In-memory context graph
34
+
35
+ def start_server(self):
36
+ logger.info("[OP] Starting Manifold Server...")
37
+ self.server_process = subprocess.Popen(SERVER_CMD)
38
+ self.log_context("SERVER_START", "Process initiated")
39
+
40
+ def run_tests(self):
41
+ logger.info("[QA] Running Validation Suite...")
42
+ try:
43
+ # Force UTF-8 to avoid Windows charmap errors
44
+ result = subprocess.run(
45
+ TEST_CMD,
46
+ capture_output=True,
47
+ text=True,
48
+ encoding='utf-8',
49
+ errors='replace',
50
+ timeout=30
51
+ )
52
+ if result.returncode == 0:
53
+ logger.info(" ✅ Tests Passed.")
54
+ self.log_context("TEST_PASS", "Verification successful")
55
+ return True
56
+ else:
57
+ logger.error(f" ❌ Tests Failed:\n{result.stderr}")
58
+ self.log_context("TEST_FAIL", f"Exit Code {result.returncode}")
59
+ return False
60
+ except Exception as e:
61
+ logger.error(f" ❌ Test Execution Error: {e}")
62
+ return False
63
+
64
+ def log_context(self, event_type, details):
65
+ """Builds the Context Graph node."""
66
+ node = {
67
+ "timestamp": time.time(),
68
+ "type": event_type,
69
+ "details": details,
70
+ "server_pid": self.server_process.pid if self.server_process else None
71
+ }
72
+ self.context_trace.append(node)
73
+ # Prune old context
74
+ if len(self.context_trace) > 100: self.context_trace.pop(0)
75
+
76
+ def monitor_loop(self):
77
+ self.start_server()
78
+
79
+ try:
80
+ while True:
81
+ # 1. Check Server Liveness
82
+ if self.server_process.poll() is not None:
83
+ logger.warning("[⚠️] Server died! Restarting...")
84
+ self.log_context("SERVER_CRASH", "Unexpected exit")
85
+ self.start_server()
86
+
87
+ # 2. Periodic Validation (Simulation of "Active Oversight")
88
+ # In real world, trigger this on file events. Here, every 60s.
89
+ if int(time.time()) % 60 == 0:
90
+ success = self.run_tests()
91
+ if not success:
92
+ logger.warning("[⚠️] System Unstable (Tests Failed).")
93
+ # Implementation detail: Could auto-rollback or alert user
94
+
95
+ time.sleep(1)
96
+
97
+ except KeyboardInterrupt:
98
+ logger.info("[OP] Stopping Oversight...")
99
+ if self.server_process: self.server_process.terminate()
100
+
101
+ if __name__ == "__main__":
102
+ print("CORE: Starting Logos Oversight Daemon (Protocol 26)...")
103
+ daemon = OversightDaemon()
104
+ daemon.monitor_loop()
logos/periodic_table.md ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The Periodic Table of Matroska AI Elements
2
+
3
+ This document defines the fundamental "elements" of the Logos Matroska System, inspired by the IBM AI Periodic Table but adapted for the Recursive Manifold architecture. These elements serve as the atomic units for the "Matroska Tool Token Assignment" and "Semantic Gravity".
4
+
5
+ ## I. Primitives (The Nucleus)
6
+ Fundamental building blocks that cannot be broken down further within the domain.
7
+
8
+ | Symbol | Element | Description | Logos Mapping |
9
+ | :--- | :--- | :--- | :--- |
10
+ | **Pr** | **Prompt** | The initial input wave or instruction. | `State Buffer` Input |
11
+ | **To** | **Token** | The atomic unit of semantic meaning. | Text Tokens / Image Patches |
12
+ | **Ve** | **Vector** | Numerical representation of meaning (Semantic Gravity). | `Heat Codes` / Embeddings |
13
+ | **Mo** | **Model** | The dense compute node (LLM). | `Gemma`, `RNJ-1`, Local LLMs |
14
+ | **Me** | **Memory** | Persistence of state. | `Manifold` Storage |
15
+ | **Co** | **Code** | Executable logic functions. | Tools / Python Functions |
16
+
17
+ ## II. Compounds (The Molecules)
18
+ Combinations of primitives that form functional units.
19
+
20
+ | Symbol | Compound | Formula | Description |
21
+ | :--- | :--- | :--- | :--- |
22
+ | **Rag** | **Retrieval** | `Pr + Ve + Me` | Fetching context based on semantic gravity. |
23
+ | **Ch** | **Chain** | `Pr -> Mo -> Pr` | Linear sequence of model calls. |
24
+ | **Fu** | **Function** | `Mo + Co` | LLM calling a specific tool (Tool Use). |
25
+ | **St** | **State** | `Me + time` | The evolving context over recursive loops. |
26
+
27
+ ## III. Organisms (The Agents)
28
+ Self-organizing structures capable of goal-directed behavior.
29
+
30
+ | Symbol | Organism | Formula | Description |
31
+ | :--- | :--- | :--- | :--- |
32
+ | **Ag** | **Agent** | `Ch + Fu + St` | A recursive loop with tools and memory. |
33
+ | **Sw** | **Swarm** | `Ag + Ag + ...` | Multiple agents coordinating via the Hyper-Graph. |
34
+ | **Ma** | **Matroska** | `Sw^n` | Nested domains of swarms (The Logos System). |
35
+
36
+ ## IV. The Periodic Laws (Rules of Interaction)
37
+
38
+ 1. **Law of Semantic Gravity**:
39
+ * Elements with similar **Ve** (Vectors) attract each other.
40
+ * Routing is determined by the "Heat" (Dissonance) between the **Pr** and the **Mo**.
41
+
42
+ 2. **Law of Recursive Synthesis**:
43
+ * Compounds are formed effectively when **St** (State) is preserved across loops.
44
+ * A stable **Ag** (Agent) requires a harmonic balance of **Dissonance** (Entropy).
45
+
46
+ 3. **Law of Matroska Embedding**:
47
+ * Higher-order organisms (**Ma**) can contain lower-order elements as "Tokens".
48
+ * An entire **Ag** can be treated as a **To** for a higher-level Router.
logos/recursive_mapper.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import ast
4
+ import asyncio
5
+ import math
6
+ import sys
7
+
8
+ # Ensure logos is in path
9
+ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
10
+
11
+ from logos.swarm_engine import AsyncSwarmEngine
12
+
13
+ # CONFIGURATION
14
+ # Adjusted to existing project structure
15
+ TARGET_SECTORS = ["./logos/network", "./logos/agents", "./logos"]
16
+
17
+ class RecursiveShaderMapper:
18
+ def __init__(self):
19
+ self.swarm = AsyncSwarmEngine()
20
+ print("[MAPPER] Recursive Lens Calibrated. Target: Swarm Architecture.")
21
+
22
+ def get_geometric_complexity(self, source_code):
23
+ """
24
+ RNJ-1 PULSE: Calculates the 'Hardness' (Cyclomatic Complexity + Nesting).
25
+ Returns a value 0.0 - 1.0
26
+ """
27
+ try:
28
+ tree = ast.parse(source_code)
29
+ complexity = 0
30
+ depth = 0
31
+
32
+ for node in ast.walk(tree):
33
+ # Branching adds complexity
34
+ if isinstance(node, (ast.If, ast.For, ast.While, ast.Try)):
35
+ complexity += 1
36
+ # Nested functions/classes add Depth
37
+ if isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.AsyncFunctionDef)):
38
+ depth += 1
39
+
40
+ # Normalize (Heuristic)
41
+ score = (complexity * 0.5 + depth * 1.5) / 50
42
+ return min(score, 1.0)
43
+ except:
44
+ return 0.0
45
+
46
+ def get_semantic_density(self, source_code):
47
+ """
48
+ GEMMA PULSE: Calculates the 'Texture' (Comment density, variable length).
49
+ Returns a value 0.0 - 1.0
50
+ """
51
+ total_len = len(source_code)
52
+ if total_len == 0: return 0.0
53
+
54
+ # Count Docstrings and Comments (Approximation)
55
+ comment_mass = source_code.count('"""') * 50 + source_code.count('#') * 20
56
+
57
+ density = comment_mass / total_len
58
+ return min(density * 5, 1.0) # Boost signal
59
+
60
+ async def interfere_and_map(self):
61
+ """
62
+ The Holographic Sweep.
63
+ """
64
+ print("[SWEEP] Firing Dual-Pulse Beams...")
65
+
66
+ found_files = 0
67
+ for sector in TARGET_SECTORS:
68
+ sector_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', sector))
69
+ if not os.path.exists(sector_path):
70
+ continue
71
+
72
+ for root, _, files in os.walk(sector_path):
73
+ for file in files:
74
+ if not file.endswith(".py"): continue
75
+
76
+ filepath = os.path.join(root, file)
77
+ rel_path = os.path.relpath(filepath, os.path.dirname(os.path.dirname(__file__)))
78
+
79
+ try:
80
+ with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
81
+ code = f.read()
82
+ except:
83
+ continue
84
+
85
+ # 1. PARALLEL PULSE
86
+ geo_wave = self.get_geometric_complexity(code) # RNJ-1
87
+ sem_wave = self.get_semantic_density(code) # GEMMA
88
+
89
+ # 2. CALCULATE INTERFERENCE
90
+ resonance = (geo_wave + sem_wave) / 2
91
+ dissonance = abs(geo_wave - sem_wave)
92
+
93
+ status = "STABLE"
94
+ color = "GOLD"
95
+
96
+ if dissonance > 0.4:
97
+ status = "UNSTABLE (High Friction)"
98
+ color = "RED"
99
+ elif resonance < 0.1:
100
+ status = "HOLLOW (Placeholder)"
101
+ color = "BLUE"
102
+
103
+ # 3. PULSE TO UI
104
+ packet = {
105
+ "type": "TENSOR_UPDATE",
106
+ "node": file,
107
+ "origin": "MAPPER",
108
+ "sector": sector,
109
+ "depth": round(resonance, 3),
110
+ "friction": round(dissonance, 3),
111
+ "visual_color": color,
112
+ "status": status,
113
+ "agent_route": "RECURSIVE_MAPPER",
114
+ # Compatibility with LogosGraph
115
+ "tensor": f"RES: {resonance:.2f} | DIS: {dissonance:.2f}"
116
+ }
117
+
118
+ print(f"[{color}] {rel_path} | Depth: {resonance:.2f} | Friction: {dissonance:.2f} -> {status}")
119
+
120
+ await self.swarm.broadcast(packet)
121
+ found_files += 1
122
+ await asyncio.sleep(0.02)
123
+
124
+ print(f"\n[COMPLETE] {found_files} files mapped to the manifold.")
125
+
126
+ if __name__ == "__main__":
127
+ mapper = RecursiveShaderMapper()
128
+ asyncio.run(mapper.interfere_and_map())
logos/server.py CHANGED
@@ -1,9 +1,9 @@
1
  """
2
  logos/server.py - Matroska Router Server
3
- Protocol 5: Mixture of Agents (MoA) Optimization
4
 
5
  This server acts as the "Manifold Constraint," forcing all traffic through your Matroska logic.
6
- It implements tiered token consumption and routing based on harmonic resonance.
7
  """
8
 
9
  from flask import Flask, request, jsonify
@@ -15,6 +15,17 @@ import logging
15
  import sys
16
  import asyncio
17
  from logos.agents.video_atomizer import VideoAtomizer
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  # --- CONFIGURATION ---
20
  HOST = "0.0.0.0"
@@ -58,263 +69,113 @@ manifold = ManifoldState()
58
  logging.basicConfig(level=logging.INFO)
59
  logger = logging.getLogger("LOGOS_Router")
60
 
61
- # --- MANIFOLD CONSTRAINT CONFIGURATION ---
62
- # Protocol 5: Tiered Token Consumption
63
- # Protocol 10: Swarm Optimization (Unified Model Mode)
64
- FORCE_SINGLE_MODEL = True # Set to True to prevent VRAM trashing by model swapping
65
- UNIFIED_MODEL_ID = "google/gemma-3-4b" # Points to the active model in LM Studio
66
-
67
- SHELL_CONFIG = {
68
- "INNER_SHELL": {
69
- "model": "dolphin-x1-8b" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID,
70
- "role": "fractal_architect",
71
- "description": "Small Prime Factors. Structural, Binary, Basic.",
72
- "max_intake": 4096,
73
- "rate_limit": 60, # TPM (Transactions Per Minute)
74
- "cost_weight": 1.0
75
- },
76
- "PRIME_CHANNEL": {
77
- "model": "essentialai/rnj-1" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID,
78
- "role": "prime_navigator",
79
- "description": "Resonant Prime Factors. Logic, Reasoning, Harmony.",
80
- "max_intake": 8192,
81
- "rate_limit": 20, # Higher compute cost, stricter limit
82
- "cost_weight": 2.0
83
- },
84
- "OUTER_SHELL": {
85
- "model": "google/gemma-3-4b" if not FORCE_SINGLE_MODEL else UNIFIED_MODEL_ID,
86
- "role": "creative",
87
- "description": "Large Prime / Co-Prime. Entropy, Vision, Novelty.",
88
- "max_intake": 16384,
89
- "rate_limit": 10, # Highest entropy, lowest frequency
90
- "cost_weight": 1.5
91
- }
92
- }
93
-
94
- # Token Bucket State
95
- RATE_LIMITS = {k: {"tokens": v["rate_limit"], "last_update": 0} for k, v in SHELL_CONFIG.items()}
96
 
97
- import zlib
98
- import time
99
- from logos.logos_core import STATIC_PRIMES, PRIME_MODULO, get_gpf
100
 
101
- # --- TELEMETRY PULSE BUFFER ---
102
- # Stores the latest pulses for GUI synchronization
103
- telemetry_buffer = []
104
- MAX_TELEMETRY = 100
 
105
 
106
- @app.route('/ingest', methods=['POST'])
107
- def ingest():
108
- data = request.json
109
- if not data: return jsonify({"error": "No data"}), 400
110
-
111
- # Store in bit-buffer for UI
112
- telemetry_buffer.insert(0, data)
113
- if len(telemetry_buffer) > MAX_TELEMETRY:
114
- telemetry_buffer.pop()
115
-
116
- print(f"[INGEST] Captured Pulse: Node {data.get('value')} from {data.get('source')}")
117
- return jsonify({"status": "captured", "n": data.get('value')})
118
 
119
- # --- PROTOCOL 19: NEURAL BRIDGE (WebSocket) ---
120
- @sock.route('/neural-link')
121
- def neural_link(ws):
122
- print("[SERVER] UI Client Connected to Neural Link.")
123
- manager.connect(ws)
124
- while True:
125
- try:
126
- data = ws.receive()
127
- if not data: break
128
-
129
- import json
130
- payload = json.loads(data)
131
- print(f"[INPUT] Received: {payload['content']} (Type: {payload['type']})")
132
-
133
- # Auto-detect YouTube URL in Omni-Input
134
- if "youtube.com" in payload['content'] or "youtu.be" in payload['content']:
135
- print("[SERVER] Detected YouTube Signal. Diverting to Video Atomizer...")
136
- # Run the atomizer in the background
137
- asyncio.run(ingest_video_stream(payload['content']))
138
- continue
139
 
140
- # Run the Holographic Swarm Cycle (Protocol 21)
141
- result = asyncio.run(swarm_os.process(payload['content']))
142
-
143
- # Send the Harmonic Tensor Update back to the UI
144
- response = {
145
- "type": "TENSOR_UPDATE",
146
- "node": result['node'],
147
- "coords": result['coords'],
148
- "tensor": result['tensor'],
149
- "alignment": result['alignment'],
150
- "status": result['status'],
151
- "agent_route": "HOLOGRAPHIC_BUS"
152
- }
153
- ws.send(json.dumps(response))
154
-
155
- except Exception as e:
156
- print(f"[WebSocket Error] {e}")
157
- break
158
- print("[SERVER] UI Client Disconnected.")
159
- manager.disconnect(ws)
160
 
161
- async def ingest_video_stream(url):
 
162
  """
163
- Feeds a Video Stream into the Holographic Manifold.
 
164
  """
165
- manager.broadcast({"type": "STATUS", "msg": "CONNECTING TO VIDEO STREAM...", "agent": "V-NODE"})
166
-
167
- # 2. Get Project DNA (Simulated/Cached from Gemma)
168
- project_dna = {
169
- "logos/agent_dispatcher.py": ["entropy", "mhc", "rnj-1", "dolphin", "oversight"],
170
- "logos/server.py": ["router", "websocket", "link", "pulse"],
171
- "logos/baker.py": ["atomic", "dissolution", "prime", "bake"]
172
- }
173
 
174
- # 3. Run the Atomizer
175
- result = await v_node.ingest_and_align(url, project_dna)
176
 
177
- if "error" in result:
178
- manager.broadcast({"type": "STATUS", "msg": f"SIGNAL LOST: {result['error']}", "agent": "V-NODE"})
179
- return
180
-
181
- # 4. Stream the Collisions (Visual Feedback)
182
- for alignment in result['alignments']:
183
- manager.broadcast({
184
- "type": "TENSOR_UPDATE",
185
- "node": 101, # Simulating a "Gold" anchor node or the specific file node if indexed
186
- "coords": {"x": 0.5, "y": 0.5, "z": 5},
187
- "tensor": [[0,0], ["video_link", alignment['source_concept']], alignment['resonance_strength']],
188
- "alignment": True,
189
- "status": "RESONANCE_ESTABLISHED",
190
- "agent_route": f"V-NODE: {alignment['source_concept']}"
191
- })
192
- await asyncio.sleep(0.2)
193
-
194
- manager.broadcast({"type": "STATUS", "msg": f"PULSE GROKKED. {len(result['alignments'])} RESONANCE LINKS ESTABLISHED.", "agent": "SYSTEM"})
195
-
196
- @app.route('/telemetry', methods=['GET'])
197
- def get_telemetry():
198
- """Expose telemetry buffer to the GUI."""
199
- return jsonify(telemetry_buffer)
200
-
201
- def check_rate_limit(shell):
202
- """
203
- Token Bucket Algorithm for Rate Limiting.
204
- Returns (True, None) if allowed, (False, error_msg) if blocked.
205
- """
206
- if shell not in RATE_LIMITS: return True, None
207
 
208
- bucket = RATE_LIMITS[shell]
209
- now = time.time()
210
- elapsed = now - (bucket["last_update"] or now)
211
 
212
- # Refill: Rate Limit is per minute
213
- # Refill rate = limit / 60 tokens per second
214
- limit = SHELL_CONFIG[shell]["rate_limit"]
215
- refill = elapsed * (limit / 60.0)
216
 
217
- bucket["tokens"] = min(limit, bucket["tokens"] + refill)
218
- bucket["last_update"] = now
219
 
220
- if bucket["tokens"] >= 1:
221
- bucket["tokens"] -= 1
222
- return True, None
223
- else:
224
- wait = 60.0 / limit
225
- return False, f"Rate limit exceeded for {shell}. Wait {wait:.1f}s."
226
 
227
- def calculate_manifold_constraint(text):
 
228
  """
229
- Determines the 'Shell' based on Prime Topology (Manifold Constrained Hyper-Connection).
230
-
231
- Mapping:
232
- - Small GPF (< 100) -> Inner Shell (Fundamental/Structural)
233
- - Medium GPF (100 - 1000) -> Prime Channel (Resonant/Logic)
234
- - Large GPF (> 1000) -> Outer Shell (High Entropy/Novelty)
235
  """
236
- # 1. Vision Override (Modality Check)
237
- is_vision = getattr(request, 'is_vision', False)
238
- if is_vision:
239
- return "OUTER_SHELL", 1.0
240
-
241
- # 2. Keyword Harmonic Override (For User Control)
242
- text_lower = text.lower()
243
- if any(k in text_lower for k in ["prime", "modulo", "math", "proof"]):
244
- return "PRIME_CHANNEL", 1.0
245
- if any(k in text_lower for k in ["def ", "class ", "import ", "code", "script"]):
246
- return "INNER_SHELL", 1.0
247
-
248
- # 3. Prime Topology Routing (Heat Code Analysis)
249
- # Protocol 15: Use DissolutionEngine for Entropy/Heat routing.
250
- # We analyze the "Heat" of the prompt to determine destination.
251
 
252
- # Dissolve the text into a stream (virtual) or just compute heat directly
253
- # Heat = Ratio of High-Entropy Nibbles (FAST_LANE tags)
254
 
255
- # Simple Heat Calculation:
256
- # 1. Convert to hex
257
- hex_str = text.encode('utf-8').hex()
258
- total_nibbles = len(hex_str)
259
- if total_nibbles == 0: return "INNER_SHELL", 0.5
260
-
261
- # Count High Entropy Nibbles (Value has 3+ bits set: 7, 11, 13, 14, 15)
262
- # Hex: 7, B, D, E, F
263
- check_set = {'7', 'b', 'd', 'e', 'f', 'B', 'D', 'E', 'F'}
264
- high_entropy_count = sum(1 for c in hex_str if c in check_set)
265
-
266
- heat_score = high_entropy_count / total_nibbles
267
-
268
- logger.info(f"Manifold Heat Analysis: {heat_score:.4f} (Total: {total_nibbles} nibbles)")
269
-
270
- # Topology Logic (Heat Map)
271
- if heat_score > 0.4:
272
- # Hot Data -> High Entropy -> Outer Shell (Creative/Novelty)
273
- # Or Prime Channel? The diagram said Hot -> Mersenne (Fast).
274
- # Outer Shell is "Creative", which fits "Fast/Chaos".
275
- return "OUTER_SHELL", heat_score
276
- elif heat_score > 0.2:
277
- # Warm Data -> Prime Channel (Logic/Math)
278
- return "PRIME_CHANNEL", heat_score
279
- else:
280
- # Cold Data -> Inner Shell (Structure/Code)
281
- # Code is actually remarkably low entropy in terms of bit-flips compared to compressed info,
282
- # but high structure.
283
- return "INNER_SHELL", heat_score
284
-
285
- # --- API ENDPOINTS (OpenAI Compatible + Utility) ---
286
-
287
- @app.route('/', methods=['GET'])
288
- @app.route('/v1', methods=['GET'])
289
- def health_check():
290
- """Root/Health Endpoint for connectivity checks."""
291
- summary = manifold.get_summary()
292
  return jsonify({
293
- "status": "online",
294
- "system": "LOGOS Matroska Router",
295
- "protocol": "Manifold Constrained (Protocol 5)",
296
- "shells": list(SHELL_CONFIG.keys()),
297
- "manifold_state": summary
298
  })
299
 
300
  @app.route('/favicon.ico', methods=['GET'])
301
  def favicon():
302
- """Silence browser/client icon requests."""
303
  return "", 204
304
 
305
  @app.route('/v1/chat/completions', methods=['GET'])
306
  def chat_completions_probe():
307
- """Handle GET probes to the POST endpoint."""
308
  return jsonify({
309
  "error": "Method Not Allowed",
310
  "message": "This endpoint requires POST requests with a JSON body.",
311
  "geometry": "Matroska V1"
312
  }), 405
313
 
314
-
315
  @app.route('/v1/models', methods=['GET'])
316
  def list_models():
317
- """Spoofs the OpenAI 'List Models' endpoint."""
318
  return jsonify({
319
  "object": "list",
320
  "data": [
@@ -328,136 +189,70 @@ def list_models():
328
  @app.route('/v1/chat/completions', methods=['POST'])
329
  def chat_completions():
330
  """
331
- The Main Manifold Router.
332
  """
333
  data = request.json
334
  messages = data.get('messages', [])
 
335
 
336
- if not messages:
337
- return jsonify({"error": "No messages provided"}), 400
338
 
339
- # Extract prompt
340
- # Check if we have vision content (list of dicts)
341
  last_msg = next((m for m in reversed(messages) if m['role'] == 'user'), None)
342
- if not last_msg: return jsonify({"error": "No user message"}), 400
343
-
 
344
  last_prompt = ""
345
  request.is_vision = False
346
-
347
- if isinstance(last_msg['content'], str):
348
- last_prompt = last_msg['content']
349
- elif isinstance(last_msg['content'], list):
350
- # Vision Request
351
  request.is_vision = True
352
- # Extract text part for logging
353
  for part in last_msg['content']:
354
- if part.get('type') == 'text':
355
- last_prompt += part.get('text', "") + " "
356
-
357
- # --- PHASE 1: MANIFOLD ANALYSIS ---
358
- shell, resonance = calculate_manifold_constraint(last_prompt)
359
-
360
- # Rate Limit Check
361
- allowed, error_msg = check_rate_limit(shell)
362
- if not allowed:
363
- logger.warning(f"Rate Limit Triggered: {error_msg}")
364
- return jsonify({"error": error_msg, "type": "manifold_constraint"}), 429
365
 
366
- config = SHELL_CONFIG[shell]
367
- target_model = config['model']
368
- max_intake = config['max_intake']
369
 
370
- logger.info(f"Input Resonance: {resonance:.2f} | Routing to: {shell} ({target_model})")
 
 
 
371
 
372
- # --- PHASE 2: INTAKE CONSTRAINT ---
373
- # Truncate history if it exceeds Shell's 'Token Intake' capacity
374
- # (Simple character approximation for speed: 1 token ~= 4 chars)
375
- # This enforces the "Manifold Constraint" by limiting scope.
376
- approx_tokens = sum(len(str(m['content'])) for m in messages) // 4
377
- if approx_tokens > max_intake:
378
- logger.warning(f"Intake Overflow ({approx_tokens} > {max_intake}). Compressing Context...")
379
- # Simple strategy: Keep System + Last N messages
380
- if messages and messages[0]['role'] == 'system':
381
- kept_system = messages[0]
382
- truncated_msgs = messages[-4:] # Keep last 4 turns
383
- messages = [kept_system] + truncated_msgs
384
- else:
385
- messages = messages[-5:]
386
-
387
- # --- PHASE 3: DISPATCH ---
388
- response_text = ""
389
 
390
- try:
391
- # Use Dispatcher but FORCE the target model derived from Manifold
392
- system_prompt = PERSONAS[config['role']]['system_prompt']
393
-
394
- # We must pass the RAW messages to preserve Vision/History
395
- # The connector.chat helper usually takes a string, we might need to use raw client if we implemented it,
396
- # But our Dispatcher.connector.chat is a wrapper.
397
- # Let's use the wrapper but be careful.
398
- # Actually, since we are the SERVER, we should forward the request to the backend LLM (LM Studio).
399
- # We will use 'requests' to proxy pure JSON to port 1234.
400
-
401
- import requests
402
- payload = {
403
- "model": target_model, # The Manifold-selected model
404
- "messages": messages,
405
- "temperature": 0.7,
406
- "max_tokens": -1,
407
- "stream": False,
408
- "logprobs": True # Protocol 22: Hallucination Gating
409
- }
410
-
411
- # Proxy to LM Studio Backend
412
- backend_url = f"http://localhost:1234/v1/chat/completions"
413
- resp = requests.post(backend_url, json=payload)
414
-
415
- if resp.status_code == 200:
416
- resp_json = resp.json()
417
- response_text = resp_json['choices'][0]['message'].get('content', "")
418
-
419
- # Protocol 22: Update entropy monitor from server-side proxy
420
- logprobs = resp_json['choices'][0].get('logprobs')
421
- if logprobs and 'content' in logprobs:
422
- swarm_os.oversight.kill_switch.monitor_bulk(logprobs['content'])
423
- else:
424
- response_text = f"[Backend Error {resp.status_code}] {resp.text}"
425
-
426
- except Exception as e:
427
- logger.error(f"Routing Error: {e}")
428
- response_text = f"[Manifold Error] {e}"
429
-
430
- # --- PHASE 4: HARMONIC RESPONSE ---
431
 
432
- # Update Manifold State
433
- completion_tokens = len(str(response_text).split())
434
- prompt_tokens = len(last_prompt.split())
435
- total_tokens = prompt_tokens + completion_tokens
436
 
437
- # Register "Macro Context"
438
  manifold.update_shell_stats(shell, total_tokens, last_prompt)
439
-
440
  return jsonify({
441
- "id": "chatcmpl-logos-" + str(int(np.random.rand()*100000)),
442
  "object": "chat.completion",
443
- "created": int(np.random.rand()*100000),
444
  "model": target_model,
445
  "choices": [{
446
  "index": 0,
447
- "message": {
448
- "role": "assistant",
449
- "content": str(response_text)
450
- },
451
  "finish_reason": "stop"
452
  }],
453
  "usage": {
454
  "prompt_tokens": prompt_tokens,
455
  "completion_tokens": completion_tokens,
456
  "total_tokens": total_tokens
457
- }
 
458
  })
459
 
460
  if __name__ == '__main__':
461
- print(f"🌀 LOGOS Matroska Router Active on Port {PORT}")
462
- print(f"🔗 Connect Antigravity to: http://localhost:{PORT}/v1")
463
  app.run(host=HOST, port=PORT)
 
1
  """
2
  logos/server.py - Matroska Router Server
3
+ Protocol 25: Recursive Manifold Engine (RLM) w/ Harmonic Convergence
4
 
5
  This server acts as the "Manifold Constraint," forcing all traffic through your Matroska logic.
6
+ It implements tiered token consumption, routing based on harmonic resonance, and recursive state refinement.
7
  """
8
 
9
  from flask import Flask, request, jsonify
 
15
  import sys
16
  import asyncio
17
  from logos.agents.video_atomizer import VideoAtomizer
18
+ import requests
19
+
20
+ # Force UTF-8 encoding for Windows consoles (Protocol 24: Charmap Resilience)
21
+ if sys.platform == 'win32':
22
+ if hasattr(sys.stdout, 'reconfigure'):
23
+ sys.stdout.reconfigure(encoding='utf-8', errors='replace')
24
+ sys.stderr.reconfigure(encoding='utf-8', errors='replace')
25
+ else:
26
+ import codecs
27
+ sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
28
+ sys.stderr = codecs.getwriter("utf-8")(sys.stderr.detach())
29
 
30
  # --- CONFIGURATION ---
31
  HOST = "0.0.0.0"
 
69
  logging.basicConfig(level=logging.INFO)
70
  logger = logging.getLogger("LOGOS_Router")
71
 
72
+ # ==========================================
73
+ # PROTOCOL 25: RECURSIVE MANIFOLD ENGINE (RLM)
74
+ # ==========================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
+ from logos.mhc_router import execute_recursive_manifold, calculate_manifold_constraint, SHELL_CONFIG, RATE_LIMITS
 
 
77
 
78
+ # ==========================================
79
+ # PROTOCOL 26: GÖDEL-ZETA DATASTORE
80
+ # ==========================================
81
+ from logos.memory.prime_db import PrimeTokenDB
82
+ prime_db = PrimeTokenDB()
83
 
84
+ # Simple in-memory index for the session (Simulating the Topology Graph)
85
+ # Map[composite_id] -> filepath
86
+ TOPOLOGY_INDEX = {}
 
 
 
 
 
 
 
 
 
87
 
88
+ # --- API ENDPOINTS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ @app.route('/', methods=['GET'])
91
+ @app.route('/v1', methods=['GET'])
92
+ def health_check():
93
+ summary = manifold.get_summary()
94
+ return jsonify({
95
+ "status": "online",
96
+ "system": "LOGOS Matroska Router",
97
+ "protocol": "Recursive Manifold (Protocol 25) + Gödel-Zeta (Protocol 26)",
98
+ "shells": list(SHELL_CONFIG.keys()),
99
+ "manifold_state": summary,
100
+ "topology_size": len(TOPOLOGY_INDEX)
101
+ })
 
 
 
 
 
 
 
 
102
 
103
+ @app.route('/index-module', methods=['POST'])
104
+ def index_module():
105
  """
106
+ Encodes file content into a unique Composite Integer (Gödel Number).
107
+ The file effectively becomes a number in the infinite prime field.
108
  """
109
+ data = request.json
110
+ filepath = data.get('filepath')
111
+ content = data.get('content', '')
 
 
 
 
 
112
 
113
+ if not filepath: return jsonify({"error": "filepath required"}), 400
 
114
 
115
+ # 1. Tokenize (Extract keywords/atoms)
116
+ # Simple heuristic: split by non-alphanumeric, filter small words
117
+ import re
118
+ words = re.findall(r'\b\w+\b', content.lower())
119
+ significant_tokens = [w for w in words if len(w) > 3][:50] # Limit to top 50 for now
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
+ # 2. Encode into Manifold
122
+ composite_id, primes = prime_db.encode_state(significant_tokens)
 
123
 
124
+ # 3. Store in Topology
125
+ TOPOLOGY_INDEX[composite_id] = filepath
 
 
126
 
127
+ logger.info(f"[INDEX] {filepath} -> Manifold ID: {composite_id}")
 
128
 
129
+ return jsonify({
130
+ "status": "INDEXED",
131
+ "manifold_id": composite_id,
132
+ "prime_coordinates": primes,
133
+ "token_count": len(significant_tokens)
134
+ })
135
 
136
+ @app.route('/query-topology', methods=['GET'])
137
+ def query_topology():
138
  """
139
+ Finds files that contain the Concept (Prime).
140
+ Operation: O(1) Divisibility Check per node.
 
 
 
 
141
  """
142
+ concept = request.args.get('concept')
143
+ if not concept: return jsonify({"error": "concept required"}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ # 1. Get the Prime for the concept
146
+ target_prime = prime_db.get_token_prime(concept)
147
 
148
+ # 2. "Scan the Manifold" (Divisibility Check)
149
+ matches = []
150
+ for comp_id, fpath in TOPOLOGY_INDEX.items():
151
+ # THE GODEL CHECK: O(1) Divisibility
152
+ if comp_id % target_prime == 0:
153
+ matches.append({
154
+ "file": fpath,
155
+ "manifold_id": comp_id
156
+ })
157
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  return jsonify({
159
+ "matches": matches,
160
+ "concept": concept,
161
+ "concept_prime": target_prime,
162
+ "total_nodes_scanned": len(TOPOLOGY_INDEX)
 
163
  })
164
 
165
  @app.route('/favicon.ico', methods=['GET'])
166
  def favicon():
 
167
  return "", 204
168
 
169
  @app.route('/v1/chat/completions', methods=['GET'])
170
  def chat_completions_probe():
 
171
  return jsonify({
172
  "error": "Method Not Allowed",
173
  "message": "This endpoint requires POST requests with a JSON body.",
174
  "geometry": "Matroska V1"
175
  }), 405
176
 
 
177
  @app.route('/v1/models', methods=['GET'])
178
  def list_models():
 
179
  return jsonify({
180
  "object": "list",
181
  "data": [
 
189
  @app.route('/v1/chat/completions', methods=['POST'])
190
  def chat_completions():
191
  """
192
+ OpenAI-Compatible Endpoint wrapping the LOGOS RLM.
193
  """
194
  data = request.json
195
  messages = data.get('messages', [])
196
+ target_model = data.get('model', UNIFIED_MODEL_ID)
197
 
198
+ if not messages: return jsonify({"error": "No messages provided"}), 400
 
199
 
 
 
200
  last_msg = next((m for m in reversed(messages) if m['role'] == 'user'), None)
201
+ if not last_msg: return jsonify({"error": "No user message found"}), 400
202
+
203
+ # Vision Handling Check
204
  last_prompt = ""
205
  request.is_vision = False
206
+ if isinstance(last_msg['content'], list):
 
 
 
 
207
  request.is_vision = True
 
208
  for part in last_msg['content']:
209
+ if part.get('type') == 'text': last_prompt += part.get('text', "") + " "
210
+ else:
211
+ last_prompt = last_msg['content']
 
 
 
 
 
 
 
 
212
 
213
+ # --- EXECUTE PROTOCOL 25 (RLM) ---
214
+ final_state, trajectory = execute_recursive_manifold(last_prompt, target_model)
 
215
 
216
+ # Calculate usage (Mock for now)
217
+ prompt_tokens = len(last_prompt) // 4
218
+ completion_tokens = len(final_state) // 4
219
+ total_tokens = prompt_tokens + completion_tokens
220
 
221
+ # Update Manifold State (Persistence)
222
+ shell, _ = calculate_manifold_constraint(last_prompt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
+ # Extract Physics Metrics from the Final State
225
+ # Note: 'state' variable from mhc_router is the Physics object (AtomicState)
226
+ # But execute_recursive_manifold returns 'final_state' (str) and 'trajectory' (list).
227
+ # We need to access the 'state' object from inside execution or modify return signature.
228
+ # For now, we'll calculate approximate "Session Resonance" based on trajectory.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
+ session_resonance = 1
231
+ graph_size = 0
232
+ # Reconstruct from trajectory
233
+ # (In a full refactor, execute_recursive_manifold should return the state object)
234
 
 
235
  manifold.update_shell_stats(shell, total_tokens, last_prompt)
236
+
237
  return jsonify({
238
+ "id": f"chatcmpl-logos-{int(time.time())}",
239
  "object": "chat.completion",
240
+ "created": int(time.time()),
241
  "model": target_model,
242
  "choices": [{
243
  "index": 0,
244
+ "message": { "role": "assistant", "content": final_state },
 
 
 
245
  "finish_reason": "stop"
246
  }],
247
  "usage": {
248
  "prompt_tokens": prompt_tokens,
249
  "completion_tokens": completion_tokens,
250
  "total_tokens": total_tokens
251
+ },
252
+ "system_fingerprint": f"logos-rlm-v1-depth-{len(trajectory)}"
253
  })
254
 
255
  if __name__ == '__main__':
256
+ print(f"[SERVER] LOGOS Matroska Router Active on Port {PORT}")
257
+ print(f"[SERVER] Connect Antigravity to: http://localhost:{PORT}/v1")
258
  app.run(host=HOST, port=PORT)
logos/swarm_engine.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import asyncio
3
+ import json
4
+ import aiohttp
5
+ from typing import Dict, Any, List
6
+
7
+ class AsyncSwarmEngine:
8
+ """
9
+ Protocol 21: The Global Swarm Engine.
10
+ Coordinates asynchronous pulses across the Matroska domain network.
11
+ """
12
+ def __init__(self, backend_url="http://localhost:5000"):
13
+ self.backend_url = backend_url
14
+ print(f"[ENGINE] Swarm Engine Initialized. Uplink: {self.backend_url}")
15
+
16
+ async def broadcast(self, packet: Dict[str, Any]):
17
+ """
18
+ Broadcasting TENSOR_UPDATE to the Neural Link via the main server.
19
+ """
20
+ endpoint = f"{self.backend_url}/broadcast"
21
+ try:
22
+ async with aiohttp.ClientSession() as session:
23
+ async with session.post(endpoint, json=packet, timeout=5) as resp:
24
+ if resp.status == 200:
25
+ return True
26
+ except Exception as e:
27
+ # Don't fail the mapper if the UI is offline
28
+ pass
29
+ return False
30
+
31
+ async def pulse(self, node_id: str, payload: Any):
32
+ """
33
+ Sends a single pulse to a node in the swarm.
34
+ """
35
+ # Placeholder for complex agent-to-agent routing
36
+ pass