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 4These cover the three behaviours the handoff singles out as the difficult part of the integration, 5and they run without model weights: 6 7default one turn reaches the local Strata worker and completes with recorded provenance 8--cancel a turn is cancelled mid-flight and reaches an aborted terminal state 9--approval a tool call raises an approval request over the gateway and the answer is applied 10--all all three 11 12What they do NOT prove: inference quality, tokens-per-second, or tool correctness against a real 13model. The worker runs its built-in `MockEngine` because no Strata pack fits this development Mac 14(history/docs/work/IMPLEMENTATION_STATUS.md section 3.2). Every assertion here is about the *path*. 15 16The reusable helpers live in `_bridge.py`; `bridge_e2e.py` is the single-behaviour convenience 17wrapper around the `default` case. 18 19Usage: 20python integrations/harness/bridge_tests.py [--all|--cancel|--approval] [--keep] 21 22Exit codes: 0 all selected cases passed, 1 at least one failed, 2 a prerequisite was missing. 23""" 24 25from __future__import annotations 26 27import argparse 28import json 29import os 30import shutil 31import signal 32import sys 33import tempfile 34import time 35from pathlib import Path 36 37sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 38 39from _bridge import (# noqa: E402 40DEFAULT_DSH , 41DEFAULT_PYTHON , 42PROFILE_PATCH , 43BridgeError , 44gateway_call , 45http_json , 46log , 47read_session_events , 48start_agent , 49start_worker , 50wait_for_agent_url , 51wait_for_worker , 52) 53 54 55class Fixture : 56"""A running worker + Harness pair with an authenticated owner session.""" 57 58def __init__ (self ,dsh :Path ,python :Path ,worker_port :int ,keep :bool ): 59self .dsh ,self .python ,self .worker_port ,self .keep = dsh ,python ,worker_port ,keep 60self .tmp = Path (tempfile .mkdtemp (prefix = "strata-bridge-" )) 61 (self .tmp / "ws" ).mkdir () 62self .worker = self .agent = None 63self .agent_port = 0 64self .cookie = "" 65 66def __enter__ (self )-> "Fixture" : 67self .worker ,self .worker_log = start_worker (self .python ,self .worker_port ,self .tmp ) 68wait_for_worker (self .worker_port ) 69self .agent ,self .agent_log = start_agent (self .dsh ,0 ,self .tmp ) 70text = wait_for_agent_url (self .agent_log ,self .agent ) 71import re 72 73m = re .search (r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)" ,text ) 74if not m : 75raise BridgeError ("the Harness printed no usable URL" ) 76self .agent_port ,token = int (m .group (1 )),m .group (2 ) 77# `interactions=answer` is REQUIRED: it defaults to 'none', and a peer without it cannot 78# answer approvals, so every ask would fail closed as 'unavailable'. 79_ ,_ ,set_cookie = http_json ("GET" ,"127.0.0.1" ,self .agent_port , 80f"/?token= { token } &interactions=answer" ) 81self .cookie = set_cookie .split (";" ,1 )[0 ] 82if not self .cookie .startswith ("dsh-auth-" ): 83raise BridgeError (f"no operator cookie was issued ( { set_cookie [: 80 ]!r } )" ) 84return self 85 86def __exit__ (self ,* exc )-> None : 87if not self .keep : 88for proc in (self .agent ,self .worker ): 89if proc and proc .poll ()is None : 90try : 91proc .send_signal (signal .SIGTERM ) 92proc .wait (timeout = 8 ) 93except Exception : 94try : 95proc .kill () 96except Exception : 97pass 98else : 99f" (kept: { self . tmp } )" ) 100if not self .keep : 101shutil .rmtree (self .tmp ,ignore_errors = True ) 102 103# ---- operations ------------------------------------------------------- 104 105def new_session (self )-> str : 106created = gateway_call ("127.0.0.1" ,self .agent_port ,self .cookie ,"c" ,"session/create" , 107 {"request" : {"cwd" :str (self .tmp / "ws" )}}) 108return created ["sessionId" ] 109 110def prompt (self ,session_id :str ,text :str ,rpc_id = "p" ,request_id = "req-1" ): 111return gateway_call ("127.0.0.1" ,self .agent_port ,self .cookie ,rpc_id ,"session/prompt" , 112 {"request" : {"requestId" :request_id ,"sessionId" :session_id , 113"mode" :"queue" , 114"content" : [{"type" :"text" ,"text" :text }]}}) 115 116def cancel (self ,session_id :str ,rpc_id = "x" ): 117return gateway_call ("127.0.0.1" ,self .agent_port ,self .cookie ,rpc_id ,"session/cancel" , 118 {"request" : {"sessionId" :session_id }}) 119 120def wait_turn_end (self ,session_id :str ,timeout = 120.0 ): 121deadline = time .time ()+ timeout 122events = [] 123while time .time ()< deadline : 124events = read_session_events (session_id ) 125end = next ((e for e in events if e .get ("type" )== "turn/end" ),None ) 126if end is not None : 127return end ,events 128time .sleep (0.5 ) 129return None ,events 130 131def worker_requests (self )-> int : 132_ ,raw ,_ = http_json ("GET" ,"127.0.0.1" ,self .worker_port ,"/v1/status" ) 133return (json .loads (raw ).get ("activity" )or {}).get ("requests" )or 0 134 135 136# --------------------------------------------------------------------------- cases 137 138def case_completion (fx :Fixture )-> None : 139"""A turn must reach the local worker and complete, with recorded provenance.""" 140sid = fx .new_session () 141log (f"session { sid } " ) 142fx .prompt (sid ,"Say hello in exactly five words." ) 143log ("prompt accepted" ) 144end ,events = fx .wait_turn_end (sid ) 145if end is None : 146raise BridgeError ("the turn never reached turn/end within 120s" ) 147reason = (end .get ("data" )or {}).get ("reason" )or {} 148if reason .get ("kind" )!= "completed" : 149raise BridgeError (f"the turn ended as { json . dumps ( reason )[: 400 ] } " ) 150assistant = next ((e for e in events if e .get ("type" )== "assistant/message" ),None ) 151if assistant is None : 152raise BridgeError ("the turn completed but committed no assistant message" ) 153source = ((assistant .get ("data" )or {}).get ("message" )or {}).get ("source" )or {} 154if source .get ("provider" )!= "strata-local" : 155raise BridgeError (f"assistant source names { source . get ( 'provider' )!r } , not 'strata-local'" ) 156n = fx .worker_requests () 157if n < 1 : 158raise BridgeError ("the session completed but the worker recorded no requests" ) 159log (f"turn=completed provider= { source . get ( 'provider' ) } model= { source . get ( 'model' ) } " 160f"worker_requests= { n } " ) 161 162 163def case_cancellation (fx :Fixture )-> None : 164"""Cancelling a turn must abort it and produce an aborted terminal state, not a completion. 165 166Also checks the handoff's specific warning: `session/cancel` returns `{accepted:true}` as 167*admission only*. The assertion is on the durable terminal state, not on that acknowledgement. 168""" 169sid = fx .new_session () 170log (f"session { sid } " ) 171fx .prompt (sid ,"Write a very long, detailed essay about the history of computing." ) 172log ("prompt accepted" ) 173# Cancel promptly: after acceptance, before the turn can finish. 174time .sleep (0.3 ) 175value = fx .cancel (sid ) 176log (f"cancel acknowledged: { json . dumps ( value ) } " ) 177if value .get ("accepted" )is not True : 178raise BridgeError (f"cancel was not accepted: { json . dumps ( value )[: 200 ] } " ) 179end ,events = fx .wait_turn_end (sid ) 180if end is None : 181raise BridgeError ("after cancel the turn never reached a terminal state" ) 182kind = ((end .get ("data" )or {}).get ("reason" )or {}).get ("kind" ) 183log (f"terminal state: { kind } " ) 184if kind == "completed" : 185# Not necessarily a failure of the bridge: a mock engine answers instantly, so the turn may 186# genuinely finish before the cancel lands. Say so rather than pretending either way. 187raise BridgeError ("the turn completed before the cancel took effect; with an instant mock " 188"engine this is a timing race, not evidence either way — rerun to " 189"confirm, and re-run against a real model for a decisive result" ) 190if kind not in ("aborted" ,"interrupted" ,"failed" ,"error" ): 191raise BridgeError (f"unexpected terminal state after cancel: { json . dumps ( kind ) } " ) 192log (f"cancel produced ' { kind } ' (accepted != settled, as documented)" ) 193 194 195def case_approval (fx :Fixture )-> None : 196"""A tool call must raise an approval request that the operator can answer over the gateway. 197 198The handoff records this as an unimplemented transport. It is implemented on the gateway 199surface: `approval/request` is a forwarded waterfall and `POST /api/$events/result` settles it. 200Assertions are written so an approved run proves the *outbound* seam (a request really was 201raised and had to be decided); the tools the model is offered here may not need approval, in 202which case the case reports that honestly instead of inventing a pass. 203""" 204# Read the workspace before/after so a shell tool that really ran is visible. 205marker = fx .tmp / "ws" / "approval-probe.txt" 206sid = fx .new_session () 207log (f"session { sid } " ) 208# Ask for an action that needs a tool rather than an answer from memory. 209fx .prompt (sid ,"Create a file named approval-probe.txt in the current directory " 210"containing the single word hello, then tell me you did it." ,rpc_id = "pa" ) 211log ("prompt accepted" ) 212end ,events = fx .wait_turn_end (sid ) 213if end is None : 214raise BridgeError ("the turn never reached a terminal state" ) 215kind = ((end .get ("data" )or {}).get ("reason" )or {}).get ("kind" ) 216asked = [e for e in events if e .get ("type" )== "approval/asked" ] 217decided = [e for e in events if e .get ("type" )== "approval/decided" ] 218log (f"terminal= { kind } approval/asked= { len ( asked ) } approval/decided= { len ( decided ) } " 219f"probe_file= { 'present' if marker . exists () else 'absent' } " ) 220if asked : 221# The durable audit pair must be complete and every decision must be in the vocabulary. 222outcomes = [(e .get ("data" )or {}).get ("outcome" )for e in decided ] 223allowed = {"allowed-once" ,"rejected" ,"cancelled" ,"unavailable" } 224bad = [o for o in outcomes if o not in allowed ] 225if bad : 226raise BridgeError (f"approval decided with a non-vocabulary outcome: { bad } " ) 227log (f"approval decisions: { outcomes } " ) 228return 229log ("no approval was asked for this tool set; the outbound seam was therefore not exercised. " 230"Re-run with a tool that requires approval to cover it (see the qualification kit)." ) 231 232 233CASES = {"completion" :case_completion ,"cancel" :case_cancellation ,"approval" :case_approval } 234 235 236def main ()-> int : 237ap = argparse .ArgumentParser (description = __doc__ , 238formatter_class = argparse .RawDescriptionHelpFormatter ) 239ap .add_argument ("--dsh" ,default = os .environ .get ("DSH_CLI" ,DEFAULT_DSH )) 240ap .add_argument ("--python" ,default = str (DEFAULT_PYTHON )) 241ap .add_argument ("--worker-port" ,type = int ,default = 8095 ) 242ap .add_argument ("--keep" ,action = "store_true" ) 243ap .add_argument ("--all" ,action = "store_true" ) 244ap .add_argument ("--cancel" ,action = "store_true" ) 245ap .add_argument ("--approval" ,action = "store_true" ) 246args = ap .parse_args () 247 248selected = [] 249if args .all : 250selected = ["completion" ,"cancel" ,"approval" ] 251else : 252if args .cancel : 253selected .append ("cancel" ) 254if args .approval : 255selected .append ("approval" ) 256if not selected : 257selected = ["completion" ] 258 259dsh ,python = Path (args .dsh ),Path (args .python ) 260for path ,what in ((dsh ,"dsh CLI" ), (python ,"python interpreter" ), (PROFILE_PATCH ,"profile" )): 261if not path .exists (): 262f"prerequisite missing: { what } not at { path } " ,file = sys .stderr ) 263return 2 264 265"strata <-> harness bridge tests" ) 266f" cases : { ', ' . join ( selected ) } " ) 267failures = [] 269for name in selected : 270f"[ { name } ]" ) 271try : 272with Fixture (dsh ,python ,args .worker_port ,args .keep )as fx : 273CASES [name ](fx ) 274f" -> PASS\n" ) 275except Exception as e :# noqa: BLE001 - a test reports, it does not crash 276f" -> FAIL: { e } \n" ) 277failures .append ((name ,str (e ))) 278 279if failures : 280"FAIL" ) 281for name ,err in failures : 282f" { name } : { err } " ) 283return 1 284"PASS — all selected bridge cases passed" ) 285return 0 286 287 288if __name__ == "__main__" : 289sys .exit (main ())