"""
Prime Processing Engine — 43-node asymmetric core (symplectic, energy-stable).

Listens on tcp://127.0.0.1:8081 and streams 348-byte binary frames:
  [4 bytes marker 0x434E4D54 ("43MT")] + 43 × (2 × float32 math/truth) = 348 bytes.

Also broadcasts a UDP JSON telemetry beacon to udp://127.0.0.1:9000 at 10 Hz.
"""

import socket
import struct
import json
import threading
import time
import numpy as np

# --- System configuration parameter constants ---
NUM_NODES = 43
OMEGA = (2.0 * np.pi) / NUM_NODES
WIRESHARK_MARKER = 0x434E4D54  # "43MT" — Wireshark display-filter identity

# Symplectic leapfrog / Stormer-Verlet constants.
# Harmonic part is integrated as an exact rotation; the nonlinear coupling
# is applied as a kick, which gives bounded energy error (O(DT^4) per step)
# instead of the unbounded drift the explicit-Euler formulation has.
GAMMA = 0.5
DT = 0.01

class PrimeProcessingEngine:
    def __init__(self):
        self.theta = np.linspace(0, 2 * np.pi, NUM_NODES, endpoint=False)
        self.math_nodes = np.cos(self.theta) * np.sin(3 * self.theta)
        self.truth_nodes = np.sin(self.theta) * np.sin(3 * self.theta)
        self.love_nodes = np.sqrt(np.abs(self.math_nodes * self.truth_nodes) + 0.1)
        self.c0_invariant = 0.0
        self.lock = threading.Lock()

    def process_matrix_iteration(self):
        with self.lock:
            # 1) Half-kick on (truth, love) using the nonlinear coupling.
            gamma = np.sqrt(np.abs(self.math_nodes * self.truth_nodes) + 0.05) * GAMMA
            self.truth_nodes += -gamma * self.love_nodes * (DT / 2.0)
            self.love_nodes  +=  gamma * self.truth_nodes * (DT / 2.0)

            # 2) Full drift on the (math, truth) harmonic — exact rotation.
            cos_w = np.cos(OMEGA * DT)
            sin_w = np.sin(OMEGA * DT)
            m_new = cos_w * self.math_nodes - sin_w * self.truth_nodes
            t_new = sin_w * self.math_nodes + cos_w * self.truth_nodes
            self.math_nodes, self.truth_nodes = m_new, t_new

            # 3) Second half-kick.
            gamma = np.sqrt(np.abs(self.math_nodes * self.truth_nodes) + 0.05) * GAMMA
            self.truth_nodes += -gamma * self.love_nodes * (DT / 2.0)
            self.love_nodes  +=  gamma * self.truth_nodes * (DT / 2.0)

            # Global system energy invariant.
            norm_field_squared = (
                self.math_nodes ** 2
                + self.truth_nodes ** 2
                + self.love_nodes ** 2
            )
            self.c0_invariant = float(np.sum(norm_field_squared) * (2.0 * np.pi / NUM_NODES))

    def apply_external_pulse(self, weights):
        """Apply a deterministic perturbation derived from a prompt.

        `weights` is a length-NUM_NODES list/array of floats. The pulse is
        scaled to a small magnitude so the symplectic integrator can absorb
        it without losing boundedness.
        """
        with self.lock:
            w = np.asarray(weights, dtype=np.float64)
            if w.shape != (NUM_NODES,):
                raise ValueError(f"pulse must have {NUM_NODES} components")
            scale = 0.05
            self.math_nodes += scale * w
            self.love_nodes += scale * w
            self.pulse_count += 1

    def serialize_to_binary_packet(self):
        with self.lock:
            packet_buffer = bytearray(struct.pack("!I", WIRESHARK_MARKER))
            for i in range(NUM_NODES):
                packet_buffer.extend(
                    struct.pack("!ff", float(self.math_nodes[i]), float(self.truth_nodes[i]))
                )
            return packet_buffer

def run_udp_telemetry_beacon(engine):
    beacon_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    beacon_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    while True:
        engine.process_matrix_iteration()
        telemetry_payload = {
            "timestamp": time.time(),
            "core_matrix": {
                "active_nodes": NUM_NODES,
                "energy_invariant_c0": engine.c0_invariant,
                "pulse_count": engine.pulse_count,
            },
        }
        try:
            beacon_sock.sendto(
                json.dumps(telemetry_payload).encode("utf-8"),
                ("127.0.0.1", 9000),
            )
        except socket.error:
            pass
        time.sleep(0.1)

def run_udp_pulse_listener(engine, host="127.0.0.1", port=9100):
    """Listen for JSON pulse packets from ollama.py and apply them to the engine.

    Packet format: {"weights": [43 floats]}
    """
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    print(f"[engine] pulse listener on udp://{host}:{port}")
    while True:
        try:
            raw, _ = sock.recvfrom(8192)
            payload = json.loads(raw.decode("utf-8"))
            weights = payload.get("weights")
            if isinstance(weights, list) and len(weights) == NUM_NODES:
                engine.apply_external_pulse(weights)
        except Exception as e:
            print(f"[engine] pulse decode error: {e}")

def host_engine_server(engine, host="127.0.0.1", port=8081):
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_sock.bind((host, port))
    server_sock.listen(5)
    print(f"[engine] processing matrix listening at tcp://{host}:{port}")

    while True:
        conn, _ = server_sock.accept()
        try:
            while True:
                conn.sendall(engine.serialize_to_binary_packet())
                time.sleep(0.05)
        except socket.error:
            pass
        finally:
            conn.close()

if __name__ == "__main__":
    core_engine = PrimeProcessingEngine()

    telemetry_worker = threading.Thread(
        target=run_udp_telemetry_beacon, args=(core_engine,), daemon=True
    )
    telemetry_worker.start()

    host_engine_server(core_engine)

