Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,18 @@ watcher's own: one `claude agents --json` per refresh, only on a live shift
holding real worker leases, and `gh pr checks` for unmerged PRs, cached for the
interval.

**Late arrivals (PyAutoBrain#594).** A worker may finish after `review-at:`,
once the digest is posted. A closed shift with a lease still held or a ledger op
still queued runs `late_sweep` on each tick: it reaps as a live tick does,
commits the queued ops through the one Mind writer, and appends one
`- late: <task> — <url> (after review-at, <time>)` line per arrival to the record
under `### Late arrivals`. It never spawns, re-dispatches, starts a close-out
or posts a second comment, because the grant ended at `review-at:` and what
arrives late waits for `/prm`. With nothing pending, the tick is idle. The worker
prompt also forbids EnterWorktree (its permission prompt stalls an unattended
worker) and requires the `decision-taken` label on any PR carrying a flagged
decision (pilot live shift 1, 2026-11-06).

**Workers start in a trusted folder.** `claude --bg` refuses an untrusted one
at once ("Workspace not trusted", exit 1) — the spawn fails and leaves no lease.
The watcher launches from the workspace root; task worktrees under the
Expand Down
60 changes: 60 additions & 0 deletions agents/conductors/batch/_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,17 @@ def tick(brief_path: Path, mind: Path, *, home: Path | None = None,
_drop_lock(slot)
_log(slot, now, result)
return result
if why.startswith("review-at") and (slot / DIGEST_MARKER).exists() and (
leases(slot) or _mind_writer.pending_ops(slot)):
if not _take_lock(slot, now):
return {"action": "busy", "reason": "another tick holds the lock"}
try:
result = late_sweep(brief_path, mind, slot, now, grace_s=grace_s,
agents=agents, tokens=tokens)
finally:
_drop_lock(slot)
_log(slot, now, result)
return result
return {"action": "idle", "reason": why}

(slot / "leases").mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -651,6 +662,55 @@ def _record_rel(brief_path: Path, mind: Path) -> str | None:
return None


LATE_HEADING = "### Late arrivals"


def late_sweep(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *,
grace_s: float = LEASE_GRACE_S, agents=None,
tokens=transcript_tokens) -> dict:
"""A closed shift whose digest is posted, with a worker still out or Mind
ops still queued (PyAutoBrain#594: a worker finished 12 minutes after
`review-at:` and its `.done` and ledger ops were stranded).

Reaps as a live tick does and commits the queued ops through the one Mind
writer, then names each late arrival in the record under `### Late
arrivals`. Never a spawn, a re-dispatch, a close-out or a second comment:
the grant ended at `review-at:`, so what arrives late waits for `/prm`."""
counters = read_counters(slot)
reaped = _reap(slot, counters, now, grace_s, agents, tokens)
counters["pending_redispatch"] = [] # the grant has ended: never re-dispatched
counters.setdefault("late", [])
first = not counters["late"] # the heading goes in once, with the first
rel = _record_rel(brief_path, mind)
lines = []
for e in reaped:
task = e["task"]
if e["event"] == "done":
urls = counters["outcomes"].get(task, {}).get("prs") or []
what = ", ".join(urls) or "finished, no PR or issue named in its .done"
elif e["event"] == "parked":
what = "parked: awaiting-input (blocked on a person)"
else:
what = "ended without a .done (crashed); not re-dispatched"
lines.append(f"- late: {task} — {what} (after review-at, {_iso(now)})")
counters["late"].append(task)
if rel is not None and lines:
head = f"\n{LATE_HEADING}\n" if first else ""
_mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR,
{"op": "append", "path": rel,
"text": head + "\n".join(lines) + "\n"})
_write_counters(slot, counters)
ledger = {"committed": None, "ops": 0}
if _mind_writer.pending_ops(slot):
try:
ledger = _mind_writer.commit_ledger(
slot, mind, f"shift {slot.name}: late arrivals after review-at")
except _mind_writer.MindWriteError as e:
ledger = {"committed": None, "error": str(e)}
return {"action": "late", "reaped": reaped, "late": lines,
"ledger": ledger}


def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *,
poster=None, health=None) -> dict:
"""Write the digest into the record and post it once on the brief's issue.
Expand Down
8 changes: 8 additions & 0 deletions agents/conductors/batch/worker_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"):

- Work only on {task_path}. The brief above is the launch; read it at the ship
step for its `heart-ack:` and `expected-effects:`.
- Never use the EnterWorktree tool. Your task worktree lives outside
`.claude/worktrees/`, so entering it raises a permission prompt that nobody
is here to answer and you stall (pilot live shift 1, PyAutoBrain#594). Work
in the worktree by absolute paths and `cd <worktree> && …` in Bash.
- If you take any decision the plan did not settle (decide-and-flag), label
the PR before you finish: `gh pr edit <url> --add-label decision-taken`.
Naming the decision in the PR body or your summary is not enough. The label
is what stops an unattended close-out from merging it.
- End at your deliverable: a PR, a posted verdict, or a park with a question
on the issue. Never arm anything that outlives your turn (no send_later,
ScheduleWakeup, CronCreate, RemoteTrigger or /loop) — the watcher keeps time.
Expand Down
99 changes: 99 additions & 0 deletions tests/test_orchestrator_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,3 +410,102 @@ def test_live_sandbox_worker():
finally:
subprocess.run(["claude", "stop", agent], capture_output=True, timeout=60)
subprocess.run(["claude", "rm", agent], capture_output=True, timeout=60)


# --- live-shift worker gaps (PyAutoBrain#594) ----------------------------------------

def test_the_worker_prompt_forbids_enterworktree_and_requires_the_decision_label(tmp_path):
prompt = orch.session_command("t1", "p.md", tmp_path / "shift.md",
tmp_path / "leases", "auto")[-1]
assert "Never use the EnterWorktree tool" in prompt
assert "--add-label decision-taken" in prompt


AFTER = NOW + _dt.timedelta(hours=3) # past review-at 11:30Z


def _closed_shift_with_a_late_worker(tmp_path):
"""A live shift whose digest is posted while one real worker is still out."""
mind, brief, home = _shift(tmp_path)
slot = orch.slot_dir(brief, home)
claude = FakeClaude()
_tick(brief, mind, home, NOW, claude)
(slot / orch.DIGEST_MARKER).write_text("{}")
return mind, brief, home, slot, claude


def test_a_late_finisher_is_reaped_after_review_at_and_nothing_starts(tmp_path):
mind, brief, home, slot, claude = _closed_shift_with_a_late_worker(tmp_path)
(slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n")
spawned = len(claude.calls)
r = orch.tick(brief, mind, home=home, now=AFTER, grace_s=0,
spawner=orch.RealSpawner(brief, "auto", run=claude),
agents=_agents({"t1": "done"}, slot), tokens=lambda s: 5)
assert r["action"] == "late"
assert r["reaped"][0] == {"task": "t1", "event": "done"}
assert r["late"][0].startswith("- late: t1 — https://github.com/o/r/pull/9 (after review-at")
c = orch.read_counters(slot)
assert c["outcomes"]["t1"]["prs"] == ["https://github.com/o/r/pull/9"]
assert c["late"] == ["t1"] and c["tokens"] == 5
assert len(claude.calls) == spawned # no spawn, no close-out
assert orch.leases(slot) == {}
# Nothing left: the closed shift is idle again.
r = orch.tick(brief, mind, home=home, now=AFTER, spawner=orch.FakeSpawner())
assert r["action"] == "idle" and "has passed" in r["reason"]


def test_a_late_crash_is_named_and_never_redispatched(tmp_path):
mind, brief, home, slot, claude = _closed_shift_with_a_late_worker(tmp_path)
spawned = len(claude.calls)
r = orch.tick(brief, mind, home=home, now=AFTER, grace_s=0,
spawner=orch.RealSpawner(brief, "auto", run=claude),
agents=_agents({"t1": "failed"}, slot))
assert r["action"] == "late" and r["reaped"][0]["event"] == "dead"
assert "crashed); not re-dispatched" in r["late"][0]
assert orch.read_counters(slot)["pending_redispatch"] == []
assert len(claude.calls) == spawned


def test_a_closed_shift_with_nothing_pending_stays_idle(tmp_path):
mind, brief, home = _shift(tmp_path)
slot = orch.slot_dir(brief, home)
(slot / "leases").mkdir(parents=True)
(slot / orch.DIGEST_MARKER).write_text("{}")
r = orch.tick(brief, mind, home=home, now=AFTER, spawner=orch.FakeSpawner())
assert r["action"] == "idle"


def test_a_late_arrival_lands_in_the_record_on_mind_main(tmp_path, monkeypatch):
import shutil
import test_orchestrator_digest as t
if not t.LEDGER_MERGE.is_file() or shutil.which("git") is None:
pytest.skip("needs git and PyAutoMind's scripts/ledger_merge.py")
monkeypatch.setattr(sys, "dont_write_bytecode", False)
bare = tmp_path / "remote.git"
t.git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare))
canon = tmp_path / "canon"
t.git(tmp_path, "clone", "-q", str(bare), str(canon))
t.git(canon, "config", "user.name", "Test")
t.git(canon, "config", "user.email", "test@example.invalid")
_, staged, _ = _shift(tmp_path / "seed")
shutil.copytree(tmp_path / "seed" / "mind" / "draft", canon / "draft")
(canon / "scripts").mkdir()
shutil.copy(t.LEDGER_MERGE, canon / "scripts" / "ledger_merge.py")
(canon / "batches").mkdir()
brief = canon / "batches" / "2026-11-04-am.md"
brief.write_text(staged.read_text())
t.git(canon, "add", "-A")
t.git(canon, "commit", "-q", "-m", "seed")
t.git(canon, "push", "-q", "origin", "HEAD:main")
home = tmp_path / "home"
slot = orch.slot_dir(brief, home)
claude = FakeClaude()
_tick(brief, canon, home, NOW, claude)
(slot / orch.DIGEST_MARKER).write_text("{}")
(slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n")
r = orch.tick(brief, canon, home=home, now=AFTER, grace_s=0,
spawner=orch.RealSpawner(brief, "auto", run=claude),
agents=_agents({"t1": "done"}, slot), tokens=lambda s: 0)
assert r["action"] == "late" and r["ledger"]["committed"], r
record = t.git(bare, "show", "main:batches/2026-11-04-am.md").stdout
assert "\n### Late arrivals\n- late: t1 — https://github.com/o/r/pull/9 (after review-at" in record
Loading