okami.mom/strata

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

Niko1221Merge f-clean-3 (321794636): docs and history (cleanup step 3, items 3.0-3.10); release manifest and capability table with checks, history/ with pointers, link check, tools/ split, bench index; owner OK'd the wording 11-082b36e8a02

main
12.5 KiB289 linesraw
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
7    default      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:
20    python 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
40    DEFAULT_DSH,
41    DEFAULT_PYTHON,
42    PROFILE_PATCH,
43    BridgeError,
44    gateway_call,
45    http_json,
46    log,
47    read_session_events,
48    start_agent,
49    start_worker,
50    wait_for_agent_url,
51    wait_for_worker,
52)
53
54
55class Fixture:
56    """A running worker + Harness pair with an authenticated owner session."""
57
58    def __init__(self, dsh: Path, python: Path, worker_port: int, keep: bool):
59        self.dsh, self.python, self.worker_port, self.keep = dsh, python, worker_port, keep
60        self.tmp = Path(tempfile.mkdtemp(prefix="strata-bridge-"))
61        (self.tmp / "ws").mkdir()
62        self.worker = self.agent = None
63        self.agent_port = 0
64        self.cookie = ""
65
66    def __enter__(self) -> "Fixture":
67        self.worker, self.worker_log = start_worker(self.python, self.worker_port, self.tmp)
68        wait_for_worker(self.worker_port)
69        self.agent, self.agent_log = start_agent(self.dsh, 0, self.tmp)
70        text = wait_for_agent_url(self.agent_log, self.agent)
71        import re
72
73        m = re.search(r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)", text)
74        if not m:
75            raise BridgeError("the Harness printed no usable URL")
76        self.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,
80                                     f"/?token={token}&interactions=answer")
81        self.cookie = set_cookie.split(";", 1)[0]
82        if not self.cookie.startswith("dsh-auth-"):
83            raise BridgeError(f"no operator cookie was issued ({set_cookie[:80]!r})")
84        return self
85
86    def __exit__(self, *exc) -> None:
87        if not self.keep:
88            for proc in (self.agent, self.worker):
89                if proc and proc.poll() is None:
90                    try:
91                        proc.send_signal(signal.SIGTERM)
92                        proc.wait(timeout=8)
93                    except Exception:
94                        try:
95                            proc.kill()
96                        except Exception:
97                            pass
98        else:
99            print(f"    (kept: {self.tmp})")
100        if not self.keep:
101            shutil.rmtree(self.tmp, ignore_errors=True)
102
103    # ---- operations -------------------------------------------------------
104
105    def new_session(self) -> str:
106        created = gateway_call("127.0.0.1", self.agent_port, self.cookie, "c", "session/create",
107                               {"request": {"cwd": str(self.tmp / "ws")}})
108        return created["sessionId"]
109
110    def prompt(self, session_id: str, text: str, rpc_id="p", request_id="req-1"):
111        return 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
116    def cancel(self, session_id: str, rpc_id="x"):
117        return gateway_call("127.0.0.1", self.agent_port, self.cookie, rpc_id, "session/cancel",
118                            {"request": {"sessionId": session_id}})
119
120    def wait_turn_end(self, session_id: str, timeout=120.0):
121        deadline = time.time() + timeout
122        events = []
123        while time.time() < deadline:
124            events = read_session_events(session_id)
125            end = next((e for e in events if e.get("type") == "turn/end"), None)
126            if end is not None:
127                return end, events
128            time.sleep(0.5)
129        return None, events
130
131    def worker_requests(self) -> int:
132        _, raw, _ = http_json("GET", "127.0.0.1", self.worker_port, "/v1/status")
133        return (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."""
140    sid = fx.new_session()
141    log(f"session {sid}")
142    fx.prompt(sid, "Say hello in exactly five words.")
143    log("prompt accepted")
144    end, events = fx.wait_turn_end(sid)
145    if end is None:
146        raise BridgeError("the turn never reached turn/end within 120s")
147    reason = (end.get("data") or {}).get("reason") or {}
148    if reason.get("kind") != "completed":
149        raise BridgeError(f"the turn ended as {json.dumps(reason)[:400]}")
150    assistant = next((e for e in events if e.get("type") == "assistant/message"), None)
151    if assistant is None:
152        raise BridgeError("the turn completed but committed no assistant message")
153    source = ((assistant.get("data") or {}).get("message") or {}).get("source") or {}
154    if source.get("provider") != "strata-local":
155        raise BridgeError(f"assistant source names {source.get('provider')!r}, not 'strata-local'")
156    n = fx.worker_requests()
157    if n < 1:
158        raise BridgeError("the session completed but the worker recorded no requests")
159    log(f"turn=completed provider={source.get('provider')} model={source.get('model')} "
160        f"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
166    Also 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    """
169    sid = fx.new_session()
170    log(f"session {sid}")
171    fx.prompt(sid, "Write a very long, detailed essay about the history of computing.")
172    log("prompt accepted")
173    # Cancel promptly: after acceptance, before the turn can finish.
174    time.sleep(0.3)
175    value = fx.cancel(sid)
176    log(f"cancel acknowledged: {json.dumps(value)}")
177    if value.get("accepted") is not True:
178        raise BridgeError(f"cancel was not accepted: {json.dumps(value)[:200]}")
179    end, events = fx.wait_turn_end(sid)
180    if end is None:
181        raise BridgeError("after cancel the turn never reached a terminal state")
182    kind = ((end.get("data") or {}).get("reason") or {}).get("kind")
183    log(f"terminal state: {kind}")
184    if 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.
187        raise 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")
190    if kind not in ("aborted", "interrupted", "failed", "error"):
191        raise BridgeError(f"unexpected terminal state after cancel: {json.dumps(kind)}")
192    log(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
198    The handoff records this as an unimplemented transport. It is implemented on the gateway
199    surface: `approval/request` is a forwarded waterfall and `POST /api/$events/result` settles it.
200    Assertions are written so an approved run proves the *outbound* seam (a request really was
201    raised and had to be decided); the tools the model is offered here may not need approval, in
202    which 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.
205    marker = fx.tmp / "ws" / "approval-probe.txt"
206    sid = fx.new_session()
207    log(f"session {sid}")
208    # Ask for an action that needs a tool rather than an answer from memory.
209    fx.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")
211    log("prompt accepted")
212    end, events = fx.wait_turn_end(sid)
213    if end is None:
214        raise BridgeError("the turn never reached a terminal state")
215    kind = ((end.get("data") or {}).get("reason") or {}).get("kind")
216    asked = [e for e in events if e.get("type") == "approval/asked"]
217    decided = [e for e in events if e.get("type") == "approval/decided"]
218    log(f"terminal={kind} approval/asked={len(asked)} approval/decided={len(decided)} "
219        f"probe_file={'present' if marker.exists() else 'absent'}")
220    if asked:
221        # The durable audit pair must be complete and every decision must be in the vocabulary.
222        outcomes = [(e.get("data") or {}).get("outcome") for e in decided]
223        allowed = {"allowed-once", "rejected", "cancelled", "unavailable"}
224        bad = [o for o in outcomes if o not in allowed]
225        if bad:
226            raise BridgeError(f"approval decided with a non-vocabulary outcome: {bad}")
227        log(f"approval decisions: {outcomes}")
228        return
229    log("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:
237    ap = argparse.ArgumentParser(description=__doc__,
238                                 formatter_class=argparse.RawDescriptionHelpFormatter)
239    ap.add_argument("--dsh", default=os.environ.get("DSH_CLI", DEFAULT_DSH))
240    ap.add_argument("--python", default=str(DEFAULT_PYTHON))
241    ap.add_argument("--worker-port", type=int, default=8095)
242    ap.add_argument("--keep", action="store_true")
243    ap.add_argument("--all", action="store_true")
244    ap.add_argument("--cancel", action="store_true")
245    ap.add_argument("--approval", action="store_true")
246    args = ap.parse_args()
247
248    selected = []
249    if args.all:
250        selected = ["completion", "cancel", "approval"]
251    else:
252        if args.cancel:
253            selected.append("cancel")
254        if args.approval:
255            selected.append("approval")
256        if not selected:
257            selected = ["completion"]
258
259    dsh, python = Path(args.dsh), Path(args.python)
260    for path, what in ((dsh, "dsh CLI"), (python, "python interpreter"), (PROFILE_PATCH, "profile")):
261        if not path.exists():
262            print(f"prerequisite missing: {what} not at {path}", file=sys.stderr)
263            return 2
264
265    print("strata <-> harness bridge tests")
266    print(f"  cases : {', '.join(selected)}")
267    print()
268    failures = []
269    for name in selected:
270        print(f"[{name}]")
271        try:
272            with Fixture(dsh, python, args.worker_port, args.keep) as fx:
273                CASES[name](fx)
274            print(f"  -> PASS\n")
275        except Exception as e:  # noqa: BLE001 - a test reports, it does not crash
276            print(f"  -> FAIL: {e}\n")
277            failures.append((name, str(e)))
278
279    if failures:
280        print("FAIL")
281        for name, err in failures:
282            print(f"  {name}: {err}")
283        return 1
284    print("PASS — all selected bridge cases passed")
285    return 0
286
287
288if __name__ == "__main__":
289    sys.exit(main())