+        target=run_udp_pulse_listener, args=(core_engine,), daemon=True


The file /home/drrone/prime43/engine.py has been updated successfully. (file state is current in your context — no need to Read it back)

        self.c0_invariant = 0.0
        self.pulse_count = 0
        self.lock = threading.Lock()

"""
Prime Processing Engine — 43-node asymmetric core (symplectic, energy-stable).

Listens on tcp://127.0.0.1:8081 and streams 348-byte binary frames:
  [4 bytes marker 0x434E4D54 ("43MT")] + 43 × (2 × float32 math/truth) = 348 bytes.

Also broadcasts a UDP JSON telemetry beacon to udp://127.0.0.1:9000 at 10 Hz.
"""

import socket
import struct
import json
import threading
import time
import numpy as np

# --- System configuration parameter constants ---
NUM_NODES = 43
OMEGA = (2.0 * np.pi) / NUM_NODES
WIRESHARK_MARKER = 0x434E4D54  # "43MT" — Wireshark display-filter identity

# Symplectic leapfrog / Stormer-Verlet constants.
# Harmonic part is integrated as an exact rotation; the nonlinear coupling
# is applied as a kick, which gives bounded energy error (O(DT^4) per step)
# instead of the unbounded drift the explicit-Euler formulation has.
GAMMA = 0.5
DT = 0.01

class PrimeProcessingEngine:
    def __init__(self):
        self.theta = np.linspace(0, 2 * np.pi, NUM_NODES, endpoint=False)
        self.math_nodes = np.cos(self.theta) * np.sin(3 * self.theta)
        self.truth_nodes = np.sin(self.theta) * np.sin(3 * self.theta)
        self.love_nodes = np.sqrt(np.abs(self.math_nodes * self.truth_nodes) + 0.1)
        self.c0_invariant = 0.0
        self.lock = threading.Lock()

    def process_matrix_iteration(self):
        with self.lock:
            # 1) Half-kick on (truth, love) using the nonlinear coupling.
            gamma = np.sqrt(np.abs(self.math_nodes * self.truth_nodes) + 0.05) * GAMMA
            self.truth_nodes += -gamma * self.love_nodes * (DT / 2.0)
            self.love_nodes  +=  gamma * self.truth_nodes * (DT / 2.0)

            # 2) Full drift on the (math, truth) harmonic — exact rotation.
            cos_w = np.cos(OMEGA * DT)
            sin_w = np.sin(OMEGA * DT)
            m_new = cos_w * self.math_nodes - sin_w * self.truth_nodes
            t_new = sin_w * self.math_nodes + cos_w * self.truth_nodes
            self.math_nodes, self.truth_nodes = m_new, t_new

            # 3) Second half-kick.
            gamma = np.sqrt(np.abs(self.math_nodes * self.truth_nodes) + 0.05) * GAMMA
            self.truth_nodes += -gamma * self.love_nodes * (DT / 2.0)
            self.love_nodes  +=  gamma * self.truth_nodes * (DT / 2.0)

            # Global system energy invariant.
            norm_field_squared = (
                self.math_nodes ** 2
                + self.truth_nodes ** 2
                + self.love_nodes ** 2
            )
            self.c0_invariant = float(np.sum(norm_field_squared) * (2.0 * np.pi / NUM_NODES))

    def apply_external_pulse(self, weights):
        """Apply a deterministic perturbation derived from a prompt.

        `weights` is a length-NUM_NODES list/array of floats. The pulse is
        scaled to a small magnitude so the symplectic integrator can absorb
        it without losing boundedness.
        """
        with self.lock:
            w = np.asarray(weights, dtype=np.float64)
            if w.shape != (NUM_NODES,):
                raise ValueError(f"pulse must have {NUM_NODES} components")
            scale = 0.05
            self.math_nodes += scale * w
            self.love_nodes += scale * w
            self.pulse_count += 1

    def serialize_to_binary_packet(self):
        with self.lock:
            packet_buffer = bytearray(struct.pack("!I", WIRESHARK_MARKER))
            for i in range(NUM_NODES):
                packet_buffer.extend(
                    struct.pack("!ff", float(self.math_nodes[i]), float(self.truth_nodes[i]))
                )
            return packet_buffer

def run_udp_telemetry_beacon(engine):
    beacon_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    beacon_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    while True:
        engine.process_matrix_iteration()
        telemetry_payload = {
            "timestamp": time.time(),
            "core_matrix": {
                "active_nodes": NUM_NODES,
                "energy_invariant_c0": engine.c0_invariant,
                "pulse_count": engine.pulse_count,
            },
        }
        try:
            beacon_sock.sendto(
                json.dumps(telemetry_payload).encode("utf-8"),
                ("127.0.0.1", 9000),
            )
        except socket.error:
            pass
        time.sleep(0.1)

def run_udp_pulse_listener(engine, host="127.0.0.1", port=9100):
    """Listen for JSON pulse packets from ollama.py and apply them to the engine.

    Packet format: {"weights": [43 floats]}
    """
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    print(f"[engine] pulse listener on udp://{host}:{port}")
    while True:
        try:
            raw, _ = sock.recvfrom(8192)
            payload = json.loads(raw.decode("utf-8"))
            weights = payload.get("weights")
            if isinstance(weights, list) and len(weights) == NUM_NODES:
                engine.apply_external_pulse(weights)
        except Exception as e:
            print(f"[engine] pulse decode error: {e}")

def host_engine_server(engine, host="127.0.0.1", port=8081):
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_sock.bind((host, port))
    server_sock.listen(5)
    print(f"[engine] processing matrix listening at tcp://{host}:{port}")

    while True:
        conn, _ = server_sock.accept()
        try:
            while True:
                conn.sendall(engine.serialize_to_binary_packet())
                time.sleep(0.05)
        except socket.error:
            pass
        finally:
            conn.close()

