From a36d298975d0da457ad64ad73511bf1775884cec Mon Sep 17 00:00:00 2001 From: HarryHe <2496583567@qq.com> Date: Sat, 21 Nov 2026 16:11:33 +0800 Subject: [PATCH] feat(cli): add read-only handoff preview --- CHANGELOG.md | 2 + tests/test_cli_preview.py | 109 ++++++++++++++++++++++++++++++++++++++ voyager/cli.py | 90 +++++++++++++++++++++++++++++++ 3 files changed, 201 insertions(+) create mode 100644 tests/test_cli_preview.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 79b8949..25963a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to Voyager are documented here. Format loosely follows ### Added +- **`voyager preview` is a read-only Handoff Preview.** It compiles the same bundle `continue` would hand off, in memory, from the existing `continue_context` / `thread_detail` API ops. It takes no lease, writes no bundle file, records no pending attach and launches nothing. With more than one active WorkThread it lists every candidate and labels the shown one a default instead of silently choosing it; `--json` exposes the same fields for tools. Tests cover the ambiguous case, explicit `--thread` and byte-identical index files before and after preview. No new Core API, Bridge op, Store/Bridge schema change or second handoff engine. + - **The Level 2 agent benchmark now has independent synthetic tasks.** `build_task()` selects from T1 (`calc.add()`), T2 (`textutil.normalize()`) and T3 (`ledger.total()`); each task owns its repo files, visible test, hidden acceptance test, hidden-answer key, session text and decoy thread. The CLI exposes `--task` and defaults to T1, so the historical `0/46/47/550` and `0/46/47/372` context measurements reproduce exactly. T2/T3 build green starting repos and fail their own hidden tests before any agent runs; T2 also passes the same three-mode/four-baseline DRY-RUN layout. The gate suite grew from 19 to 25 checks. No model, paid call, real session or live completion rate is involved. Runner isolation was separately probed and remains BLOCKED: `docs/audits/2026-11-20-runner-isolation-gate.md`. - **A Level 2 Agent Continuation Effectiveness harness is in the repo** (`scripts/agent_continuity_benchmark.py`, tests in `tests/test_agent_continuity_benchmark.py`). It extends PR #64's context-preparation benchmark with a real synthetic software task whose requirement lives only in prior-agent sessions: four equal-budget context variants, a pluggable agent runner, and an independent HIDDEN acceptance test the incoming agent never sees. DRY-RUN (default) executes the task/context/evaluator for real and marks every agent-outcome metric `LIVE_MODEL_NOT_VERIFIED` — no model, no paid call, no invented completion rate. Quality gates prove the starting repo is green, the hidden test fails on it, and a mutation that reveals the answer turns two gates red. This v1 entry is superseded by the v2 fairness correction below: the original `--runner` was not safely isolated and is now disabled. Report: `docs/audits/2026-11-20-agent-continuity-benchmark.md`. Level 1 scorer, Store/Bridge schema and shipped behaviour untouched. diff --git a/tests/test_cli_preview.py b/tests/test_cli_preview.py new file mode 100644 index 0000000..6ef131a --- /dev/null +++ b/tests/test_cli_preview.py @@ -0,0 +1,109 @@ +"""Read-only CLI Handoff Preview. + +A user should be able to answer "what would I hand off?" without taking a +lease, writing a bundle file, recording a pending attach or launching an agent. +The regression tests below pin the observable contract and the read-only +guarantee; they are deliberately written against the CLI, not the API helper, +because the friction being fixed is the missing user entry point. +""" +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from voyager.cli import main +from voyager.model import new_event, new_session +from voyager.store import Store + + +def _seed(store, sid, provider, title, content, born): + src = store.db_path.parent / (sid.replace(":", "_") + ".jsonl") + src.write_text("{}", encoding="utf-8") + s = new_session(id=sid, provider=provider, native_session_id=sid.split(":", 1)[1], + title=title, started_at=born, updated_at=born, + cwd="E:/proj/demo", repo_root="E:/proj/demo", message_count=1) + store.replace_session( + s, + [new_event(sid=sid, ts=born, seq=0, kind="user", content=content)], + provider, src) + + +def _db_fingerprint(db: Path) -> dict: + out = {} + for p in sorted(db.parent.glob(db.name + "*")): + if p.is_file(): + out[p.name] = hashlib.sha256(p.read_bytes()).hexdigest() + return out + + +def _fixture(tmp_path): + db = tmp_path / "preview.db" + store = Store(db) + _seed(store, "codex:a1", "codex", "strict flag", + "TODO: raise ValueError in the strict branch; command failed: pytest -q exit 1", + 1000.0) + _seed(store, "claude:a2", "claude", "claude review", + "TODO remains: strict branch still returns; rerun pytest -q", + 2000.0) + tid = store.thread_create(repo_root="E:/proj/demo", title="strict work", + goal="finish strict=True") + store.thread_attach(tid, "codex:a1") + store.thread_attach(tid, "claude:a2") + store.close() + return db, tid + + +def test_preview_json_is_read_only_and_shows_the_selected_work(tmp_path, capsys): + db, tid = _fixture(tmp_path) + before = _db_fingerprint(db) + + rc = main(["preview", "--db", str(db), "--thread", tid, + "--to", "claude", "--budget", "balanced", "--json"]) + payload = json.loads(capsys.readouterr().out) + + assert rc == 0 + assert payload["read_only"] is True + assert payload["selected_thread"]["id"] == tid + assert payload["selected_thread"]["goal"] == "finish strict=True" + assert payload["budget"] == 20000 + assert "TODO" in payload["bundle"] + assert "pytest -q" in payload["bundle"] + assert payload["members"][0]["source_state"] == "ACTIVE_SOURCE" + assert _db_fingerprint(db) == before, "preview must not write the index" + + +def test_preview_marks_ambiguous_threads_without_pretending_to_choose(tmp_path, capsys): + db, tid = _fixture(tmp_path) + store = Store(db) + _seed(store, "codex:b1", "codex", "unrelated task", "done", 3000.0) + store.thread_create(repo_root="E:/proj/demo", title="other work", + goal="unrelated", ) + store.thread_attach(store.thread_find_by_members({"codex:b1"}), "codex:b1") + store.close() + + rc = main(["preview", "--db", str(db), "--repo", "E:/proj/demo", "--json"]) + payload = json.loads(capsys.readouterr().out) + + assert rc == 0 + assert payload["thread_ambiguous"] is True + candidates = {c["id"] for c in payload["thread_candidates"]} + assert tid in candidates + assert len(candidates) >= 2 + assert "default" in payload["thread_default_reason"] + assert "not a choice" in payload["thread_default_reason"] + + +def test_preview_human_output_states_that_nothing_was_written(tmp_path, capsys): + db, tid = _fixture(tmp_path) + before = _db_fingerprint(db) + + rc = main(["preview", "--db", str(db), "--thread", tid]) + + out = capsys.readouterr().out + assert rc == 0 + assert "READ ONLY" in out + assert "no lease" in out.lower() + assert "bundle" in out.lower() + assert "strict work" in out + assert _db_fingerprint(db) == before diff --git a/voyager/cli.py b/voyager/cli.py index 2d2b630..9419f4a 100644 --- a/voyager/cli.py +++ b/voyager/cli.py @@ -894,6 +894,84 @@ def _continuity_status_enum(disc: dict) -> str: return "READY" +def cmd_preview(args) -> int: + """Read-only Handoff Preview for the three user questions. + + This is the CLI spelling of the API's ``continue_context`` op. It compiles + exactly the bundle ``continue`` would hand off, but deliberately performs + none of ``continue``'s writes: no scan, no lease, no pending attach, no + bundle file and no launch. Ambiguity is surfaced rather than silently + resolved, so a user can choose a WorkThread before committing to an act. + """ + from .api import continue_context, thread_detail + + refs = None + raw_refs = getattr(args, "from_sessions", None) + if raw_refs: + refs = [r.strip() for r in raw_refs.split(",") if r.strip()] + out = continue_context( + db=_db_path_arg(args), + session_refs=refs, + thread_id=getattr(args, "thread", None), + repo=getattr(args, "repo", None), + goal=getattr(args, "goal", None), + budget=getattr(args, "budget", None), + target=getattr(args, "to", None), + ) + if not isinstance(out, dict) or out.get("error"): + print(out.get("error") if isinstance(out, dict) else "preview failed", + file=sys.stderr) + return 2 + + # `continue_context` deliberately keeps its response shape stable: it + # reports ambiguity and scope, not a second copy of thread metadata. The + # CLI preview needs that metadata to be a useful chooser, so read it from + # the existing thread_detail op instead of changing the API contract. + if getattr(args, "thread", None): + detail = thread_detail(_db_path_arg(args), args.thread) + if detail.get("thread"): + out["selected_thread"] = detail["thread"] + out.setdefault("members", detail.get("members", [])) + out.setdefault("lease", detail.get("lease")) + + out["read_only"] = True + out["writes_if_committed"] = ( + "voyager continue will take a lease, write a bundle file, record a " + "pending attach and (unless --no-launch is given) launch the target.") + if args.json: + print(json.dumps(out, ensure_ascii=False, indent=2, default=str)) + return 0 + + print("READ ONLY Handoff Preview — no lease was taken, nothing was written or launched.") + if out.get("repo_scope"): + print("selection: " + str(out["repo_scope"].get("selection_reason", ""))) + if out.get("thread_ambiguous"): + print("AMBIGUOUS: {0} active WorkThreads; the shown thread is only a " + "default.".format(len(out.get("thread_candidates") or []))) + for c in out.get("thread_candidates") or []: + print(" {0} {1} {2}".format(c.get("id"), c.get("title"), + c.get("goal") or "")) + print("choose one with: voyager preview --thread (then continue --thread )") + chosen = out.get("thread") or out.get("selected_thread") or out.get("session") or {} + if chosen: + print("thread : {0}".format(chosen.get("title") or chosen.get("id"))) + print("goal : {0}".format(chosen.get("goal") or chosen.get("title") or "?")) + print("repo : {0}".format(chosen.get("repo_root") or chosen.get("repo") or "?")) + print("target : {0}".format(getattr(args, "to", None) or "default")) + members = out.get("members") or [] + missing = [m for m in members if m.get("source_state") == "SOURCE_MISSING"] + if missing: + print("sources : {0} retained session(s) are SOURCE_MISSING".format(len(missing))) + print("budget : {0} (est. {1} tokens)".format( + out.get("budget"), out.get("estimated_tokens"))) + if out.get("dropped"): + print("dropped : {0}".format(", ".join(map(str, out["dropped"])))) + if out.get("bundle"): + print("\n" + out["bundle"]) + print("\n" + out["writes_if_committed"]) + return 0 + + def cmd_status(args) -> int: """Phase I: show the automatic-continuity state for the current repo.""" import json as _json @@ -2563,6 +2641,18 @@ def _cmd_demo(args) -> int: sp.add_argument("verb", nargs="?", choices=["serve"], help=argparse.SUPPRESS) sp.set_defaults(func=cmd_api) + sp = sub.add_parser("preview", parents=[common], + help="read-only Handoff Preview: show what would be handed off") + sp.add_argument("--thread", help="preview a specific WorkThread") + sp.add_argument("--from", dest="from_sessions", + help="comma-separated session ids/prefixes to preview") + sp.add_argument("--repo", help="resolve the current WorkThread by repo") + sp.add_argument("--goal", help="goal used to rank the previewed evidence") + sp.add_argument("--to", help="target agent for the preview") + sp.add_argument("--budget", help="compact|balanced|full|auto|Nk|") + sp.add_argument("--json", action="store_true", help="machine-readable preview") + sp.set_defaults(func=cmd_preview) + sp = sub.add_parser("status", parents=[common], help="automatic-continuity state for the current repo") sp.add_argument("--repo", help="resolve by repo instead of cwd")