okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1#!/usr/bin/env python3 2"""Agent bridge tests: Strata API worker -> DeepSeek Harness -> durable session. 3 4This exercises the integration that the handoff calls the difficult part, without needing model 5weights. It proves the *bridge*: that the pinned Harness boots with the Strata profile, that an 6agent turn reaches the local Strata API worker, that the assistant message records the Strata 7provider and model as its source, and that the turn reaches a terminal state in a durable session. 8 9It does NOT prove inference quality. The worker runs its built-in `MockEngine`, because no Strata 10pack fits this development Mac (see history/docs/work/IMPLEMENTATION_STATUS.md section 3.2). Every reported 11fact is about the path, not the model; the qualification kit replaces the mock engine with a real 12one on a machine that can hold a pack. 13 14Usage: 15python integrations/harness/bridge_e2e.py [--dsh /path/to/dsh] [--port 8095] [--keep] 16 17Exit codes: 180 the turn completed and the assistant message names the Strata provider and model 191 the bridge failed; the durable session events are printed to help diagnose it 202 a prerequisite was missing (the dsh CLI, the worker, or the profile) 21""" 22 23from __future__import annotations 24 25import http .client 26import json 27import os 28import re 29import subprocess 30import time 31from pathlib import Path 32 33HERE = Path (__file__ ).resolve ().parent 34REPO = HERE .parent .parent 35PROFILE_PATCH = HERE / "profile" / "cordis.patch.yml" 36 37DEFAULT_DSH = "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh" 38DEFAULT_PYTHON = REPO .parent / "python311" / "bin" / "python" 39 40WORKSPACE_MARKER = "strata-bridge-e2e" 41PROMPT = "Say hello in exactly five words." 42 43 44class BridgeError (RuntimeError ): 45pass 46 47 48def log (msg :str )-> None : 49f" { msg } " ,flush = True ) 50 51 52def http_json (method :str ,host :str ,port :int ,path :str ,body = None ,cookie :str | None = None ): 53conn = http .client .HTTPConnection (host ,port ,timeout = 30 ) 54headers = {} 55data = None 56if body is not None : 57data = json .dumps (body ).encode () 58headers ["content-type" ]= "application/json" 59if cookie : 60headers ["cookie" ]= cookie 61conn .request (method ,path ,body = data ,headers = headers ) 62resp = conn .getresponse () 63raw = resp .read ().decode ("utf-8" ,"replace" ) 64set_cookie = resp .getheader ("set-cookie" )or "" 65conn .close () 66return resp .status ,raw ,set_cookie 67 68 69def wait_for_worker (port :int ,timeout = 60.0 )-> dict : 70deadline = time .time ()+ timeout 71while time .time ()< deadline : 72try : 73status ,raw ,_ = http_json ("GET" ,"127.0.0.1" ,port ,"/health" ) 74if status == 200 : 75return json .loads (raw ) 76except OSError : 77pass 78time .sleep (0.4 ) 79raise BridgeError (f"the Strata worker did not answer /health on 127.0.0.1: { port } within { timeout } s" ) 80 81 82def start_worker (python :Path ,port :int ,tmp :Path )-> tuple [subprocess .Popen ,Path ]: 83logfile = tmp / "worker.log" 84handle = logfile .open ("w" ) 85proc = subprocess .Popen ( 86 [str (python ),"-m" ,"serve.server" ,"--engine" ,"mock" ,"--port" ,str (port ), 87"--script" ,"I am a local Strata model." ], 88cwd = str (REPO ),stdout = handle ,stderr = subprocess .STDOUT , 89 ) 90return proc ,logfile 91 92 93def start_agent (dsh :Path ,port :int ,tmp :Path )-> tuple [subprocess .Popen ,Path ]: 94logfile = tmp / "dsh.log" 95handle = logfile .open ("w" ) 96proc = subprocess .Popen ( 97 [str (dsh ),"--profile" ,"web" ,"--patch" ,str (PROFILE_PATCH ), 98"--port" ,str (port ),"--no-open" ], 99cwd = str (tmp / "ws" ),stdout = handle ,stderr = subprocess .STDOUT , 100 ) 101return proc ,logfile 102 103 104def wait_for_agent_url (logfile :Path ,proc :subprocess .Popen ,timeout = 120.0 )-> str : 105deadline = time .time ()+ timeout 106pattern = re .compile (r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)" ) 107while time .time ()< deadline : 108if proc .poll ()is not None : 109raise BridgeError (f"the Harness exited early (code { proc . returncode } ); log:\n" 110+ logfile .read_text (errors = "replace" )[- 2000 :]) 111text = logfile .read_text (errors = "replace" )if logfile .exists ()else "" 112m = pattern .search (text ) 113if m : 114return text 115time .sleep (0.5 ) 116raise BridgeError (f"the Harness did not print its URL within { timeout } s; log:\n" 117+ (logfile .read_text (errors = "replace" )[- 2000 :]if logfile .exists ()else "(none)" )) 118 119 120def gateway_call (host :str ,port :int ,cookie :str ,rpc_id :str ,method :str ,args :dict ): 121body = {"type" :"client-request" ,"rpcId" :rpc_id ,"method" :method ,"payload" : {"args" :args }} 122status ,raw ,_ = http_json ("POST" ,host ,port ,f"/api/ { method } " ,body ,cookie = cookie ) 123try : 124parsed = json .loads (raw ) 125except json .JSONDecodeError as e : 126raise BridgeError (f" { method } : the gateway returned non-JSON ( { status } ): { raw [: 300 ] } " )from e 127result = parsed .get ("result" )or {} 128if not result .get ("ok" ): 129raise BridgeError (f" { method } was refused: { json . dumps ( result . get ( 'error' ))[: 400 ] } " ) 130return result .get ("value" ) 131 132 133def read_session_events (session_id :str ,home :Path | None = None )-> list [dict ]: 134"""Read the durable session file, across every concatenated zstd frame. 135 136`home` names the Harness home explicitly. A per-attempt revision runs with its own DSH_HOME, so 137relying on this process's environment would read the wrong sessions directory. 138""" 139base = Path (home )if home is not None else Path (os .environ .get ("DSH_HOME" ,Path .home ()/ ".dsh" )) 140root = base / "sessions" 141matches = list (root .glob (f"*/ { session_id } /session.v*.jsonl*" )) 142if not matches : 143return [] 144path = matches [0 ] 145if not path .name .endswith (".zstd" ): 146return [json .loads (l )for l in path .read_text (errors = "replace" ).splitlines ()if l .strip ()] 147# zstd frames are concatenated as the session is appended to; `zstd -d` reads them all. 148try : 149raw = subprocess .run (["zstd" ,"-d" ,"-c" ,"--long=27" ,str (path )], 150capture_output = True ,check = True ).stdout 151except (FileNotFoundError ,subprocess .CalledProcessError ): 152return [] 153out = [] 154for line in raw .decode ("utf-8" ,"replace" ).splitlines (): 155if line .strip (): 156try : 157out .append (json .loads (line )) 158except json .JSONDecodeError : 159pass 160return out 161 162