if __name__ == "__main__":
    core_engine = PrimeProcessingEngine()

    telemetry_worker = threading.Thread(
        target=run_udp_telemetry_beacon, args=(core_engine,), daemon=True
    )
    telemetry_worker.start()

    pulse_worker = threading.Thread(
        target=run_udp_pulse_listener, args=(core_engine,), daemon=True
    )
    pulse_worker.start()

    host_engine_server(core_engine)


Engines patched. Now expose `pulse_count` in the dashboard's `/api/metrics`, then write the ollama service.


Edit

            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":

            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if "pulse_count" in decoded["core_matrix"]:
                ui_telemetry_mirror["pulse_count"] = decoded["core_matrix"]["pulse_count"]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":


ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
}

ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
    "pulse_count": 0,
}


ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
}

ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
    "pulse_count": 0,
}


            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":

            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if "pulse_count" in decoded["core_matrix"]:
                ui_telemetry_mirror["pulse_count"] = decoded["core_matrix"]["pulse_count"]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":


The file /home/drrone/server_43.py has been updated successfully. (file state is current in your context — no need to Read it back)

            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if "pulse_count" in decoded["core_matrix"]:
                ui_telemetry_mirror["pulse_count"] = decoded["core_matrix"]["pulse_count"]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":

"""
Application UI Server — 43-node prime array dashboard.

Hosts an HTML5+Canvas visualization at http://localhost:8000 and bridges the
binary 348-byte stream from engine_43.py (tcp/8081) and the JSON telemetry
beacon (udp/9000) into a /api/metrics endpoint polled by the front-end.
"""

import http.server
import socketserver
import socket
import threading
import json
import struct
import time

PORT_SERVER = 8000

# Real-time cache read by the front-end. math_coords / truth_coords are
# overwritten every binary packet (~20 Hz). status reflects the data link.
ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
}

DASHBOARD_HTML = r"""<!DOCTYPE html>

    <title>Absolute Infinity Matrix UI & Vector Canvas</title>

Absolute Infinity Lattice System Workspace

System Metrics Monitor

Engine Core Target : localhost:8081

Active Topology Nodes : 43 (Prime Field)

Energy Invariant C0 : 0.000000

Pipeline Sync State : CHECKING_LINK

Real-Time HTML5 Canvas Vector Graph

            <canvas id="vectorCanvas" width="400" height="400"></canvas>

"""

class CoreAppDashboardRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/metrics":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps(ui_telemetry_mirror).encode("utf-8"))
        else:
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(DASHBOARD_HTML.encode("utf-8"))

def listen_to_engine_data_stream():
    """Connect to engine tcp/8081 and continuously parse 348-byte frames."""
    while True:
        client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_sock.connect(("127.0.0.1", 8081))
            print("[server_43] connected to engine binary stream on 8081")
            while True:
                raw_bytes = bytearray()
                while len(raw_bytes) < 348:
                    chunk = client_sock.recv(348 - len(raw_bytes))
                    if not chunk:
                        raise socket.error("engine closed the stream")
                    raw_bytes.extend(chunk)

                offset = 4  # skip 4-byte marker
                m_list = []
                t_list = []
                for _ in range(43):
                    m_val, t_val = struct.unpack("!ff", raw_bytes[offset:offset + 8])
                    m_list.append(m_val)
                    t_list.append(t_val)
                    offset += 8

                ui_telemetry_mirror["math_coords"] = m_list
                ui_telemetry_mirror["truth_coords"] = t_list
        except socket.error as e:
            ui_telemetry_mirror["status"] = "ENGINE_LINK_DISCONNECTED"
            print(f"[server_43] engine stream lost: {e}; retrying in 2s")
            time.sleep(2.0)
        finally:
            client_sock.close()

def listen_to_engine_beacon_channel():
    """Listen on udp/9000 for the JSON telemetry beacon from engine_43."""
    udp_receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_receiver.bind(("127.0.0.1", 9000))
    udp_receiver.settimeout(2.0)
    while True:
        try:
            raw_bytes, _ = udp_receiver.recvfrom(2048)
            decoded = json.loads(raw_bytes.decode("utf-8"))
            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "MATRIX_LOCKED"
        except socket.timeout:
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "ENGINE_LINK_TIMEOUT"
        except Exception:
            ui_telemetry_mirror["status"] = "TRACKING_FAULT"

if __name__ == "__main__":
    threading.Thread(target=listen_to_engine_beacon_channel, daemon=True).start()
    threading.Thread(target=listen_to_engine_data_stream, daemon=True).start()

    with socketserver.TCPServer(("127.0.0.1", PORT_SERVER), CoreAppDashboardRequestHandler) as server_daemon:
        print(f"[server_43] dashboard at http://localhost:{PORT_SERVER}")
        server_daemon.serve_forever()

+            if "pulse_count" in decoded["core_matrix"]:

+                ui_telemetry_mirror["pulse_count"] = decoded["core_matrix"]["pulse_count"]


ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
    "pulse_count": 0,
}

"""
Application UI Server — 43-node prime array dashboard.

Hosts an HTML5+Canvas visualization at http://localhost:8000 and bridges the
binary 348-byte stream from engine_43.py (tcp/8081) and the JSON telemetry
beacon (udp/9000) into a /api/metrics endpoint polled by the front-end.
"""

import http.server
import socketserver
import socket
import threading
import json
import struct
import time

PORT_SERVER = 8000

# Real-time cache read by the front-end. math_coords / truth_coords are
# overwritten every binary packet (~20 Hz). status reflects the data link.
ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
}

