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
6.3 KiB162 linesraw
1#!/usr/bin/env python3
2"""Agent bridge tests: 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 http.client
26import json
27import os
28import re
29import subprocess
30import time
31from pathlib import Path
32
33HERE = Path(__file__).resolve().parent
34REPO = HERE.parent.parent
35PROFILE_PATCH = HERE / "profile" / "cordis.patch.yml"
36
37DEFAULT_DSH = "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/cli/bin/dsh"
38DEFAULT_PYTHON = REPO.parent / "python311" / "bin" / "python"
39
40WORKSPACE_MARKER = "strata-bridge-e2e"
41PROMPT = "Say hello in exactly five words."
42
43
44class BridgeError(RuntimeError):
45    pass
46
47
48def log(msg: str) -> None:
49    print(f"  {msg}", flush=True)
50
51
52def http_json(method: str, host: str, port: int, path: str, body=None, cookie: str | None = None):
53    conn = http.client.HTTPConnection(host, port, timeout=30)
54    headers = {}
55    data = None
56    if body is not None:
57        data = json.dumps(body).encode()
58        headers["content-type"] = "application/json"
59    if cookie:
60        headers["cookie"] = cookie
61    conn.request(method, path, body=data, headers=headers)
62    resp = conn.getresponse()
63    raw = resp.read().decode("utf-8", "replace")
64    set_cookie = resp.getheader("set-cookie") or ""
65    conn.close()
66    return resp.status, raw, set_cookie
67
68
69def wait_for_worker(port: int, timeout=60.0) -> dict:
70    deadline = time.time() + timeout
71    while time.time() < deadline:
72        try:
73            status, raw, _ = http_json("GET", "127.0.0.1", port, "/health")
74            if status == 200:
75                return json.loads(raw)
76        except OSError:
77            pass
78        time.sleep(0.4)
79    raise BridgeError(f"the Strata worker did not answer /health on 127.0.0.1:{port} within {timeout}s")
80
81
82def start_worker(python: Path, port: int, tmp: Path) -> tuple[subprocess.Popen, Path]:
83    logfile = tmp / "worker.log"
84    handle = logfile.open("w")
85    proc = subprocess.Popen(
86        [str(python), "-m", "serve.server", "--engine", "mock", "--port", str(port),
87         "--script", "I am a local Strata model."],
88        cwd=str(REPO), stdout=handle, stderr=subprocess.STDOUT,
89    )
90    return proc, logfile
91
92
93def start_agent(dsh: Path, port: int, tmp: Path) -> tuple[subprocess.Popen, Path]:
94    logfile = tmp / "dsh.log"
95    handle = logfile.open("w")
96    proc = subprocess.Popen(
97        [str(dsh), "--profile", "web", "--patch", str(PROFILE_PATCH),
98         "--port", str(port), "--no-open"],
99        cwd=str(tmp / "ws"), stdout=handle, stderr=subprocess.STDOUT,
100    )
101    return proc, logfile
102
103
104def wait_for_agent_url(logfile: Path, proc: subprocess.Popen, timeout=120.0) -> str:
105    deadline = time.time() + timeout
106    pattern = re.compile(r"http://127\.0\.0\.1:(\d+)/\?token=([A-Za-z0-9_-]+)")
107    while time.time() < deadline:
108        if proc.poll() is not None:
109            raise BridgeError(f"the Harness exited early (code {proc.returncode}); log:\n"
110                              + logfile.read_text(errors="replace")[-2000:])
111        text = logfile.read_text(errors="replace") if logfile.exists() else ""
112        m = pattern.search(text)
113        if m:
114            return text
115        time.sleep(0.5)
116    raise BridgeError(f"the Harness did not print its URL within {timeout}s; log:\n"
117                      + (logfile.read_text(errors="replace")[-2000:] if logfile.exists() else "(none)"))
118
119
120def gateway_call(host: str, port: int, cookie: str, rpc_id: str, method: str, args: dict):
121    body = {"type": "client-request", "rpcId": rpc_id, "method": method, "payload": {"args": args}}
122    status, raw, _ = http_json("POST", host, port, f"/api/{method}", body, cookie=cookie)
123    try:
124        parsed = json.loads(raw)
125    except json.JSONDecodeError as e:
126        raise BridgeError(f"{method}: the gateway returned non-JSON ({status}): {raw[:300]}") from e
127    result = parsed.get("result") or {}
128    if not result.get("ok"):
129        raise BridgeError(f"{method} was refused: {json.dumps(result.get('error'))[:400]}")
130    return result.get("value")
131
132
133def read_session_events(session_id: str, home: Path | None = None) -> list[dict]:
134    """Read the durable session file, across every concatenated zstd frame.
135
136    `home` names the Harness home explicitly. A per-attempt revision runs with its own DSH_HOME, so
137    relying on this process's environment would read the wrong sessions directory.
138    """
139    base = Path(home) if home is not None else Path(os.environ.get("DSH_HOME", Path.home() / ".dsh"))
140    root = base / "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