diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f7b545..2e48626 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ All notable changes to Voyager are documented here. Format loosely follows [Keep a Changelog](https://keepachangelog.com/); versions are dated. +## [Unreleased] + +### Fixed + +- A failed Continuation Bundle write no longer leaves a WorkThread leased to a handoff that never happened. Both failures to create the output directory and failures from the atomic writer now release the single-writer lease, clear the returned token and record no pending attach, so the next legal handoff is not refused. Regression tests cover mkdir failure, atomic write failure and a successful retry without `thread unlock --steal`. + +- `voyager demo --db PATH` now honours the global database override on either side of the subcommand. The demo seeds exactly the requested index and prints commands pointing at it, instead of silently writing the default `demo.db` under the real home directory. + ## [1.6.0] — 2026-11-22 ### Added diff --git a/tests/test_demo_db_override.py b/tests/test_demo_db_override.py new file mode 100644 index 0000000..a868f8b --- /dev/null +++ b/tests/test_demo_db_override.py @@ -0,0 +1,38 @@ +"""`voyager demo --db` must seed the requested index, not the default one. + +The global `--db` flag is documented as valid on either side of the +subcommand. `demo` was the exception: the subparser did not inherit the common +arguments, and `_cmd_demo` called `demo.main()` with no path, so an explicit +database was silently ignored and the synthetic story landed in the default +home. Regression for R14 ENG-1. +""" + +from __future__ import annotations + +import pytest + +from voyager.cli import main +from voyager.demo import DEMO_DB_NAME + + +@pytest.mark.parametrize("db_before_subcommand", [True, False]) +def test_demo_honours_explicit_db(tmp_path, monkeypatch, + db_before_subcommand, capsys): + import voyager.store as store_mod + + fake_home_db = tmp_path / "home" / ".voyager" / "index.db" + monkeypatch.setattr(store_mod, "default_db_path", lambda: fake_home_db) + + explicit = tmp_path / "custom" / "demo.db" + argv = (["--db", str(explicit), "demo"] if db_before_subcommand + else ["demo", "--db", str(explicit)]) + + assert main(argv) == 0 + out = capsys.readouterr().out + assert str(explicit) in out + assert explicit.exists() + assert explicit.parent / DEMO_DB_NAME == explicit + + default_demo = fake_home_db.parent / DEMO_DB_NAME + assert not default_demo.exists() + assert "Seeded a synthetic demo index" in out diff --git a/tests/test_handoff_lease_cleanup.py b/tests/test_handoff_lease_cleanup.py new file mode 100644 index 0000000..d16bfe7 --- /dev/null +++ b/tests/test_handoff_lease_cleanup.py @@ -0,0 +1,103 @@ +"""Write failures must not leave a WorkThread leased to a non-existent handoff. + +Regression for R14 BUG-1 / ENG-2. `handoff_thread` takes the single-writer +lease before it compiles and writes the bundle; the existing early returns for +an unsupported transcript and an invalid budget both release it. A filesystem +error while creating the output directory or writing the file must obey the +same invariant, or the next legal handoff is refused until someone knows to +run `thread unlock --steal`. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from voyager.continuity import handoff_thread +from voyager.store import Store + + +@pytest.fixture +def leased_thread(tmp_path): + """A two-member WorkThread whose source files exist (no native resume).""" + store = Store(tmp_path / "index.db") + src = tmp_path / "source.jsonl" + src.write_text("{}\n", encoding="utf-8") + + for i, (sid, provider) in enumerate(( + ("codex:m0", "codex"), ("claude:m1", "claude"))): + session = { + "id": sid, "provider": provider, + "native_session_id": sid.split(":")[-1], + "title": "work {0}".format(i), + "started_at": 1000.0 + i, "updated_at": 2000.0 + i, + "cwd": "E:/proj/demo", "repo_root": "E:/proj/demo", + "message_count": 2, "tool_count": 1, + "can_resume": False, "can_fork": False, "resume_cmd": None, + "metadata": {}, "raw_metadata": {}, + } + event = { + "sid": sid, "ts": 2000.0 + i, "seq": 0, "kind": "user", + "content": "conv work {0}".format(i), + } + store.replace_session(session, [event], provider, src) + + tid = store.thread_create(repo_root="E:/proj/demo", title="the task") + for sid in ("codex:m0", "claude:m1"): + store.thread_attach(tid, sid) + yield store, tid + store.close() + + +def _handoff(store, tid, output, target="grok"): + return handoff_thread( + store=store, target=target, thread=tid, mode="bundle", + style="continuation", output=str(output), force_bundle=True) + + +def test_mkdir_failure_releases_lease_and_allows_retry(tmp_path, leased_thread): + store, tid = leased_thread + blocker = tmp_path / "not-a-directory" + blocker.write_text("file", encoding="utf-8") + failed_out = blocker / "bundle.md" + + first = _handoff(store, tid, failed_out) + assert first["action"] == "error" + assert first["exit_code"] == 2 + assert "cannot create bundle directory" in first["error"] + assert not failed_out.exists() + assert store.thread_lease_get(tid) is None + assert store.thread_pending_list(tid) == [] + + good_out = tmp_path / "good.md" + second = _handoff(store, tid, good_out, target="claude") + assert second["action"] == "bundle" + assert good_out.exists() + assert "Continuation Bundle" in good_out.read_text(encoding="utf-8") + + +def test_atomic_write_failure_releases_lease(tmp_path, leased_thread, + monkeypatch): + import voyager.continuity as continuity + + store, tid = leased_thread + + def boom(path, text): + raise OSError(28, "No space left on device") + + monkeypatch.setattr(continuity, "_write_atomic", boom) + out = tmp_path / "bundle.md" + + res = _handoff(store, tid, out) + assert res["action"] == "error" + assert res["exit_code"] == 2 + assert "cannot write bundle" in res["error"] + assert not out.exists() + assert store.thread_lease_get(tid) is None + assert store.thread_pending_list(tid) == [] + + monkeypatch.undo() + retry = _handoff(store, tid, out, target="claude") + assert retry["action"] == "bundle" + assert out.exists() diff --git a/voyager/cli.py b/voyager/cli.py index 9419f4a..dfeb1a7 100644 --- a/voyager/cli.py +++ b/voyager/cli.py @@ -2543,10 +2543,11 @@ def main(argv=None) -> int: # voyager demo — synthetic five-minute first run (no real agents needed) sp = sub.add_parser( - "demo", help="seed a synthetic demo index and show what to try next") + "demo", help="seed a synthetic demo index and show what to try next", + parents=[common]) def _cmd_demo(args) -> int: from .demo import main as demo_main - return demo_main() + return demo_main(getattr(args, "db", None)) sp.set_defaults(func=_cmd_demo) # voyager verify [provider] [--all] [--verbose] [--json] [--matrix] diff --git a/voyager/continuity.py b/voyager/continuity.py index 343e239..745322a 100644 --- a/voyager/continuity.py +++ b/voyager/continuity.py @@ -1554,6 +1554,13 @@ def handoff_thread( res["lease_token"] = lease_token = lease["lease_token"] res["lease_holder"] = target + def release_lease(reason: str) -> None: + """Give back the single-writer lease when a handoff write fails.""" + if tid and lease_token: + store.thread_lease_release(tid, lease_token, reason=reason) + res["lease_token"] = None + res["lease_holder"] = None + # -- same-provider native resume (D7 priority) ------------------------- resumable = [m for m in members if target and m["provider"] == target @@ -1642,12 +1649,21 @@ def handoff_thread( try: out.parent.mkdir(parents=True, exist_ok=True) except OSError as e: + release_lease("bundle-dir-failed") res["action"] = "error" res["error"] = "cannot create bundle directory {0}: {1}".format( out.parent, e.strerror or e) res["exit_code"] = 2 return res - _write_atomic(out, packed) + try: + _write_atomic(out, packed) + except OSError as e: + release_lease("bundle-write-failed") + res["action"] = "error" + res["error"] = "cannot write bundle {0}: {1}".format( + out, e.strerror or e) + res["exit_code"] = 2 + return res res["bundle_path"] = res["context_path"] = str(out.resolve()) res["context_chars"] = len(packed) diff --git a/voyager/demo.py b/voyager/demo.py index c12ef86..537695a 100644 --- a/voyager/demo.py +++ b/voyager/demo.py @@ -17,7 +17,7 @@ import tempfile import time from pathlib import Path -from typing import Any, Dict, List +from typing import Any, Dict, List, Optional from .model import new_event, new_session from .store import Store @@ -139,9 +139,9 @@ def default_index() -> Path: return default_db_path().parent / DEMO_DB_NAME -def run() -> int: +def run(index: Optional[Path] = None) -> int: """The `voyager demo` verb: seed, then tell the user what to try.""" - index = default_index() + index = Path(index) if index else default_index() tid = build(index) rel = index try: @@ -169,9 +169,9 @@ def run() -> int: return 0 -def main() -> int: +def main(index: Optional[Path] = None) -> int: try: - return run() + return run(index) except Exception as e: # a demo must never explode print(f"demo failed: {e}", file=sys.stderr) return 1