Files
gabrielvidalandClaude Opus 5.5 65f3eb3468 feat(converters): pi, opencode and agy write v1 transcripts
runner/cli.mjs (pi), sidecar/opencode_mirror.py and sidecar/agy_mirror.py
write v1 events (docs/transcript-format.md) instead of Claude-Code-shaped
records: a header naming the harness, each model step whole — its call, its
blocks, its usage, in one append — tool calls under their neutral name with
the harness's own in `native`, the hub envelopes (author tag, inbox note)
unwrapped and the old text conventions said as events. Shared Python helpers
in sidecar/transcript_v1.py (Out: header, moved facts, dedup keys rebuilt
from the file, a v1 header before the first v1 line appended to an
old-format file); backend/test_converter_tables.py keeps its copies of the
hub's tables equal to the hub's.

- opencode: a step goes out once it has ended (its tokens come then, after
  its tools ran), so a step seen while it streamed no longer splits into
  content + a late usage record (quirk a). A step still running when its
  turn ends (idle, a new turn, the next step) goes out as it stands; a step
  that failed or was aborted and left nothing is not written (its error, or
  the interrupt, says it).
- agy: what closes a turn (turn_end, the interrupt, the interrupted results,
  the API-error call) carries the latest time agy recorded in it, never the
  mirror's clock (quirk c).
- pi: a fork copies its source's v1 history under the new id.
- gen_progress.tool_running reads v1 transcripts too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 11:13:21 +01:00

411 lines
21 KiB
Python

