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