okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2b36e8a02
main
1#!/usr/bin/env python3 2"""End-to-end agent bridge test: 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 argparse 26import http .client 27import json 28import os 29import re 30import shutil 31import signal 32import subprocess 33import sys 34import tempfile 35import time 36from pathlib import Path 37 38HERE = Path (__file__ ).resolve ().parent 39REPO = HERE .parent .parent 40PROFILE_PATCH = HERE / "profile" / "cordis.patch.yml" 41 42DEFAULT_DSH = "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh" 43DEFAULT_PYTHON = REPO .parent / "python311" / "bin" / "python" 44 45WORKSPACE_MARKER = "strata-bridge-e2e" 46PROMPT = "Say hello in exactly five words." 47 48 49class BridgeError (RuntimeError ): 50pass 51 52 53def log (msg :str )-> None : 54f" { msg } " ,flush = True ) 55 56 57def http_json (method :str ,host :str ,port :int ,path :str ,body = None ,cookie :str | None = None ): 58conn = http .client .HTTPConnection (host ,port ,timeout = 30 ) 59headers = {} 60data = None 61if body is not None : 62data = json .dumps (body ).encode () 63headers ["content-type" ]= "application/json" 64if cookie : 65headers ["cookie" ]= cookie 66conn .request (method ,path ,body = data ,headers = headers ) 67resp = conn .getresponse () 68raw = resp .read ().decode ("utf-8" ,"replace" ) 69set_cookie = resp .getheader ("set-cookie" )or "" 70conn .close () 71return resp .status ,raw ,set_cookie 72 73 74def wait_for_worker (port :int ,timeout = 60.0 )-> dict : 75deadline = time .time ()+ timeout 76while time .time ()< deadline : 77try : 78status ,raw ,_ = http_json ("GET" ,"127.0.0.1" ,port ,"/health" ) 79if status == 200 : 80return json .loads (raw ) 81except OSError : 82pass 83time .sleep (0.4 ) 84raise BridgeError (f"the Strata worker did not answer /health on 127.0.0.1: { port } within { timeout } s" ) 85 86 87def start_worker (python :Path ,port :int ,tmp :Path )-> tuple [subprocess .Popen ,Path ]: 88logfile = tmp / "worker.log" 89handle = logfile .open ("w" ) 90proc = subprocess .Popen ( 91 [str (python ),"-m" ,"serve.server" ,"--engine" ,"mock" ,"--port" ,str (port ), 92"--script" ,"I am a local Strata model." ], 93cwd = str (REPO ),stdout = handle ,stderr = subprocess .STDOUT , 94 ) 95return proc ,logfile 96 97 98def start_agent (dsh :Path ,port :int ,tmp :Path )-> tuple [subprocess .Popen ,Path ]: 99logfile = tmp / "dsh.log" 100handle = logfile .open ("w" ) 101proc = subprocess .Popen ( 102 [str (dsh ),"--profile" ,"web" ,"--patch" ,str (PROFILE_PATCH ), 103"--port" ,str (port ),"--no-open" ], 104cwd = str (tmp / "ws" ),stdout = handle ,stderr = subprocess .STDOUT , 105 ) 106return proc ,logfile 107 108 109def wait_for_agent_url (logfile :Path ,proc :subprocess .Popen ,timeout = 120.0 )-> str : 110deadline = time .time ()+ timeout 111pattern = re .compile (r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)" ) 112while time .time ()< deadline : 113if proc .poll ()is not None : 114raise BridgeError (f"the Harness exited early (code { proc . returncode } ); log:\n" 115+ logfile .read_text (errors = "replace" )[- 2000 :]) 116text = logfile .read_text (errors = "replace" )if logfile .exists ()else "" 117m = pattern .search (text ) 118if m : 119return text 120time .sleep (0.5 ) 121raise BridgeError (f"the Harness did not print its URL within { timeout } s; log:\n" 122+ (logfile .read_text (errors = "replace" )[- 2000 :]if logfile .exists ()else "(none)" )) 123 124 125def gateway_call (host :str ,port :int ,cookie :str ,rpc_id :str ,method :str ,args :dict ): 126body = {"type" :"client-request" ,"rpcId" :rpc_id ,"method" :method ,"payload" : {"args" :args }} 127status ,raw ,_ = http_json ("POST" ,host ,port ,f"/api/ { method } " ,body ,cookie = cookie ) 128try : 129parsed = json .loads (raw ) 130except json .JSONDecodeError as e : 131raise BridgeError (f" { method } : the gateway returned non-JSON ( { status } ): { raw [: 300 ] } " )from e 132result = parsed .get ("result" )or {} 133if not result .get ("ok" ): 134raise BridgeError (f" { method } was refused: { json . dumps ( result . get ( 'error' ))[: 400 ] } " ) 135return result .get ("value" ) 136 137 138def read_session_events (session_id :str )-> list [dict ]: 139"""Read the durable session file, across every concatenated zstd frame.""" 140root = Path (os .environ .get ("DSH_HOME" ,Path .home ()/ ".dsh" ))/ "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 163def main ()-> int : 164ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 165ap .add_argument ("--dsh" ,default = os .environ .get ("DSH_CLI" ,DEFAULT_DSH )) 166ap .add_argument ("--python" ,default = str (DEFAULT_PYTHON )) 167ap .add_argument ("--worker-port" ,type = int ,default = 8095 ) 168ap .add_argument ("--agent-port" ,type = int ,default = 0 ,help = "0 lets the OS choose" ) 169ap .add_argument ("--keep" ,action = "store_true" ,help = "leave the processes and temp dir in place" ) 170args = ap .parse_args () 171 172dsh = Path (args .dsh ) 173python = Path (args .python ) 174if not dsh .exists (): 175f"prerequisite missing: the dsh CLI is not at { dsh } " ,file = sys .stderr ) 176return 2 177if not python .exists (): 178f"prerequisite missing: no interpreter at { python } " ,file = sys .stderr ) 179return 2 180if not PROFILE_PATCH .exists (): 181f"prerequisite missing: the Strata profile patch is not at { PROFILE_PATCH } " ,file = sys .stderr ) 182return 2 183 184tmp = Path (tempfile .mkdtemp (prefix = f" { WORKSPACE_MARKER } -" )) 185 (tmp / "ws" ).mkdir () 186worker = agent = None 187failure :str | None = None 188session_id = None 189 190"strata agent bridge — end to end" ) 191f" profile : { PROFILE_PATCH } " ) 192f" dsh : { dsh } " ) 193f" temp : { tmp } " ) 194try : 197"[1/5] Strata API worker" ) 198worker ,worker_log = start_worker (python ,args .worker_port ,tmp ) 199health = wait_for_worker (args .worker_port ) 200log (f"ready: model= { health . get ( 'model' ) } context= { health . get ( 'max_context' ) } " ) 201 202"[2/5] DeepSeek Harness with the Strata profile" ) 203agent ,dsh_log = start_agent (dsh ,args .agent_port ,tmp ) 204text = wait_for_agent_url (dsh_log ,agent ) 205m = re .search (r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)" ,text ) 206assert m ,"URL was matched by the caller but not re-matched here" 207agent_port ,token = int (m .group (1 )),m .group (2 ) 208log (f"ready on 127.0.0.1: { agent_port } " ) 209 210"[3/5] Operator session with approval answering enabled" ) 211# `interactions=answer` is required: it defaults to 'none', and a peer without it cannot 212# answer approvals, so every ask would fail closed as 'unavailable'. 213_ ,_ ,set_cookie = http_json ("GET" ,"127.0.0.1" ,agent_port , 214f"/?token= { token } &interactions=answer" ) 215cookie = set_cookie .split (";" ,1 )[0 ] 216if not cookie .startswith ("dsh-auth-" ): 217raise BridgeError (f"no operator cookie was issued (got { set_cookie [: 80 ]!r } )" ) 218log ("authenticated as owner with interactions=answer" ) 219 220"[4/5] Session, then one agent turn" ) 221created = gateway_call ("127.0.0.1" ,agent_port ,cookie ,"c1" ,"session/create" , 222 {"request" : {"cwd" :str (tmp / "ws" )}}) 223session_id = created ["sessionId" ] 224log (f"session { session_id } " ) 225gateway_call ("127.0.0.1" ,agent_port ,cookie ,"p1" ,"session/prompt" , 226 {"request" : {"requestId" :"req-1" ,"sessionId" :session_id , 227"mode" :"queue" , 228"content" : [{"type" :"text" ,"text" :PROMPT }]}}) 229log ("prompt accepted" ) 230 231"[5/5] Waiting for the turn to reach a terminal state" ) 232events = [] 233deadline = time .time ()+ 120 234while time .time ()< deadline : 235events = read_session_events (session_id ) 236if any (e .get ("type" )== "turn/end" for e in events ): 237break 238time .sleep (1.0 ) 239 240turn_end = next ((e for e in events if e .get ("type" )== "turn/end" ),None ) 241if turn_end is None : 242raise BridgeError ("the turn never reached turn/end within 120s" ) 243reason = (turn_end .get ("data" )or {}).get ("reason" )or {} 244if reason .get ("kind" )!= "completed" : 245raise BridgeError (f"the turn ended as { json . dumps ( reason )[: 400 ] } " ) 246 247assistant = next ((e for e in events if e .get ("type" )== "assistant/message" ),None ) 248if assistant is None : 249raise BridgeError ("the turn completed but committed no assistant message" ) 250source = ((assistant .get ("data" )or {}).get ("message" )or {}).get ("source" )or {} 251if source .get ("provider" )!= "strata-local" : 252raise BridgeError (f"the assistant message names provider { source . get ( 'provider' )!r } , " 253f"not 'strata-local'" ) 254 255# Independent confirmation that the request actually reached the worker, not just that the 256# session recorded a plausible-looking source. 257_ ,raw ,_ = http_json ("GET" ,"127.0.0.1" ,args .worker_port ,"/v1/status" ) 258activity = (json .loads (raw ).get ("activity" )or {}) 259requests = activity .get ("requests" )or 0 260if requests < 1 : 261raise BridgeError ("the session completed but the Strata worker recorded no requests" ) 262 263"PASS" ) 265f" turn : { reason . get ( 'kind' ) } " ) 266f" provider/model : { source . get ( 'provider' ) } / { source . get ( 'model' ) } " ) 267f" worker requests : { requests } " ) 268f" turn statements : { ', ' . join ( e . get ( 'type' , '?' ) for e in events if e . get ( 'type' , '' ). startswith ( 'turn/' )) } " ) 269return 0 270 271except BridgeError as e : 272failure = str (e ) 273except Exception as e :# noqa: BLE001 - a test harness reports, it does not crash 274failure = f" { type ( e ). __name__ } : { e } " 275finally : 276if not args .keep : 277for proc in (agent ,worker ): 278if proc and proc .poll ()is None : 279try : 280proc .send_signal (signal .SIGTERM ) 281proc .wait (timeout = 8 ) 282except Exception : 283try : 284proc .kill () 285except Exception : 286pass 287else : 288f"\nkeeping processes; temp dir: { tmp } " ) 289 290"FAIL" ) 292f" { failure } " ) 293if session_id : 294evs = read_session_events (session_id ) 295f" durable session events ( { len ( evs ) } ):" ) 296for e in evs [- 18 :]: 297t = e .get ("type" ) 298d = e .get ("data" )or {} 299extra = "" 300if t == "turn/end" : 301extra = json .dumps (d .get ("reason" ))[:220 ] 302elif t == "assistant/message" : 303extra = json .dumps ((d .get ("message" )or {}).get ("source" ))[:160 ] 304f" { e . get ( 'seq' ) } { t } { extra } " ) 305if not args .keep : 306shutil .rmtree (tmp ,ignore_errors = True ) 307else : 308f" logs left in { tmp } " ) 309return 1 310 311 312if __name__ == "__main__" : 313sys .exit (main ())