DASHBOARD_HTML = r"""<!DOCTYPE html>

    <title>Absolute Infinity Matrix UI & Vector Canvas</title>

Absolute Infinity Lattice System Workspace

System Metrics Monitor

Engine Core Target : localhost:8081

Active Topology Nodes : 43 (Prime Field)

Energy Invariant C0 : 0.000000

Pipeline Sync State : CHECKING_LINK

Real-Time HTML5 Canvas Vector Graph

            <canvas id="vectorCanvas" width="400" height="400"></canvas>

"""

class CoreAppDashboardRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/metrics":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps(ui_telemetry_mirror).encode("utf-8"))
        else:
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(DASHBOARD_HTML.encode("utf-8"))

def listen_to_engine_data_stream():
    """Connect to engine tcp/8081 and continuously parse 348-byte frames."""
    while True:
        client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_sock.connect(("127.0.0.1", 8081))
            print("[server_43] connected to engine binary stream on 8081")
            while True:
                raw_bytes = bytearray()
                while len(raw_bytes) < 348:
                    chunk = client_sock.recv(348 - len(raw_bytes))
                    if not chunk:
                        raise socket.error("engine closed the stream")
                    raw_bytes.extend(chunk)

                offset = 4  # skip 4-byte marker
                m_list = []
                t_list = []
                for _ in range(43):
                    m_val, t_val = struct.unpack("!ff", raw_bytes[offset:offset + 8])
                    m_list.append(m_val)
                    t_list.append(t_val)
                    offset += 8

                ui_telemetry_mirror["math_coords"] = m_list
                ui_telemetry_mirror["truth_coords"] = t_list
        except socket.error as e:
            ui_telemetry_mirror["status"] = "ENGINE_LINK_DISCONNECTED"
            print(f"[server_43] engine stream lost: {e}; retrying in 2s")
            time.sleep(2.0)
        finally:
            client_sock.close()

def listen_to_engine_beacon_channel():
    """Listen on udp/9000 for the JSON telemetry beacon from engine_43."""
    udp_receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_receiver.bind(("127.0.0.1", 9000))
    udp_receiver.settimeout(2.0)
    while True:
        try:
            raw_bytes, _ = udp_receiver.recvfrom(2048)
            decoded = json.loads(raw_bytes.decode("utf-8"))
            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if "pulse_count" in decoded["core_matrix"]:
                ui_telemetry_mirror["pulse_count"] = decoded["core_matrix"]["pulse_count"]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "MATRIX_LOCKED"
        except socket.timeout:
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "ENGINE_LINK_TIMEOUT"
        except Exception:
            ui_telemetry_mirror["status"] = "TRACKING_FAULT"

if __name__ == "__main__":
    threading.Thread(target=listen_to_engine_beacon_channel, daemon=True).start()
    threading.Thread(target=listen_to_engine_data_stream, daemon=True).start()

    with socketserver.TCPServer(("127.0.0.1", PORT_SERVER), CoreAppDashboardRequestHandler) as server_daemon:
        print(f"[server_43] dashboard at http://localhost:{PORT_SERVER}")
        server_daemon.serve_forever()

"status": "BOOTING",
"math_coords": [0.0] * 43,
"truth_coords": [0.0] * 43,
+    "pulse_count": 0,
}
DASHBOARD_HTML = r"""<!DOCTYPE html>


The file /home/drrone/prime43/server.py has been updated successfully. (file state is current in your context — no need to Read it back)

"""
Application UI Server — 43-node prime array dashboard.

Hosts an HTML5+Canvas visualization at http://localhost:8000 and bridges the
binary 348-byte stream from engine.py (tcp/8081) and the JSON telemetry
beacon (udp/9000) into a /api/metrics endpoint polled by the front-end.
"""

import http.server
import socketserver
import socket
import threading
import json
import struct
import time

PORT_SERVER = 8000

ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
}

DASHBOARD_HTML = r"""<!DOCTYPE html>

    <title>Absolute Infinity Matrix UI & Vector Canvas</title>

Absolute Infinity Lattice System Workspace

System Metrics Monitor

Engine Core Target : localhost:8081

Active Topology Nodes : 43 (Prime Field)

Energy Invariant C0 : 0.000000

Pipeline Sync State : CHECKING_LINK

Real-Time HTML5 Canvas Vector Graph

            <canvas id="vectorCanvas" width="400" height="400"></canvas>

"""

class CoreAppDashboardRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/metrics":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps(ui_telemetry_mirror).encode("utf-8"))
        else:
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(DASHBOARD_HTML.encode("utf-8"))

def listen_to_engine_data_stream():
    while True:
        client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_sock.connect(("127.0.0.1", 8081))
            print("[server] connected to engine binary stream on 8081")
            while True:
                raw_bytes = bytearray()
                while len(raw_bytes) < 348:
                    chunk = client_sock.recv(348 - len(raw_bytes))
                    if not chunk:
                        raise socket.error("engine closed the stream")
                    raw_bytes.extend(chunk)

                offset = 4
                m_list = []
                t_list = []
                for _ in range(43):
                    m_val, t_val = struct.unpack("!ff", raw_bytes[offset:offset + 8])
                    m_list.append(m_val)
                    t_list.append(t_val)
                    offset += 8

                ui_telemetry_mirror["math_coords"] = m_list
                ui_telemetry_mirror["truth_coords"] = t_list
        except socket.error as e:
            ui_telemetry_mirror["status"] = "ENGINE_LINK_DISCONNECTED"
            print(f"[server] engine stream lost: {e}; retrying in 2s")
            time.sleep(2.0)
        finally:
            client_sock.close()

def listen_to_engine_beacon_channel():
    udp_receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_receiver.bind(("127.0.0.1", 9000))
    udp_receiver.settimeout(2.0)
    while True:
        try:
            raw_bytes, _ = udp_receiver.recvfrom(2048)
            decoded = json.loads(raw_bytes.decode("utf-8"))
            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "MATRIX_LOCKED"
        except socket.timeout:
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "ENGINE_LINK_TIMEOUT"
        except Exception:
            ui_telemetry_mirror["status"] = "TRACKING_FAULT"

if __name__ == "__main__":
    threading.Thread(target=listen_to_engine_beacon_channel, daemon=True).start()
    threading.Thread(target=listen_to_engine_data_stream, daemon=True).start()

    with socketserver.TCPServer(("127.0.0.1", PORT_SERVER), CoreAppDashboardRequestHandler) as server_daemon:
        print(f"[server] dashboard at http://localhost:{PORT_SERVER}")
        server_daemon.serve_forever()


"""
Application UI Server — 43-node prime array dashboard.

