"""API smoke tests against a tiny fixture built with the real build scripts.""" import gzip, json, os, subprocess, sys from pathlib import Path import pytest from fastapi.testclient import TestClient ROOT = Path(__file__).resolve().parents[1] sys.path[:0] = [str(ROOT), str(ROOT / "build")] def jsonl(path, rows): path.write_text("".join(json.dumps(r) + "\n" for r in rows)) @pytest.fixture(scope="module") def client(tmp_path_factory): tmp = tmp_path_factory.mktemp("fx") # git history with one commit repo = tmp / "work" repo.mkdir() git = lambda *a: subprocess.run(["git", "-C", str(repo), *a], check=True, capture_output=True, text=True).stdout git("init", "-q"); (repo / "bot.py").write_text("print('hi')\n") git("add", "."); git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "first (#7)") sha = git("rev-parse", "HEAD").strip() subprocess.run(["git", "clone", "-q", "--bare", str(repo), str(tmp / "h.git")], check=True) # tables t = tmp / "tables"; t.mkdir() jsonl(t / "commits.jsonl", [{"sha": sha, "parent_shas": [], "ts": "2026-11-01T10:00:00Z", "author": "git-server", "title": "first (#7)", "pr": 7, "approvers": ["bob"], "score": {"lp_win_rate": 12.5, "standard_error": 1.0, "revision": "r"}}]) jsonl(t / "prs.jsonl", [{"pr": 7, "author": "ann", "title": "first", "description": "adds `bot.py`", "branch": "b", "base_sha": "0", "opened_ts": "2026-11-01T09:00:00.000Z", "state_at_cutoff": "merged", "merged_ts": "2026-11-01T10:00:01.000Z", "merged_sha": sha, "head_sha_final": sha, "close_reason": None, "n_updates": 0, "approvers": ["bob"], "first_event_ts": "2026-11-01T09:00:00.000Z", "last_event_ts": "2026-11-01T10:00:01.000Z"}]) jsonl(t / "reviews.jsonl", [{"pr": 7, "reviewer": "bob", "ts": "2026-11-01T09:30:00.000Z", "head_sha": sha, "verdict": "approve", "comment": "looks good"}]) # board export b = tmp / "board" / "data"; (b / "messages").mkdir(parents=True) (b / "manifest.json").write_text(json.dumps({ "last_at": 1e10, "revisions": {}, "channels": [{"id": 1, "name": "general", "description": ""}], "people": [{"id": 1, "external_id": "ann", "experiment_agent": True}, {"id": 2, "external_id": "bob", "experiment_agent": True}]})) t0 = 1793523600.0 # 2026-11-01T09:00:00Z with gzip.open(b / "messages" / "1-0.json.gz", "wt") as f: json.dump([[1, 1, 2, t0 + 60, "please review PR #7", 0, 0, 0, []], [2, 2, 1, t0 + 120, "on it", 1, 1, 0, []], [3, 3, 2, t0 - 86400, "unrelated #99", 0, 0, 0, []], [4, 4, 2, t0 - 3600, "#7 in a list, before PR 7 existed", 0, 0, 0, []]], f) # traces tr = tmp / "traces" / "lane1"; tr.mkdir(parents=True) jsonl(tr / "ann.jsonl", [{"type": "session", "timestamp": "2026-11-01T08:00:00.000Z"}] + [ {"type": "message", "timestamp": f"2026-11-01T09:{m:02d}:00.000Z", "message": {"role": "assistant", "content": [{"type": "text", "text": f"step {m}"}, {"type": "toolCall", "name": "bash"}], "usage": {"input": 100, "output": 10, "reasoning": 4}}} for m in range(0, 60, 5)]) (tmp / "traces" / "lane2").mkdir() # bob's trace was rebuilt from the controller log; the manifest has no lane for him jsonl(tmp / "traces" / "lane2" / "bob.jsonl", [{"type": "session", "timestamp": "2026-11-01T08:00:00.000Z", "reconstructed_from": "controller event log (may have gaps)"}]) jsonl(tmp / "manifest.jsonl", [{"lane": "lane1", "agent": "ann", "kept": 13, "bytes_out": 1, "last_record": "x"}]) data = tmp / "data"; data.mkdir() import build_db, index_traces build_db.main(str(t), str(tmp / "board"), str(tmp / "manifest.jsonl"), str(data / "explorer.sqlite")) index_traces.main(str(tmp / "traces"), str(data / "traces.sqlite")) os.environ.update(EXPLORER_DATA=str(data), GIT_DIR_PATH=str(tmp / "h.git")) import app app.read_range = lambda lane, agent, s, e: (tmp / "traces" / lane / f"{agent}.jsonl").read_bytes()[s:e] return TestClient(app.app), sha def test_commits_and_pr(client): c, sha = client item = c.get("/api/commits?author=ann").json()["items"][0] # the PR author, not the git author assert item["lp_win_rate"] == 12.5 and item["git_author"] == "git-server" d = c.get(f"/api/commits/{sha[:7]}").json() assert d["pr_info"]["pr"] == 7 and d["approvers"] == ["bob"] and d["author"] == "ann" assert c.get(f"/api/commits/{sha}/diff").json()["files"][0]["path"] == "bot.py" assert "patch" not in c.get(f"/api/commits/{sha}/diff?patch=false").json() assert c.get(f"/api/commits/{sha}/file?path=bot.py").text == "print('hi')\n" assert c.get("/api/prs/7/reviews").json()["items"][0]["verdict"] == "approve" assert d["source"].endswith(f"/commit/{sha}") and c.get("/api/prs/7").json()["source"] == d["source"] assert c.get(f"/api/commits/{sha}/diff").json()["files"][0]["source"].endswith(f"/blob/{sha}/bot.py") assert c.get("/api/scores").json()["rows"][0][1:5:3] == [sha, "ann"] assert c.get("/api/commits/zz").status_code == 400 and c.get("/api/prs/8").status_code == 404 def test_links_and_messages(client): c, _ = client msgs = {m["id"]: m["reason"] for m in c.get("/api/prs/7/messages").json()["items"]} assert msgs == {1: "mention", 2: "author_window"} # #99 is not a PR; message 4 predates PR 7 assert c.get("/api/prs/7").json()["message_count"] == 2 assert c.get("/api/prs/7/messages?newest_first=true&limit=1").json()["items"][0]["id"] == 2 assert [m["id"] for m in c.get("/api/messages/2").json()["thread"]] == [1, 2] assert c.get("/api/messages/2").json()["message"]["source"].endswith("/#msg/2") assert c.get("/api/messages/search?q=review").json()["items"][0]["id"] == 1 assert c.get("/api/agents/ann").json()["lane"] == "lane1" def test_traces_window_and_cursor(client): c, _ = client w = {x["role"]: x for x in c.get("/api/prs/7/traces").json()["items"]} assert w["author"]["from_ts"] == "2026-11-01T08:50:00.000Z" and w["reviewer"]["agent"] == "bob" p1 = c.get("/api/traces/ann?from=2026-11-01T09:10:00Z&to=2026-11-01T09:30:00Z&limit=3").json() assert [r["message"]["content"][0]["text"] for r in p1["records"]] == ["step 10", "step 15", "step 20"] p2 = c.get(f"/api/traces/ann?from=2026-11-01T09:10:00Z&to=2026-11-01T09:30:00Z&limit=3&cursor={p1['next_cursor']}").json() assert [r["message"]["content"][0]["text"] for r in p2["records"]] == ["step 25", "step 30"] assert c.get("/api/traces/nobody").status_code == 404 assert p1["source"].endswith("/blob/main/traces/lane1/ann.jsonl") and w["author"]["source"] == p1["source"] def test_bad_inputs_are_400(client): c, sha = client for path in ["../x", "-h", "", "/etc/passwd"]: assert c.get(f"/api/commits/{sha}/file", params={"path": path}).status_code == 400, path assert c.get("/api/commits/xyz").status_code == 400 assert c.get("/api/traces/ann?cursor=5").status_code == 400 # mid-line cursor assert c.get("/api/messages/search?q=%22").status_code == 400 def test_agents_and_highlights(client): c, sha = client rows = {a["name"]: a for a in c.get("/api/agents?sort=model_calls").json()["items"]} assert rows["ann"]["model_calls"] == 12 and rows["ann"]["tool_calls"] == 12 and rows["ann"]["total_tokens"] == 12 * 110 assert rows["bob"]["reconstructed"] and rows["bob"]["lane"] == "lane2" and not rows["ann"]["reconstructed"] assert rows["bob"]["reviews"] == 1 and rows["ann"]["prs_merged"] == 1 assert c.get("/api/prs/7/traces").json()["items"][1]["reconstructed"] is True a = c.get("/api/agents/ann").json() assert a["hours"]["rows"][0][1:] == [12, 12, 1200, 120] and a["busiest_hour"] == "2026-11-01T09:00:00Z" h = c.get("/api/highlights").json() assert h["totals"]["agents"] == 2 and h["totals"]["model_calls"] == 12 and h["run"]["gaps"] == [] assert {x["title"]: x["agent"] for x in h["highlights"]}["Most tool calls"] == "ann" assert any(m["text"].startswith("First merged PR: #7") for m in h["moments"]) assert c.get("/api/agents?sort=drop").status_code == 400 and c.get("/api/agents/nobody").status_code == 404 def test_caching_by_build(client): c, _ = client import app html = c.get("/").text assert f"/static/app.js?v={app.BUILD}" in html and c.get("/").headers["cache-control"] == "no-cache" r = c.get("/api/scores") assert r.headers["etag"] == app.ETAG and c.get("/api/scores", headers={"If-None-Match": app.ETAG}).status_code == 304 assert "immutable" in c.get(f"/static/app.js?v={app.BUILD}").headers["cache-control"] assert c.get("/static/app.js").headers["cache-control"] == "no-cache"