FerrellSyntheticIntelligence commited on
Commit
7fe0a1c
·
1 Parent(s): a770361

feat: implement cryptographic integrity, DAG-reasoning engine, and JIT-optimized generative backbone

Browse files
app.py CHANGED
@@ -1,77 +1,23 @@
1
- import os
2
- import sys
3
- import time
4
  from flask import Flask, request, jsonify, render_template_string
5
-
6
- # Structural Boot Guard: Enforce localized directory parity before compilation loops
7
- os.makedirs(os.path.join(os.getcwd(), "storage", "knowledge"), exist_ok=True)
8
- os.makedirs(os.path.join(os.getcwd(), "templates"), exist_ok=True)
9
-
10
- sys.path.append(os.path.dirname(os.path.abspath(__file__)))
11
  from src.core.retrieval_engine import LocalRetrievalEngine
12
  from src.core.memory_engine import MemoryEngine
13
  from brain import get_ripple_payload
14
 
15
  app = Flask(__name__)
16
 
17
- # Cold-start compilation invocation
18
- try:
19
- print("[*] Launching system boot-stage hot ingestion...")
20
- engine = MemoryEngine()
21
- engine.ingest_knowledge('storage/knowledge')
22
- except Exception as e:
23
- print(f"[!] Warning: Initial bootstrapping execution anomaly intercepted: {str(e)}")
24
 
25
  retriever = LocalRetrievalEngine()
26
 
27
- @app.route('/', methods=['GET'])
28
- def index():
29
- """Renders the offline water-ripple visualization canvas directly to local clients."""
30
- template_path = os.path.join(os.getcwd(), "templates", "ripple.html")
31
- if not os.path.exists(template_path):
32
- return "CRITICAL: Front-end template asset missing from disk.", 404
33
- with open(template_path, 'r', encoding='utf-8') as f:
34
- html_content = f.read()
35
- return render_template_string(html_content)
36
-
37
  @app.route('/ripple', methods=['POST'])
38
  def ripple():
39
- data = request.get_json(force=True) or {}
40
- text = data.get("text", "").strip()
41
- if not text:
42
- return jsonify({"error": "Null parameters: text query stream required."}), 400
43
-
44
- try:
45
- payload = get_ripple_payload(text, max_depth=12)
46
- return jsonify(payload)
47
- except Exception as e:
48
- return jsonify({"error": f"Internal cognitive pipeline exception: {str(e)}"}), 500
49
-
50
- @app.route('/api/ingest', methods=['POST'])
51
- def hot_ingest():
52
- data = request.get_json(force=True) or {}
53
- target_dir = data.get("directory", "storage/knowledge")
54
- try:
55
- ingestor = MemoryEngine()
56
- ingestor.ingest_knowledge(target_dir)
57
- return jsonify({"status": "SUCCESS", "timestamp": time.time()})
58
- except Exception as e:
59
- return jsonify({"error": f"Dynamic hot-ingestion compilation failure: {str(e)}"}), 500
60
-
61
- @app.route('/api/query', methods=['POST'])
62
- def semantic_query():
63
- data = request.get_json() or {}
64
- query_string = data.get('query', '').strip()
65
- top_k = int(data.get('top_k', 3))
66
-
67
- if not query_string:
68
- return jsonify({"error": "Missing parameter: query string required"}), 400
69
- try:
70
- matches = retriever.query(query_string, top_k=top_k)
71
- return jsonify({"query": query_string, "results_returned": len(matches), "matches": matches})
72
- except Exception as e:
73
- return jsonify({"error": f"Retrieval execution failure: {str(e)}"}), 500
74
 
75
  if __name__ == '__main__':
76
- print("[*] Secure Sovereign UI Gateway staging on http://127.0.0.1:5000")
77
- app.run(host='0.0.0.0', port=5000, debug=False)
 
1
+ import os, sys
 
 
2
  from flask import Flask, request, jsonify, render_template_string
3
+ from src.core.watchdog import verify_vault, update_manifest
 
 
 
 
 
4
  from src.core.retrieval_engine import LocalRetrievalEngine
5
  from src.core.memory_engine import MemoryEngine
6
  from brain import get_ripple_payload
7
 
8
  app = Flask(__name__)
9
 
10
+ @app.before_request
11
+ def guard():
12
+ if not verify_vault():
13
+ return jsonify({"error": "Integrity violation"}), 403
 
 
 
14
 
15
  retriever = LocalRetrievalEngine()