Hosts an HTML5+Canvas visualization at http://localhost:8000 and bridges the
binary 348-byte stream from engine.py (tcp/8081) and the JSON telemetry
beacon (udp/9000) into a /api/metrics endpoint polled by the front-end.
"""

import http.server
import socketserver
import socket
import threading
import json
import struct
import time

PORT_SERVER = 8000

ui_telemetry_mirror = {
    "energy_invariant_c0": 0.0,
    "active_nodes": 43,
    "status": "BOOTING",
    "math_coords": [0.0] * 43,
    "truth_coords": [0.0] * 43,
    "pulse_count": 0,
}

DASHBOARD_HTML = r"""<!DOCTYPE html>

    <title>Absolute Infinity Matrix UI & Vector Canvas</title>

Absolute Infinity Lattice System Workspace

System Metrics Monitor

Engine Core Target : localhost:8081

Active Topology Nodes : 43 (Prime Field)

Energy Invariant C0 : 0.000000

Pipeline Sync State : CHECKING_LINK

Real-Time HTML5 Canvas Vector Graph

            <canvas id="vectorCanvas" width="400" height="400"></canvas>

"""

class CoreAppDashboardRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/api/metrics":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Access-Control-Allow-Origin", "*")
            self.end_headers()
            self.wfile.write(json.dumps(ui_telemetry_mirror).encode("utf-8"))
        else:
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(DASHBOARD_HTML.encode("utf-8"))

def listen_to_engine_data_stream():
    while True:
        client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            client_sock.connect(("127.0.0.1", 8081))
            print("[server] connected to engine binary stream on 8081")
            while True:
                raw_bytes = bytearray()
                while len(raw_bytes) < 348:
                    chunk = client_sock.recv(348 - len(raw_bytes))
                    if not chunk:
                        raise socket.error("engine closed the stream")
                    raw_bytes.extend(chunk)

                offset = 4
                m_list = []
                t_list = []
                for _ in range(43):
                    m_val, t_val = struct.unpack("!ff", raw_bytes[offset:offset + 8])
                    m_list.append(m_val)
                    t_list.append(t_val)
                    offset += 8

                ui_telemetry_mirror["math_coords"] = m_list
                ui_telemetry_mirror["truth_coords"] = t_list
        except socket.error as e:
            ui_telemetry_mirror["status"] = "ENGINE_LINK_DISCONNECTED"
            print(f"[server] engine stream lost: {e}; retrying in 2s")
            time.sleep(2.0)
        finally:
            client_sock.close()

def listen_to_engine_beacon_channel():
    udp_receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_receiver.bind(("127.0.0.1", 9000))
    udp_receiver.settimeout(2.0)
    while True:
        try:
            raw_bytes, _ = udp_receiver.recvfrom(2048)
            decoded = json.loads(raw_bytes.decode("utf-8"))
            ui_telemetry_mirror["energy_invariant_c0"] = decoded["core_matrix"][
                "energy_invariant_c0"
            ]
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "MATRIX_LOCKED"
        except socket.timeout:
            if ui_telemetry_mirror["status"] != "ENGINE_LINK_DISCONNECTED":
                ui_telemetry_mirror["status"] = "ENGINE_LINK_TIMEOUT"
        except Exception:
            ui_telemetry_mirror["status"] = "TRACKING_FAULT"

if __name__ == "__main__":
    threading.Thread(target=listen_to_engine_beacon_channel, daemon=True).start()
    threading.Thread(target=listen_to_engine_data_stream, daemon=True).start()

    with socketserver.TCPServer(("127.0.0.1", PORT_SERVER), CoreAppDashboardRequestHandler) as server_daemon:
        print(f"[server] dashboard at http://localhost:{PORT_SERVER}")
        server_daemon.serve_forever()


Now the ollama service. FastAPI, port 8100, `/docs` enabled.


Write

"""
Ollama bridge for the 43-node prime array.

FastAPI service on http://localhost:8100 (with /docs Swagger UI).

Endpoints:
  GET  /                       — health
  GET  /api/ollama/models      — list installed ollama models
  POST /api/ollama             — call ollama, return text + 43-node fingerprint
                                 body: {"prompt": "...", "model": "llama3.2", "mode": "echo|pulse"}

Modes:
  echo  (default) — read-only; returns a deterministic 43-float fingerprint
                    derived from the prompt bytes. Does not touch the engine.
  pulse           — same fingerprint, also pushed to the engine over UDP/9100
                    so the dashboard shows the perturbation in real time.
