Files

265 lines
12 KiB
Python

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["click", "requests", "pytest"]
# ///
"""Tests for the skill's CLI (skill/scripts/handoff.py) — run them with
`uv run --script plugins/handoff/tests/test_handoff_cli.py`.
The hub and git are stubbed: these cover what the CLI decides (the prompt it
assembles, what it refuses, the cold writer's prompt, the plugin's `link` call),
not the hub's answers. Without click installed (a bare `python3 -m pytest`),
this module is skipped.
"""
import importlib.util
import json
import subprocess
import sys
from pathlib import Path
import pytest
pytest.importorskip("click")
pytest.importorskip("requests")
from click.testing import CliRunner # noqa: E402
SCRIPT = Path(__file__).resolve().parent.parent / "skill" / "scripts" / "handoff.py"
_spec = importlib.util.spec_from_file_location("handoff_cli", SCRIPT)
h = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(h)
cli = h.cli
GUIDE = ("Guidelines:\n- Make your changes in an isolated git worktree.\n"
"- When you finish, end your final message with a ```notify block.")
BRIEF = "Continue: ship the thing\n\n## Goal\n" + "Make the thing work end to end. " * 12
def facts(**kw):
f = {"id": "01a2-conv", "sessionId": "6fa67bc8-0000-0000-0000-000000000000",
"url": "https://hub/conversation/01a2-conv", "title": "The thing", "model": "claude-opus-5-5",
"harness": "claude", "account": "personal", "worker": None, "machine": "lab",
"projects": ["homelab"], "cwd": "/home/x/homelab", "worktrees": [], "repos": [],
"guidelines": GUIDE}
f.update(kw)
return f
@pytest.fixture
def runner():
return CliRunner()
@pytest.fixture
def stub(monkeypatch, tmp_path):
"""No hub, no git: `conversation` + `facts` return canned data, `ai-agent new` is recorded."""
calls = []
state = {"facts": facts(), "new_rc": 0, "new_err": ""}
monkeypatch.setenv("HANDOFF_DIR", str(tmp_path / "handoffs"))
monkeypatch.setattr(h, "my_session", lambda: "6fa67bc8-0000-0000-0000-000000000000")
monkeypatch.setattr(h, "conversation", lambda ref, messages=True, rendered=False: {"meta": {}})
monkeypatch.setattr(h, "facts", lambda c, cwd=None: state["facts"])
monkeypatch.setattr(h, "workers", lambda: [{"id": "0a1b2c3d4e5f", "name": "Acme Macbook"}])
def fake_ai_agent(*args, timeout=120):
calls.append(list(args))
if args[0] == "new":
if state["new_rc"]:
return subprocess.CompletedProcess(args, state["new_rc"], "", state["new_err"])
# The real CLI names the session only; the link comes from `show`.
return subprocess.CompletedProcess(args, 0, json.dumps(
{"sessionId": "new-sid", "delivered": None, "reportsBack": False}) + "\n", "")
if args[0] == "show":
return subprocess.CompletedProcess(args, 0, json.dumps(
{"sessionId": args[1], "id": "01b3-new", "url": "https://hub/conversation/01b3-new"}), "")
return subprocess.CompletedProcess(args, 0, "", "")
monkeypatch.setattr(h, "ai_agent", fake_ai_agent)
links = []
state["link_error"] = None
def fake_link(src, new, **kw):
if state["link_error"]:
raise h.hubclient.HubError(state["link_error"], 403, "capability")
links.append({"from": src, "to": new, **kw})
return {"ok": True}
monkeypatch.setattr(h, "link_call", fake_link)
state["calls"] = calls
state["links"] = links
return state
def brief_file(tmp_path, text=BRIEF):
p = tmp_path / "brief.md"
p.write_text(text)
return str(p)
# ── pure helpers ──────────────────────────────────────────────────────────────
def test_guidelines_are_the_last_block_of_the_first_prompt():
prompt = "do the thing\n\nGuidelines:\n- old\n\nmore text\n\n" + GUIDE
assert h.guidelines_of(prompt) == GUIDE
assert h.guidelines_of("no guidelines here") == ""
def test_assemble_adds_link_and_guidelines_verbatim():
out = h.assemble(BRIEF, facts())
assert out.startswith("Continue: ship the thing")
assert "Handed over from conversation 01a2-conv (claude-opus-5-5 · claude · lab)" in out
assert out.rstrip().endswith(GUIDE)
assert "is not repeated" in out
def test_assemble_keeps_a_brief_that_already_has_guidelines_alone():
out = h.assemble(BRIEF + "\n\n" + GUIDE, facts())
assert out.count("Guidelines:") == 1
def test_same_machine():
assert h.same_machine(None, None)
assert h.same_machine(None, "local")
assert not h.same_machine(None, "Acme Macbook")
assert not h.same_machine("0a1b2c3d4e5f", None)
def test_same_machine_by_worker_name(monkeypatch):
monkeypatch.setattr(h, "workers", lambda: [{"id": "0a1b2c3d4e5f", "name": "Acme Macbook"}])
assert h.same_machine("0a1b2c3d4e5f", "0a1b2c3d4e5f")
assert h.same_machine("0a1b2c3d4e5f", "acme macbook")
assert not h.same_machine("0a1b2c3d4e5f", "Mac perso")
def test_unpushed():
base = {"branch": "x", "upstream": "origin/x", "ahead": 0, "commits": ["abc"]}
assert not h.unpushed(base)
assert h.unpushed({**base, "ahead": 2})
assert h.unpushed({**base, "upstream": None})
assert not h.unpushed({**base, "upstream": None, "commits": []})
def test_trim_thread_keeps_the_opening_and_the_latest():
msgs = "".join(f"## {'You' if i % 2 == 0 else 'Claude'} [{i}]\n\n" + ("x" * 900) + "\n\n" for i in range(40))
out = h.trim_thread("# head\n\n" + msgs, 10_000)
assert len(out) <= 11_000
assert "## You [0]" in out and "## Claude [1]" in out and "## Claude [39]" in out
assert "messages cut" in out
def test_writer_prompt_matches_the_plugin_contract():
p = h.writer_prompt("01a2-conv", "gpt-6.1-sol", None, "Acme Macbook", None, None, "use the staging DB")
assert p.startswith("Hand off conversation 01a2-conv to gpt-6.1-sol — write its handoff brief from the transcript.")
assert "Use the handoff skill: run its `handoff material 01a2-conv --model gpt-6.1-sol --on 'Acme Macbook'`" in p
assert p.endswith("Note for the next agent (put it in the brief): use the staging DB")
def test_writer_prompt_is_the_plugin_actions():
"""The dialog's cold path (handlers/handoff_lib.cold_prompt) and `handoff cold`
write the same prompt."""
sys.path.insert(0, str(SCRIPT.parent.parent.parent / "handlers"))
import handoff_lib
flags = handoff_lib.target_flags("gpt-6.1-sol", None, "Acme Macbook")
assert handoff_lib.cold_prompt("01a2-conv", "gpt-6.1-sol", flags, "x") == \
h.writer_prompt("01a2-conv", "gpt-6.1-sol", None, "Acme Macbook", None, None, "x")
def test_material_names_the_wrapper_by_its_path():
assert h.HANDOFF_CMD.endswith("/skill/scripts/handoff")
assert Path(h.HANDOFF_CMD).is_file()
def test_title_of_drops_continue():
assert h.title_of("\n# Continue: ship the thing\n\nmore") == "ship the thing"
# ── CLI ───────────────────────────────────────────────────────────────────────
def test_help(runner):
res = runner.invoke(cli, ["--help"])
assert res.exit_code == 0
for cmd in ("context", "start", "material", "cold", "link"):
assert cmd in res.output
def test_start_refuses_an_empty_brief(runner, stub, tmp_path):
res = runner.invoke(cli, ["start", brief_file(tmp_path, "Continue: x"), "--model", "opus"])
assert res.exit_code == 1 and "nearly empty" in res.output
def test_start_needs_a_target_unless_print(runner, stub, tmp_path):
res = runner.invoke(cli, ["start", brief_file(tmp_path)])
assert res.exit_code == 2
def test_print_saves_and_prints_without_starting(runner, stub, tmp_path):
res = runner.invoke(cli, ["start", brief_file(tmp_path), "--print"])
assert res.exit_code == 0, res.output
assert "Continue: ship the thing" in res.output and GUIDE in res.output
assert not [c for c in stub["calls"] if c[0] == "new"]
saved = list((tmp_path / "handoffs").iterdir())
assert len(saved) == 1 and saved[0].name.endswith("-6fa67bc8-ship-the-thing.md")
def test_start_same_machine_reuses_cwd_and_links(runner, stub, tmp_path):
stub["facts"] = facts(repos=[{"dir": "/w/x", "branch": "x", "upstream": None, "ahead": None,
"commits": ["abc wip"], "dirty": 3, "status": [" M a.py"]}])
res = runner.invoke(cli, ["--json", "start", brief_file(tmp_path), "--model", "gpt-6.1-sol"])
assert res.exit_code == 0, res.output
new = next(c for c in stub["calls"] if c[0] == "new")
assert "--detach" in new and "--handoff-from" not in new
assert new[new.index("--cwd") + 1] == "/home/x/homelab"
assert new[new.index("--model") + 1] == "gpt-6.1-sol"
assert new[new.index("--project") + 1] == "homelab"
out = json.loads(res.output)
assert out["url"] == "https://hub/conversation/01b3-new" and out["linked"] is True
assert stub["links"] == [{"from": "6fa67bc8-0000-0000-0000-000000000000", "to": "new-sid",
"model": "gpt-6.1-sol", "harness": None, "worker": None,
"title": "ship the thing"}]
def test_start_elsewhere_refuses_uncommitted_work(runner, stub, tmp_path):
stub["facts"] = facts(repos=[{"dir": "/w/x", "branch": "x", "upstream": "origin/x", "ahead": 0,
"commits": [], "dirty": 2, "status": [" M a.py", "?? b.py"]}])
res = runner.invoke(cli, ["start", brief_file(tmp_path), "--model", "opus", "--on", "Acme Macbook"])
assert res.exit_code == 1
assert "can't see this work" in res.output and " M a.py" in res.output
assert not [c for c in stub["calls"] if c[0] == "new"]
res = runner.invoke(cli, ["start", brief_file(tmp_path), "--model", "opus", "--on", "Acme Macbook",
"--allow-dirty"])
assert res.exit_code == 0, res.output
new = next(c for c in stub["calls"] if c[0] == "new")
assert "--cwd" not in new # another machine: the lab's path means nothing there
def test_start_survives_a_failed_link(runner, stub, tmp_path):
stub["link_error"] = "plugin lacks conversations.data capability"
res = runner.invoke(cli, ["--json", "start", brief_file(tmp_path), "--model", "opus"])
assert res.exit_code == 0, res.output
assert "started, but not linked" in res.output and "link 6fa67bc8" in res.output
assert '"linked": false' in res.output
def test_link_command(runner, stub):
res = runner.invoke(cli, ["link", "src-sid-0001", "new-sid-0001", "--model", "qwen local", "--on", "w1"])
assert res.exit_code == 0, res.output
assert stub["links"] == [{"from": "src-sid-0001", "to": "new-sid-0001", "model": "qwen local",
"harness": None, "worker": "w1", "title": None}]
stub["link_error"] = "nope"
res = runner.invoke(cli, ["link", "a", "b"])
assert res.exit_code == 1 and "link: nope" in res.output
def test_cold_starts_a_test_writer_in_the_homelab(runner, stub):
stub_conv = {"id": "01a2-conv", "sessionId": "s", "meta": {}}
h.conversation = lambda ref, messages=True, rendered=False: stub_conv
res = runner.invoke(cli, ["cold", "01a2", "--model", "gpt-6.1-sol", "--writer", "qwen"])
assert res.exit_code == 0, res.output
new = next(c for c in stub["calls"] if c[0] == "new")
assert new[1].startswith("Hand off conversation 01a2-conv to gpt-6.1-sol")
assert new[new.index("--model") + 1] == "qwen"
assert "--test" in new and "--detach" in new
assert new[new.index("--cwd") + 1] == str(h.HOMELAB)
if __name__ == "__main__":
sys.exit(pytest.main([__file__, "-q"]))