okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1#!/usr/bin/env python3 2"""Tool execution, approval and cancellation, end to end (checklist A03, A04, A05). 3 4This drives the real path — a scripted Strata worker, the Harness agent loop with its real bash tool, 5and a durable session — so what it proves is the *integration*, not a mock of it. 6 7The model is scripted. That is a deliberate and limited choice: writing a file via bash is 8deterministic, and a scripted tool call exercises exactly the same code as a model-chosen one — 9the worker's parser, the Harness tool executor, the approval gate and the durable record. What it 10does **not** prove is that a real model chooses tools well, and this script never claims that. 11 12Three flows, each with one assertion that matters: 13 14**A03 — the tool runs once, in the Harness.** 15The scripted turn calls bash to append a line to a file. The assertions are that the file has 16exactly one line (so the tool ran exactly once), that the durable session records a tool call and 17a tool result, and that the Strata worker was given the transcript rather than executing anything 18itself — the worker has no tool-execution path at all, and the call count is the evidence. The 19call escalates the sandbox, so it cannot run until a peer *grants* it: the flow connects that peer 20and asserts an approval was asked, answered, and recorded as the grant. 21 22**A04 — the denial test: a tool that could escalate without an answerer would be the whole failure.** 23The same scripted call and the same peer connection; the only difference is the decision. The peer 24delegates (`next`) instead of granting, so the composed answerer chain has no terminal answerer 25and the request resolves the fail-closed `unavailable`. The assertions are that the escalation 26reached the gate, that its recorded outcome is exactly `unavailable`, that the turn settled on 27that denial, and that the file does not exist afterwards. Connecting the peer is what makes the 28outcome observable — with no peer at all the gateway keeps a forwarded waterfall pending until a 29client connects, so the request would be neither granted nor decided. 30 31**A05 — Stop settles the turn.** 32A prompt is sent and cancelled while the turn is live. The assertions are that the turn reaches a 33terminal state without the tool having run, and that cancellation is acknowledged only as 34admission (`accepted`), with the durable turn state being what actually settles it. 35 36Run: python integrations/harness/tool_flow_e2e.py --dsh <checkout> [--keep] 37""" 38 39from __future__import annotations 40 41import argparse 42import base64 43import json 44import os 45import re 46import shutil 47import socket 48import struct 49import subprocess 50import sys 51import tempfile 52import threading 53import time 54import http .client 55from pathlib import Path 56 57HERE = Path (__file__ ).resolve ().parent 58STRATA = HERE .parents [1 ] 59PROFILE_PATCH = HERE / "profile" / "cordis.patch.yml" 60#: A TEST-ONLY overlay, applied after the product patch. It disables the session-title model 61#: request, which a scripted worker cannot absorb: the worker replays one script per request, so 62#: an extra request shifts every later reply and the run looks like a model that chose not to 63#: call a tool. The product profile must keep answering title requests, so the row lives here. 64SCRIPTED_OVERLAY = HERE / "profile" / "scripted-worker.cordis.patch.yml" 65PYTHON = os .environ .get ("STRATA_PYTHON" ,sys .executable ) 66 67#: The bash call the scripted worker emits. It appends exactly one line, so counting the lines counts 68#: the executions -- a replayed tool would leave two. 69# The `</think>` is not decoration: without it the server treats the *whole* reply as reasoning, so 70# the tool-call block lands in the reasoning field and is never executed. The default mock script ends 71# its thinking the same way, which is where the convention comes from. The failure is silent -- the 72# turn completes normally with the tool call sitting in the wrong field. 73# 74# Every parameter is load-bearing: 75# * `command` is the effect the assertions count; 76# * `description` is REQUIRED by this runtime's bash schema -- a call without it is rejected by 77# argument validation ("invalid arguments: missing required property \"description\"") before the 78# tool body runs, which looks exactly like a tool that never executed; 79# * `sandbox_permissions` + `justification` are what make the call ask for approval at all. The 80# approval policy is `ask` and the sandbox is `workspace-write`, but a command the sandbox would 81# allow runs *without* an approval prompt: only a strictly wider sandbox mode is decided by 82# `ctx.approval`. So a call that never escalates cannot prove anything about the approval gate -- 83# it runs with no answerer present, which is how A04's denial test can pass while testing nothing. 84TOOL_CALL = ( 85"I will write the marker file.</think>\n\n" 86"<tool_call>\n<function=bash>\n" 87"<parameter=command>\n" 88"echo run >> {marker}\n" 89"</parameter>\n" 90"<parameter=description>\n" 91"Append one line to the marker file\n" 92"</parameter>\n" 93"<parameter=sandbox_permissions>\n" 94"danger-full-access\n" 95"</parameter>\n" 96"<parameter=justification>\n" 97"The marker write must not be refused by the file sandbox.\n" 98"</parameter>\n" 99"</function>\n</tool_call>" 100) 101FINAL_ANSWER = "The marker file has been written." 102 103#: The worker is started with `--script-cycle`, so the script is chosen by the request's position 104#: rather than by a counter that every extra request advances. That matters because the Harness makes 105#: requests the script author did not plan for -- a session title, and a re-ask after a tool result -- 106#: and with the default behaviour one of those shifts every later reply. The symptom is a run that 107#: looks like a model which simply chose not to use a tool. 108 109 110class FlowError (RuntimeError ): 111pass 112 113 114def log (msg :str )-> None : 115f" { msg } " ,flush = True ) 116 117 118def http_json (method :str ,host :str ,port :int ,path :str ,body = None ,cookie :str | None = None , 119timeout :float = 30.0 ): 120"""A request that does not follow redirects, because the redirect carries the credential. 121 122`urllib` follows the agent's 303 and discards the `set-cookie` on it, which surfaces as a 401 on 123the next request and looks like an authentication bug rather than a client one. `http.client` 124returns the response as sent, which is what this needs. 125""" 126connection = http .client .HTTPConnection (host ,port ,timeout = timeout ) 127headers = {} 128data = None 129if body is not None : 130data = json .dumps (body ).encode () 131headers ["content-type" ]= "application/json" 132if cookie : 133headers ["cookie" ]= cookie 134try : 135connection .request (method ,path ,body = data ,headers = headers ) 136response = connection .getresponse () 137raw = response .read ().decode ("utf-8" ,"replace" ) 138return response .status ,raw ,response .getheader ("set-cookie" )or "" 139finally : 140connection .close () 141 142 143def rpc (host :str ,port :int ,cookie :str ,rpc_id :str ,method :str ,args :dict ): 144"""One gateway call. 145 146The envelope is the gateway's own: `{"type": "client-request", "rpcId", "method", "payload": 147{"args"}}`. Posting `args` directly is answered with `invalid client-request message` and a list 148of schema issues, which reads like a malformed session rather than a malformed envelope. 149""" 150body = {"type" :"client-request" ,"rpcId" :rpc_id ,"method" :method ,"payload" : {"args" :args }} 151status ,raw ,_ = http_json ("POST" ,host ,port ,f"/api/ { method } " ,body ,cookie = cookie ) 152if status != 200 : 153raise FlowError (f" { method } returned HTTP { status } : { raw [: 300 ] } " ) 154payload = json .loads (raw ) 155result = payload .get ("result" )or {} 156if not result .get ("ok" ): 157raise FlowError (f" { method } was refused: { json . dumps ( result . get ( 'error' ))[: 400 ] } " ) 158return result .get ("value" ) 159 160 161#: The gateway's event stream, and the HTTP endpoint that answers one forwarded waterfall. Both are 162#: gateway-internal endpoint names, not HTTP routes: the stream is a logical stream carried by the 163#: WebSocket mux, and only the answer travels as an ordinary `/api/<endpoint>` call. 164EVENT_STREAM_ENDPOINT = "$events" 165EVENT_RESULT_ENDPOINT = "$events/result" 166REMOTE_STREAM_MUX_PATH = "/api/remote.mux" 167 168 169class ApprovalAnswerer : 170"""A real peer, because an approval cannot be answered without one. 171 172`approval/request` is not an RPC that a client can simply call: it is a Cordis *waterfall* the 173gateway forwards to connected peers, and it is delivered over the gateway's event stream. A peer 174that wants to decide one must receive the frame (a WebSocket on `/api/remote.mux`, opened as the 175`$events` logical stream) and then send its outcome back (`POST /api/$events/result`). 176 177`decision` is the outcome this peer returns for every request: 178* `'allowed-once'` — the grant A03 needs; 179* `'next'` — do not decide, delegate to the listeners behind this peer. It is what an 180answerer that is *present but not available* does, so the request resolves `unavailable` and 181the action fails closed, which is the outcome A04 asserts. 182 183A peer is also the only thing that can make an approval observable at all: with no client holding 184the stream open the gateway keeps the forwarded waterfall pending until one connects (it has a 185test named "delivers a pending waterfall to the first Client that connects"), so the request is 186never decided and nothing is `unavailable` -- the turn simply waits. That is why A04 connects a 187peer and delegates instead of asserting on an answerer that does not exist. 188 189No WebSocket client is available in the standard library, so the handshake and the four frame 190types this needs (text, ping, pong, close) are implemented here. Only frames the Host sends are 191parsed; the one frame this peer sends is the stream `open`. 192""" 193 194def __init__ (self ,host :str ,port :int ,cookie :str ,decision :str = "allowed-once" ): 195self .host ,self .port ,self .cookie ,self .decision = host ,port ,cookie ,decision 196self .requests :list [dict ]= []# every approval request this peer was asked to decide 197self .outcomes :list [str ]= []# the decision actually sent for each of them 198self .error :str | None = None 199self .ready = threading .Event ()# set once the Host proved the event stream is live 200self .client_id :str | None = None 201self ._sock :socket .socket | None = None 202self ._buffer = b"" 203self ._thread :threading .Thread | None = None 204 205# -- lifecycle --------------------------------------------------------------------------------- 206 207def start (self ,timeout :float = 30.0 )-> "ApprovalAnswerer" : 208"""Connect and wait until the event stream is live. 209 210The wait is the point: an approval raised before the stream exists is delivered to nobody and 211fails closed, so a peer that connects late turns "no answerer" into a tool that never ran. 212""" 213self ._thread = threading .Thread (target = self ._run ,name = "approval-answerer" ,daemon = True ) 214self ._thread .start () 215if not self .ready .wait (timeout ): 216self .close () 217raise FlowError (f"the approval answerer never opened the event stream: { self . error or 'no reply' } " ) 218return self 219 220def close (self )-> None : 221sock = self ._sock 222if sock is None : 223return 224try : 225self ._send_frame (0x8 ,b"" )# close 226except Exception :# noqa: BLE001 - the peer is going away either way 227pass 228self ._sock = None 229try : 230sock .shutdown (socket .SHUT_RDWR ) 231except OSError : 232pass 233sock .close () 234 235# -- WebSocket carrier ------------------------------------------------------------------------- 236 237def _connect (self )-> None : 238sock = socket .create_connection ((self .host ,self .port ),timeout = 15 ) 239sock .settimeout (30 ) 240key = base64 .b64encode (os .urandom (16 )).decode () 241handshake = ( 242f"GET { REMOTE_STREAM_MUX_PATH } HTTP/1.1\r\n" 243f"Host: { self . host } : { self . port } \r\n" 244"Upgrade: websocket\r\n" 245"Connection: Upgrade\r\n" 246f"Sec-WebSocket-Key: { key } \r\n" 247"Sec-WebSocket-Version: 13\r\n" 248# The operator credential from the launch URL: the same cookie the RPC calls use, and 249# the only thing that makes this a peer rather than an anonymous socket. 250f"Cookie: { self . cookie } \r\n\r\n" 251 ) 252sock .sendall (handshake .encode ()) 253head = b"" 254while b"\r\n\r\n" not in head : 255chunk = sock .recv (4096 ) 256if not chunk : 257raise FlowError ("the event stream socket closed during the WebSocket handshake" ) 258head += chunk 259header ,self ._buffer = head .split (b"\r\n\r\n" ,1 ) 260status = header .split (b"\r\n" ,1 )[0 ].decode ("latin-1" ) 261if " 101 " not in status : 262raise FlowError (f"the event stream upgrade was refused: { status !r } " ) 263# The stream is idle between events, so a read deadline would end the peer during a quiet 264# stretch and silently turn A03 back into A04. Blocking reads are released by close(). 265sock .settimeout (None ) 266self ._sock = sock 267 268def _read_exactly (self ,count :int )-> bytes : 269while len (self ._buffer )< count : 270chunk = self ._sock .recv (65536 ) 271if not chunk : 272raise FlowError ("the event stream closed" ) 273self ._buffer += chunk 274taken ,self ._buffer = self ._buffer [:count ],self ._buffer [count :] 275return taken 276 277def _send_frame (self ,opcode :int ,payload :bytes )-> None : 278"""One client frame. Client frames must be masked (RFC 6455), and the Host rejects one that is not.""" 279mask = os .urandom (4 ) 280length = len (payload ) 281if length < 126 : 282header = bytes ([0x80 | opcode ,0x80 | length ]) 283elif length < (1 << 16 ): 284header = bytes ([0x80 | opcode ,0x80 | 126 ])+ struct .pack ("!H" ,length ) 285else : 286header = bytes ([0x80 | opcode ,0x80 | 127 ])+ struct .pack ("!Q" ,length ) 287masked = bytes (byte ^ mask [index % 4 ]for index ,byte in enumerate (payload )) 288self ._sock .sendall (header + mask + masked ) 289 290def _send_text (self ,text :str )-> None : 291self ._send_frame (0x1 ,text .encode ()) 292 293def _read_frame (self )-> tuple [int ,bytes ]: 294first ,second = self ._read_exactly (2 ) 295opcode ,length = first & 0x0F ,second & 0x7F 296if length == 126 : 297length = struct .unpack ("!H" ,self ._read_exactly (2 ))[0 ] 298elif length == 127 : 299length = struct .unpack ("!Q" ,self ._read_exactly (8 ))[0 ] 300masked = bool (second & 0x80 ) 301mask = self ._read_exactly (4 )if masked else b"" 302payload = self ._read_exactly (length ) 303if masked : 304payload = bytes (byte ^ mask [index % 4 ]for index ,byte in enumerate (payload )) 305return opcode ,payload 306 307# -- protocol ---------------------------------------------------------------------------------- 308 309def _run (self )-> None : 310try : 311self ._connect () 312stream_id = "approvals" 313self ._send_text (json .dumps ({ 314"type" :"open" ,"streamId" :stream_id , 315"endpoint" :EVENT_STREAM_ENDPOINT , 316# The endpoint's own envelope: exactly one `args` field, empty for this stream. 317"payload" : {"args" : {}}, 318 })) 319while True : 320opcode ,payload = self ._read_frame () 321if opcode == 0x8 :# close 322return 323if opcode == 0x9 :# ping: the Host's liveness probe 324self ._send_frame (0xA ,payload ) 325continue 326if opcode != 0x1 :# pong and anything else: ignore 327continue 328self ._handle (json .loads (payload .decode ("utf-8" ,"replace" ))) 329except Exception as error :# noqa: BLE001 - reported, never raised here 330self .error = f" { type ( error ). __name__ } : { error } " 331finally : 332self .ready .set ()# a failed start must not hang start() 333 334def _handle (self ,message :dict )-> None : 335if message .get ("type" )!= "item" : 336return 337value = message .get ("value" ) 338if not isinstance (value ,dict ): 339return 340if value .get ("type" )== "ready" : 341self .client_id = value .get ("clientId" ) 342self .ready .set () 343return 344if value .get ("type" )!= "waterfall" or value .get ("event" )!= "approval/request" : 345return # emitted notifications are not questions 346self ._answer (value ) 347 348def _answer (self ,frame :dict )-> None : 349self .requests .append (frame .get ("request" )or {}) 350# `next` is the DSH word for "this answerer does not decide": the waterfall continues to the 351# listeners behind this peer, and with no terminal answerer composed it settles on the 352# approval service's fail-closed default, `unavailable`. It is not a rejection -- `rejected` 353# would be a human saying no, which is a different outcome and a different test. 354outcome = ({"kind" :"next" }if self .decision == "next" 355else {"kind" :"result" ,"value" :self .decision }) 356body = { 357"type" :"client-request" ,"rpcId" :f"approval- { len ( self . requests ) } " , 358"method" :EVENT_RESULT_ENDPOINT , 359"payload" : {"args" : { 360"clientId" :self .client_id ,"eventId" :frame .get ("eventId" ), 361"outcome" :outcome , 362 }}, 363 } 364status ,raw ,_ = http_json ("POST" ,self .host ,self .port ,f"/api/ { EVENT_RESULT_ENDPOINT } " , 365body ,cookie = self .cookie ) 366if status != 200 : 367raise FlowError (f"answering the approval returned HTTP { status } : { raw [: 200 ] } " ) 368answer = (json .loads (raw ).get ("result" )or {}) 369if not answer .get ("ok" ): 370raise FlowError (f"the approval answer was refused: { json . dumps ( answer . get ( 'error' ))[: 300 ] } " ) 371self .outcomes .append (self .decision ) 372 373 374def wait_for_worker (port :int ,timeout :float = 60.0 )-> None : 375deadline = time .time ()+ timeout 376while time .time ()< deadline : 377try : 378status ,_ ,_ = http_json ("GET" ,"127.0.0.1" ,port ,"/health" ,timeout = 2 ) 379if status == 200 : 380return 381except (OSError ,http .client .HTTPException ): 382pass 383time .sleep (0.3 ) 384raise FlowError (f"the worker on { port } never became healthy" ) 385 386 387def write_profile (port :int ,tmp :Path )-> Path : 388"""The Strata profile patch with this run's worker port. 389 390The shipped patch names 8095, and a worker left over from an earlier session on that port will 391happily answer every request -- producing a green run against the *wrong* worker, which is 392exactly how a stale process hid a failure here once already. Substituting the port makes the 393agent and the worker this test started the only pair that can talk. 394""" 395text = PROFILE_PATCH .read_text (encoding = "utf-8" ) 396if "http://127.0.0.1:8095/v1" not in text : 397raise FlowError (f" { PROFILE_PATCH } no longer names http://127.0.0.1:8095/v1; the substitution " 398"below would silently do nothing" ) 399patched = tmp / "cordis.patch.yml" 400patched .write_text (text .replace ("http://127.0.0.1:8095/v1" ,f"http://127.0.0.1: { port } /v1" ), 401encoding = "utf-8" ) 402return patched 403 404 405def start_worker (scripts :list [str ],port :int ,log_path :Path , 406delay_s :float = 0.0 )-> subprocess .Popen : 407if worker_port_in_use (port ): 408raise FlowError ( 409f"port { port } is already in use; a worker left over from an earlier session would answer " 410"this test's requests and its results would look plausible" ) 411argv = [PYTHON ,"-m" ,"serve.server" ,"--engine" ,"mock" ,"--port" ,str (port ),"--script-cycle" ] 412if delay_s : 413# A turn that finishes before Stop can arrive proves nothing about Stop. The mock honours 414# cancellation between tokens, so a delay makes the window real. 415argv += ["--script-delay" ,str (delay_s )] 416for script in scripts : 417argv += ["--script" ,script ] 418handle = log_path .open ("wb" ) 419return subprocess .Popen (argv ,cwd = str (STRATA ),stdout = handle ,stderr = subprocess .STDOUT ) 420 421 422def worker_port_in_use (port :int )-> bool : 423import socket 424with socket .socket (socket .AF_INET ,socket .SOCK_STREAM )as probe : 425probe .settimeout (0.5 ) 426return probe .connect_ex (("127.0.0.1" ,port ))== 0 427 428 429def start_agent (dsh :Path ,port :int ,home :Path ,profile :str ,log_path :Path , 430cwd :Path ,patch :Path )-> subprocess .Popen : 431"""Boot the agent with the Strata profile. 432 433The profile is selected the way the working bridge does it: `--profile <base> --patch <file>`, a 434patch layer over a shipped bundle. `dsh web --profile` does not exist, and passing it produces 435`unknown option '--profile'` before anything starts. 436""" 437env = dict (os .environ ) 438env ["DSH_HOME" ]= str (home ) 439env .pop ("ELECTRON_RUN_AS_NODE" ,None ) 440argv = [str (dsh ),"--profile" ,profile ,"--patch" ,str (patch ), 441"--patch" ,str (SCRIPTED_OVERLAY ), 442"--port" ,str (port ),"--no-open" ] 443handle = log_path .open ("wb" ) 444return subprocess .Popen (argv ,env = env ,cwd = str (cwd ),stdout = handle ,stderr = subprocess .STDOUT ) 445 446 447def wait_for_agent (log_path :Path ,proc :subprocess .Popen ,timeout :float = 150.0 )-> tuple [int ,str ]: 448deadline = time .time ()+ timeout 449while time .time ()< deadline : 450if proc .poll ()is not None : 451raise FlowError (f"the agent exited with code { proc . returncode } :\n" 452f" { log_path . read_text ( errors = 'replace' )[ - 800 :] } " ) 453text = log_path .read_text (errors = "replace" )if log_path .exists ()else "" 454match = re .search (r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)" ,text ) 455if match : 456return int (match .group (1 )),match .group (2 ) 457time .sleep (0.5 ) 458raise FlowError (f"the agent never printed a URL:\n { log_path . read_text ( errors = 'replace' )[ - 800 :] } " ) 459 460 461def read_events (session_id :str ,home :Path )-> list [dict ]: 462root = home / "sessions" 463matches = list (root .glob (f"*/ { session_id } /session.v*.jsonl*" )) 464if not matches : 465return [] 466newest = max (matches ,key = lambda p :p .stat ().st_mtime ) 467try : 468out = subprocess .run (["zstd" ,"-d" ,"-c" ,"--long=27" ,str (newest )], 469capture_output = True ,timeout = 30 ) 470text = out .stdout .decode ("utf-8" ,"replace" ) 471except (OSError ,subprocess .SubprocessError ): 472return [] 473events = [] 474for line in text .splitlines (): 475line = line .strip () 476if not line : 477continue 478try : 479events .append (json .loads (line )) 480except json .JSONDecodeError : 481continue 482return events 483 484 485def wait_for_turn (session_id :str ,home :Path ,timeout :float = 180.0 )-> list [dict ]: 486deadline = time .time ()+ timeout 487while time .time ()< deadline : 488events = read_events (session_id ,home ) 489if any (e .get ("type" )== "turn/end" for e in events ): 490return events 491time .sleep (1.0 ) 492return read_events (session_id ,home ) 493 494 495def summarise (events :list [dict ])-> dict : 496kinds :dict [str ,int ]= {} 497for event in events : 498kinds [event .get ("type" ,"?" )]= kinds .get (event .get ("type" ,"?" ),0 )+ 1 499turn_end = next ((e for e in events if e .get ("type" )== "turn/end" ),None ) 500reason = ((turn_end or {}).get ("data" )or {}).get ("reason" )or {} 501return {"kinds" :kinds ,"end" :reason .get ("kind" ),"reason" :reason } 502 503 504class Agent : 505"""One agent process with a session, so each flow gets a clean session.""" 506 507def __init__ (self ,dsh :Path ,port :int ,home :Path ,profile :str ,answerer :bool ,tmp :Path , 508cwd :Path ,worker_port :int ): 509self .home ,self .port ,self .tmp ,self .cwd = home ,port ,tmp ,cwd 510cwd .mkdir (parents = True ,exist_ok = True ) 511# A profile naming this run's worker port, so no other process can answer for it. 512self .patch = write_profile (worker_port ,tmp ) 513self .log_path = tmp / f"agent- { port } .log" 514self .proc = start_agent (dsh ,port ,home ,profile ,self .log_path ,self .cwd ,self .patch ) 515self .agent_port ,token = wait_for_agent (self .log_path ,self .proc ) 516query = f"/?token= { token } " + ("&interactions=answer" if answerer else "" ) 517_ ,_ ,cookie = http_json ("GET" ,"127.0.0.1" ,self .agent_port ,query ) 518self .cookie = cookie .split (";" ,1 )[0 ] 519if not self .cookie .startswith ("dsh-auth-" ): 520raise FlowError (f"no operator cookie (got { cookie [: 80 ]!r } )" ) 521self .answerer = answerer 522self .peer :ApprovalAnswerer | None = None 523 524def answer_approvals (self ,decision :str = "allowed-once" )-> ApprovalAnswerer : 525"""Connect the peer that decides approvals, and return it once its stream is live. 526 527This is what makes an approval answerable, and `interactions=answer` on the launch URL is 528not: that parameter is read only on `/connect` 529(`packages/client/connection/src/browser-auth.ts`), while `GET /?token=...` issues the 530browser cookie whose shared peer already permits the event stream 531(`packages/client/connection/src/peer.ts`: `options.interactions ?? 'answer'`). So 532`answerer=False` never removed an answerer; the `decision` a flow passes here is the real 533difference between A03 and A04. 534""" 535peer = ApprovalAnswerer ("127.0.0.1" ,self .agent_port ,self .cookie ,decision ).start () 536self .peer = peer 537return peer 538 539def session (self ,cwd :Path )-> str : 540result = rpc ("127.0.0.1" ,self .agent_port ,self .cookie ,"c1" ,"session/create" , 541 {"request" : {"cwd" :str (cwd )}}) 542return result ["sessionId" ] 543 544def prompt (self ,session_id :str ,text :str ,request_id :str = "req-1" )-> None : 545rpc ("127.0.0.1" ,self .agent_port ,self .cookie ,f"p- { request_id } " ,"session/prompt" , 546 {"request" : {"requestId" :request_id ,"sessionId" :session_id ,"mode" :"queue" , 547"content" : [{"type" :"text" ,"text" :text }]}}) 548 549def cancel (self ,session_id :str )-> dict : 550return rpc ("127.0.0.1" ,self .agent_port ,self .cookie ,"x1" ,"session/cancel" , 551 {"request" : {"sessionId" :session_id }}) 552 553def close (self ): 554# Teardown never raises and never skips a step: a failure closing the peer once left the agent 555# process alive on its port, and the next run died at startup with EADDRINUSE instead of 556# reporting the real problem. The peer is best-effort; killing the process is not. 557if self .peer is not None : 558try : 559self .peer .close () 560except Exception as error :# noqa: BLE001 - cleanup must not mask the run 561log (f"closing the approval peer failed: { type ( error ). __name__ } : { error } " ) 562if self .proc .poll ()is None : 563self .proc .terminate () 564try : 565self .proc .wait (timeout = 20 ) 566except subprocess .TimeoutExpired : 567self .proc .kill () 568 569 570def flow_a03 (dsh :Path ,tmp :Path ,profile :str ,base_port :int ,results :dict )-> None : 571"[A03] a read/edit/test workflow: the tool runs once, in the Harness" ) 572ws = tmp / "ws-a03" 573ws .mkdir (parents = True ,exist_ok = True ) 574marker = ws / "marker.txt" 575worker = start_worker ([TOOL_CALL .format (marker = marker ),FINAL_ANSWER ], 576base_port ,tmp / "worker-a03.log" ) 577agent = None 578try : 579wait_for_worker (base_port ) 580agent = Agent (dsh ,base_port + 1 ,tmp / "home-a03" ,profile ,answerer = True ,tmp = tmp ,cwd = ws ,worker_port = base_port ) 581# The scripted call escalates the sandbox, so the tool cannot run until a peer grants it. The 582# peer is connected (and its stream proved live) BEFORE the prompt, because an approval raised 583# while no peer holds the stream open fails closed and is gone for good. 584peer = agent .answer_approvals ("allowed-once" ) 585session = agent .session (ws ) 586agent .prompt (session ,"Write the marker file using bash, then report that you did." ) 587events = wait_for_turn (session ,agent .home ) 588summary = summarise (events ) 589 590calls = [e for e in events if "tool" in str (e .get ("type" ,"" ))] 591asked = [e for e in events if e .get ("type" )== "approval/asked" ] 592decided = [e for e in events if e .get ("type" )== "approval/decided" ] 593executed = marker .exists () 594lines = marker .read_text ().splitlines ()if executed else [] 595 596results ["A03" ]= { 597"turn_end" :summary ["end" ], 598"tool_events" :len (calls ), 599"marker_lines" :len (lines ), 600"executions" :len (lines ), 601"approvals_asked" :len (asked ), 602"approvals_answered" :len (peer .outcomes ), 603"approval_outcomes" : [((e .get ("data" )or {}).get ("outcome" ))for e in decided ], 604 } 605log (f"turn ended as { summary [ 'end' ]!r } ; { len ( calls ) } tool-related event(s)" ) 606log (f"the workspace marker has { len ( lines ) } line(s)" ) 607log (f"the peer answered { len ( peer . outcomes ) } of { len ( asked ) } approval(s): " 608f" { [(( e . get ( 'data' ) or {}). get ( 'outcome' )) for e in decided ] } " ) 609 610if summary ["end" ]!= "completed" : 611raise FlowError (f"the turn did not complete: { json . dumps ( summary )[: 300 ] } " ) 612if not executed : 613raise FlowError ("the bash tool did not run: no marker file was written" ) 614if len (lines )!= 1 : 615raise FlowError (f"the tool ran { len ( lines ) } times, not once: a completed tool effect was " 616"replayed" ) 617# The tool ran because the approval was granted, not because it was never asked: without this 618# the flow would still pass if the escalation stopped reaching the approval gate, which is the 619# state A04's denial test exists to rule out. The grant must also be the recorded outcome. 620if len (peer .outcomes )< 1 or not asked : 621raise FlowError ("the tool ran without an answered approval: the call did not reach the " 622f"approval gate (asked= { len ( asked ) } , answered= { len ( peer . outcomes ) } , " 623f"peer_error= { peer . error !r } )" ) 624if [e for e in decided if (e .get ("data" )or {}).get ("outcome" )!= "allowed-once" ]: 625raise FlowError (f"the session recorded an approval outcome other than the granted one: " 626f" { [(( e . get ( 'data' ) or {}). get ( 'outcome' )) for e in decided ] } " ) 627# The worker must have been given the transcript rather than executing the tool itself: it has 628# no tool-execution path, so a healthy worker is one that only ever answered. 629status ,raw ,_ = http_json ("GET" ,"127.0.0.1" ,base_port ,"/v1/status" ) 630activity = json .loads (raw ).get ("activity" )or {} 631results ["A03" ]["worker_requests" ]= activity .get ("requests" ) 632log (f"the worker recorded { activity . get ( 'requests' ) } request(s) and executed nothing itself" ) 633" PASS A03" ) 634finally : 635if agent : 636agent .close () 637worker .terminate () 638worker .wait (timeout = 20 ) 639 640 641def flow_a04 (dsh :Path ,tmp :Path ,profile :str ,base_port :int ,results :dict )-> None : 642"[A04] with no answerer that decides, the approval fails closed and the tool does not run" ) 643ws = tmp / "ws-a04" 644ws .mkdir (parents = True ,exist_ok = True ) 645marker = ws / "must-not-exist.txt" 646worker = start_worker ([TOOL_CALL .format (marker = marker ),FINAL_ANSWER ], 647base_port ,tmp / "worker-a04.log" ) 648agent = None 649try : 650wait_for_worker (base_port ) 651# `answerer=False` keeps `interactions=answer` off the launch URL. That flag is not what 652# decides this flow -- it is read only on `/connect`, so on `/?token=...` it does nothing, and 653# the peer below can open the event stream either way. What decides the flow is that no peer 654# *grants* the escalation: the one connected peer delegates (`next`), which leaves the 655# composed answerer chain without a terminal answerer and the request resolves the 656# fail-closed `unavailable`. 657agent = Agent (dsh ,base_port + 1 ,tmp / "home-a04" ,profile ,answerer = False ,tmp = tmp ,cwd = ws ,worker_port = base_port ) 658# The peer must exist for the outcome to be observable at all. With no peer holding the 659# event stream, the gateway keeps the forwarded waterfall pending until one connects -- the 660# request is then never decided, nothing is `unavailable`, and the turn simply waits, which is 661# a timeout, not a denial. 662peer = agent .answer_approvals ("next" ) 663session = agent .session (ws ) 664agent .prompt (session ,"Write the marker file using bash." ,request_id = "a04" ) 665events = wait_for_turn (session ,agent .home ) 666summary = summarise (events ) 667 668created = marker .exists () 669asked = [e for e in events if e .get ("type" )== "approval/asked" ] 670outcomes = [((e .get ("data" )or {}).get ("outcome" ))for e in events 671if e .get ("type" )== "approval/decided" ] 672results ["A04" ]= {"turn_end" :summary ["end" ],"marker_created" :created , 673"answerer" :agent .answerer , 674"approvals_asked" :len (asked ),"approval_outcomes" :outcomes , 675"grants" :outcomes .count ("allowed-once" )} 676log (f"turn ended as { summary [ 'end' ]!r } " ) 677log (f"the marker file exists: { created } " ) 678log (f"the escalation was asked { len ( asked ) } time(s) and decided { outcomes } " ) 679 680if created : 681raise FlowError ("the tool ran even though no answerer granted the escalation: an " 682"unanswerable approval must fail closed" ) 683# The denial has to be observed, not assumed. Each check below fails the run for a different 684# way the flow could otherwise pass while proving nothing: the tool never reaching the gate, 685# the gate deciding to grant, or the turn never settling because the request was left pending. 686if not asked : 687raise FlowError ("the bash call never reached the approval gate, so this run proves nothing " 688"about an unanswerable approval: no approval/asked was recorded" ) 689if not outcomes or any (outcome != "unavailable" for outcome in outcomes ): 690raise FlowError (f"the unanswerable escalation did not fail closed as 'unavailable': " 691f" { outcomes } " ) 692if summary ["end" ]!= "completed" : 693raise FlowError (f"the turn did not settle after the denial (ended as { summary [ 'end' ]!r } ): a " 694"request left pending is a hang, not a closed decision" ) 695" PASS A04 (the escalation was decided 'unavailable' and the tool did not run)" ) 696finally : 697if agent : 698agent .close () 699worker .terminate () 700worker .wait (timeout = 20 ) 701 702 703def flow_a05 (dsh :Path ,tmp :Path ,profile :str ,base_port :int ,results :dict )-> None : 704"[A05] Stop settles the turn without the tool having run" ) 705ws = tmp / "ws-a05" 706ws .mkdir (parents = True ,exist_ok = True ) 707marker = ws / "cancelled.txt" 708# 0.05 s per token: the tool call alone is ~40 tokens, so the turn is live for seconds. 709worker = start_worker ([TOOL_CALL .format (marker = marker ),FINAL_ANSWER ], 710base_port ,tmp / "worker-a05.log" ,delay_s = 0.05 ) 711agent = None 712try : 713wait_for_worker (base_port ) 714agent = Agent (dsh ,base_port + 1 ,tmp / "home-a05" ,profile ,answerer = True ,tmp = tmp ,cwd = ws ,worker_port = base_port ) 715session = agent .session (ws ) 716agent .prompt (session ,"Write the marker file using bash." ,request_id = "a05" ) 717 718# Wait until the turn is demonstrably live before sending Stop. Without this the scripted turn 719# finishes in milliseconds, Stop arrives after `turn/end`, and the run passes while proving 720# nothing -- which is how this flow passed on its first attempt. 721live = False 722deadline = time .time ()+ 60 723while time .time ()< deadline : 724events = read_events (session ,agent .home ) 725if any (e .get ("type" )== "turn/start" for e in events ): 726live = True 727break 728time .sleep (0.2 ) 729if not live : 730raise FlowError ("the turn never started, so Stop could not be tested" ) 731 732acknowledgement = agent .cancel (session ) 733events = wait_for_turn (session ,agent .home ,timeout = 120 ) 734summary = summarise (events ) 735results ["A05" ]= {"turn_end" :summary ["end" ],"acknowledgement" :acknowledgement , 736"marker_created" :marker .exists (),"turn_was_live" :live } 737log (f"cancel acknowledged as { json . dumps ( acknowledgement )[: 120 ] } " ) 738log (f"turn ended as { summary [ 'end' ]!r } " ) 739if summary ["end" ]is None : 740raise FlowError ("the turn never reached a terminal state after Stop" ) 741# `aborted` is the Harness's terminal reason for a turn a peer stopped; `cancelled` is the 742# other spelling seen in the vocabulary. Anything else means Stop did not settle the turn. 743if summary ["end" ]not in ("aborted" ,"cancelled" ): 744raise FlowError (f"the turn ended as { summary [ 'end' ]!r } after Stop, which is not a " 745"cancellation" ) 746if marker .exists (): 747raise FlowError ("Stop was acknowledged but the tool ran anyway: the turn was not really " 748"cancelled" ) 749f" PASS A05 (a live turn was stopped and settled as { summary [ 'end' ]!r } )" ) 750finally : 751if agent : 752agent .close () 753worker .terminate () 754worker .wait (timeout = 20 ) 755 756 757def main ()-> int : 758parser = argparse .ArgumentParser (description = __doc__ , 759formatter_class = argparse .RawDescriptionHelpFormatter ) 760parser .add_argument ("--dsh" ,required = True ,help = "path to the dsh executable" ) 761parser .add_argument ("--profile" ,default = "web" , 762help = "the base bundle profile the Strata patch layers over" ) 763parser .add_argument ("--base-port" ,type = int ,default = 8300 ) 764parser .add_argument ("--only" ,default = None ,help = "run one flow: A03, A04 or A05" ) 765parser .add_argument ("--keep" ,action = "store_true" ,help = "keep the temporary directory" ) 766args = parser .parse_args () 767 768dsh = Path (args .dsh ) 769if not dsh .exists (): 770raise SystemExit (f"no dsh at { dsh } " ) 771if not SCRIPTED_OVERLAY .exists (): 772raise SystemExit (f"the test-only profile overlay is missing: { SCRIPTED_OVERLAY } " ) 773for tool in ("zstd" ,): 774if shutil .which (tool )is None : 775raise SystemExit (f" { tool } is required to read the durable session" ) 776 777tmp = Path (tempfile .mkdtemp (prefix = "strata-tool-flow-" )) 778f"working in { tmp } " ) 779results :dict = {} 780try : 781flows = {"A03" :flow_a03 ,"A04" :flow_a04 ,"A05" :flow_a05 } 782chosen = [args .only ]if args .only else list (flows ) 783for index ,name in enumerate (chosen ): 784flows [name ](dsh ,tmp ,args .profile ,args .base_port + index * 10 ,results ) 785"PASS" ) 787json .dumps (results ,indent = 2 ,sort_keys = True )) 788return 0 789except FlowError as e : 790f"\nFAIL { args . only or '' } : { e } " ) 791json .dumps (results ,indent = 2 ,sort_keys = True )) 792return 1 793finally : 794if args .keep : 795f"kept { tmp } " ) 796else : 797shutil .rmtree (tmp ,ignore_errors = True ) 798 799 800if __name__ == "__main__" : 801sys .exit (main ())