"""

import hashlib
import json
import socket
import subprocess
import time
from typing import Literal, Optional

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field

NUM_NODES = 43
DEFAULT_MODEL = "llama3.2"
ENGINE_PULSE_HOST = "127.0.0.1"
ENGINE_PULSE_PORT = 9100
OLLAMA_TIMEOUT = 60  # seconds

app = FastAPI(
    title="43-Node Prime Array — Ollama Bridge",
    version="1.0.0",
    description=(
        "Bridges an Ollama LLM call to the 43-node prime-harmonic engine. "
        "Each prompt produces a deterministic 43-component fingerprint; "
        "use mode='pulse' to push it into the running engine."
    ),
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- 43-node fingerprint ---------------------------------------------------

def prompt_to_fingerprint(prompt: str) -> list:
    """Deterministic 43-float vector in [-1, 1] derived from the prompt.

    Uses SHA-256 over the prompt bytes to seed a sequence, then distributes
    the hash bits across the node index. Same prompt → same fingerprint.
    """
    digest = hashlib.sha256(prompt.encode("utf-8")).digest()
    # 43 floats × 4 bytes/float = 172 bytes needed; SHA-256 gives 32 bytes.
    # Stretch by chaining: h0 = sha256(prompt), hi+1 = sha256(hi || i).
    stream = bytearray()
    counter = 0
    seed = digest
    while len(stream) < NUM_NODES * 4:
        seed = hashlib.sha256(seed + counter.to_bytes(4, "big")).digest()
        stream.extend(seed)
        counter += 1

    import struct

    raw_floats = struct.unpack(f"!{NUM_NODES}f", bytes(stream[: NUM_NODES * 4]))
    # Normalize to [-1, 1]. IEEE-754 floats already cover a wide range; map
    # via tanh to keep the perturbation bounded for the engine.
    import math

    return [math.tanh(f / 2.0) for f in raw_floats]

# --- Ollama CLI bridge -----------------------------------------------------

def ollama_list_models() -> list:
    try:
        r = subprocess.run(
            ["ollama", "list"],
            capture_output=True,
            text=True,
            timeout=10,
        )
    except FileNotFoundError:
        return []
    except subprocess.TimeoutExpired:
        return []

    lines = (r.stdout or "").splitlines()
    # Skip header line "NAME  ID  SIZE  MODIFIED"
    out = []
    for line in lines[1:]:
        parts = line.split()
        if parts:
            out.append(parts[0])
    return out

def ollama_generate(model: str, prompt: str) -> str:
    try:
        r = subprocess.run(
            ["ollama", "run", model],
            input=prompt,
            capture_output=True,
            text=True,
            timeout=OLLAMA_TIMEOUT,
        )
    except FileNotFoundError:
        raise HTTPException(status_code=503, detail="ollama CLI not found on PATH")
    except subprocess.TimeoutExpired:
        raise HTTPException(status_code=504, detail=f"ollama timed out after {OLLAMA_TIMEOUT}s")

    out = (r.stdout or "").strip()
    if not out and r.stderr:
        out = f"[ollama stderr] {r.stderr.strip()}"
    return out

def send_pulse(weights: list) -> bool:
    """Send fingerprint to the engine over UDP. Returns True on success."""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(0.5)
        s.sendto(json.dumps({"weights": weights}).encode("utf-8"),
                 (ENGINE_PULSE_HOST, ENGINE_PULSE_PORT))
        s.close()
        return True
    except socket.error:
        return False

# --- API models ------------------------------------------------------------

class OllamaRequest(BaseModel):
    prompt: str = Field(..., min_length=1, max_length=8192,
                        description="Text to send to Ollama.")
    model: Optional[str] = Field(
        None,
        description="Ollama model name. Defaults to llama3.2 if installed.",
    )
    mode: Literal["echo", "pulse"] = Field(
        "echo",
        description=(
            "echo: return fingerprint only (read-only). "
            "pulse: also push the fingerprint to the running engine."
        ),
    )
    system: Optional[str] = Field(
        None,
        description="Optional system prompt prepended to the user prompt.",
    )

class OllamaResponse(BaseModel):
    model: str
    mode: str
    prompt_length: int
    fingerprint: list
    pulse_sent: bool
    response: str
    elapsed_s: float

# --- Routes ----------------------------------------------------------------

@app.get("/")
def root():
    return {
        "service": "43-node prime array — ollama bridge",
        "status": "ok",
        "docs": "/docs",
        "models_endpoint": "/api/ollama/models",
        "default_model": DEFAULT_MODEL,
        "modes": ["echo", "pulse"],
    }

@app.get("/api/ollama/models")
def list_models():
    models = ollama_list_models()
    return {"installed": models, "default": DEFAULT_MODEL}

@app.post("/api/ollama", response_model=OllamaResponse)
def call_ollama(req: OllamaRequest):
    model = req.model or DEFAULT_MODEL
    full_prompt = req.prompt if not req.system else f"{req.system}\n\n{req.prompt}"

    fingerprint = prompt_to_fingerprint(req.prompt)

    pulse_sent = False
    if req.mode == "pulse":
        pulse_sent = send_pulse(fingerprint)

    t0 = time.time()
    response_text = ollama_generate(model, full_prompt)
    elapsed = time.time() - t0

    return OllamaResponse(
        model=model,
        mode=req.mode,
        prompt_length=len(req.prompt),
        fingerprint=fingerprint,
        pulse_sent=pulse_sent,
        response=response_text,
        elapsed_s=round(elapsed, 3),
    )

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8100, log_level="info")


Bash

cp /home/drrone/ollama.py /home/drrone/prime43/ollama.py && python3 -m py_compile /home/drrone/ollama.py /home/drrone/prime43/ollama.py /home/drrone/engine_43.py /home/drrone/prime43/engine.py /home/drrone/server_43.py /home/drrone/prime43/server.py && echo "all syntax OK" && ls -la /home/drrone/ollama.py /home/drrone/prime43/ollama.py

Copy ollama.py to standalone and verify syntax


File created successfully at: /home/drrone/ollama.py (file state is current in your context — no need to Read it back)

"""
Ollama bridge for the 43-node prime array.