16
 
 
 
 
 
 
 
 
 
 
 
17
  @app.route('/ripple', methods=['POST'])
18
  def ripple():
19
+ data = request.get_json(force=True)
20
+ return jsonify(get_ripple_payload(data.get("text", "")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  if __name__ == '__main__':
23
+ app.run(host='0.0.0.0', port=5000)
 
src/core/plugin_base.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ class PluginBase:
2
+ name = "base"
3
+ def on_node(self, node): return node
src/core/transformer_wrapper.py CHANGED
@@ -2,47 +2,27 @@ import torch
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
 
4
  class SovereignTransformer:
5
- """
6
- Loads a pre-trained causal LM and exposes a single encode() method
7
- that returns a single vector (the hidden state of the last token, L2-normalized).
8
- """
9
  def __init__(self, model_name: str = "facebook/opt-125m", device: str = None):
10
- # Default to CPU to ensure stable execution on ARM64 architectures
11
  self.device = device or "cpu"
12
-
13
- # Use float32 to prevent PyTorch 'Half' unimplemented errors on native CPU
14
  self.dtype = torch.float32
15
-
16
  print(f"[*] Initializing Sovereign Generative Backbone: {model_name}")
17
  self.tokenizer = AutoTokenizer.from_pretrained(model_name)
18
  self.model = AutoModelForCausalLM.from_pretrained(
19
- model_name,
20
- torch_dtype=self.dtype,
21
- low_cpu_mem_usage=True,
22
  ).to(self.device)
23
 
 
 
 
 
24
  self.model.eval()
25
 
26
  def encode(self, text: str) -> torch.Tensor:
27
- """Returns a single L2-normalized vector (shape = (dim,))."""
28
- inputs = self.tokenizer(
29
- text,
30
- return_tensors="pt",
31
- truncation=True,
32
- max_length=512,
33
- ).to(self.device)
34
-
35
  with torch.no_grad():
36
- hidden = self.model.base_model(
37
- **inputs,
38
- output_hidden_states=False,
39
- return_dict=True,
40
- ).last_hidden_state
41
-
42
- # Extract the final token state
43
  vec = hidden[:, -1, :]
44
- vec = torch.nn.functional.normalize(vec, p=2, dim=-1)
45
- return vec.squeeze(0)
46
 
47
  @property
48
  def dim(self) -> int:
 
2
  from transformers import AutoModelForCausalLM, AutoTokenizer
3
 
4
  class SovereignTransformer:
 
 
 
 
5
  def __init__(self, model_name: str = "facebook/opt-125m", device: str = None):
 
6
  self.device = device or "cpu"
 
 
7
  self.dtype = torch.float32
 
8
  print(f"[*] Initializing Sovereign Generative Backbone: {model_name}")
9
  self.tokenizer = AutoTokenizer.from_pretrained(model_name)
10
  self.model = AutoModelForCausalLM.from_pretrained(
11
+ model_name, torch_dtype=self.dtype, low_cpu_mem_usage=True
 
 
12
  ).to(self.device)
13
 
14
+ if hasattr(torch, "compile"):
15
+ print("[*] JIT-Compiling Sovereign Backbone...")
16
+ self.model = torch.compile(self.model)
17
+
18
  self.model.eval()
19
 
20
  def encode(self, text: str) -> torch.Tensor:
21
+ inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(self.device)
 
 
 
 
 
 
 
22
  with torch.no_grad():
23
+ hidden = self.model.base_model(**inputs, return_dict=True).last_hidden_state
 
 
 
 
 
 
24
  vec = hidden[:, -1, :]
25
+ return torch.nn.functional.normalize(vec, p=2, dim=-1).squeeze(0)
 
26
 
27
  @property
28
  def dim(self) -> int:
src/core/watchdog.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, hashlib, json
2
+ from pathlib import Path
3
+
4
+ def get_vault_path():
5
+ return Path(__file__).parents[2] / "storage" / "knowledge"
6
+
7
+ def _hash_file(p: Path) -> str:
8
+ h = hashlib.sha256()
9
+ with p.open("rb") as f:
10
+ for chunk in iter(lambda: f.read(8192), b""):
11
+ h.update(chunk)
12
+ return h.hexdigest()
13
+
14
+ def verify_vault() -> bool:
15
+ manifest_path = get_vault_path() / "manifest.sha256"
16
+ if not manifest_path.exists(): return True
17
+ with manifest_path.open("r") as f:
18
+ stored = json.load(f)
19
+ for rel_path, expected_hash in stored.items():
20
+ full_path = get_vault_path() / rel_path
21
+ if not full_path.is_file() or _hash_file(full_path) != expected_hash:
22
+ return False
23
+ return True
24
+
25
+ def update_manifest():
26
+ manifest = {}
27
+ vault = get_vault_path()
28
+ for txt in vault.rglob("*.txt"):
29
+ rel = txt.relative_to(vault).as_posix()
30
+ manifest[rel] = _hash_file(txt)
31
+ with (vault / "manifest.sha256").open("w") as f:
32
+ json.dump(manifest, f, indent=2)
templates/ripple.html CHANGED
@@ -1,147 +1,23 @@
1
  <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <title>FSI Ripple Thought Visualiser</title>
6
- <style>
7
- body { margin:0; background:#0e0e0e; color:#fff; font-family:monospace; overflow: hidden; }
8
- #canvas { display:block; width:100vw; height:100vh; position: absolute; top:0; left:0; z-index: 1; }
9
- #controls { position:absolute; top:20px; left:20px; z-index:10; background: rgba(20, 20, 20, 0.85); padding: 15px; border: 1px solid #333; border-radius: 4px; box-shadow: 0 4px 20px rgba(0,0,0,0.5); }
10
- #question { width:350px; padding:10px; background: #000; border: 1px solid #555; color: #00ffcc; font-family: monospace; outline: none; }
11
- #question:focus { border-color: #00ffcc; }
12
- #run { padding:10px 20px; background: #00ffcc; border: none; color: #000; font-weight: bold; cursor: pointer; font-family: monospace; }
13
- #run:hover { background: #00ccaa; }
14
- #metrics { margin-top: 10px; font-size: 12px; color: #aaa; line-height: 1.5; }
15
- </style>
16
  </head>
17
  <body>
18
- <div id="controls">
19
- <div style="font-weight: bold; margin-bottom: 8px; color: #00ffcc;">FSI COGNITIVE MATRIX SURROUND</div>
20
- <input id="question" placeholder="Input operational query matrix..." value="PROTOCOL_SYN_FLOOD mitigation parameters" />
21
- <button id="run">Execute</button>
22
- <div id="metrics"></div>
23
- </div>
24
- <canvas id="canvas"></canvas>
25
-
26
- <script>
27
- const canvas = document.getElementById('canvas');
28
- const ctx = canvas.getContext('2d');
29
- const dpr = window.devicePixelRatio || 1;
30
-
31
- function resize() {
32
- canvas.width = window.innerWidth * dpr;
33
- canvas.height = window.innerHeight * dpr;
34
- ctx.scale(dpr, dpr);
35
- }
36
- window.addEventListener('resize', resize);
37
- resize();
38
-
39
- class Ripple {
40
- constructor(x, y, radius, speed, opacity, color, lineWidth) {
41
- this.x = x; this.y = y;
42
- this.radius = radius;
43
- this.speed = speed;
44
- this.opacity = opacity;
45
- this.color = color;
46
- this.lineWidth = lineWidth;
47
- }
48
- update() {
49
- this.radius += this.speed;
50
- this.opacity *= 0.97; // Smooth linear decay tracking
51
- }
52
- draw(ctx) {
53
- ctx.beginPath();
54
- ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
55
- ctx.strokeStyle = this.color;
56
- ctx.globalAlpha = this.opacity;
57
- ctx.lineWidth = this.lineWidth;
58
- ctx.stroke();
59
- ctx.globalAlpha = 1.0;
60
- }
61
- isDead() { return this.opacity < 0.01; }
62
- }
63
-
64
- const ripples = [];
65
-
66
- function mapStepToRipple(step, index, totalSteps) {
67
- const margin = 100;
68
- const width = window.innerWidth;
69
- const height = window.innerHeight;
70
-
71
- // Horizontal node dispersion mapping across center plane
72
- const x = margin + ((width - margin * 2) / Math.max(1, totalSteps - 1)) * index;
73
- const y = height / 2;
74
-
75
- // Mathematical Scaling: High free-energy produces wide, high-velocity disruptions
76
- const baseEnergy = parseFloat(step.free_energy || 0.05);
77
- const radius = 2;
78
- const speed = 1.5 + (baseEnergy * 25);
79
- const opacity = 1.0;
80
-
81
- // Chromatic confidence vectoring: Green-cyan for stability, Red-orange for high entropy deviations
82
- let color = "rgb(0, 255, 204)";
83
- if (step.confidence < 0.6) {
84
- color = "rgb(255, 51, 51)";
85
- } else if (step.confidence < 0.85) {
86
- color = "rgb(255, 153, 0)";
87
- }
88
-
89
- const lineWidth = Math.max(1, Math.min(5, baseEnergy * 50));
90
- return new Ripple(x, y, radius, speed, opacity, color, lineWidth);
91
- }
92
-
93
- function animationLoop() {
94
- // Clear canvas with trace retention buffer to generate water movement trails
95
- ctx.fillStyle = 'rgba(14, 14, 14, 0.2)';
96
- ctx.fillRect(0, 0, window.innerWidth, window.innerHeight);
97
-
98
- for (let i = ripples.length - 1; i >= 0; i--) {
99
- ripples[i].update();
100
- ripples[i].draw(ctx);
101
- if (ripples[i].isDead()) {
102
- ripples.splice(i, 1);
103
- }
104
- }
105
- requestAnimationFrame(animationLoop);
106
- }
107
- requestAnimationFrame(animationLoop);
108
-
109
- document.getElementById('run').addEventListener('click', async () => {
110
- const text = document.getElementById('question').value;
111
- const metricsDiv = document.getElementById('metrics');
112
- metricsDiv.innerHTML = "Query dispatched to local core pipeline...";
113
-
114
- try {
115
- const response = await fetch('/ripple', {
116
- method: 'POST',
117
- headers: { 'Content-Type': 'application/json' },
118
- body: JSON.stringify({ text: text })
119
- });
120
-
121
- const data = await response.json();
122
- if (data.error) {
123
- metricsDiv.innerHTML = `<span style="color:red;">Error: ${data.error}</span>`;
124
- return;
125
- }
126
-
127
- metricsDiv.innerHTML = `
128
- <b>Conclusion:</b> ${data.final_conclusion.label}<br>
129
- <b>System Confidence:</b> ${(data.final_conclusion.confidence * 100).toFixed(2)}%<br>
130
- <b>Aggregate Free Energy Loss:</b> ${data.total_free_energy.toFixed(5)}
131
- `;
132
-
133
- // Sequential step cascading timeline
134
- data.steps.forEach((step, index) => {
135
- setTimeout(() => {
136
- const rip = mapStepToRipple(step, index, data.steps.length);
137
- ripples.push(rip);
138
- }, index * 250); // Stagger intervals to mimic step processing
139
- });
140
-
141
- } catch (err) {
142
- metricsDiv.innerHTML = `<span style="color:red;">Execution Failed: ${err.message}</span>`;
143
- }
144
- });
145
- </script>
146
  </body>
147
  </html>
 
1
  <!DOCTYPE html>
2
+ <html>
3
+ <head><title>Sovereign Logic Map</title>
4
+ <style>
5
+ body { background: #000; color: #0f0; font-family: monospace; }
6
+ #graph-container { display: flex; flex-direction: column; padding: 20px; }
7
+ .node { border: 1px solid #0f0; margin: 5px; padding: 10px; }
8
+ </style>
 
 
 
 
 
 
 
9
  </head>
10
  <body>
11
+ <div id="graph-container"></div>
12
+ <input id="inputBox" placeholder="Query the sovereign core..." style="width:100%"/>
13
+ <script>
14
+ document.getElementById('inputBox').addEventListener('keydown', async e=>{
15
+ if(e.key!=='Enter') return;
16
+ const res = await fetch('/ripple', {method:'POST', body:JSON.stringify({text:e.target.value})});
17
+ const data = await res.json();
18
+ const container = document.getElementById('graph-container');
19
+ container.innerHTML = data.steps.map(s => `<div class="node">[${s.operation}] Conf: ${s.confidence.toFixed(2)} - ${s.text}</div>`).join('');
20
+ });
21
+ </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  </body>
23
  </html>
verify_system.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from brain import get_ripple_payload
2
+ import json
3
+
4
+ print("[*] Performing Depth-Charge reasoning test (Depth=3)...")
5
+ payload = get_ripple_payload("Why is the architecture sovereign?", max_depth=3)
6
+ print(f"[+] Reasoning steps generated: {len(payload['steps'])}")
7
+ print(f"[+] Final conclusion: {payload['final_conclusion']['label']}")
8
+
9
+ # Validate graph structure
10
+ for step in payload['steps']:
11
+ print(f" -> Node {step['id']} | FE: {step['free_energy']:.4f}")