"""The agy harness: tool mapping, the brain/ transcript → Claude-schema mirror
(bound to the hub's uuid through the run log's init event, turns closed by the
run's result events, interrupts, subagents as sidechains, restart-proof), the
/usage snapshot, the run argv and the failure classification."""
import json
import pathlib
import pytest
import agy_cli
import agy_mirror
import agy_tools as tools
import agy_usage
HUB = "11111111-2222-3333-4444-555555555555"
CONV = "a262e8ee-718a-47a6-b06f-a3bd386d9169"
CHILD = "b5900408-e3aa-4b5d-ade0-add408e7f2be"
# ── tools ───────────────────────────────────────────────────────────────────
def test_tool_shapes_take_both_spellings():
cwd = "/w"
assert tools.map_call("read_file", {"Path": "a.txt"}, cwd) == ("Read", {"file_path": "/w/a.txt"})
assert tools.map_call("view_file", {"AbsolutePath": "/x", "StartLine": 3, "EndLine": 5}, cwd) == \
("Read", {"file_path": "/x", "offset": 3, "limit": 3})
assert tools.map_call("write_file", {"Path": "/a", "Content": "ok"}, cwd) == \
("Write", {"file_path": "/a", "content": "ok"})
assert tools.map_call("write_to_file", {"TargetFile": "/a", "CodeContent": "ok"}, cwd) == \
("Write", {"file_path": "/a", "content": "ok"})
assert tools.map_call("edit_file", {"Path": "/a", "Target": "o", "Replacement": "n"}, cwd) == \
("Edit", {"file_path": "/a", "old_string": "o", "new_string": "n"})
assert tools.map_call("replace_file_content", {"TargetFile": "/a", "TargetContent": "o",
"ReplacementContent": "n", "AllowMultiple": True},
cwd)[1]["replace_all"] is True
name, inp = tools.map_call("multi_replace_file_content", {"TargetFile": "/a", "ReplacementChunks": [
{"TargetContent": "a", "ReplacementContent": "b"}]}, cwd)
assert name == "MultiEdit" and inp["edits"] == [{"old_string": "a", "new_string": "b"}]
assert tools.map_call("run_command", {"CommandLine": "ls", "toolSummary": "List"}, cwd) == \
("Bash", {"command": "ls", "description": "List"})
assert tools.map_call("invoke_subagent", {"Subagents": [{"Prompt": "p", "Role": "Lister",
"TypeName": "research"}]}, cwd) == \
("Agent", {"description": "Lister", "prompt": "p", "subagent_type": "research",
"run_in_background": True})
assert tools.map_call("call_mcp_tool", {"ServerName": "pen pot", "ToolName": "x",
"Arguments": {"a": 1}}, cwd) == ("mcp__pen_pot__x", {"a": 1})
assert tools.map_call("browser_click_element", {"x": 1}, cwd) == ("browser_click_element", {"x": 1})
def test_result_text_drops_agys_timestamps():
assert tools.result_text("Created At: 2026-11-22T01:58:38+01:00\nCompleted At: 2026-11-22T01:58:40"
"+01:00\nCreated At: x\nCompleted At: y\nCommand exited with code 0.") == \
"Command exited with code 0."
# ── models / args / failures ────────────────────────────────────────────────
def test_split_model_and_args():
assert agy_cli.split_model("gemini-4-neon-high") == ("gemini-4-neon", "high")
assert agy_cli.split_model("gemini-3.8-flash-low") == ("gemini-3.8-flash", "low")
assert agy_cli.split_model("gemini-4-neon") == ("gemini-4-neon", None)
assert agy_cli.valid_model("gemini-4-hydrogen-xhigh") == "gemini-4-hydrogen"
args = agy_cli.run_args("hi", "gemini-4-neon", "high", conversation=CONV)
assert args[1:3] == ["--print", "hi"]
assert args[args.index("--model") + 1] == "gemini-4-neon"
assert args[args.index("--effort") + 1] == "high"
assert args[args.index("--conversation") + 1] == CONV
assert "--dangerously-skip-permissions" in args and "stream-json" in args
def test_effort_is_a_closed_set():
with pytest.raises(Exception):
agy_cli.valid_effort("ultra")
assert agy_cli.valid_effort("XHigh") == "xhigh"
def test_run_failure():
assert agy_cli.run_failure("error: authentication required\n") == ("error: authentication required", "auth")
msg, kind = agy_cli.run_failure('{"event":"result","result":{"status":"ERROR",'
'"error":"RESOURCE_EXHAUSTED: quota"}}')
assert kind == "rate_limit" and "quota" in msg
assert agy_cli.run_failure('AGY_ERROR:{"message":"unknown model foo"}')[1] == "cli_outdated"
RDRAND_ABORT = """CRNGT failed.
SIGABRT: abort
PC=0x7f728678369c m=0 sigcode=18446744073709551610
signal arrived during cgo execution
goroutine 1 gp=0x5f128f361e0 m=0 mp=0x55f67f27f360 [syscall, locked to thread]:
runtime.cgocall(0x55f67cae8d20, 0x5f12910dab0)
rflags 0x246
cs 0x33
fs 0x0
gs 0x0
"""
def test_run_failure_names_a_go_crash_not_its_last_register():
assert agy_cli.run_failure(RDRAND_ABORT)[0] == "agy crashed: CRNGT failed."
assert agy_cli.run_failure("panic: runtime error: index out of range\n\ngoroutine 1 [running]:\n"
"rip 0x1\ngs 0x0\n")[0] == "agy crashed: panic: runtime error: index out of range"
assert agy_cli.run_failure("SIGSEGV: segmentation violation\ngs 0x0\n")[0] == \
"agy crashed: SIGSEGV: segmentation violation"
def test_env_drops_dbus_and_sets_home(monkeypatch):
env = agy_cli.run_env("google-personal", {"DBUS_SESSION_BUS_ADDRESS": "x", "PATH": "/bin"}, "/w")
assert "DBUS_SESSION_BUS_ADDRESS" not in env and env["PWD"] == "/w" and env["HOME"]
def test_env_masks_the_hardware_rng_unless_told_otherwise():
assert agy_cli.account_env("google-personal", {})["OPENSSL_ia32cap"] == "~0x4000000000000000:~0x40000"
assert agy_cli.account_env("google-personal", {"OPENSSL_ia32cap": "0:0"})["OPENSSL_ia32cap"] == "0:0"
# ── usage ───────────────────────────────────────────────────────────────────
USAGE = {"groups": [
{"name": "Gemini Models", "buckets": [
{"id": "gemini-weekly", "window": "weekly", "remaining_fraction": 0.75,
"reset_time": "2026-11-29T00:58:19Z"},
{"id": "gemini-5h", "window": "5h", "reset_time": "2026-11-22T05:58:19Z"}]},
{"name": "Claude and GPT models", "buckets": [
{"id": "3p-weekly", "window": "weekly", "remaining_fraction": 1}]}]}
def test_usage_parse_maps_the_gemini_group():
snap = agy_usage.parse(USAGE)
rl = snap["rate_limits"]
assert rl["seven_day"]["used_percentage"] == 25.0
assert rl["seven_day"]["window_seconds"] == 604800
# a bucket without its fraction is empty
assert rl["five_hour"]["used_percentage"] == 100.0
assert snap["limit_reached"] is True
assert [g["name"] for g in snap["groups"]] == ["Gemini Models", "Claude and GPT models"]
# ── the mirror ──────────────────────────────────────────────────────────────
def _line(**kw) -> str:
return json.dumps(kw)
def _conv_dir(app: pathlib.Path, conv: str) -> pathlib.Path:
d = app / "brain" / conv / ".system_generated" / "logs"
d.mkdir(parents=True, exist_ok=True)
return d
TURN1 = [
_line(step_index=0, source="USER_EXPLICIT", type="USER_INPUT", status="DONE",
created_at="2026-11-22T00:58:35Z",
content="<USER_REQUEST>\nedit a.txt\n</USER_REQUEST>\n<ADDITIONAL_METADATA>\nt\n</ADDITIONAL_METADATA>"),
_line(step_index=1, type="PLANNER_RESPONSE", status="DONE", created_at="2026-11-22T00:58:36Z",
model="gemini-4-hydrogen-low", input_tokens=9490, cache_read_tokens=0, output_tokens=403,
thinking="plan", tool_calls=[
{"name": "read_file", "args": {"Path": "/w/a.txt"}},
{"name": "edit_file", "args": {"Path": "/w/a.txt", "Target": "b", "Replacement": "g"}}]),
_line(step_index=2, type="GENERIC", status="DONE", content="Created At: x\n1: a\n2: b"),
_line(step_index=3, type="GENERIC", status="DONE", content="Made 1 replacement"),
_line(step_index=4, type="PLANNER_RESPONSE", status="DONE", model="gemini-4-hydrogen-low",
input_tokens=2313, cache_read_tokens=8167, output_tokens=174, content="Done."),
]
@pytest.fixture
def env(tmp_path, monkeypatch):
home = tmp_path / "home"
app = home / ".gemini" / "antigravity-cli"
logs = tmp_path / "logs"
logs.mkdir()
runner = tmp_path / "runner"
monkeypatch.setattr(agy_cli, "AGY_ACCOUNTS", {"google-personal": home})
monkeypatch.setattr(agy_cli, "IDS_PATH", runner / "ids.json")
monkeypatch.setattr(agy_mirror, "LOG_DIR", logs)
monkeypatch.setattr(agy_mirror.pids, "_live_record", lambda sid: None)
m = agy_mirror.AccountMirror("google-personal", runner / "transcripts" / "google-personal",
runner / "state")
return {"app": app, "logs": logs, "runner": runner, "mirror": m}
def _records(env) -> list[dict]:
files = list((env["runner"] / "transcripts" / "google-personal").glob(f"*/{HUB}.jsonl"))
assert len(files) == 1, files
return [json.loads(ln) for ln in files[0].read_text().splitlines()]
def _start_run(env, *results):
agy_cli.record(HUB, account="google-personal", cwd="/w", pendingSince=0)
log = env["logs"] / f"{HUB}.log"
lines = [_line(event="init", conversation_id=CONV, init={"cwd": "/w"})]
lines += [_line(event="result", result=r) for r in results]
log.write_text("\n".join(lines) + "\n")
def _kinds(evs: list[dict]) -> list[str]:
return [e["t"] + (f":{e['reason']}" if e["t"] == "turn_end" else "") for e in evs]
def test_a_hub_run_is_bound_mirrored_and_closed_by_its_result(env):
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text("\n".join(TURN1) + "\n")
_start_run(env, {"status": "SUCCESS", "response": "Done."})
env["mirror"].tick()
assert agy_cli.ids()[HUB]["agy"] == CONV
evs = _records(env)
head = evs[0]
assert head["v"] == 1 and head["id"] == HUB and head["harness"] == "agy" and head["cwd"] == "/w"
assert evs[1]["t"] == "prompt" and evs[1]["text"] == "edit a.txt" and evs[1]["agyKey"] == "user:0"
# one whole step: call, blocks, usage
assert _kinds(evs[2:7]) == ["call", "thinking", "tool_call", "tool_call", "usage"]
call, _th, read, edit, usage = evs[2:7]
assert call["agyKey"] == "step:1" and call["effort"] == "low"
assert call["model"] == "gemini-4-hydrogen"
assert usage == {"t": "usage", "at": call["at"], "input": 9490, "output": 403,
"call": call["id"]}
assert (read["tool"], read["native"], edit["tool"], edit["native"]) == \
("read", "read_file", "edit", "edit_file")
results = [e for e in evs if e["t"] == "tool_result"]
assert [r["toolCall"] for r in results] == [read["id"], edit["id"]]
assert results[0]["text"] == "1: a\n2: b"
assert evs[-1]["t"] == "turn_end" and evs[-1]["reason"] == "done"
# restart-proof: a new mirror over the same files adds nothing
m2 = agy_mirror.AccountMirror("google-personal", env["runner"] / "transcripts" / "google-personal",
env["runner"] / "state")
m2.tick()
assert len(_records(env)) == len(evs)
def test_what_closes_a_turn_carries_the_sources_time_not_the_mirrors(env):
d = _conv_dir(env["app"], CONV)
timed = [json.dumps({**json.loads(ln), "created_at": f"2026-11-22T00:58:4{i}Z"})
for i, ln in enumerate(TURN1)]
(d / "transcript_full.jsonl").write_text("\n".join(timed) + "\n")
_start_run(env, {"status": "SUCCESS", "response": "Done."})
env["mirror"].tick()
end = _records(env)[-1]
# the run log's result has no time: the turn ends at the last step agy recorded
assert end["t"] == "turn_end" and end["at"] == "2026-11-22T00:58:44.000Z"
def test_an_interrupted_turn_ends_interrupted(env):
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text("\n".join(TURN1[:2]) + "\n")
_start_run(env, {"status": "ERROR", "error": "interrupted", "finished_reason": "interrupted"})
env["mirror"].tick()
evs = _records(env)
assert _kinds(evs[-4:]) == ["tool_result", "tool_result", "turn_end:interrupted",
"turn_end:done"]
assert evs[-3]["ok"] is False and evs[-3]["text"] == "[Request interrupted by user for tool use]"
assert evs[-2]["agyKey"].startswith("interrupt:")
def test_a_failed_turn_is_an_api_error(env):
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text(TURN1[0] + "\n")
_start_run(env, {"status": "ERROR", "error": "RESOURCE_EXHAUSTED: weekly limit"})
env["mirror"].tick()
evs = _records(env)
call = next(e for e in evs if e["t"] == "call")
err = next(e for e in evs if e["t"] == "error")
assert call["failed"] is True and call["model"] == "<synthetic>"
assert err["kind"] == "rate_limit" and "weekly limit" in err["text"]
def test_a_new_message_closes_the_previous_turn(env):
d = _conv_dir(env["app"], CONV)
turn2 = [_line(step_index=5, source="USER_EXPLICIT", type="USER_INPUT", status="DONE",
content="<USER_REQUEST>\nagain\n</USER_REQUEST>")]
(d / "transcript_full.jsonl").write_text("\n".join(TURN1 + turn2) + "\n")
agy_cli.record(HUB, account="google-personal", cwd="/w", agy=CONV)
env["mirror"].tick()
keys = [e.get("agyKey") for e in _records(env)]
assert keys.index("end:0:4") < keys.index("user:5")
def test_unbound_conversations_wait_for_a_pending_run(env, monkeypatch):
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text(TURN1[0] + "\n")
import time as _t
agy_cli.record(HUB, account="google-personal", cwd="/w", pendingSince=_t.time())
env["mirror"].tick() # no init in the log yet: nothing filed under agy's id
assert not list((env["runner"] / "transcripts").rglob(f"{CONV}.jsonl"))
def test_subagents_become_sidechains_linked_to_their_call(env):
parent = [
TURN1[0],
_line(step_index=1, type="PLANNER_RESPONSE", status="DONE", model="gemini-4-hydrogen-low",
input_tokens=1, output_tokens=1, tool_calls=[
{"name": "invoke_subagent", "args": {"Prompt": "list", "Role": "Lister",
"TypeName": "research"}}]),
_line(step_index=2, type="GENERIC", status="DONE",
content=f'Created the following subagent:\n{{"conversationId": "{CHILD}"}}'),
]
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text("\n".join(parent) + "\n")
sub = env["app"] / "brain" / CONV / ".system_generated" / "subagents"
sub.mkdir(parents=True)
(sub / f"{CHILD}.json").write_text(json.dumps({
"conversationId": CHILD, "subagentDescriptor": {"typeName": "research", "role": "Lister"},
"spawnStepIndex": 2}))
c = _conv_dir(env["app"], CHILD)
(c / "transcript_full.jsonl").write_text("\n".join([
_line(step_index=0, type="SYSTEM_MESSAGE", status="DONE",
content="<SYSTEM_MESSAGE>\n[Message] sender=x content=list the files\n</SYSTEM_MESSAGE>"),
_line(step_index=1, type="PLANNER_RESPONSE", status="DONE", model="gemini-4-hydrogen-low",
input_tokens=1, output_tokens=1, content="a.txt"),
]) + "\n")
_start_run(env)
env["mirror"].tick()
root = next((env["runner"] / "transcripts").rglob(f"{HUB}.jsonl"))
side = root.with_suffix("") / "subagents" / f"agent-{CHILD}.jsonl"
meta = json.loads(side.with_name(f"agent-{CHILD}.meta.json").read_text())
call = next(e for e in _records(env) if e["t"] == "tool_call")
assert call["tool"] == "agent" and call["native"] == "invoke_subagent"
assert meta == {"agentType": "research", "description": "Lister", "toolUseId": call["id"],
"spawnDepth": 1, "harness": "agy"}
sevs = [json.loads(ln) for ln in side.read_text().splitlines()]
assert sevs[0]["sidechain"] is True and sevs[0]["agent"] == CHILD and sevs[0]["id"] == HUB
assert sevs[1]["t"] == "prompt" and sevs[1]["text"] == "list the files"
# the child is not also mirrored as a conversation of its own
assert not list((env["runner"] / "transcripts").rglob(f"{CHILD}.jsonl"))[1:]
def test_session_model_reads_the_last_step(env):
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text("\n".join(TURN1) + "\n")
assert agy_cli.session_model("google-personal", CONV) == ("gemini-4-hydrogen", "low")
def test_customizations_point_agy_at_claude_md(env, monkeypatch, tmp_path):
skills = tmp_path / "skills"
skills.mkdir()
monkeypatch.setattr(agy_cli, "AGY_SKILL_DIRS", [str(skills), str(tmp_path / "missing")])
agy_cli.ensure_customizations("google-personal")
cfg = agy_cli.gemini_dir("google-personal") / "config"
assert (cfg / "rules" / agy_cli.RULE_NAME).read_text().startswith("---\ntrigger: always_on")
man = json.loads((cfg / "skills.json").read_text())
assert man["entries"] == [{"path": str(skills)}]
# idempotent, and keeps the user's own entries
man["entries"].append({"path": "/mine"})
(cfg / "skills.json").write_text(json.dumps(man))
agy_cli.ensure_customizations("google-personal")
assert json.loads((cfg / "skills.json").read_text())["entries"] == [{"path": str(skills)},
{"path": "/mine"}]
def test_plan_tier_from_the_argon_bucket():
assert agy_usage.plan_tier({"groups": [{"buckets": [{"id": "gemini-argon-wtu-weekly"}]}]}) == "google_ai_pro"
assert agy_usage.plan_tier({"groups": [{"buckets": [{"id": "gemini-weekly"}]}]}) == "google_ai_ultra"
assert agy_usage.plan_tier(None) is None
def test_a_first_prompt_carries_the_claude_md_files(tmp_path, monkeypatch):
home = tmp_path / "home"
(home / ".claude").mkdir(parents=True)
(home / ".claude" / "CLAUDE.md").write_text("global rules")
repo = tmp_path / "repo"
(repo / ".git").mkdir(parents=True)
(repo / "CLAUDE.md").write_text("repo rules")
sub = repo / "pkg"
sub.mkdir()
(sub / "CLAUDE.md").write_text("x" * (agy_cli.INLINE_FILE_MAX + 1))
(tmp_path / "CLAUDE.md").write_text("outside the repo: not loaded")
monkeypatch.setattr(agy_cli.pathlib.Path, "home", classmethod(lambda cls: home))
files = agy_cli.instruction_files(str(sub))
assert files == [home / ".claude" / "CLAUDE.md", repo / "CLAUDE.md", sub / "CLAUDE.md"]
out = agy_cli.with_instructions("do it", str(sub))
assert out.startswith("<ai-agent-instructions>") and out.endswith("\n\ndo it")
assert "global rules" in out and "repo rules" in out
assert f"`{sub / 'CLAUDE.md'}`" in out and "x" * 100 not in out # too big: named
# the mirror shows only what the user typed
assert agy_mirror.user_text(f"<USER_REQUEST>\n{out}\n</USER_REQUEST>") == "do it"
def test_a_system_message_shows_its_body_only(env):
d = _conv_dir(env["app"], CONV)
(d / "transcript_full.jsonl").write_text("\n".join([TURN1[0], _line(
step_index=1, type="SYSTEM_MESSAGE", status="DONE",
content="The following is a <SYSTEM_MESSAGE> not actually sent by the user.\n\n"
"<SYSTEM_MESSAGE>\nReminder: work efficiently.\n</SYSTEM_MESSAGE>")]) + "\n")
_start_run(env)
env["mirror"].tick()
ev = next(e for e in _records(env) if (e.get("agyKey") or "").startswith("sys:"))
assert ev["t"] == "inject" and ev["kind"] == "reminder"
assert ev["text"] == "<system-reminder>\nReminder: work efficiently.\n</system-reminder>"
def test_a_guests_agy_run_is_held_to_its_project(tmp_path, monkeypatch):
"""A guest's Gemini run: agy's allow-rules instead of
--dangerously-skip-permissions — file tools in the project, /tmp and the
read dirs, the CLAUDE.md files, the shell unless noBash."""
import json as _json
proj = tmp_path / "proj"
proj.mkdir()
(proj / ".git").mkdir()
(proj / "CLAUDE.md").write_text("rules")
monkeypatch.setattr(agy_cli.pathlib.Path, "home", staticmethod(lambda: tmp_path / "home"))
scope = {"writeDirs": ["/tmp"], "readDirs": [str(tmp_path / "att")], "systemPrompt": "x"}
allow = _json.loads(agy_cli.guest_settings(str(proj), scope))["permissions"]["allow"]
p = str(proj.resolve())
assert f"write_file({p})" in allow and "write_file(/tmp)" in allow
assert f"read_file({tmp_path.resolve() / 'att'})" in allow
assert not any("*" in a for a in allow if not a.startswith("command(")) # agy: no globs
assert not any(a.startswith("write_file(") and "att" in a for a in allow)
assert f"read_file({proj.resolve() / 'CLAUDE.md'})" in allow
assert "command(*)" in allow
assert "command(*)" not in agy_cli.guest_settings(str(proj), {**scope, "noBash": True})
args = agy_cli.run_args("hi", "gemini-4-neon", "high", settings='{"permissions":{}}')
assert "--dangerously-skip-permissions" not in args and "--settings" in args
assert "--dangerously-skip-permissions" in agy_cli.run_args("hi", "gemini-4-neon", "high")