Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

runner: the CLI home is checkpointed by tar, not by the workspace repo; opencode stops snapshotting (#194)

Hao Lu86fba9c2e29c
diff --git a/runner/server.py b/runner/server.py
index 11d06ef5..0dd60ab2 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -149,10 +149,7 @@ def _reap_workspaces(keep: str = "") -> int:
if e.stat().st_mtime >= cutoff:
continue
shutil.rmtree(e.path, ignore_errors=True)
- try:
- _ws_marker_path(e.name).unlink()
- except OSError:
- pass
+ _ws_marker_clear(e.name)
removed += 1
except OSError:
continue
@@ -374,6 +371,11 @@ CHECKPOINT_EXCLUDE = ["./tmp", "./.gcp-sa.json", "./.codex", "./.credentials.jso
# claude's .mcp.json); the provider KEY itself never lands anywhere —
# it lives only in the driver process (see dsh_driver.py's relay).
"./.harness/home/.dsh/cordis.yml",
+ # opencode's undo/revert history: a git repo of the workspace that grew to
+ # 699 MB / 71k files in twenty turns (#193). _opencode_config turns it off;
+ # this keeps a workspace that already carries one from dragging it through
+ # every later checkpoint. Nothing reads it once snapshots are off.
+ "./.harness/home/.local/share/opencode/snapshot",
# Dependency/scratch dirs (any depth): re-creatable by the agent, and they
# dominate checkpoint size — a node project checkpointed 200MB+ and paid
# that again on every hydrate. The agent reinstalls when it needs them.
@@ -459,14 +461,23 @@ def _ver(cmd: list[str]) -> str:
# ── git-backed workspace (hydrate at turn start, checkpoint at turn end) ───────────
-def _git(ws: str, *args: str, check: bool = False) -> subprocess.CompletedProcess:
+def _git(ws: str, *args: str, check: bool = False, env: dict | None = None) -> subprocess.CompletedProcess:
return subprocess.run(["git", "-C", ws, *args], capture_output=True, text=True,
- env={**os.environ, **_GIT_ENV}, check=check, **_as_session(ws))
+ env={**os.environ, **_GIT_ENV, **(env or {})}, check=check, **_as_session(ws))
def _git_ensure(ws: str) -> None:
"""Make /workspace a git repo with a secret-safe .gitignore (so .git, which travels in the
- checkpoint tarball, never carries credentials)."""
+ checkpoint tarball, never carries credentials).
+
+ The CLI home (.harness/home) is ignored here too. The repo has one reader, /produced, and it
+ already drops every `.harness/` path (_PRODUCED_EXCLUDE_PREFIX); the home still travels
+ between turns because the checkpoint is a tar of the directory, not a `git archive`, so
+ --resume is unaffected. Committing it gave every transcript and session database a second
+ copy in .git/objects per checkpoint — and on opencode the two fed each other, its snapshot
+ repo (work tree = the workspace) capturing our .git while we committed its snapshots: twenty
+ turns of one small file reached a 1.4 GB tarball for ~220 KB of output and the gateway OOMed
+ (#193, 2026-09-16)."""
p = pathlib.Path(ws)
p.mkdir(parents=True, exist_ok=True)
(p / ".gitignore").write_text("\n".join([
@@ -475,12 +486,77 @@ def _git_ensure(ws: str) -> None:
".harness/home/.hermes/.env", ".harness/home/.hermes/auth.json",
".harness/home/.pi/agent/auth.json", ".harness/home/.pi/agent/models.json",
".harness/goose/config/secrets.yaml",
+ "# harness: the CLI home is checkpointed by tar, not by this repo (see _git_ensure)",
+ ".harness/home/",
"",
]))
if not (p / ".git").exists():
_git(ws, "init", "-q")
_git(ws, "config", "user.email", _GIT_ENV["GIT_AUTHOR_EMAIL"])
_git(ws, "config", "user.name", _GIT_ENV["GIT_AUTHOR_NAME"])
+ else:
+ # An ignore rule does not release what an earlier checkpoint already committed: a
+ # tracked path is re-added by every `git add -A` regardless of .gitignore, so a session
+ # hydrated from before this rule would keep growing exactly as before. Drop the CLI
+ # home from the index (not from disk); from then on the ignore rule holds.
+ tracked = bool(_git(ws, "ls-files", "--", ".harness/home").stdout.strip())
+ if tracked:
+ _git(ws, "rm", "-r", "-q", "--cached", "--ignore-unmatch", "--", ".harness/home")
+ # Untracking releases the index, not .git/objects: every copy the old checkpoints
+ # committed stays reachable from those commits and rides in every later tarball of the
+ # session (722 MB of the 1.4 GB in #193). The gate is the index or the tip's tree, both
+ # O(1): before the rule every checkpoint re-added the home with `add -A`, so a history
+ # that holds it also holds it at the tip (the one gap, the index released but the tip
+ # not yet rewritten, is a crash between the two calls above and below, and the tip
+ # covers it). A walk of the history (`rev-list -- .harness/home`) would find the same
+ # repos and cost 130 ms per call at a thousand commits, four calls a turn, for the life
+ # of every session. Once per session: the shed leaves no home in either tree it keeps.
+ if tracked or _git(ws, "rev-parse", "-q", "--verify", "HEAD:.harness/home").returncode == 0:
+ _git_shed_cli_home_history(ws)
+
+
+def _git_shed_cli_home_history(ws: str) -> None:
+ """Rewrite a pre-#193 workspace repo down to what /produced reads — the collected cursor's
+ tree and HEAD's tree, each without .harness/home — and prune everything else.
+
+ /produced is the repo's one reader, and it reads two things: `diff refs/hr/collected` against
+ the worktree, and `status` (see _produced_list). Neither looks past those two trees, so the
+ history between and before them is dead weight, and for a session checkpointed before the
+ ignore rule it is where every earlier copy of the CLI home lives. Untracking alone leaves those
+ blobs reachable from the old commits, so the tarball would carry them on every later turn.
+ Each tree is rebuilt in a scratch index minus .harness/home (a path /produced excludes anyway),
+ so the cursor→worktree diff a caller sees before and after this is the same set of files.
+ gc prunes the unreachable blobs; on the reported repo that is the one-off cost of one gc,
+ paid at the session's first turn after upgrade."""
+ if _git(ws, "rev-parse", "-q", "--verify", "HEAD").returncode != 0:
+ return # nothing committed yet: nothing to shed
+ scratch = os.path.join(ws, ".git", "hr-shed-index") # owned by the session, like the rest of .git
+
+ def _tree_without_home(commit: str) -> str:
+ env = {"GIT_INDEX_FILE": scratch}
+ _git(ws, "read-tree", commit, env=env)
+ _git(ws, "rm", "-r", "-q", "--cached", "--ignore-unmatch", "--", ".harness/home", env=env)
+ return _git(ws, "write-tree", env=env).stdout.strip()
+
+ try:
+ parent: list[str] = []
+ if _git(ws, "rev-parse", "-q", "--verify", _COLLECTED_REF).returncode == 0:
+ c_tree = _tree_without_home(_COLLECTED_REF)
+ c_new = _git(ws, "commit-tree", c_tree, "-m", "collected (cli home history shed)").stdout.strip()
+ if c_new:
+ _git(ws, "update-ref", _COLLECTED_REF, c_new)
+ parent = ["-p", c_new]
+ h_tree = _tree_without_home("HEAD")
+ h_new = _git(ws, "commit-tree", h_tree, *parent, "-m", "checkpoint (cli home history shed)").stdout.strip()
+ if h_new:
+ _git(ws, "update-ref", "HEAD", h_new) # HEAD is symbolic: this moves the branch
+ finally:
+ try:
+ os.unlink(scratch)
+ except OSError:
+ pass
+ _git(ws, "reflog", "expire", "--expire=now", "--all")
+ _git(ws, "gc", "-q", "--prune=now")
# ── input/output file plumbing (OpenAI Responses input_file blocks + container files) ──
@@ -4088,6 +4164,10 @@ def _opencode_config(auth: Auth, model: str, cwd: str, mcp_servers: list[dict] |
"models": {model: {}},
}
},
+ # opencode's filesystem snapshots back the TUI's undo/revert; a fresh `run` per turn has
+ # no one to undo for, and HarnessRouter's checkpoint is the rollback here. Left on, it is
+ # a git repo of the workspace under $HOME — 699 MB of the 1.4 GB tarball in #193.
+ "snapshot": False,
}
mcp = _opencode_mcp(mcp_servers)
if mcp:
@@ -5554,6 +5634,32 @@ def _ws_marker_get(identifier: str) -> str:
return ""
+def _ws_marker_clear(identifier: str) -> None:
+ try:
+ _ws_marker_path(identifier).unlink()
+ except OSError:
+ pass
+
+
+def _ws_holds(identifier: str, ws_path: pathlib.Path, sha: str) -> bool:
+ """Whether this session's workspace still holds checkpoint `sha`: the marker says so AND the
+ folder is there to back it. The marker lives outside the workspace on purpose (it has to
+ survive the wipe), which also lets it outlive the workspace: the folder deleted from the
+ volume by hand while the runner container was merely stopped and started, or removed by
+ DELETE /workspace before it learned to drop the marker. Either way the next probe answered
+ "held", the gateway skipped the restore, and the turn ran on an empty folder — the CLI found
+ no session to resume and the conversation started over (richard-epsilla, #194). A workspace
+ restored from a checkpoint always carries its .git (the tarball does, and _git_ensure runs
+ after every restore), so a folder without one holds nothing, whatever the marker says; the
+ marker that vouched for it is dropped so the full hydrate that follows starts clean."""
+ if _ws_marker_get(identifier) != sha:
+ return False
+ if (ws_path / ".git").is_dir():
+ return True
+ _ws_marker_clear(identifier)
+ return False
+
+
@app.post("/hydrate")
async def hydrate(request: Request, identifier: str = "") -> dict:
"""Restore /workspace from a checkpoint tarball (the request body). Empty body = a fresh
@@ -5591,7 +5697,7 @@ async def hydrate(request: Request, identifier: str = "") -> dict:
# answers yes — making follow-up turns start instantly instead of paying wipe + untar.
probe = request.query_params.get("probe", "")
if probe and nbytes == 0:
- if _ws_marker_get(identifier) == probe:
+ if _ws_holds(identifier, ws_path, probe):
collab_url = request.query_params.get("collab_url", "")
room = request.query_params.get("room", "")
if collab_url and room:
@@ -6095,6 +6201,11 @@ async def delete_workspace(identifier: str = "") -> dict:
ws = _ws(ident)
if os.path.realpath(ws) in (os.path.realpath(WORKSPACE_ROOT), "/"):
raise HTTPException(status_code=400, detail="refusing to remove the workspace root")
+ # Whether or not the folder is still there: after this call the session holds nothing on
+ # this box, and the marker is part of that. Cleared before the "no folder" answer below,
+ # since a folder already gone behind its marker is exactly the case in which a marker left
+ # behind would answer the next probe "held" (as the reaper does when it removes a folder).
+ _ws_marker_clear(ident)
if not os.path.isdir(ws):
return {"identifier": ident, "removed": False, "reason": "no folder"}
uid = _session_uid(ws)
diff --git a/runner/tests/test_hydrate_probe_marker.py b/runner/tests/test_hydrate_probe_marker.py
new file mode 100644
index 00000000..1ea45a99
--- /dev/null
+++ b/runner/tests/test_hydrate_probe_marker.py
@@ -0,0 +1,86 @@
+"""The warm-resume probe vouches for a workspace that is actually there.
+
+/hydrate?probe=<sha> asks "do you still hold this checkpoint?" so a follow-up turn on a warm
+sandbox can skip the download and the wipe+untar. The answer came from the per-session marker
+under /tmp/hr-ws alone — and the marker outlives the workspace: delete the folder from the
+volume by hand and `docker stop`/`start` the runner, or call DELETE /workspace (which removed
+the folder but, unlike the reaper, left the marker), and the next probe still said "held".
+The gateway then skipped the restore and the turn ran on an empty workspace: the CLI found no
+session to resume and the conversation started over (seen by richard-epsilla on #194).
+"""
+import hashlib
+import io
+import pathlib
+import sys
+import tarfile
+
+import pytest
+from fastapi.testclient import TestClient
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import server # noqa: E402
+
+
+def runner(monkeypatch, tmp_path):
+ monkeypatch.setattr(server, "WORKSPACE_ROOT", str(tmp_path / "ws"))
+ monkeypatch.setattr(server, "_WS_MARKER_DIR", str(tmp_path / "markers"))
+ monkeypatch.setattr(server, "SPOOL_DIR", str(tmp_path))
+ monkeypatch.setattr(server, "_SANDBOX_PER_SESSION", False)
+ monkeypatch.setattr(server, "_SESSION_UIDS", False)
+ monkeypatch.setattr(server, "_INTERNAL_KEY", "")
+ (tmp_path / "ws").mkdir()
+ return TestClient(server.app)
+
+
+def _checkpoint() -> tuple[bytes, str]:
+ """A checkpoint tarball as the gateway would stream it, and the sha it will probe with."""
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w:gz") as tar:
+ data = b'{"step": 1}'
+ info = tarfile.TarInfo("./plan.json")
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ body = buf.getvalue()
+ return body, hashlib.sha256(body).hexdigest()
+
+
+def test_a_warm_workspace_answers_the_probe(runner):
+ body, sha = _checkpoint()
+ assert runner.post("/hydrate?identifier=s1", content=body).json()["restored"] is True
+ assert runner.post(f"/hydrate?identifier=s1&probe={sha}", content=b"").json()["skipped"] is True
+
+
+def test_a_workspace_deleted_behind_the_marker_is_hydrated_again(runner, tmp_path):
+ body, sha = _checkpoint()
+ runner.post("/hydrate?identifier=s1", content=body)
+ import shutil
+ shutil.rmtree(tmp_path / "ws" / "s1") # by hand on the volume, runner still up
+ assert runner.post(f"/hydrate?identifier=s1&probe={sha}", content=b"").json()["skipped"] is False
+ assert not server._ws_marker_path("s1").exists(), "the marker that lied is gone"
+ # and the full hydrate the gateway then sends lands as usual
+ r = runner.post("/hydrate?identifier=s1", content=body).json()
+ assert r["restored"] is True and (tmp_path / "ws" / "s1" / "plan.json").read_text() == '{"step": 1}'
+
+
+def test_delete_workspace_takes_the_marker_with_it(runner, tmp_path):
+ body, sha = _checkpoint()
+ runner.post("/hydrate?identifier=s1", content=body)
+ assert server._ws_marker_path("s1").exists()
+ assert runner.delete("/workspace?identifier=s1").json()["removed"] is True
+ assert not server._ws_marker_path("s1").exists()
+ assert runner.post(f"/hydrate?identifier=s1&probe={sha}", content=b"").json()["skipped"] is False
+
+
+def test_delete_workspace_clears_the_marker_even_when_the_folder_is_already_gone(runner, tmp_path):
+ # the folder removed by hand, the marker left standing: DELETE answers "no folder", and must
+ # still take the marker with it — this is the very state in which a marker lies to the probe
+ body, sha = _checkpoint()
+ runner.post("/hydrate?identifier=s1", content=body)
+ import shutil
+ shutil.rmtree(tmp_path / "ws" / "s1")
+ assert server._ws_marker_path("s1").exists()
+ r = runner.delete("/workspace?identifier=s1").json()
+ assert r["removed"] is False and r["reason"] == "no folder"
+ assert not server._ws_marker_path("s1").exists()
+ assert runner.post(f"/hydrate?identifier=s1&probe={sha}", content=b"").json()["skipped"] is False
diff --git a/runner/tests/test_workspace_cli_home_not_tracked.py b/runner/tests/test_workspace_cli_home_not_tracked.py
new file mode 100644
index 00000000..0b5a558b
--- /dev/null
+++ b/runner/tests/test_workspace_cli_home_not_tracked.py
@@ -0,0 +1,165 @@
+"""The CLI home under .harness/home is carried by the checkpoint tar, never by the workspace repo.
+
+The defect these pin (#193, 2026-09-16, opencode 1.18.31): `git add -A` before every checkpoint
+committed .harness/home — opencode's snapshot repo and its SQLite session database — into
+.git/objects, while opencode's snapshot repo (work tree = the workspace) snapshotted our .git
+back. Twenty turns of one small file grew to a 1.4 GB tarball, ~140k files, for ~220 KB of
+agent output, and the gateway's buffering local-backing relay took the host to OOM.
+
+The repo has exactly one reader, /produced, and it already excludes `.harness/`, so ignoring
+the CLI home changes nothing that reader reports. What must still hold: the checkpoint tar
+keeps .harness/home — that is what --resume rides on.
+"""
+import json
+import pathlib
+import subprocess
+import sys
+import tempfile
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+import server # noqa: E402
+from server import CHECKPOINT_EXCLUDE, _git, _git_ensure, _produced_ack, _produced_list # noqa: E402
+
+
+def _ws_with_cli_home():
+ d = pathlib.Path(tempfile.mkdtemp())
+ _git_ensure(str(d))
+ # what a turn leaves behind: a deliverable, and a CLI home with a session db and transcripts
+ (d / "plan.json").write_text("{}")
+ oc = d / ".harness" / "home" / ".local" / "share" / "opencode"
+ (oc / "snapshot" / "global" / "objects").mkdir(parents=True) # what an old session still carries
+ (oc / "snapshot" / "global" / "objects" / "ab").write_bytes(b"\x03" * 512)
+ (oc / "opencode.db").write_bytes(b"\x00" * 1024)
+ (d / ".harness" / "home" / ".claude" / "projects").mkdir(parents=True)
+ (d / ".harness" / "home" / ".claude" / "projects" / "t.jsonl").write_text("{}\n")
+ return d
+
+
+def test_the_cli_home_never_enters_the_workspace_repo():
+ d = _ws_with_cli_home()
+ _git(str(d), "add", "-A")
+ _git(str(d), "commit", "-q", "-m", "checkpoint")
+ tracked = _git(str(d), "ls-files").stdout.split()
+ assert "plan.json" in tracked
+ assert not any(p.startswith(".harness/home/") for p in tracked), tracked
+ # and git no longer has to walk it either: a status of the workspace is silent about it
+ status = _git(str(d), "status", "--porcelain", "-uall").stdout
+ assert ".harness/home" not in status
+
+
+def test_a_workspace_that_already_tracks_the_cli_home_lets_go_of_it():
+ # a session hydrated from before the rule: .harness/home is IN the index, and an ignore
+ # rule alone would leave it there — every later `git add -A` would keep committing it
+ d = _ws_with_cli_home()
+ subprocess.run(["git", "-C", str(d), "add", "-f", "--", "plan.json",
+ ".harness/home/.local/share/opencode/opencode.db",
+ ".harness/home/.claude/projects/t.jsonl"], check=True)
+ subprocess.run(["git", "-C", str(d), "commit", "-q", "-m", "old checkpoint"], check=True)
+ assert any(p.startswith(".harness/home/") for p in _git(str(d), "ls-files").stdout.split())
+ (d / ".harness" / "home" / ".local" / "share" / "opencode" / "opencode.db").write_bytes(b"\x02" * 4096)
+ _git_ensure(str(d)) # what every checkpoint/hydrate/produced call runs first
+ _git(str(d), "add", "-A")
+ _git(str(d), "commit", "-q", "-m", "checkpoint")
+ tracked = _git(str(d), "ls-files").stdout.split()
+ assert "plan.json" in tracked
+ assert not any(p.startswith(".harness/home/") for p in tracked), tracked
+ assert (d / ".harness" / "home" / ".local" / "share" / "opencode" / "opencode.db").exists(), "only the index lets go; the file stays"
+
+
+def test_produced_reports_the_deliverable_and_not_the_cli_home():
+ d = _ws_with_cli_home()
+ assert {f["path"] for f in _produced_list(str(d))} == {"plan.json"}
+ _produced_ack(str(d))
+ # a later turn touches only the CLI home: nothing new is produced
+ (d / ".harness" / "home" / ".local" / "share" / "opencode" / "opencode.db").write_bytes(b"\x01" * 2048)
+ assert _produced_list(str(d)) == []
+
+
+def test_the_checkpoint_tar_keeps_the_cli_home_but_drops_the_snapshot_store():
+ # the tar is what --resume rides on: transcripts and the session db must still travel;
+ # opencode's undo history must not (it is the 699 MB half of #193)
+ d = _ws_with_cli_home()
+ excl = [f"--exclude={p}" for p in CHECKPOINT_EXCLUDE]
+ out = subprocess.run(["tar", "-cf", "-", *excl, "-C", str(d), "."], capture_output=True, check=True)
+ names = subprocess.run(["tar", "-tf", "-"], input=out.stdout, capture_output=True, check=True).stdout.decode().split()
+ assert "./.harness/home/.local/share/opencode/opencode.db" in names
+ assert "./.harness/home/.claude/projects/t.jsonl" in names
+ assert not any("/opencode/snapshot" in n for n in names), [n for n in names if "snapshot" in n]
+
+
+def test_opencode_is_told_not_to_snapshot(tmp_path):
+ server._opencode_config(server.Auth(provider="openai", base_url="https://api.openai.com/v1", api_key="k"),
+ "gpt-5.4", str(tmp_path), None, None, pr="openai")
+ cfg = json.load(open(tmp_path / ".harness" / "opencode.json"))
+ assert cfg["snapshot"] is False
+
+
+def test_a_workspace_that_already_tracks_the_cli_home_sheds_the_copies_in_its_history():
+ # untracking releases the index; it does not release .git/objects. Twenty pre-fix checkpoints
+ # of a 136 MB session db are twenty reachable blobs, and the tarball carries them on every
+ # later turn of that session (722 MB of the 1.4 GB in #193). The repo's one reader needs only
+ # the cursor's tree and HEAD's tree, so the rest is rewritten away — and what /produced
+ # answers must be the same before and after.
+ d = _ws_with_cli_home()
+ db = d / ".harness" / "home" / ".local" / "share" / "opencode" / "opencode.db"
+ blobs = []
+ for i in range(3): # three pre-fix checkpoints, each a new copy
+ db.write_bytes(bytes([i + 1]) * 65536)
+ blobs.append(_git(str(d), "hash-object", "--", str(db)).stdout.strip())
+ subprocess.run(["git", "-C", str(d), "add", "-f", "-A", "--", "plan.json", ".harness/home"], check=True)
+ subprocess.run(["git", "-C", str(d), "commit", "-q", "-m", f"checkpoint {i}"], check=True)
+ # the cursor exists and sits on that history (set by hand: _produced_ack runs _git_ensure,
+ # the very call under test)
+ _git(str(d), "update-ref", server._COLLECTED_REF, "HEAD")
+ (d / "plan.json").write_text('{"step": 2}') # produced since the last collection, not yet collected
+ (d / "report.md").write_text("done")
+ before = {"plan.json", "report.md"}
+ for b in blobs:
+ assert _git(str(d), "cat-file", "-e", b).returncode == 0
+
+ _git_ensure(str(d)) # the first call of the session's next turn
+
+ assert {f["path"] for f in _produced_list(str(d))} == before, "the cursor→worktree answer is unchanged"
+ assert not any(p.startswith(".harness/home/") for p in _git(str(d), "ls-files").stdout.split())
+ assert db.exists() and db.read_bytes()[:1] == b"\x03", "the file itself is untouched"
+ for b in blobs:
+ assert _git(str(d), "cat-file", "-e", b).returncode != 0, f"blob {b} is still reachable"
+ assert _git(str(d), "rev-list", "--count", "HEAD").stdout.strip() == "2"
+ # and the session goes on: the next checkpoint commits on top of the rewritten tip
+ _git(str(d), "add", "-A")
+ _git(str(d), "commit", "-q", "-m", "checkpoint")
+ assert _git(str(d), "rev-list", "--count", "HEAD").stdout.strip() == "3"
+ assert _git(str(d), "fsck", "--no-progress").returncode == 0
+
+
+def test_a_workspace_that_never_tracked_the_cli_home_is_not_rewritten():
+ d = _ws_with_cli_home()
+ _git(str(d), "add", "-A")
+ _git(str(d), "commit", "-q", "-m", "checkpoint 0")
+ (d / "plan.json").write_text("{1}")
+ _git(str(d), "add", "-A")
+ _git(str(d), "commit", "-q", "-m", "checkpoint 1")
+ head = _git(str(d), "rev-parse", "HEAD").stdout.strip()
+ _git_ensure(str(d))
+ assert _git(str(d), "rev-parse", "HEAD").stdout.strip() == head
+ assert _git(str(d), "rev-list", "--count", "HEAD").stdout.strip() == "2"
+
+
+def test_an_index_released_but_a_tip_not_yet_rewritten_still_sheds_and_only_once():
+ # the gate is the tip's tree, not a walk of the history: the one state with a clean index and
+ # the copies still reachable is a crash between the untrack and the shed, and the tip covers it
+ d = _ws_with_cli_home()
+ db = d / ".harness" / "home" / ".local" / "share" / "opencode" / "opencode.db"
+ db.write_bytes(b"\x07" * 65536)
+ blob = _git(str(d), "hash-object", "--", str(db)).stdout.strip()
+ subprocess.run(["git", "-C", str(d), "add", "-f", "-A", "--", "plan.json", ".harness/home"], check=True)
+ subprocess.run(["git", "-C", str(d), "commit", "-q", "-m", "pre-fix checkpoint"], check=True)
+ subprocess.run(["git", "-C", str(d), "rm", "-r", "-q", "--cached", "--", ".harness/home"], check=True) # ...and then the process died
+ assert not _git(str(d), "ls-files", "--", ".harness/home").stdout.strip()
+ assert _git(str(d), "cat-file", "-e", blob).returncode == 0
+ _git_ensure(str(d))
+ assert _git(str(d), "cat-file", "-e", blob).returncode != 0
+ assert _git(str(d), "rev-list", "--count", "HEAD").stdout.strip() == "1" # no cursor yet: HEAD's tree alone
+ head = _git(str(d), "rev-parse", "HEAD").stdout.strip()
+ _git_ensure(str(d)) # and it does not run twice
+ assert _git(str(d), "rev-parse", "HEAD").stdout.strip() == head