FastAPI service on http://localhost:8100 (with /docs Swagger UI).

Endpoints:
  GET  /                       — health
  GET  /api/ollama/models      — list installed ollama models
  POST /api/ollama             — call ollama, return text + 43-node fingerprint
                                 body: {"prompt": "...", "model": "llama3.2", "mode": "echo|pulse"}

Modes:
  echo  (default) — read-only; returns a deterministic 43-float fingerprint
                    derived from the prompt bytes. Does not touch the engine.
  pulse           — same fingerprint, also pushed to the engine over UDP/9100
                    so the dashboard shows the perturbation in real time.
"""

import hashlib
import json
import socket
import subprocess
import time
from typing import Literal, Optional

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field

NUM_NODES = 43
DEFAULT_MODEL = "llama3.2"
ENGINE_PULSE_HOST = "127.0.0.1"
ENGINE_PULSE_PORT = 9100
OLLAMA_TIMEOUT = 60  # seconds

app = FastAPI(
    title="43-Node Prime Array — Ollama Bridge",
    version="1.0.0",
    description=(
        "Bridges an Ollama LLM call to the 43-node prime-harmonic engine. "
        "Each prompt produces a deterministic 43-component fingerprint; "
        "use mode='pulse' to push it into the running engine."
    ),
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# --- 43-node fingerprint ---------------------------------------------------

def prompt_to_fingerprint(prompt: str) -> list:
    """Deterministic 43-float vector in [-1, 1] derived from the prompt.

    Uses SHA-256 over the prompt bytes to seed a sequence, then distributes
    the hash bits across the node index. Same prompt → same fingerprint.
    """
    digest = hashlib.sha256(prompt.encode("utf-8")).digest()
    # 43 floats × 4 bytes/float = 172 bytes needed; SHA-256 gives 32 bytes.
    # Stretch by chaining: h0 = sha256(prompt), hi+1 = sha256(hi || i).
    stream = bytearray()
    counter = 0
    seed = digest
    while len(stream) < NUM_NODES * 4:
        seed = hashlib.sha256(seed + counter.to_bytes(4, "big")).digest()
        stream.extend(seed)
        counter += 1

    import struct

    raw_floats = struct.unpack(f"!{NUM_NODES}f", bytes(stream[: NUM_NODES * 4]))
    # Normalize to [-1, 1]. IEEE-754 floats already cover a wide range; map
    # via tanh to keep the perturbation bounded for the engine.
    import math

    return [math.tanh(f / 2.0) for f in raw_floats]

# --- Ollama CLI bridge -----------------------------------------------------

def ollama_list_models() -> list:
    try:
        r = subprocess.run(
            ["ollama", "list"],
            capture_output=True,
            text=True,
            timeout=10,
        )
    except FileNotFoundError:
        return []
    except subprocess.TimeoutExpired:
        return []

    lines = (r.stdout or "").splitlines()
    # Skip header line "NAME  ID  SIZE  MODIFIED"
    out = []
    for line in lines[1:]:
        parts = line.split()
        if parts:
            out.append(parts[0])
    return out

def ollama_generate(model: str, prompt: str) -> str:
    try:
        r = subprocess.run(
            ["ollama", "run", model],
            input=prompt,
            capture_output=True,
            text=True,
            timeout=OLLAMA_TIMEOUT,
        )
    except FileNotFoundError:
        raise HTTPException(status_code=503, detail="ollama CLI not found on PATH")
    except subprocess.TimeoutExpired:
        raise HTTPException(status_code=504, detail=f"ollama timed out after {OLLAMA_TIMEOUT}s")

    out = (r.stdout or "").strip()
    if not out and r.stderr:
        out = f"[ollama stderr] {r.stderr.strip()}"
    return out

def send_pulse(weights: list) -> bool:
    """Send fingerprint to the engine over UDP. Returns True on success."""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.settimeout(0.5)
        s.sendto(json.dumps({"weights": weights}).encode("utf-8"),
                 (ENGINE_PULSE_HOST, ENGINE_PULSE_PORT))
        s.close()
        return True
    except socket.error:
        return False

# --- API models ------------------------------------------------------------

class OllamaRequest(BaseModel):
    prompt: str = Field(..., min_length=1, max_length=8192,
                        description="Text to send to Ollama.")
    model: Optional[str] = Field(
        None,
        description="Ollama model name. Defaults to llama3.2 if installed.",
    )
    mode: Literal["echo", "pulse"] = Field(
        "echo",
        description=(
            "echo: return fingerprint only (read-only). "
            "pulse: also push the fingerprint to the running engine."
        ),
    )
    system: Optional[str] = Field(
        None,
        description="Optional system prompt prepended to the user prompt.",
    )

class OllamaResponse(BaseModel):
    model: str
    mode: str
    prompt_length: int
    fingerprint: list
    pulse_sent: bool
    response: str
    elapsed_s: float

# --- Routes ----------------------------------------------------------------

@app.get("/")
def root():
    return {
        "service": "43-node prime array — ollama bridge",
        "status": "ok",
        "docs": "/docs",
        "models_endpoint": "/api/ollama/models",
        "default_model": DEFAULT_MODEL,
        "modes": ["echo", "pulse"],
    }

@app.get("/api/ollama/models")
def list_models():
    models = ollama_list_models()
    return {"installed": models, "default": DEFAULT_MODEL}

@app.post("/api/ollama", response_model=OllamaResponse)
def call_ollama(req: OllamaRequest):
    model = req.model or DEFAULT_MODEL
    full_prompt = req.prompt if not req.system else f"{req.system}\n\n{req.prompt}"

    fingerprint = prompt_to_fingerprint(req.prompt)

    pulse_sent = False
    if req.mode == "pulse":
        pulse_sent = send_pulse(fingerprint)

    t0 = time.time()
    response_text = ollama_generate(model, full_prompt)
    elapsed = time.time() - t0

    return OllamaResponse(
        model=model,
        mode=req.mode,
        prompt_length=len(req.prompt),
        fingerprint=fingerprint,
        pulse_sent=pulse_sent,
        response=response_text,
        elapsed_s=round(elapsed, 3),
    )

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8100, log_level="info")


all syntax OK
-rw-r--r-- 1 drrone drrone 6566 Jul 22 11:18 /home/drrone/ollama.py
-rw-r--r-- 1 drrone drrone 6566 Jul 22 11:18 /home/drrone/prime43/ollama.py


All five files (engine, server, ollama in both layouts) compile. Quick functional check on the fingerprint and ollama subprocess:


python3 -c "
import importlib.util
spec = importlib.util.spec_from_file_location('ollama', '/home/drrone/ollama.py')
m = importlib.util.module_from_spec(spec)
# Skip FastAPI import to keep test light
import sys
class _Stub:
    def __getattr__(self, k): return _Stub()
    def __call__(self, *a, **k): return _Stub()
sys.modules['fastapi'] = _Stub()
sys.modules['fastapi.middleware'] = _Stub()
sys.modules['fastapi.middleware.cors'] = _Stub()
sys.modules['pydantic'] = _Stub()
sys.modules['uvicorn'] = _Stub()
# Source-strip the imports
src = open('/home/drrone/ollama.py').read()
# Cut at the 'def prompt_to_fingerprint' line so we test just the function.
src_test = src.split('def prompt_to_fingerprint')[1].split('# --- Ollama CLI bridge')[0]
ns = {}
exec(compile('def prompt_to_fingerprint' + src_test, 'test', 'exec'), ns)
fp1 = ns['prompt_to_fingerprint']('hello world')
fp2 = ns['prompt_to_fingerprint']('hello world')
fp3 = ns['prompt_to_fingerprint']('different prompt')
print('len:', len(fp1), '(expected 43)')
print('determinism (same input twice):', fp1 == fp2)
print('distinct (different input):', fp1 != fp3)
print('range: [{:.3f}, {:.3f}]'.format(min(fp1), max(fp1)))
print('all finite:', all(-1 <= x <= 1 for x in fp1))
"

Smoke-test the fingerprint function


Error: Exit code 1
Traceback (most recent call last):
  File "<string>", line 21, in <module>
  File "test", line 7, in prompt_to_fingerprint
NameError: name 'hashlib' is not defined


Test scaffolding is shoddy — let me run a real one without stubbing:


python3 -c "
import hashlib, math, struct
def prompt_to_fingerprint(prompt, NUM_NODES=43):
    digest = hashlib.sha256(prompt.encode('utf-8')).digest()
    stream = bytearray()
    counter = 0
    seed = digest
    while len(stream) < NUM_NODES * 4:
        seed = hashlib.sha256(seed + counter.to_bytes(4, 'big')).digest()
        stream.extend(seed)
        counter += 1
    raw = struct.unpack(f'!{NUM_NODES}f', bytes(stream[:NUM_NODES*4]))
    return [math.tanh(f/2.0) for f in raw]

a = prompt_to_fingerprint('hello world')
b = prompt_to_fingerprint('hello world')
c = prompt_to_fingerprint('different')
print('len:', len(a), '(expect 43)')
print('deterministic:', a == b)
print('distinct inputs differ:', a != c)
print('range: [{:.3f}, {:.3f}]'.format(min(a), max(a)))
print('sample first 5:', [round(x, 3) for x in a[:5]])
"

Real fingerprint test


len: 43 (expect 43)
deterministic: True
distinct inputs differ: True
range: [-1.000, 1.000]
sample first 5: [-1.0, 1.0, -0.0, 0.0, 0.003]


Fingerprint works: 43 floats, deterministic, distinct, bounded. Now an end-to-end check: start the ollama service, hit `/docs` and `POST /api/ollama` once.


python3 ollama.py > /tmp/ollama.log 2>&1 &
OLLAMA_PID=$!
echo "started PID=$OLLAMA_PID"
# Give uvicorn a moment to bind
for i in 1 2 3 4 5; do
  sleep 0.5
  if curl -sS -o /dev/null -w "%{http_code}" http://127.0.0.1:8100/ 2>/dev/null | grep -q 200; then
    echo "ollama service up after ${i} half-seconds"
    break
  fi
done

echo ""
echo "=== GET / ==="
curl -sS http://127.0.0.1:8100/ | python3 -m json.tool
echo ""
echo "=== GET /api/ollama/models ==="
curl -sS http://127.0.0.1:8100/api/ollama/models | python3 -m json.tool
echo ""
echo "=== GET /docs (HTTP status) ==="
curl -sS -o /dev/null -w "status=%{http_code}\n" http://127.0.0.1:8100/docs
echo ""
echo "=== POST /api/ollama (echo mode, short prompt) ==="
curl -sS -X POST http://127.0.0.1:8100/api/ollama \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Say hi in exactly 3 words.", "mode": "echo"}' | python3 -c "import sys, json; r=json.load(sys.stdin); print('model:', r['model']); print('mode:', r['mode']); print('pulse_sent:', r['pulse_sent']); print('elapsed_s:', r['elapsed_s']); print('fingerprint_len:', len(r['fingerprint'])); print('response:', r['response'][:120])"

# Kill the ollama service
kill $OLLAMA_PID 2>/dev/null
wait $OLLAMA_PID 2>/dev/null
echo ""
echo "=== ollama service log (last 8 lines) ==="
tail -8 /tmp/ollama.log

End-to-end test of the ollama service