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.

fix(runner,gateway): the collection cursor — checkpointed must never imply collected

richard-epsilla1d329baa4702
diff --git a/gateway/app.py b/gateway/app.py
index 840bea37..ac07a244 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -2085,7 +2085,10 @@ async def _adopt_orphan_turn(sid: str, org: str, v: dict) -> bool:
rec["usage"] = translator.usage
await _vertex_upsert(sid, {"status": rec["status"], "turn_status": rec["status"]})
try:
- produced = (await _collect_produced(sid, set()) if terminal in ("completed", "incomplete") else [])
+ # Every terminal outcome collects. A cancelled or failed turn may already have written the
+ # deliverable (a Stop that lands after the file is saved, an OOM at finalize) — skipping
+ # collection threw those files away from the record while they sat in the workspace.
+ produced = await _collect_produced(sid, set())
for oev in translator.complete(rec["status"], produced):
_emit(oev)
except Exception: # noqa: BLE001
@@ -4785,6 +4788,15 @@ async def _collect_produced(sid: str, exclude: set[str] | None = None) -> list[d
out.append({"container_id": sid, "file_id": cfile, "filename": fname, "bytes": len(fr.content)})
except Exception: # noqa: BLE001
continue
+ # Advance the runner's collection cursor ONLY now that the files are captured to blobs. This is
+ # the other half of the stranded-artifact fix: /produced lists everything since the last ack,
+ # so a turn that died before this line leaves the cursor untouched and the next collection
+ # simply picks its files up. A skipped file (size cap, internal) is a decision, not a failure,
+ # so it is acked too rather than re-offered forever.
+ try:
+ await _sandbox("/produced/ack", sid, "POST")
+ except Exception: # noqa: BLE001 — cursor stays behind; the next collection re-lists, harmless
+ pass
return out
diff --git a/runner/server.py b/runner/server.py
index e7b1517c..62f814ab 100644
--- a/runner/server.py
+++ b/runner/server.py
@@ -3091,14 +3091,49 @@ def checkpoint(background_tasks: BackgroundTasks, identifier: str = "") -> Respo
raise
[email protected]("/produced")
-def produced(identifier: str = "") -> dict:
- """Files created/modified during the current turn (uncommitted vs the hydrated checkpoint).
- Call BEFORE /checkpoint commits them. Excludes internal state / scratch / secrets / vcs."""
- ws = _ws(identifier)
+# ── the COLLECTION cursor: a git ref advanced only when the gateway has captured the files ──────
+# Collection used to be "uncommitted vs HEAD", which made HEAD double as the collection cursor —
+# and /checkpoint moves HEAD unconditionally. Any terminal path that skipped collection (crash,
+# cancel, OOM kill, sweep-settle) followed by any checkpoint therefore buried the turn's files:
+# still on disk, permanently invisible to /produced. Watched happen live, twice, to the same deck
+# (2026-08-25). The cursor is now its own ref, so "checkpointed" no longer implies "collected",
+# and whatever a dead turn left behind is simply produced by the next turn that does collect.
+_COLLECTED_REF = "refs/hr/collected"
+
+
+def _collected_init(ws: str) -> None:
+ """Point the cursor at the current HEAD if it does not exist yet — hydrate/first-turn
+ semantics: what arrived in the checkpoint was not produced by any turn here."""
+ if _git(ws, "rev-parse", "-q", "--verify", _COLLECTED_REF).returncode != 0:
+ head = _git(ws, "rev-parse", "-q", "--verify", "HEAD")
+ if head.returncode == 0:
+ _git(ws, "update-ref", _COLLECTED_REF, head.stdout.strip())
+
+
+def _produced_keep(status: str, path: str) -> bool:
+ if not path or path.endswith("/") or status.startswith("D"):
+ return False
+ if path in _PRODUCED_EXCLUDE_NAMES or path.startswith(_PRODUCED_EXCLUDE_PREFIX):
+ return False
+ return not _is_produced_noise(path)
+
+
+def _produced_list(ws: str) -> list[dict]:
+ """Everything changed since the last ACKNOWLEDGED collection: committed changes past the
+ cursor (diff <ref> → worktree) plus untracked files. NOT merely uncommitted-vs-HEAD."""
_git_ensure(ws)
+ _collected_init(ws)
+ seen: dict[str, str] = {}
+ if _git(ws, "rev-parse", "-q", "--verify", _COLLECTED_REF).returncode == 0:
+ d = _git(ws, "diff", "--name-status", _COLLECTED_REF)
+ for line in (d.stdout or "").splitlines():
+ parts = line.split("\t")
+ if len(parts) < 2:
+ continue
+ status, path = parts[0], parts[-1].strip().strip('"')
+ if _produced_keep(status, path):
+ seen[path] = status[:1]
p = _git(ws, "status", "--porcelain", "-uall")
- out = []
for line in (p.stdout or "").splitlines():
if len(line) < 4:
continue
@@ -3106,16 +3141,38 @@ def produced(identifier: str = "") -> dict:
if " -> " in path: # rename: take the new path
path = path.split(" -> ", 1)[1]
path = path.strip().strip('"')
- if not path or path.endswith("/") or status == "D ":
- continue
- if path in _PRODUCED_EXCLUDE_NAMES or path.startswith(_PRODUCED_EXCLUDE_PREFIX):
- continue
- if _is_produced_noise(path):
- continue
- out.append({"path": path, "status": status.strip() or "?"})
+ if _produced_keep(status, path):
+ seen.setdefault(path, status.strip() or "?")
+ return [{"path": k, "status": v} for k, v in seen.items()]
+
+
+def _produced_ack(ws: str) -> str:
+ """Advance the cursor: commit the current state and point the ref at it. Called by the gateway
+ ONLY after it has captured the listed files, which is the one thing that makes 'collected'
+ mean collected."""
+ _git_ensure(ws)
+ _git(ws, "add", "-A")
+ _git(ws, "commit", "-q", "-m", f"collected {int(time.time())}", "--allow-empty")
+ head = _git(ws, "rev-parse", "HEAD").stdout.strip()
+ _git(ws, "update-ref", _COLLECTED_REF, head)
+ return head
+
+
[email protected]("/produced")
+def produced(identifier: str = "") -> dict:
+ """Files changed since the last acknowledged collection — surviving checkpoints, crashes and
+ cancels in between. Excludes internal state / scratch / secrets / vcs."""
+ ws = _ws(identifier)
+ out = _produced_list(ws)
return {"files": out, "count": len(out)}
[email protected]("/produced/ack")
+def produced_ack(identifier: str = "") -> dict:
+ ws = _ws(identifier)
+ return {"ok": True, "collected": _produced_ack(ws)}
+
+
@app.get("/file")
def get_file(path: str, identifier: str = "") -> Response:
"""Raw bytes of a workspace file (for downloading turn-produced container files)."""
diff --git a/runner/tests/test_produced_cursor.py b/runner/tests/test_produced_cursor.py
new file mode 100644
index 00000000..9235278c
--- /dev/null
+++ b/runner/tests/test_produced_cursor.py
@@ -0,0 +1,66 @@
+"""The collection cursor: 'checkpointed' must never imply 'collected'.
+
+The defect these pin (seen live, twice, same deck, 2026-08-25): /produced was
+uncommitted-vs-HEAD while /checkpoint moved HEAD unconditionally, so any terminal path
+that skipped collection (crash, cancel, OOM, sweep-settle) followed by any checkpoint
+buried the turn's files — on disk, invisible to collection, forever.
+"""
+import pathlib
+import subprocess
+import sys
+import tempfile
+import time
+
+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
+from server import _git, _git_ensure, _produced_ack, _produced_list # noqa: E402
+
+
+def _ws():
+ d = tempfile.mkdtemp()
+ _git_ensure(d)
+ (pathlib.Path(d) / "base.txt").write_text("base")
+ _git(d, "add", "-A")
+ _git(d, "commit", "-q", "-m", "hydrated")
+ _produced_ack(d) # cursor at the hydrated state: nothing produced yet
+ return d
+
+
+def test_untracked_and_committed_changes_are_both_produced():
+ d = _ws()
+ (pathlib.Path(d) / "deck.pptx").write_text("v1")
+ assert {f["path"] for f in _produced_list(d)} == {"deck.pptx"}
+ # a checkpoint commits it — the old design lost it here
+ _git(d, "add", "-A")
+ _git(d, "commit", "-q", "-m", f"checkpoint {int(time.time())}")
+ assert {f["path"] for f in _produced_list(d)} == {"deck.pptx"}
+
+
+def test_files_survive_any_number_of_checkpoints_until_acked():
+ d = _ws()
+ (pathlib.Path(d) / "deck.pptx").write_text("v1")
+ for i in range(3):
+ _git(d, "add", "-A")
+ _git(d, "commit", "-q", "--allow-empty", "-m", f"checkpoint {i}")
+ (pathlib.Path(d) / "deck.pptx").write_text("v2 restyled")
+ _git(d, "add", "-A")
+ _git(d, "commit", "-q", "-m", "another checkpoint")
+ assert {f["path"] for f in _produced_list(d)} == {"deck.pptx"}
+
+
+def test_ack_is_what_consumes_the_list():
+ d = _ws()
+ (pathlib.Path(d) / "deck.pptx").write_text("v1")
+ _produced_ack(d)
+ assert _produced_list(d) == []
+ (pathlib.Path(d) / "notes.md").write_text("later work")
+ assert {f["path"] for f in _produced_list(d)} == {"notes.md"}
+
+
+def test_a_deleted_file_is_not_offered():
+ d = _ws()
+ (pathlib.Path(d) / "gone.txt").write_text("x")
+ _produced_ack(d)
+ (pathlib.Path(d) / "gone.txt").unlink()
+ _git(d, "add", "-A")
+ _git(d, "commit", "-q", "-m", "checkpoint")
+ assert _produced_list(d) == []