From 4cf96b0c3dff2cd01bb7267968a21f5615ac3110 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Wed, 18 Nov 2026 20:46:27 +0000 Subject: [PATCH] fix(batch): a shift worker's own claim update is not a conflict (#681) A drop-section paired with an append of the same task re-adding that ## slug to the same path is an update of the worker's claim, not a closing op: the drop applies directly before its append as one unit, guarded so main's section must be this shift's own (committed earlier this shift, or its session line names this slot's shift worker). A lone drop-section stays closing. Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 8 ++- agents/conductors/batch/_mind_writer.py | 77 ++++++++++++++++++++- agents/conductors/batch/_orchestrator.py | 2 +- tests/test_orchestrator_mind_writer.py | 87 ++++++++++++++++++++++++ 4 files changed, 170 insertions(+), 4 deletions(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index af7dfdc..e420790 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -420,7 +420,13 @@ when any op of that task was set aside for a human this shift, so Mind never records it shipped with a change missing. They apply as one group per task: if one fails for a human the group is rolled back and withheld; while a sibling op is *held* (retried) the group stays pending beside it; an op on a path the -group creates (an edit of the `complete/` record) is part of the group. Two +group creates (an edit of the `complete/` record) is part of the group. A +`drop-section` paired with an `append` of the same task re-adding that +`## slug` to the same path is not closing but an *update* of the worker's own +claim (2026-11-18, PyAutoBrain#681: a worker's PR-open claim update was set +aside as a conflict): the drop applies just before its append, as one unit, +and only when main's section is one this shift committed or its `- session:` +names this slot's shift worker — anyone else's is a conflict, set aside. Two limits: a `complete/` record committed in an earlier tick than a sibling that fails later stays on main (the NEEDS YOU line and the digest say "already on main"), and the block is sticky for the shift — a re-dispatched task's record diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index 1a4c0d1..ff6c54c 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -76,7 +76,12 @@ sibling op of that task was set aside for a human, this run or earlier in the shift (a group that fails part-way is rolled back first); while a sibling is *held* the group stays pending beside it. Mind never records a task -shipped while one of its changes is missing. An op that fails only because it is already true on main +shipped while one of its changes is missing. A `drop-section` paired with +an `append` of the same task re-adding that `## slug` to the same path is an +*update* of the task's own claim, not a close (PyAutoBrain#681): the drop +applies directly before its append, the two as one unit, and only when main's +section is this shift's own (`_own_section`) — else a conflict, set aside. +An op that fails only because it is already true on main (`MechanicalError`: an edit already applied, a write of the text the file has, a remove of a file that is gone) is set aside as `needs: mechanical` — a digest line, not a "needs you". `shift_ledger.py` refuses at queue time @@ -139,6 +144,9 @@ #: `lifecycle.py close` it did not run. QUEUE_RETIRED_BY = "retired by the shift close-out (queue-retire)" PUSH_TRIES = 3 +#: A claim's `- session:` naming a shift worker: `shift worker ()`, +#: the id a short one or a full session UUID (the orchestrator's own test). +SHIFT_WORKER_SESSION_RE = re.compile(r"^shift worker ([A-Za-z0-9_.-]+) \(([^()\s]+)\)$") LEDGER_DIR = "ledger" COMMITTED_DIR = "committed" #: Ops that could not apply (or were invalid), kept for the human with their @@ -678,6 +686,52 @@ def _new_sections(old: str, text: str, path: str, lm, return (pre + "".join(rest) if rest else ""), note +def _update_pairs(ops: list) -> dict: + """{append file: (drop file, drop op)} — each task's `drop-section` whose + `## slug` an `append` of the same task re-adds to the same path: an update + of its own claim (PyAutoBrain#681), not a closing op. A lone drop stays + closing.""" + pairs = {} + for f, op in ops: + if op.get("op") != "drop-section" or not op.get("task"): + continue + heading = f"## {op['section']}" + for g, other in ops: + if (g not in pairs and other.get("op") == "append" + and other.get("task") == op["task"] and other.get("path") == op["path"] + and any(ln.strip() == heading + for ln in str(other.get("text", "")).splitlines())): + pairs[g] = (f, op) + break + return pairs + + +def _own_section(tree: Path, op: dict, lm, ctx: dict) -> None: + """ConflictError unless main's `## section` (the one an update pair drops) + is this shift's own: exactly a section this shift committed earlier + (`ctx["prior"]`), or its `- session:` names this slot's shift worker. A + section that is not there is left to the drop's own error (#681).""" + target, heading = tree / op["path"], f"## {op['section']}" + if not target.is_file(): + return + body = dict(lm.split_entries(target.read_text(encoding="utf-8"))[1]).get(heading) + if body is None: + return + ours = {} + for p in ctx["prior"]: + if p.get("op") == "append" and p.get("path") == op["path"]: + ours.update(lm.split_entries(p.get("text") or "")[1]) + if ours.get(heading) == body: + return + for ln in body.splitlines(): + if ln.startswith("- session:"): + m = SHIFT_WORKER_SESSION_RE.match(ln[len("- session:"):].strip()) + if m and ctx.get("slot") and m.group(1) == ctx["slot"]: + return + raise ConflictError(f"drop-section: {heading} in {op['path']} is not this shift's " + "own claim — its update is a conflict") + + def record_key(text: str, key: str, value: str, after: tuple[str, ...] = ("issue", "review-at")) -> str: """`text` with one top-level `- key: value` line above the first `## ` @@ -987,7 +1041,7 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, if not files: return {"committed": None, "ops": 0, "tries": 0} lm = _ledger_merge(mind_repo) - ctx = {"own": set(own_tasks), "prior": committed_ops(slot)} + ctx = {"own": set(own_tasks), "prior": committed_ops(slot), "slot": Path(slot).name} ops, invalid, unready = [], {}, {} for f in files: try: @@ -1001,6 +1055,11 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, "held" if is_critical(op) else "set-aside", "; ".join(errs), NEEDS_HUMAN) continue ops.append((f, op)) + # A drop + append of the task's own `## slug` is an update, applied as + # one unit where the append stands (#681); the drop is not closing. + pairs = _update_pairs(ops) + paired = {f for f, _op in pairs.values()} + ops = [x for x in ops if x[0] not in paired] # A task's ops land together: its closing ops go last, grouped by task. creates: dict = {} for _f, op in ops: @@ -1036,6 +1095,20 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, if isinstance(task, str): blocked.setdefault(task, f.name) for f, op in ops: + if f in pairs: # an update of the task's own claim (#681) + unit = [pairs[f], (f, op)] + try: + _own_section(tree, pairs[f][1], lm, ctx) + except ConflictError as e: + failed[unit[0][0]] = ("conflict", str(e), NEEDS_HUMAN) + failed[f] = _withheld(op["task"], unit[0][0].name) + else: + notes += _apply_group(tree, op["task"], unit, lm, ctx, + failed, held, deferred) + for g, _op in unit: + if g in failed and failed[g][2] != NEEDS_MECHANICAL: + blocked.setdefault(op["task"], g.name) + continue where, out = _apply_one(tree, op, lm, ctx) if where == "ok": if out: diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 4e7f69d..7c08b27 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -1550,7 +1550,7 @@ def claimed_repos(sections: dict[str, dict]) -> dict[str, tuple[str, str]]: #: `worker_template.md` pins: `shift worker ()`. Anything #: else (a desktop session, a human who took the task over and rewrote the #: line, the free wording of the first shifts) is not resumed unattended. -SHIFT_WORKER_SESSION_RE = re.compile(r"^shift worker ([A-Za-z0-9_.-]+) \(([^()\s]+)\)$") +SHIFT_WORKER_SESSION_RE = _mind_writer.SHIFT_WORKER_SESSION_RE def shift_worker_slot(session: str) -> str: diff --git a/tests/test_orchestrator_mind_writer.py b/tests/test_orchestrator_mind_writer.py index 3cf2eb6..db95e1f 100644 --- a/tests/test_orchestrator_mind_writer.py +++ b/tests/test_orchestrator_mind_writer.py @@ -664,3 +664,90 @@ def test_shift_ledger_names_a_missing_mind_checkout_cleanly(tmp_path): mind_repo=tmp_path / "no-such-mind", worker=True) assert res.returncode == 2 and "Traceback" not in res.stderr assert "no-such-mind" in res.stderr + + +# --- A shift worker updating its own claim (PyAutoBrain#681) ------------------------ + +SLOT = "2026-11-18-pm2" +SESSION = "- session: shift worker {slot} (b53f7ee2-2b5d-47c1-9042-4f2098218a54)\n" + + +def _claim(status, slot=SLOT): + """The `## t1` claim a shift worker appends, as shift 2026-11-18-pm2's did.""" + return ("\n## t1\n- issue: https://example.invalid/issues/1\n" + SESSION.format(slot=slot) + + f"- status: {status}\n- prompt: active/t1.md\n") + + +def _update(slot, section="t1"): + """The worker's update at PR-open: drop its `## slug`, append it anew.""" + _q(slot, op="drop-section", path="active.md", task=section, section=section) + _q(slot, op="append", path="active.md", task=section, + text=_claim("library-shipped, awaiting-merge").replace("## t1", f"## {section}")) + + +def test_an_update_of_the_shifts_own_claim_commits(tmp_path, mind): + """The claim this shift committed earlier is replaced in place; nothing is + set aside, and a re-dispatch's repeat of the new claim is still skipped.""" + bare, canon, _ = mind + slot = tmp_path / SLOT + _q(slot, op="append", path="active.md", task="t1", text=_claim("in-progress")) + assert mw.commit_ledger(slot, canon, "claim")["committed"] + _update(slot) + res = mw.commit_ledger(slot, canon, "update") + assert res["committed"] and res["set_aside"] == [] and res["ops"] == 2 + active = _remote_tree(bare, "active.md").stdout + assert active.count("## t1") == 1 and "awaiting-merge" in active + assert "in-progress" not in active and "## t2" in active + assert mw.report(slot) == [] + _q(slot, op="append", path="active.md", task="t1", + text=_claim("library-shipped, awaiting-merge")) + res = mw.commit_ledger(slot, canon, "again", own_tasks={"t1"}) + assert res["set_aside"] == [] and res["skipped"] == [ + "append: ## t1 already in active.md from this shift's own claim — skipped"] + + +def test_an_update_of_a_claim_whose_session_names_this_slot_commits(tmp_path, mind): + """Main's section is not one this shift committed (rewritten since, or + from an earlier ledger), but its session line names this slot's worker.""" + bare, canon, other = mind + slot = tmp_path / SLOT + _push_from(other, "active.md", ACTIVE + _claim("in-progress"), "t1 claim") + _update(slot) + res = mw.commit_ledger(slot, canon, "update") + assert res["committed"] and res["set_aside"] == [] + active = _remote_tree(bare, "active.md").stdout + assert active.count("## t1") == 1 and "awaiting-merge" in active + + +@pytest.mark.parametrize("owner", ["other-slot", "human"]) +def test_an_update_of_someone_elses_claim_is_a_conflict(tmp_path, mind, owner): + bare, canon, other = mind + slot = tmp_path / SLOT + if owner == "other-slot": + _push_from(other, "active.md", ACTIVE + _claim("in-progress", slot="2026-11-18-am"), + "t1 claim by another shift") + section = "t1" + else: # the seed's `## t2`, written by a human, no session line + section = "t2" + before = _remote_tree(bare, "active.md").stdout + _update(slot, section) + res = mw.commit_ledger(slot, canon, "update") + by = {a["op"]: a for a in res["set_aside"]} + assert by["drop-section"]["kind"] == "conflict" and by["append"]["kind"] == "withheld" + assert "conflict" in by["drop-section"]["why"] + assert _remote_tree(bare, "active.md").stdout == before + + +def test_a_lone_drop_section_still_closes_and_is_withheld(tmp_path, mind): + """No matching append: the drop is closing as before — applied last, and + withheld with its task when a sibling op is set aside.""" + bare, canon, _ = mind + slot = tmp_path / SLOT + _q(slot, op="drop-section", path="active.md", task="t2", section="t2") + _q(slot, op="append", path="active.md", task="t2", text="\n## t9\n- issue: other\n") + _q(slot, op="edit", path="active/t2.md", task="t2", old="# nope\n", new="# t2!\n") + res = mw.commit_ledger(slot, canon, "lone drop") + by = {a["op"]: a for a in res["set_aside"]} + assert by["edit"]["kind"] == "set-aside" and by["drop-section"]["kind"] == "withheld" + active = _remote_tree(bare, "active.md").stdout + assert "## t2" in active and "## t9" in active