Files
resonance-engine/market_wave_probe.py
T
2026-06-08 19:34:30 +07:00

217 lines
8.9 KiB
Python

"""market_wave_probe.py - executes Claude Desktop's 3-test directive.
Test 1: Khra 0.030 -> 0.050 (5min hold + query + 5min restore)
Test 2: Gixx 0.008 -> 0.024 (5min hold + query + 5min restore)
Test 3: Combined elevated + opposing inject every 60s, 4 queries
Uses verified command field "value" (kernel source line 619 / 631).
Fractonaut API on port 28822. Sets injection_state hint correctly.
Safety: try/finally restores Khra=0.030 / Gixx=0.008 / inj_state=UNKNOWN.
"""
import zmq, json, time, urllib.request, sys
from datetime import datetime
from pathlib import Path
CMD_PORT = 5557
TEL_PORT = 5556
FRACTO_API = "http://127.0.0.1:28822"
BASELINE_KHRA = 0.030
BASELINE_GIXX = 0.008
ELEV_KHRA = 0.050
ELEV_GIXX = 0.024
LEFT_X, RIGHT_X, CENTER_Y, SIGMA = 400, 624, 512, 48
OUT_DIR = Path(f"/mnt/d/Resonance_Engine/traj/market_wave_probe_{datetime.now().strftime('%Y%m%dT%H%M%S')}")
OUT_DIR.mkdir(parents=True, exist_ok=True)
OUT_FILE = OUT_DIR / "responses.jsonl"
LOG_FILE = OUT_DIR / "probe.log"
ctx = zmq.Context()
cmd = ctx.socket(zmq.PUB)
cmd.connect(f"tcp://127.0.0.1:{CMD_PORT}")
tel = ctx.socket(zmq.SUB)
tel.connect(f"tcp://127.0.0.1:{TEL_PORT}")
tel.setsockopt_string(zmq.SUBSCRIBE, "")
time.sleep(1.0)
def log(m):
line = f"[{datetime.now().strftime('%H:%M:%S')}] {m}"
print(line, flush=True)
with open(LOG_FILE, "a") as f:
f.write(line + "\n")
def send(d):
cmd.send_string(json.dumps(d)); time.sleep(0.1)
def set_inj(state):
body = json.dumps({"state": state}).encode()
req = urllib.request.Request(f"{FRACTO_API}/set_injection_state",
data=body, headers={"Content-Type":"application/json"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=5) as r:
return json.loads(r.read())
except Exception as e:
log(f" WARN set_inj({state}) failed: {e}")
def ask(question, timeout=180):
body = json.dumps({"question": question}).encode()
req = urllib.request.Request(f"{FRACTO_API}/ask",
data=body, headers={"Content-Type":"application/json"}, method="POST")
t0 = time.time()
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read()).get("response",""), time.time()-t0
except Exception as e:
return f"(error: {e})", time.time()-t0
def sample_telemetry():
"""Drain whatever telemetry is queued, return latest frame."""
latest = None
while True:
try:
raw = tel.recv_string(zmq.NOBLOCK)
latest = json.loads(raw)
except zmq.Again:
break
return latest
def dwell(seconds, tag):
"""Wait, sampling telemetry periodically for log."""
log(f" dwelling {seconds}s [{tag}]...")
t_end = time.time() + seconds
last_log = time.time()
while time.time() < t_end:
time.sleep(2)
if time.time() - last_log >= 60:
t = sample_telemetry()
if t:
log(f" [t+{int(seconds - (t_end-time.time()))}s] khra={t.get('khra_amp','?')} gixx={t.get('gixx_amp','?')} asym={t.get('asymmetry','?'):.3f} coh={t.get('coherence','?'):.4f}")
last_log = time.time()
def record(test, label, question, response, took, telemetry):
rec = {
"ts": datetime.now().isoformat(),
"test": test, "label": label,
"question": question, "response": response,
"took_s": took, "telemetry_at_query": telemetry,
}
with open(OUT_FILE, "a") as f:
f.write(json.dumps(rec) + "\n")
log(f" [{test}/{label}] fracto ({took:.1f}s):")
for line in response.split("\n"):
log(f" {line}")
# ============================================================
def test_1_khra():
log("=" * 60)
log("TEST 1 — Khra modulation 0.030 -> 0.050")
log("=" * 60)
set_inj("INACTIVE") # Khra/Gixx are internal forcings, not external injections
send({"cmd":"set_khra_amp","value":ELEV_KHRA})
log(f" sent set_khra_amp value={ELEV_KHRA}")
dwell(300, "khra elevated")
t_now = sample_telemetry()
if t_now:
log(f" telemetry pre-query: khra={t_now.get('khra_amp','?')} gixx={t_now.get('gixx_amp','?')} asym={t_now.get('asymmetry','?'):.3f}")
q = ("Khra amplitude has been raised from 0.030 to 0.050 about 5 minutes ago. "
"Describe the current field character. How does the asymmetry and coherence "
"behaviour differ from what you observed at baseline? Is the field more or "
"less ordered? What is the large-scale structure doing?")
resp, took = ask(q)
record("test_1_khra", "elevated", q, resp, took, t_now)
send({"cmd":"set_khra_amp","value":BASELINE_KHRA})
log(f" sent set_khra_amp value={BASELINE_KHRA} (restore)")
dwell(300, "khra restoring")
# ============================================================
def test_2_gixx():
log("=" * 60)
log("TEST 2 — Gixx modulation 0.008 -> 0.024")
log("=" * 60)
set_inj("INACTIVE")
send({"cmd":"set_gixx_amp","value":ELEV_GIXX})
log(f" sent set_gixx_amp value={ELEV_GIXX}")
dwell(300, "gixx elevated")
t_now = sample_telemetry()
if t_now:
log(f" telemetry pre-query: khra={t_now.get('khra_amp','?')} gixx={t_now.get('gixx_amp','?')} asym={t_now.get('asymmetry','?'):.3f}")
q = ("Gixx amplitude has been raised from 0.008 to 0.024 about 5 minutes ago. "
"Describe the current field character. How does the fine-scale texture "
"differ from baseline? Is the velocity variance different? What does the "
"stress field look like compared to normal?")
resp, took = ask(q)
record("test_2_gixx", "elevated", q, resp, took, t_now)
send({"cmd":"set_gixx_amp","value":BASELINE_GIXX})
log(f" sent set_gixx_amp value={BASELINE_GIXX} (restore)")
dwell(300, "gixx restoring")
# ============================================================
def test_3_combined():
log("=" * 60)
log("TEST 3 — Combined elevated + opposing dipole inject")
log("=" * 60)
send({"cmd":"set_khra_amp","value":ELEV_KHRA})
send({"cmd":"set_gixx_amp","value":ELEV_GIXX})
log(f" sent khra={ELEV_KHRA} gixx={ELEV_GIXX}")
set_inj("ACTIVE")
# Initial inject
send({"cmd":"inject_density","x":LEFT_X, "y":CENTER_Y,"sigma":SIGMA,"strength":+0.25})
send({"cmd":"inject_density","x":RIGHT_X,"y":CENTER_Y,"sigma":SIGMA,"strength":-0.25})
log(f" initial dipole inject (buy+0.25 at x={LEFT_X}, sell-0.25 at x={RIGHT_X})")
dwell(180, "combined elevated + inject1")
q = ("The field is currently running at elevated Khra=0.050 and Gixx=0.024 "
f"with opposing density injections at x={LEFT_X} (buy, +0.25) and x={RIGHT_X} "
"(sell, -0.25). Describe what you observe. The global scalars cannot resolve "
"left vs right spatially, but stress_xy and the magnitude/sign of stress "
"channels can reveal directional tension. How does this combined state differ "
"from either elevated Khra or elevated Gixx alone? What is the stress tensor "
"telling you?")
t_now = sample_telemetry()
resp, took = ask(q)
record("test_3_combined", "after_first_inject", q, resp, took, t_now)
# Three more injects at 60s intervals, query after each
for i in range(3):
log(f" --- pulse {i+2} ---")
send({"cmd":"inject_density","x":LEFT_X, "y":CENTER_Y,"sigma":SIGMA,"strength":+0.25})
send({"cmd":"inject_density","x":RIGHT_X,"y":CENTER_Y,"sigma":SIGMA,"strength":-0.25})
dwell(60, f"after pulse {i+2}")
q2 = (f"Pulse {i+2} of the opposing dipole has just fired (buy+0.25 at x={LEFT_X}, "
f"sell-0.25 at x={RIGHT_X}). Describe how the field has changed since "
"the previous observation. Are the stress channels building, stable, "
"or oscillating? Is the field accumulating directional tension or "
"absorbing the perturbation?")
t_now = sample_telemetry()
resp, took = ask(q2)
record("test_3_combined", f"after_pulse_{i+2}", q2, resp, took, t_now)
# Restore handled in main() finally
def main():
log("=" * 60)
log("market_wave_probe — Claude Desktop directive")
log(f"out: {OUT_DIR}")
log("=" * 60)
try:
with urllib.request.urlopen(f"{FRACTO_API}/status", timeout=5) as r:
st = json.loads(r.read())
log(f"fracto OK: model={st['model']} cycle={st['cycle']} inj_state={st.get('injection_state','?')}")
except Exception as e:
log(f"FATAL: Fractonaut not reachable: {e}")
sys.exit(1)
try:
test_1_khra()
test_2_gixx()
test_3_combined()
finally:
log("=" * 60)
log("RESTORE baseline")
send({"cmd":"set_khra_amp","value":BASELINE_KHRA})
send({"cmd":"set_gixx_amp","value":BASELINE_GIXX})
set_inj("UNKNOWN")
log(f" baseline restored (khra={BASELINE_KHRA}, gixx={BASELINE_GIXX})")
log(f" responses: {OUT_FILE}")
sys.exit(0)
if __name__ == "__main__":
main()