okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
39.4 KiB801 linesraw
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.**
15    The scripted turn calls bash to append a line to a file. The assertions are that the file has
16    exactly one line (so the tool ran exactly once), that the durable session records a tool call and
17    a tool result, and that the Strata worker was given the transcript rather than executing anything
18    itself — the worker has no tool-execution path at all, and the call count is the evidence. The
19    call escalates the sandbox, so it cannot run until a peer *grants* it: the flow connects that peer
20    and 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.**
23    The same scripted call and the same peer connection; the only difference is the decision. The peer
24    delegates (`next`) instead of granting, so the composed answerer chain has no terminal answerer
25    and the request resolves the fail-closed `unavailable`. The assertions are that the escalation
26    reached the gate, that its recorded outcome is exactly `unavailable`, that the turn settled on
27    that denial, and that the file does not exist afterwards. Connecting the peer is what makes the
28    outcome observable — with no peer at all the gateway keeps a forwarded waterfall pending until a
29    client connects, so the request would be neither granted nor decided.
30
31**A05 — Stop settles the turn.**
32    A prompt is sent and cancelled while the turn is live. The assertions are that the turn reaches a
33    terminal state without the tool having run, and that cancellation is acknowledged only as
34    admission (`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):
111    pass
112
113
114def log(msg: str) -> None:
115    print(f"  {msg}", flush=True)
116
117
118def http_json(method: str, host: str, port: int, path: str, body=None, cookie: str | None = None,
119              timeout: 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
123    the next request and looks like an authentication bug rather than a client one. `http.client`
124    returns the response as sent, which is what this needs.
125    """
126    connection = http.client.HTTPConnection(host, port, timeout=timeout)
127    headers = {}
128    data = None
129    if body is not None:
130        data = json.dumps(body).encode()
131        headers["content-type"] = "application/json"
132    if cookie:
133        headers["cookie"] = cookie
134    try:
135        connection.request(method, path, body=data, headers=headers)
136        response = connection.getresponse()
137        raw = response.read().decode("utf-8", "replace")
138        return response.status, raw, response.getheader("set-cookie") or ""
139    finally:
140        connection.close()
141
142
143def rpc(host: str, port: int, cookie: str, rpc_id: str, method: str, args: dict):
144    """One gateway call.
145
146    The 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
148    of schema issues, which reads like a malformed session rather than a malformed envelope.
149    """
150    body = {"type": "client-request", "rpcId": rpc_id, "method": method, "payload": {"args": args}}
151    status, raw, _ = http_json("POST", host, port, f"/api/{method}", body, cookie=cookie)
152    if status != 200:
153        raise FlowError(f"{method} returned HTTP {status}: {raw[:300]}")
154    payload = json.loads(raw)
155    result = payload.get("result") or {}
156    if not result.get("ok"):
157        raise FlowError(f"{method} was refused: {json.dumps(result.get('error'))[:400]}")
158    return 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
173    gateway forwards to connected peers, and it is delivered over the gateway's event stream. A peer
174    that 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
180        answerer that is *present but not available* does, so the request resolves `unavailable` and
181        the action fails closed, which is the outcome A04 asserts.
182
183    A peer is also the only thing that can make an approval observable at all: with no client holding
184    the stream open the gateway keeps the forwarded waterfall pending until one connects (it has a
185    test named "delivers a pending waterfall to the first Client that connects"), so the request is
186    never decided and nothing is `unavailable` -- the turn simply waits. That is why A04 connects a
187    peer and delegates instead of asserting on an answerer that does not exist.
188
189    No WebSocket client is available in the standard library, so the handshake and the four frame
190    types this needs (text, ping, pong, close) are implemented here. Only frames the Host sends are
191    parsed; the one frame this peer sends is the stream `open`.
192    """
193
194    def __init__(self, host: str, port: int, cookie: str, decision: str = "allowed-once"):
195        self.host, self.port, self.cookie, self.decision = host, port, cookie, decision
196        self.requests: list[dict] = []      # every approval request this peer was asked to decide
197        self.outcomes: list[str] = []       # the decision actually sent for each of them
198        self.error: str | None = None
199        self.ready = threading.Event()      # set once the Host proved the event stream is live
200        self.client_id: str | None = None
201        self._sock: socket.socket | None = None
202        self._buffer = b""
203        self._thread: threading.Thread | None = None
204
205    # -- lifecycle ---------------------------------------------------------------------------------
206
207    def start(self, timeout: float = 30.0) -> "ApprovalAnswerer":
208        """Connect and wait until the event stream is live.
209
210        The wait is the point: an approval raised before the stream exists is delivered to nobody and
211        fails closed, so a peer that connects late turns "no answerer" into a tool that never ran.
212        """
213        self._thread = threading.Thread(target=self._run, name="approval-answerer", daemon=True)
214        self._thread.start()
215        if not self.ready.wait(timeout):
216            self.close()
217            raise FlowError(f"the approval answerer never opened the event stream: {self.error or 'no reply'}")
218        return self
219
220    def close(self) -> None:
221        sock = self._sock
222        if sock is None:
223            return
224        try:
225            self._send_frame(0x8, b"")       # close
226        except Exception:                    # noqa: BLE001 - the peer is going away either way
227            pass
228        self._sock = None
229        try:
230            sock.shutdown(socket.SHUT_RDWR)
231        except OSError:
232            pass
233        sock.close()
234
235    # -- WebSocket carrier -------------------------------------------------------------------------
236
237    def _connect(self) -> None:
238        sock = socket.create_connection((self.host, self.port), timeout=15)
239        sock.settimeout(30)
240        key = base64.b64encode(os.urandom(16)).decode()
241        handshake = (
242            f"GET {REMOTE_STREAM_MUX_PATH} HTTP/1.1\r\n"
243            f"Host: {self.host}:{self.port}\r\n"
244            "Upgrade: websocket\r\n"
245            "Connection: Upgrade\r\n"
246            f"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.
250            f"Cookie: {self.cookie}\r\n\r\n"
251        )
252        sock.sendall(handshake.encode())
253        head = b""
254        while b"\r\n\r\n" not in head:
255            chunk = sock.recv(4096)
256            if not chunk:
257                raise FlowError("the event stream socket closed during the WebSocket handshake")
258            head += chunk
259        header, self._buffer = head.split(b"\r\n\r\n", 1)
260        status = header.split(b"\r\n", 1)[0].decode("latin-1")
261        if " 101 " not in status:
262            raise 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().
265        sock.settimeout(None)
266        self._sock = sock
267
268    def _read_exactly(self, count: int) -> bytes:
269        while len(self._buffer) < count:
270            chunk = self._sock.recv(65536)
271            if not chunk:
272                raise FlowError("the event stream closed")
273            self._buffer += chunk
274        taken, self._buffer = self._buffer[:count], self._buffer[count:]
275        return taken
276
277    def _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."""
279        mask = os.urandom(4)
280        length = len(payload)
281        if length < 126:
282            header = bytes([0x80 | opcode, 0x80 | length])
283        elif length < (1 << 16):
284            header = bytes([0x80 | opcode, 0x80 | 126]) + struct.pack("!H", length)
285        else:
286            header = bytes([0x80 | opcode, 0x80 | 127]) + struct.pack("!Q", length)
287        masked = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
288        self._sock.sendall(header + mask + masked)
289
290    def _send_text(self, text: str) -> None:
291        self._send_frame(0x1, text.encode())
292
293    def _read_frame(self) -> tuple[int, bytes]:
294        first, second = self._read_exactly(2)
295        opcode, length = first & 0x0F, second & 0x7F
296        if length == 126:
297            length = struct.unpack("!H", self._read_exactly(2))[0]
298        elif length == 127:
299            length = struct.unpack("!Q", self._read_exactly(8))[0]
300        masked = bool(second & 0x80)
301        mask = self._read_exactly(4) if masked else b""
302        payload = self._read_exactly(length)
303        if masked:
304            payload = bytes(byte ^ mask[index % 4] for index, byte in enumerate(payload))
305        return opcode, payload
306
307    # -- protocol ----------------------------------------------------------------------------------
308
309    def _run(self) -> None:
310        try:
311            self._connect()
312            stream_id = "approvals"
313            self._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            }))
319            while True:
320                opcode, payload = self._read_frame()
321                if opcode == 0x8:                                  # close
322                    return
323                if opcode == 0x9:                                  # ping: the Host's liveness probe
324                    self._send_frame(0xA, payload)
325                    continue
326                if opcode != 0x1:                                  # pong and anything else: ignore
327                    continue
328                self._handle(json.loads(payload.decode("utf-8", "replace")))
329        except Exception as error:                                 # noqa: BLE001 - reported, never raised here
330            self.error = f"{type(error).__name__}: {error}"
331        finally:
332            self.ready.set()                                       # a failed start must not hang start()
333
334    def _handle(self, message: dict) -> None:
335        if message.get("type") != "item":
336            return
337        value = message.get("value")
338        if not isinstance(value, dict):
339            return
340        if value.get("type") == "ready":
341            self.client_id = value.get("clientId")
342            self.ready.set()
343            return
344        if value.get("type") != "waterfall" or value.get("event") != "approval/request":
345            return                                          # emitted notifications are not questions
346        self._answer(value)
347
348    def _answer(self, frame: dict) -> None:
349        self.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.
354        outcome = ({"kind": "next"} if self.decision == "next"
355                   else {"kind": "result", "value": self.decision})
356        body = {
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        }
364        status, raw, _ = http_json("POST", self.host, self.port, f"/api/{EVENT_RESULT_ENDPOINT}",
365                                   body, cookie=self.cookie)
366        if status != 200:
367            raise FlowError(f"answering the approval returned HTTP {status}: {raw[:200]}")
368        answer = (json.loads(raw).get("result") or {})
369        if not answer.get("ok"):
370            raise FlowError(f"the approval answer was refused: {json.dumps(answer.get('error'))[:300]}")
371        self.outcomes.append(self.decision)
372
373
374def wait_for_worker(port: int, timeout: float = 60.0) -> None:
375    deadline = time.time() + timeout
376    while time.time() < deadline:
377        try:
378            status, _, _ = http_json("GET", "127.0.0.1", port, "/health", timeout=2)
379            if status == 200:
380                return
381        except (OSError, http.client.HTTPException):
382            pass
383        time.sleep(0.3)
384    raise 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
390    The shipped patch names 8095, and a worker left over from an earlier session on that port will
391    happily answer every request -- producing a green run against the *wrong* worker, which is
392    exactly how a stale process hid a failure here once already. Substituting the port makes the
393    agent and the worker this test started the only pair that can talk.
394    """
395    text = PROFILE_PATCH.read_text(encoding="utf-8")
396    if "http://127.0.0.1:8095/v1" not in text:
397        raise FlowError(f"{PROFILE_PATCH} no longer names http://127.0.0.1:8095/v1; the substitution "
398                        "below would silently do nothing")
399    patched = tmp / "cordis.patch.yml"
400    patched.write_text(text.replace("http://127.0.0.1:8095/v1", f"http://127.0.0.1:{port}/v1"),
401                       encoding="utf-8")
402    return patched
403
404
405def start_worker(scripts: list[str], port: int, log_path: Path,
406                 delay_s: float = 0.0) -> subprocess.Popen:
407    if worker_port_in_use(port):
408        raise FlowError(
409            f"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")
411    argv = [PYTHON, "-m", "serve.server", "--engine", "mock", "--port", str(port), "--script-cycle"]
412    if 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.
415        argv += ["--script-delay", str(delay_s)]
416    for script in scripts:
417        argv += ["--script", script]
418    handle = log_path.open("wb")
419    return subprocess.Popen(argv, cwd=str(STRATA), stdout=handle, stderr=subprocess.STDOUT)
420
421
422def worker_port_in_use(port: int) -> bool:
423    import socket
424    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
425        probe.settimeout(0.5)
426        return 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,
430                cwd: Path, patch: Path) -> subprocess.Popen:
431    """Boot the agent with the Strata profile.
432
433    The profile is selected the way the working bridge does it: `--profile <base> --patch <file>`, a
434    patch layer over a shipped bundle. `dsh web --profile` does not exist, and passing it produces
435    `unknown option '--profile'` before anything starts.
436    """
437    env = dict(os.environ)
438    env["DSH_HOME"] = str(home)
439    env.pop("ELECTRON_RUN_AS_NODE", None)
440    argv = [str(dsh), "--profile", profile, "--patch", str(patch),
441            "--patch", str(SCRIPTED_OVERLAY),
442            "--port", str(port), "--no-open"]
443    handle = log_path.open("wb")
444    return 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]:
448    deadline = time.time() + timeout
449    while time.time() < deadline:
450        if proc.poll() is not None:
451            raise FlowError(f"the agent exited with code {proc.returncode}:\n"
452                            f"{log_path.read_text(errors='replace')[-800:]}")
453        text = log_path.read_text(errors="replace") if log_path.exists() else ""
454        match = re.search(r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)", text)
455        if match:
456            return int(match.group(1)), match.group(2)
457        time.sleep(0.5)
458    raise 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]:
462    root = home / "sessions"
463    matches = list(root.glob(f"*/{session_id}/session.v*.jsonl*"))
464    if not matches:
465        return []
466    newest = max(matches, key=lambda p: p.stat().st_mtime)
467    try:
468        out = subprocess.run(["zstd", "-d", "-c", "--long=27", str(newest)],
469                             capture_output=True, timeout=30)
470        text = out.stdout.decode("utf-8", "replace")
471    except (OSError, subprocess.SubprocessError):
472        return []
473    events = []
474    for line in text.splitlines():
475        line = line.strip()
476        if not line:
477            continue
478        try:
479            events.append(json.loads(line))
480        except json.JSONDecodeError:
481            continue
482    return events
483
484
485def wait_for_turn(session_id: str, home: Path, timeout: float = 180.0) -> list[dict]:
486    deadline = time.time() + timeout
487    while time.time() < deadline:
488        events = read_events(session_id, home)
489        if any(e.get("type") == "turn/end" for e in events):
490            return events
491        time.sleep(1.0)
492    return read_events(session_id, home)
493
494
495def summarise(events: list[dict]) -> dict:
496    kinds: dict[str, int] = {}
497    for event in events:
498        kinds[event.get("type", "?")] = kinds.get(event.get("type", "?"), 0) + 1
499    turn_end = next((e for e in events if e.get("type") == "turn/end"), None)
500    reason = ((turn_end or {}).get("data") or {}).get("reason") or {}
501    return {"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
507    def __init__(self, dsh: Path, port: int, home: Path, profile: str, answerer: bool, tmp: Path,
508                 cwd: Path, worker_port: int):
509        self.home, self.port, self.tmp, self.cwd = home, port, tmp, cwd
510        cwd.mkdir(parents=True, exist_ok=True)
511        # A profile naming this run's worker port, so no other process can answer for it.
512        self.patch = write_profile(worker_port, tmp)
513        self.log_path = tmp / f"agent-{port}.log"
514        self.proc = start_agent(dsh, port, home, profile, self.log_path, self.cwd, self.patch)
515        self.agent_port, token = wait_for_agent(self.log_path, self.proc)
516        query = f"/?token={token}" + ("&interactions=answer" if answerer else "")
517        _, _, cookie = http_json("GET", "127.0.0.1", self.agent_port, query)
518        self.cookie = cookie.split(";", 1)[0]
519        if not self.cookie.startswith("dsh-auth-"):
520            raise FlowError(f"no operator cookie (got {cookie[:80]!r})")
521        self.answerer = answerer
522        self.peer: ApprovalAnswerer | None = None
523
524    def answer_approvals(self, decision: str = "allowed-once") -> ApprovalAnswerer:
525        """Connect the peer that decides approvals, and return it once its stream is live.
526
527        This is what makes an approval answerable, and `interactions=answer` on the launch URL is
528        not: that parameter is read only on `/connect`
529        (`packages/client/connection/src/browser-auth.ts`), while `GET /?token=...` issues the
530        browser 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
533        difference between A03 and A04.
534        """
535        peer = ApprovalAnswerer("127.0.0.1", self.agent_port, self.cookie, decision).start()
536        self.peer = peer
537        return peer
538
539    def session(self, cwd: Path) -> str:
540        result = rpc("127.0.0.1", self.agent_port, self.cookie, "c1", "session/create",
541                     {"request": {"cwd": str(cwd)}})
542        return result["sessionId"]
543
544    def prompt(self, session_id: str, text: str, request_id: str = "req-1") -> None:
545        rpc("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
549    def cancel(self, session_id: str) -> dict:
550        return rpc("127.0.0.1", self.agent_port, self.cookie, "x1", "session/cancel",
551                   {"request": {"sessionId": session_id}})
552
553    def 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.
557        if self.peer is not None:
558            try:
559                self.peer.close()
560            except Exception as error:                     # noqa: BLE001 - cleanup must not mask the run
561                log(f"closing the approval peer failed: {type(error).__name__}: {error}")
562        if self.proc.poll() is None:
563            self.proc.terminate()
564            try:
565                self.proc.wait(timeout=20)
566            except subprocess.TimeoutExpired:
567                self.proc.kill()
568
569
570def flow_a03(dsh: Path, tmp: Path, profile: str, base_port: int, results: dict) -> None:
571    print("[A03] a read/edit/test workflow: the tool runs once, in the Harness")
572    ws = tmp / "ws-a03"
573    ws.mkdir(parents=True, exist_ok=True)
574    marker = ws / "marker.txt"
575    worker = start_worker([TOOL_CALL.format(marker=marker), FINAL_ANSWER],
576                          base_port, tmp / "worker-a03.log")
577    agent = None
578    try:
579        wait_for_worker(base_port)
580        agent = 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.
584        peer = agent.answer_approvals("allowed-once")
585        session = agent.session(ws)
586        agent.prompt(session, "Write the marker file using bash, then report that you did.")
587        events = wait_for_turn(session, agent.home)
588        summary = summarise(events)
589
590        calls = [e for e in events if "tool" in str(e.get("type", ""))]
591        asked = [e for e in events if e.get("type") == "approval/asked"]
592        decided = [e for e in events if e.get("type") == "approval/decided"]
593        executed = marker.exists()
594        lines = marker.read_text().splitlines() if executed else []
595
596        results["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        }
605        log(f"turn ended as {summary['end']!r}; {len(calls)} tool-related event(s)")
606        log(f"the workspace marker has {len(lines)} line(s)")
607        log(f"the peer answered {len(peer.outcomes)} of {len(asked)} approval(s): "
608            f"{[((e.get('data') or {}).get('outcome')) for e in decided]}")
609
610        if summary["end"] != "completed":
611            raise FlowError(f"the turn did not complete: {json.dumps(summary)[:300]}")
612        if not executed:
613            raise FlowError("the bash tool did not run: no marker file was written")
614        if len(lines) != 1:
615            raise 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.
620        if len(peer.outcomes) < 1 or not asked:
621            raise FlowError("the tool ran without an answered approval: the call did not reach the "
622                            f"approval gate (asked={len(asked)}, answered={len(peer.outcomes)}, "
623                            f"peer_error={peer.error!r})")
624        if [e for e in decided if (e.get("data") or {}).get("outcome") != "allowed-once"]:
625            raise FlowError(f"the session recorded an approval outcome other than the granted one: "
626                            f"{[((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.
629        status, raw, _ = http_json("GET", "127.0.0.1", base_port, "/v1/status")
630        activity = json.loads(raw).get("activity") or {}
631        results["A03"]["worker_requests"] = activity.get("requests")
632        log(f"the worker recorded {activity.get('requests')} request(s) and executed nothing itself")
633        print("  PASS A03")
634    finally:
635        if agent:
636            agent.close()
637        worker.terminate()
638        worker.wait(timeout=20)
639
640
641def flow_a04(dsh: Path, tmp: Path, profile: str, base_port: int, results: dict) -> None:
642    print("[A04] with no answerer that decides, the approval fails closed and the tool does not run")
643    ws = tmp / "ws-a04"
644    ws.mkdir(parents=True, exist_ok=True)
645    marker = ws / "must-not-exist.txt"
646    worker = start_worker([TOOL_CALL.format(marker=marker), FINAL_ANSWER],
647                          base_port, tmp / "worker-a04.log")
648    agent = None
649    try:
650        wait_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`.
657        agent = 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.
662        peer = agent.answer_approvals("next")
663        session = agent.session(ws)
664        agent.prompt(session, "Write the marker file using bash.", request_id="a04")
665        events = wait_for_turn(session, agent.home)
666        summary = summarise(events)
667
668        created = marker.exists()
669        asked = [e for e in events if e.get("type") == "approval/asked"]
670        outcomes = [((e.get("data") or {}).get("outcome")) for e in events
671                    if e.get("type") == "approval/decided"]
672        results["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")}
676        log(f"turn ended as {summary['end']!r}")
677        log(f"the marker file exists: {created}")
678        log(f"the escalation was asked {len(asked)} time(s) and decided {outcomes}")
679
680        if created:
681            raise 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.
686        if not asked:
687            raise FlowError("the bash call never reached the approval gate, so this run proves nothing "
688                            "about an unanswerable approval: no approval/asked was recorded")
689        if not outcomes or any(outcome != "unavailable" for outcome in outcomes):
690            raise FlowError(f"the unanswerable escalation did not fail closed as 'unavailable': "
691                            f"{outcomes}")
692        if summary["end"] != "completed":
693            raise 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        print("  PASS A04 (the escalation was decided 'unavailable' and the tool did not run)")
696    finally:
697        if agent:
698            agent.close()
699        worker.terminate()
700        worker.wait(timeout=20)
701
702
703def flow_a05(dsh: Path, tmp: Path, profile: str, base_port: int, results: dict) -> None:
704    print("[A05] Stop settles the turn without the tool having run")
705    ws = tmp / "ws-a05"
706    ws.mkdir(parents=True, exist_ok=True)
707    marker = ws / "cancelled.txt"
708    # 0.05 s per token: the tool call alone is ~40 tokens, so the turn is live for seconds.
709    worker = start_worker([TOOL_CALL.format(marker=marker), FINAL_ANSWER],
710                          base_port, tmp / "worker-a05.log", delay_s=0.05)
711    agent = None
712    try:
713        wait_for_worker(base_port)
714        agent = Agent(dsh, base_port + 1, tmp / "home-a05", profile, answerer=True, tmp=tmp, cwd=ws, worker_port=base_port)
715        session = agent.session(ws)
716        agent.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.
721        live = False
722        deadline = time.time() + 60
723        while time.time() < deadline:
724            events = read_events(session, agent.home)
725            if any(e.get("type") == "turn/start" for e in events):
726                live = True
727                break
728            time.sleep(0.2)
729        if not live:
730            raise FlowError("the turn never started, so Stop could not be tested")
731
732        acknowledgement = agent.cancel(session)
733        events = wait_for_turn(session, agent.home, timeout=120)
734        summary = summarise(events)
735        results["A05"] = {"turn_end": summary["end"], "acknowledgement": acknowledgement,
736                          "marker_created": marker.exists(), "turn_was_live": live}
737        log(f"cancel acknowledged as {json.dumps(acknowledgement)[:120]}")
738        log(f"turn ended as {summary['end']!r}")
739        if summary["end"] is None:
740            raise 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.
743        if summary["end"] not in ("aborted", "cancelled"):
744            raise FlowError(f"the turn ended as {summary['end']!r} after Stop, which is not a "
745                            "cancellation")
746        if marker.exists():
747            raise FlowError("Stop was acknowledged but the tool ran anyway: the turn was not really "
748                            "cancelled")
749        print(f"  PASS A05 (a live turn was stopped and settled as {summary['end']!r})")
750    finally:
751        if agent:
752            agent.close()
753        worker.terminate()
754        worker.wait(timeout=20)
755
756
757def main() -> int:
758    parser = argparse.ArgumentParser(description=__doc__,
759                                     formatter_class=argparse.RawDescriptionHelpFormatter)
760    parser.add_argument("--dsh", required=True, help="path to the dsh executable")
761    parser.add_argument("--profile", default="web",
762                        help="the base bundle profile the Strata patch layers over")
763    parser.add_argument("--base-port", type=int, default=8300)
764    parser.add_argument("--only", default=None, help="run one flow: A03, A04 or A05")
765    parser.add_argument("--keep", action="store_true", help="keep the temporary directory")
766    args = parser.parse_args()
767
768    dsh = Path(args.dsh)
769    if not dsh.exists():
770        raise SystemExit(f"no dsh at {dsh}")
771    if not SCRIPTED_OVERLAY.exists():
772        raise SystemExit(f"the test-only profile overlay is missing: {SCRIPTED_OVERLAY}")
773    for tool in ("zstd",):
774        if shutil.which(tool) is None:
775            raise SystemExit(f"{tool} is required to read the durable session")
776
777    tmp = Path(tempfile.mkdtemp(prefix="strata-tool-flow-"))
778    print(f"working in {tmp}")
779    results: dict = {}
780    try:
781        flows = {"A03": flow_a03, "A04": flow_a04, "A05": flow_a05}
782        chosen = [args.only] if args.only else list(flows)
783        for index, name in enumerate(chosen):
784            flows[name](dsh, tmp, args.profile, args.base_port + index * 10, results)
785            print()
786        print("PASS")
787        print(json.dumps(results, indent=2, sort_keys=True))
788        return 0
789    except FlowError as e:
790        print(f"\nFAIL {args.only or ''}: {e}")
791        print(json.dumps(results, indent=2, sort_keys=True))
792        return 1
793    finally:
794        if args.keep:
795            print(f"kept {tmp}")
796        else:
797            shutil.rmtree(tmp, ignore_errors=True)
798
799
800if __name__ == "__main__":
801    sys.exit(main())