From 225373419f44af8d5ab99e593c02bb4589f93585 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 13:42:34 +0000 Subject: [PATCH 1/3] fix: shift ledger edit op; hold a task's completion on a set-aside MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Shift 2026-11-16-pm: a worker's `write` edits to existing Mind drafts were set aside while its complete/ record committed, so Mind recorded the task shipped with the drafts unchanged; five workers' calibration rows could not be queued (table-append never set its heading or row). - _mind_writer: `edit` op (expected old text exactly once; MechanicalError when already applied); write of identical text and remove of a missing file are mechanical; ops carry `task`; closing ops (complete/ write, drop-section, active/ remove, queue/question retire) apply last and are `withheld` when a sibling op was set aside for a human, this run or earlier; queue_refusals checks write/edit/table-append against Mind origin/main and the queued ops (no fetch; fails open); a tagged table-append is not critical. - shift_ledger: --task (required for a shift worker), edit --old/--new(-file), table-append heading/row/--unique, Mind lookup --mind → $PYAUTO_MIND → sibling checkout; refused ops are not queued. - _events: mechanical set-asides are no NEEDS YOU; human ones are one event per task. _digest: withheld and mechanical wording. - Templates and docs: --task, write creates/edit changes, edits first and the complete record last, the `## Calibration runs` table-append. Refs #660 Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 20 +- agents/conductors/batch/_digest.py | 10 +- agents/conductors/batch/_events.py | 32 ++- agents/conductors/batch/_mind_writer.py | 243 +++++++++++++++++-- agents/conductors/batch/closeout_template.md | 16 +- agents/conductors/batch/worker_template.md | 10 +- bin/shift_ledger.py | 70 +++++- bin/worker_git_hooks/pre-commit | 2 +- skills/ship_library/reference.md | 5 +- skills/ship_library/ship_library.md | 2 +- skills/ship_workspace/ship_workspace.md | 2 +- tests/test_orchestrator_dispatch.py | 7 +- tests/test_orchestrator_mind_writer.py | 212 +++++++++++++++- 13 files changed, 568 insertions(+), 63 deletions(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 4986f481..7545f2f2 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -326,8 +326,14 @@ a failed launch is one `launch-failed` record per task) with its blocked minutes **One Mind writer (phase 3c).** Workers never commit to PyAutoMind. Each Mind change — the `active.md` claim, the `draft/ → active/` move, the close-out — is queued as an op file in `/ledger/` by `bin/shift_ledger.py` -(`append | write | move | remove | drop-section`; every path must be *ledger* -by PyAutoMind's own `scripts/ledger_merge.py`, default deny). Each tick, after +(`--task ` then `append | write | edit | move | remove | drop-section | +table-append | set-header | queue-retire`; every path must be *ledger* by +PyAutoMind's own `scripts/ledger_merge.py`, default deny). `write` only +creates; `edit` replaces an expected old text that must appear exactly once, +so it never clobbers a concurrent change. `shift_ledger.py` refuses at queue +time a `write` to a path already on Mind `origin/main` (or created by a queued +op), an `edit` whose base is not there, and a `table-append` whose `## ` +heading or table is missing, so the worker can switch while it runs. Each tick, after the reap, `_mind_writer.commit_ledger` applies all pending ops in a temporary detached worktree on `origin/main`, commits once and pushes; if `main` moved it replays the ops on the new `origin/main` (up to three tries). It never resets, @@ -336,7 +342,15 @@ Committed op files move to `ledger/committed/`. One bad op never strands the rest (#632): a re-dispatched task's repeat of a claim this shift already committed, with main's content matching it, is a skipped note; the same shape from anyone else is a conflict, set aside; any other worker op that is invalid -or cannot apply is set aside in `ledger/set_aside/` — and the rest commit. The +or cannot apply is set aside in `ledger/set_aside/` — and the rest commit. A +task's ops land together (#660): its closing ops (the `complete/` record, +`drop-section`, the `active/` prompt's `remove`, `queue-retire`, +`question-retire`) apply last, and are *withheld* — set aside, not retried — +when any op of that task was set aside for a human this shift, so Mind never +records it shipped with a change missing. An op that is already true on main +(an edit already applied, a write of the same text, a remove of a gone file) is +set aside as *mechanical*: a digest line, never a NEEDS YOU; a task's human +set-asides are one NEEDS YOU event naming the task. The watcher's own ops (record appends, pilot row, live line, stage-2 rows) are never set aside: they are held pending and retried. Every note, set-aside, conflict and hold goes to `ledger/report.jsonl`, into the digest, and after `review-at:` diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 16faef1f..5c9c2bb2 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -585,14 +585,20 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, "set-aside": "warning: Mind ledger op set aside, not committed", "conflict": "warning: CONFLICT — Mind ledger op set aside, not committed", "held": "warning: Mind ledger op held pending, retried every tick", + "withheld": "warning: Mind ledger op withheld with its task, not committed", + # A set-aside whose `needs` is mechanical (#660): already true on main. + "mechanical": "note: Mind ledger op set aside (mechanical — already true on main, " + "no action)", } def report_line(e: dict) -> str: """One `ledger/report.jsonl` entry as a digest or late line.""" - head = _REPORT_WORDS.get(e.get("kind"), f"warning: Mind ledger {e.get('kind')}") + kind = "mechanical" if (e.get("kind") == "set-aside" + and e.get("needs") == "mechanical") else e.get("kind") + head = _REPORT_WORDS.get(kind, f"warning: Mind ledger {e.get('kind')}") where = f" (`ledger/set_aside/{e.get('file')}`)" if e.get("kind") in ( - "set-aside", "conflict") else "" + "set-aside", "conflict", "withheld") else "" return f"- {head} — {e.get('op') or '?'} {e.get('path') or '?'}: {e.get('why')}{where}" diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index 99351126..ad7a0f9d 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -362,13 +362,31 @@ def _impaired(b: _Batch, result: dict) -> None: why = str(ledger["error"])[:160] b.add("impaired", f"impaired:ledger-error:{why[:80]}", f"Mind write failed: {why}.", needs_you=True) - for word, items in (("set aside", ledger.get("set_aside")), ("held", ledger.get("held"))): - for x in items or []: - op = x.get("op") if isinstance(x, dict) else str(x) - why = (x.get("why") if isinstance(x, dict) else "") or "?" - where = x.get("file") if isinstance(x, dict) else "" - b.add("impaired", f"impaired:ledger:{word}:{where or op}:{str(why)[:60]}", - f"Mind write {word}: {op}, {why}.", needs_you=True) + # A mechanical set-aside (already true on main) is a digest line only; + # a worker's human set-asides are one NEEDS YOU per task (#660). + by_task: dict = {} + per_op = [] + for x in ledger.get("set_aside") or []: + if isinstance(x, dict) and x.get("needs") == "mechanical": + continue + if isinstance(x, dict) and isinstance(x.get("task"), str) and x["task"]: + by_task.setdefault(x["task"], []).append(x) + else: + per_op.append(("set aside", x)) + for task, xs in sorted(by_task.items()): + paths = ", ".join(sorted({str(x.get("path") or x.get("op") or "?") for x in xs})) + n = len(xs) + b.add("impaired", f"impaired:ledger:task:{task}", + f"Mind write set aside for `{task}`: {n} op{'s' if n != 1 else ''} " + f"({paths}); its completion record is held — not shipped to Mind.", + needs_you=True, task=task) + per_op += [("held", x) for x in ledger.get("held") or []] + for word, x in per_op: + op = x.get("op") if isinstance(x, dict) else str(x) + why = (x.get("why") if isinstance(x, dict) else "") or "?" + where = x.get("file") if isinstance(x, dict) else "" + b.add("impaired", f"impaired:ledger:{word}:{where or op}:{str(why)[:60]}", + f"Mind write {word}: {op}, {why}.", needs_you=True) def _late(b: _Batch, result: dict) -> None: diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index 662abbd2..2ff14317 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -13,6 +13,7 @@ {"op": "append", "path": "active.md", "text": "..."} {"op": "write", "path": "complete/2026/11/x.md", "text": "..."} # must not exist + {"op": "edit", "path": "draft/a/b/x.md", "old": "...", "new": "..."} # must exist {"op": "move", "path": "draft/a/b/x.md", "to": "active/x.md"} {"op": "remove", "path": "active/x.md"} {"op": "drop-section", "path": "active.md", "section": "task-name"} @@ -61,6 +62,23 @@ The watcher writes the dashboard's `- live:` status line this way (PyAutoBrain#622); a record no longer on main is skipped, like `set-header`. +`write` only creates; `edit` changes a file that exists, replacing `old`, +which must appear in it exactly once, with `new` — an expected-base check, so +an edit never clobbers a concurrent change (M3.6d, PyAutoBrain#660: shift +2026-11-16-pm's `write` edits to existing drafts were set aside). + +A worker's ops carry their `task` (`shift_ledger.py --task`). A task's +*closing* ops (`_closing`: its `complete/` record, `drop-section`, the +`active/` prompt's `remove`, `queue-retire`, `question-retire`) apply after +every other op, and are *withheld* — set aside with the task, never retried — +when any sibling op of that task was set aside for a human, this run or +earlier in the shift: 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 +(`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 +what would fail (`queue_refusals`), so the worker can still switch. + `set-header` sets one `Key: value` line in a prompt's header block (replacing the key's line if present) — how a shift worker records the premise check's `Verified:` stamp (`batch premise --record`) without touching the file itself. @@ -101,9 +119,13 @@ import types from pathlib import Path -OPS = ("append", "write", "move", "remove", "drop-section", "table-append", +OPS = ("append", "write", "edit", "move", "remove", "drop-section", "table-append", "set-header", "jsonl-upsert", "table-upsert", "record-key", "queue-retire", "question-add", "question-retire") +#: A worker's task name, as `shift_ledger.py --task` tags its ops. +TASK_RE = re.compile(r"[A-Za-z0-9][\w.-]*") +#: The `needs` of a set-aside op: already true on main, or the human's call. +NEEDS_MECHANICAL, NEEDS_HUMAN = "mechanical", "human" #: The keys a `question-add` entry carries; all strings but `options`. QUESTION_KEYS = ("task", "issue", "kind", "ask", "options", "shift", "asked", "worker") #: What a watcher-run queue retirement says in the footer, in place of the @@ -129,9 +151,27 @@ def is_critical(op) -> bool: - return isinstance(op, dict) and ( - op.get("op") in CRITICAL_KINDS - or (op.get("op") == "append" and str(op.get("path", "")).startswith("batches/"))) + """A watcher op (never set aside, held pending). A worker's own + `table-append` (its calibration row, tagged with its `task`) is not: a + bad one is set aside and told, never retried every tick (#660).""" + if not isinstance(op, dict): + return False + if op.get("op") == "table-append" and op.get("task"): + return False + return (op.get("op") in CRITICAL_KINDS + or (op.get("op") == "append" and str(op.get("path", "")).startswith("batches/"))) + + +def _closing(op) -> bool: + """A tagged op that records its task done: the `complete/` record, the + `## slug` drop, the `active/` prompt's removal, the queue and questions + retirements. Applied last, and withheld when a sibling was set aside.""" + if not isinstance(op, dict) or not op.get("task"): + return False + kind, path = op.get("op"), str(op.get("path", "")) + return ((kind == "write" and path.startswith("complete/")) + or (kind == "remove" and path.startswith("active/")) + or kind in ("drop-section", "queue-retire", "question-retire")) class ConflictError(RuntimeError): @@ -142,6 +182,12 @@ class MindWriteError(RuntimeError): pass +class MechanicalError(MindWriteError): + """The op is already true on main (an edit already applied, a write of the + text the file already has, a remove of a file that is gone): set aside + with `needs: mechanical` — a digest line, nothing for the human.""" + + class GoneError(MindWriteError): """The op's subject is gone from Mind main (a question whose prompt was completed or retired): set aside even when the op is critical.""" @@ -186,6 +232,17 @@ def validate_op(op: dict, lm) -> list[str]: errs.append(f"{kind}: a path is missing") elif p.startswith("/") or not lm.is_ledger_path(p): errs.append(f"{kind}: {p} is not a ledger path (scripts/ledger_merge.py)") + if "task" in op and (not isinstance(op["task"], str) + or not TASK_RE.fullmatch(op["task"])): + errs.append(f"{kind}: task must be one task name ([A-Za-z0-9][\\w.-]*)") + if kind == "edit": + old, new = op.get("old"), op.get("new") + if not isinstance(old, str) or not old: + errs.append("edit: old (the expected base text) is missing") + if not isinstance(new, str): + errs.append("edit: new is missing") + elif new == old: + errs.append("edit: new is the same as old — nothing to change") if kind in ("append", "write") and not isinstance(op.get("text"), str): errs.append(f"{kind}: text is missing") elif kind == "append" and op.get("path") == "active.md": @@ -317,9 +374,18 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: return note elif kind == "write": if target.exists(): - raise MindWriteError(f"write: {op['path']} already exists") + if target.read_text(encoding="utf-8") == op["text"]: + raise MechanicalError(f"write: {op['path']} already has this text on main") + raise MindWriteError(f"write: {op['path']} already exists — `write` only " + "creates; `edit` changes an existing file") target.parent.mkdir(parents=True, exist_ok=True) target.write_text(op["text"], encoding="utf-8") + elif kind == "edit": + if not target.exists(): + raise MindWriteError(f"edit: {op['path']} does not exist on main") + text = target.read_text(encoding="utf-8") + target.write_text(edit_text(text, op["path"], op["old"], op["new"]), + encoding="utf-8") elif kind == "move": dest = tree / op["to"] if not target.exists() and dest.exists(): @@ -341,7 +407,7 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: _git(tree, "mv", op["path"], op["to"]) elif kind == "remove": if not target.exists(): - raise MindWriteError(f"remove: {op['path']} does not exist") + raise MechanicalError(f"remove: {op['path']} does not exist (already gone)") _git(tree, "rm", "-q", op["path"]) elif kind == "drop-section": preamble, entries = lm.split_entries(target.read_text(encoding="utf-8")) @@ -427,6 +493,101 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: encoding="utf-8") +def edit_text(text: str, path: str, old: str, new: str) -> str: + """`text` with its one `old` replaced by `new`. `MechanicalError` when the + edit is already there (`new` present and every `old` inside it); + `MindWriteError` when `old` is not there exactly once (the base moved).""" + n, done = text.count(old), text.count(new) + if done and n == done * new.count(old): + raise MechanicalError(f"edit: {path} already has the new text on main") + if n != 1: + raise MindWriteError(f"edit: expected base not found in {path}" if not n else + f"edit: expected base ambiguous in {path} ({n} matches)") + return text.replace(old, new, 1) + + +def _main_text(mind: Path, path: str, ref: str = "origin/main") -> str | None: + """`path` as Mind's `origin/main` has it (no fetch: the writer fetches + each tick); None when it is not there. Raises MindWriteError when git + cannot read the ref at all.""" + if _git(Path(mind), "rev-parse", "--verify", "-q", ref, check=False).returncode: + raise MindWriteError(f"no {ref} in {mind}") + res = _git(Path(mind), "show", f"{ref}:{path}", check=False) + return res.stdout if res.returncode == 0 else None + + +def _ledger_ops(ledger_dir: Path) -> list[dict]: + """This shift's committed then pending ops, in order.""" + d = Path(ledger_dir) + files = sorted((d / COMMITTED_DIR).glob("*.json")) + sorted(d.glob("*.json")) + return [op for f in files if (op := _op_of(f))] + + +def _expected(mind: Path, path: str, ops: list[dict]) -> str | None: + """`path` once this shift's queued ops apply over origin/main: what a new + op on it will meet (a `draft/ → active/` move, then an edit of it).""" + state: dict = {} + + def get(p): + if p not in state: + state[p] = _main_text(mind, p) + return state[p] + + for o in ops: + kind, p = o.get("op"), o.get("path") + if not isinstance(p, str): + continue + if kind == "write" and isinstance(o.get("text"), str): + state[p] = o["text"] + elif kind == "remove": + state[p] = None + elif kind == "move" and isinstance(o.get("to"), str) and get(p) is not None: + state[o["to"]], state[p] = get(p), None + elif kind == "edit" and get(p) is not None: + try: + state[p] = edit_text(get(p), p, o.get("old") or "", o.get("new") or "") + except MindWriteError: + pass # already applied, or will be set aside: main's text stands + return get(path) + + +def queue_refusals(mind: Path, op: dict, ledger_dir: Path) -> list[str]: + """Why `shift_ledger.py` refuses to queue `op`, checked against Mind + `origin/main` and this shift's queued ops — so the worker, still running, + can switch (#660). Empty when it may be queued, and when git cannot be + read: then apply time is the backstop.""" + kind, path = op.get("op"), op.get("path") + if kind not in ("write", "edit", "table-append") or not isinstance(path, str): + return [] + try: + text = _expected(Path(mind), path, _ledger_ops(ledger_dir)) + except MindWriteError: + return [] + if kind == "write" and text is not None: + if text == op.get("text"): + return [] # already true: set aside as mechanical, a note + return [f"write: {path} already exists on Mind origin/main (or a queued op " + "creates it) — use `edit` to change it (`write` only creates)"] + if kind == "edit": + if text is None: + return [f"edit: {path} is not on Mind origin/main — use `write` to create it"] + try: + edit_text(text, path, op.get("old") or "", op.get("new") or "") + except MechanicalError as e: + return [f"{e} — nothing to queue"] + except MindWriteError as e: + return [f"{e} — `old` must appear exactly once in {path} as it is on " + "Mind origin/main"] + if kind == "table-append": + if text is None: + return [f"table-append: {path} is not on Mind origin/main"] + try: + table_append(text, str(op.get("heading", "")), str(op.get("row", ""))) + except MindWriteError as e: + return [f"{e} in {path} on Mind origin/main"] + return [] + + def _mind_module(tree: Path, name: str, deps: tuple = ()): """A PyAutoMind `scripts/.py`, compiled from `tree` (the temporary worktree on origin/main) as `_ledger_merge` compiles its own: no import, @@ -671,14 +832,19 @@ def pending_ops(slot: Path) -> list[Path]: return sorted(f for f in d.glob("*.json")) if d.is_dir() else [] -def _set_aside(slot: Path, f: Path, why: str) -> dict: - """Move one op file out of the way with its reason; returns its record.""" +def _set_aside(slot: Path, f: Path, why: str, needs: str = NEEDS_HUMAN) -> dict: + """Move one op file out of the way with its reason; returns its record, + with the op's `task` (when tagged) and whose move it is (`needs`).""" d = Path(slot) / LEDGER_DIR / SET_ASIDE_DIR d.mkdir(parents=True, exist_ok=True) op = _op_of(f) (d / (f.name + ".why")).write_text(why + "\n", encoding="utf-8") f.replace(d / f.name) - return {"file": f.name, "op": op.get("op"), "path": op.get("path"), "why": why} + out = {"file": f.name, "op": op.get("op"), "path": op.get("path"), "why": why, + "needs": needs} + if isinstance(op.get("task"), str): + out["task"] = op["task"] + return out def _op_of(f: Path) -> dict: @@ -691,7 +857,8 @@ def _op_of(f: Path) -> dict: def report(slot: Path) -> list[dict]: """Every entry of `ledger/report.jsonl`, oldest first: {kind: skipped | - set-aside | conflict | held, file, op, path, why}.""" + set-aside | conflict | withheld | held, file, op, path, why, and for a + set-aside op its `needs` (mechanical | human) and `task` when tagged}.""" f = Path(slot) / LEDGER_DIR / REPORT_FILE out = [] for line in (f.read_text(encoding="utf-8").splitlines() if f.is_file() else ()): @@ -724,12 +891,16 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, """Commit every pending op in `/ledger/` to PyAutoMind as one commit. Returns {"committed": sha | None, "ops": n, "tries": k, "skipped": notes, - "set_aside": [{file, op, path, why, kind}], "held": [...]}. `own_tasks` + "set_aside": [{file, op, path, why, kind, needs, task?}], "held": [...]}. `own_tasks` are the tasks this shift re-dispatched: only their repeated claims may be skipped as already done (#632 review). A worker op that is invalid or cannot apply is set aside (a claim already on main from someone else as a `conflict`); a critical op is held pending instead. Only a push rejected `PUSH_TRIES` times raises, with every op left pending. + + A task's closing ops (`_closing`) apply after every other op; when one of + its ops was set aside for a human (this run or in an earlier `report`) or + is in conflict, they are `withheld` — set aside with it, not retried. """ mind_repo = Path(mind_repo) files = pending_ops(slot) @@ -742,15 +913,22 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, try: op = json.loads(f.read_text(encoding="utf-8")) except ValueError as e: - invalid[f] = ("set-aside", f"not JSON ({e})") + invalid[f] = ("set-aside", f"not JSON ({e})", NEEDS_HUMAN) continue errs = validate_op(op, lm) if isinstance(op, dict) else ["not a JSON object"] if errs: (unready if is_critical(op) else invalid)[f] = ( - "held" if is_critical(op) else "set-aside", "; ".join(errs)) + "held" if is_critical(op) else "set-aside", "; ".join(errs), NEEDS_HUMAN) continue ops.append((f, op)) - seen_held = {(e.get("file"), e.get("kind")) for e in report(slot)} + # A task's ops land together: its closing ops go last (stable). + ops = [x for x in ops if not _closing(x[1])] + [x for x in ops if _closing(x[1])] + earlier = report(slot) + seen_held = {(e.get("file"), e.get("kind")) for e in earlier} + blocked_before = {e["task"]: e.get("file") for e in earlier + if isinstance(e.get("task"), str) + and e.get("kind") in ("set-aside", "conflict", "withheld") + and e.get("needs") != NEEDS_MECHANICAL} for attempt in range(1, PUSH_TRIES + 1): fetch(mind_repo, remote, branch) @@ -760,23 +938,40 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, _git(mind_repo, "worktree", "add", "-q", "--detach", str(tree), f"{remote}/{branch}") notes, failed, held = [], dict(invalid), dict(unready) + blocked = dict(blocked_before) + for f in invalid: + task = _op_of(f).get("task") + if isinstance(task, str): + blocked.setdefault(task, f.name) for f, op in ops: + task = op.get("task") + if _closing(op) and task in blocked: + failed[f] = ("withheld", f"{task}: held with its task — " + f"{blocked[task]} set aside; not recorded shipped", + NEEDS_HUMAN) + continue try: note = apply_op(tree, op, lm, ctx) except ConflictError as e: (held if is_critical(op) else failed)[f] = ( - "held" if is_critical(op) else "conflict", str(e)) - continue + "held" if is_critical(op) else "conflict", str(e), NEEDS_HUMAN) except GoneError as e: - failed[f] = ("set-aside", str(e)) - continue + failed[f] = ("set-aside", str(e), NEEDS_HUMAN) + except MechanicalError as e: + (held if is_critical(op) else failed)[f] = ( + "held" if is_critical(op) else "set-aside", str(e), + NEEDS_MECHANICAL) except (MindWriteError, OSError, KeyError, TypeError, ValueError) as e: (held if is_critical(op) else failed)[f] = ( "held" if is_critical(op) else "set-aside", - str(e) or type(e).__name__) + str(e) or type(e).__name__, NEEDS_HUMAN) + else: + if note: + notes.append((f, op, note)) continue - if note: - notes.append((f, op, note)) + if f in failed and failed[f][2] != NEEDS_MECHANICAL \ + and isinstance(task, str): + blocked.setdefault(task, f.name) _git(tree, "add", "-A") if not _git(tree, "status", "--porcelain").stdout.strip(): sha = None # every op was already true on main (or set aside) @@ -787,11 +982,11 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, if pushed.returncode != 0: continue # main moved: replay the ops on the new origin/main aside = [] - for f, (kind, why) in sorted(failed.items()): - aside.append({**_set_aside(slot, f, why), "kind": kind}) + for f, (kind, why, needs) in sorted(failed.items()): + aside.append({**_set_aside(slot, f, why, needs), "kind": kind}) held_out = [{"file": f.name, "op": _op_of(f).get("op"), "path": _op_of(f).get("path"), "why": why, "kind": "held"} - for f, (_k, why) in sorted(held.items())] + for f, (_k, why, _n) in sorted(held.items())] _report(slot, [{"kind": "skipped", "file": f.name, "op": op.get("op"), "path": op.get("path"), "why": n} for f, op, n in notes] + aside + [h for h in held_out if (h["file"], "held") not in seen_held]) diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index c4d53433..2b5ecadc 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -53,12 +53,18 @@ outcome — the human merges by `/prm` at check-in. 6. If everything passed, use the prm skill on {pr_url}: the full close-out, judged exactly as a human-typed `/prm`. Never commit to PyAutoMind yourself — a hook refuses it; queue each Mind change with - `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in - {ledger_dir}/) and the orchestrator commits them. With the complete - record, also retire the task's `queue.md` entry, as `lifecycle.py close` - does (it is silent when there is none): + `{shift_ledger} --task {task} append|write|edit|move|remove|drop-section ...` + (ops land in {ledger_dir}/) and the orchestrator commits them. `write` + only creates a file; change one that exists with + `{shift_ledger} --task {task} edit --old-file --new-file ` + (`--old` must appear exactly once in it on Mind main). Queue every edit + first and the complete record last: if any op of the task is set aside, + its record is held, not recorded shipped. A refused op is not queued; fix + it and queue it again. With the complete record, also retire the task's + `queue.md` entry, as `lifecycle.py close` does (it is silent when there is + none): - {shift_ledger} queue-retire queue.md --text "{pr_url} → ()" + {shift_ledger} --task {task} queue-retire queue.md --text "{pr_url} → ()" Do **not** append the Shadow-window row: the watcher writes the stage-2 row from your verdict. diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index a4dde44f..2b5c2faa 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -50,9 +50,17 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): session that runs the witness and merges, or refuses (AUTONOMY.md "Unattended `glance` merges"). A `notify` task merges in-turn as usual. - Never commit to PyAutoMind yourself — a hook refuses it. Queue each Mind - change with `{shift_ledger} append|write|move|remove|drop-section ...` + change with `{shift_ledger} --task {task} append|write|edit|move|remove|drop-section ...` (ops land in {ledger_dir}/) and the orchestrator commits them. This covers your `active.md` claim, the `draft/ → active/` move and your close-out. + `write` only creates a file; to change one that exists, use + `{shift_ledger} --task {task} edit --old-file --new-file ` + (`--old` must appear exactly once in the file as it is on Mind main). Queue + your edits first and your `complete/` record last: if any op of yours is + set aside, the record is held and the task is not recorded shipped. A + refused op is not queued; read why, fix it and queue it again. Your + calibration row is + `{shift_ledger} --task {task} table-append autonomy_log.md "## Calibration runs" --text "| … |"`. Your claim's session line is exactly `- session: shift worker ()`, `` being the brief file's name without `.md`: after the human answers a question you diff --git a/bin/shift_ledger.py b/bin/shift_ledger.py index e11e8e0f..bbb3fc01 100755 --- a/bin/shift_ledger.py +++ b/bin/shift_ledger.py @@ -5,14 +5,24 @@ shift"); it writes one op file per change here and the orchestrator commits them all from a temporary worktree. Paths are PyAutoMind-relative and must be ledger paths (`draft/`, `active/`, `complete/`, `batches/`, the registries). +A shift worker names its task on every op (`--task`): a task's ops land +together, and its completion record is held while any of them is set aside. - shift_ledger.py append active.md --text-file entry.md - shift_ledger.py write complete/2026/11/x.md --text-file record.md - shift_ledger.py move draft/feature/x/y.md active/y.md - shift_ledger.py remove active/y.md - shift_ledger.py drop-section active.md my-task - shift_ledger.py set-header draft/x/y.md Verified --text "2026-11-12 abc1234 (Repo)" - shift_ledger.py queue-retire queue.md y.md --text " → complete/2026/11/y.md (2026-11-14)" + shift_ledger.py --task T append active.md --text-file entry.md + shift_ledger.py --task T write complete/2026/11/x.md --text-file record.md # creates only + shift_ledger.py --task T edit draft/feature/x/y.md --old-file was.txt --new-file now.txt + shift_ledger.py --task T move draft/feature/x/y.md active/y.md + shift_ledger.py --task T remove active/y.md + shift_ledger.py --task T drop-section active.md my-task + shift_ledger.py --task T set-header draft/x/y.md Verified --text "2026-11-12 abc1234 (Repo)" + shift_ledger.py --task T table-append autonomy_log.md "## Calibration runs" --text "| … |" + shift_ledger.py --task T queue-retire queue.md y.md --text " → complete/2026/11/y.md (2026-11-14)" + +`write` refuses a path that already exists; `edit` replaces `--old`, which must +appear exactly once in the file as it is on Mind origin/main, with `--new`. +Queue edits first and the complete record last. Each op is checked against +Mind `origin/main` before it is queued (`--mind`, else `$PYAUTO_MIND`, else +the PyAutoMind checkout beside this Brain); a refused op is not queued. The ledger directory is `$PYAUTO_SHIFT_LEDGER_DIR` (set for every worker). """ @@ -26,15 +36,37 @@ import _mind_writer as mw # noqa: E402 +def _mind(given) -> Path | None: + """The Mind checkout to check ops against: `--mind`, `$PYAUTO_MIND`, else + the PyAutoMind beside this Brain (organs layout) when it has the script.""" + if given: + return Path(given) + sibling = Path(__file__).resolve().parents[2] / "PyAutoMind" + return sibling if (sibling / "scripts" / "ledger_merge.py").is_file() else None + + +def _text(inline, path): + return path.read_text(encoding="utf-8") if path else inline + + def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="shift_ledger", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("op", choices=mw.OPS) ap.add_argument("path") ap.add_argument("arg", nargs="?", help="move: destination; drop-section: section; " - "set-header: the header key; queue-retire: the prompt file name") + "set-header: the header key; queue-retire: the prompt file name; " + "table-append: the `## ` heading of the table") + ap.add_argument("--task", help="the task this op belongs to (required for a shift worker)") ap.add_argument("--text-file", type=Path) ap.add_argument("--text") + ap.add_argument("--old", help="edit: the exact text to replace (must appear once)") + ap.add_argument("--old-file", type=Path) + ap.add_argument("--new", help="edit: the text to put in its place") + ap.add_argument("--new-file", type=Path) + ap.add_argument("--unique", nargs="?", const=True, + help="table-append: skip if a row under the heading already holds " + "this text (bare: the row itself)") ap.add_argument("--mind", type=Path, default=os.environ.get("PYAUTO_MIND"), help="PyAutoMind checkout to validate paths against (read only)") a = ap.parse_args(argv) @@ -43,7 +75,14 @@ def main(argv=None) -> int: print("shift_ledger: PYAUTO_SHIFT_LEDGER_DIR is not set — this is for " "shift workers only", file=sys.stderr) return 2 + if not a.task and os.environ.get("PYAUTO_SHIFT_WORKER") == "1": + print("shift_ledger: refused — a shift worker names its task on every op: " + f"`shift_ledger.py --task {a.op} {a.path} …` (the task " + "name your brief gave you), so its ops land together", file=sys.stderr) + return 2 op = {"op": a.op, "path": a.path} + if a.task: + op["task"] = a.task if a.op == "move": op["to"] = a.arg if a.op == "drop-section": @@ -53,9 +92,18 @@ def main(argv=None) -> int: if a.op == "queue-retire": op["prompt"], op["shipped_as"] = a.arg, (a.text or "") if a.op in ("append", "write"): - op["text"] = a.text_file.read_text(encoding="utf-8") if a.text_file else (a.text or "") - if a.mind: - errs = mw.validate_op(op, mw._ledger_merge(a.mind)) + op["text"] = _text(a.text or "", a.text_file) + if a.op == "edit": + op["old"], op["new"] = _text(a.old, a.old_file), _text(a.new, a.new_file) + if a.op == "table-append": + op["heading"] = a.arg + op["row"] = (_text(a.text, a.text_file) or "").rstrip("\n") + if a.unique: + op["unique"] = op["row"] if a.unique is True else a.unique + mind = _mind(a.mind) + if mind: + errs = mw.validate_op(op, mw._ledger_merge(mind)) + errs = errs or mw.queue_refusals(mind, op, Path(ledger)) if errs: print("shift_ledger: refused — " + "; ".join(errs), file=sys.stderr) return 1 diff --git a/bin/worker_git_hooks/pre-commit b/bin/worker_git_hooks/pre-commit index b3efc6cf..62604026 100755 --- a/bin/worker_git_hooks/pre-commit +++ b/bin/worker_git_hooks/pre-commit @@ -10,7 +10,7 @@ if [ "${PYAUTO_SHIFT_WORKER:-}" = "1" ]; then case "$origin" in */PyAutoMind|*/PyAutoMind.git|*/PyAutoMind/) echo "pre-commit: shift workers never commit to PyAutoMind — hand the change to the orchestrator with" >&2 - echo " bin/shift_ledger.py append|write|move|remove|drop-section ... (ledger: \$PYAUTO_SHIFT_LEDGER_DIR)" >&2 + echo " bin/shift_ledger.py --task append|write|edit|move|remove|drop-section ... (ledger: \$PYAUTO_SHIFT_LEDGER_DIR)" >&2 exit 1 ;; esac fi diff --git a/skills/ship_library/reference.md b/skills/ship_library/reference.md index fde8dcb3..c3fab2d1 100644 --- a/skills/ship_library/reference.md +++ b/skills/ship_library/reference.md @@ -79,8 +79,9 @@ human's merge decision) and push Mind with **Which table.** The calibration row goes in the **first** table of that file — the five-cell `| date | task | effective level | gates | outcome |` -table under the top heading — as the last row of its final segment, in date -order. It never goes at the end of the file: the table that sits there is the +table under the `## Calibration runs` heading — as the last row of its final +segment, in date order. A shift worker queues it as +`shift_ledger.py --task table-append autonomy_log.md "## Calibration runs" --text "| … |"`. It never goes at the end of the file: the table that sits there is the **Shadow window** (`## Shadow window`), which is the close-out's alone, tier-`glance` only (tier-`notify` until 2026-10-02), appended at close-out with a fixed `human action` vocabulary. Six diff --git a/skills/ship_library/ship_library.md b/skills/ship_library/ship_library.md index fcec2206..70c609ed 100644 --- a/skills/ship_library/ship_library.md +++ b/skills/ship_library/ship_library.md @@ -107,7 +107,7 @@ step or evidence leg fails, stop and report — do not proceed. carries the `## Validation checklist` section ([`reference.md`](reference.md) → "Validation checklist (--auto)"), the run **stops at PR-open** unless step 6's declared tier merges it, a calibration row is -appended to `PyAutoMind/autonomy_log.md` (its **first** table, never the +appended to `PyAutoMind/autonomy_log.md` (its **first** table, `## Calibration runs`, never the Shadow window at the end — [`reference.md`](reference.md) → "Which table"), and `active.md` moves to `library-shipped, awaiting-merge`. Any failed leg → park per diff --git a/skills/ship_workspace/ship_workspace.md b/skills/ship_workspace/ship_workspace.md index b0139e70..ef2367da 100644 --- a/skills/ship_workspace/ship_workspace.md +++ b/skills/ship_workspace/ship_workspace.md @@ -93,7 +93,7 @@ stop and report. 3 note); ship without interactive sign-off, add the `## Validation checklist` to the PR body (`../ship_library/reference.md` → "Validation checklist (--auto)"), **stop at PR-open**, append the calibration row to -`PyAutoMind/autonomy_log.md` (its **first** table, never the Shadow window at +`PyAutoMind/autonomy_log.md` (its **first** table, `## Calibration runs`, never the Shadow window at the end — `../ship_library/reference.md` → "Which table"), set `active.md` to awaiting-merge. Failed leg → park per [`../../AUTONOMY.md`](../../AUTONOMY.md). Step 5's offered merge is diff --git a/tests/test_orchestrator_dispatch.py b/tests/test_orchestrator_dispatch.py index 9d0adbab..5736e4eb 100644 --- a/tests/test_orchestrator_dispatch.py +++ b/tests/test_orchestrator_dispatch.py @@ -614,13 +614,16 @@ def test_an_op_set_aside_after_the_digest_reaches_the_human(tmp_path, monkeypatc claude = FakeClaude() _tick(brief, canon, home, NOW, claude) (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") - mw.queue_op(slot / mw.LEDGER_DIR, {"op": "remove", "path": "active/missing.md"}) + # A set-aside that needs the human (a move whose source is not there): a + # remove of a missing file is mechanical since #660, a note only. + mw.queue_op(slot / mw.LEDGER_DIR, {"op": "move", "path": "active/missing.md", + "to": "active/elsewhere.md"}) poster = td.Poster() kw = dict(home=home, grace_s=0, spawner=orch.RealSpawner(brief, "auto", run=claude), agents=_agents({"t1": "done"}, slot), tokens=lambda s: 0, poster=poster) r = orch.tick(brief, canon, now=AFTER, **kw) assert r["action"] == "digest" and r["ledger"]["committed"] - assert [a["op"] for a in r["ledger"]["set_aside"]] == ["remove"] + assert [a["op"] for a in r["ledger"]["set_aside"]] == ["move"] assert "set aside" not in poster.calls[0][1] # the digest was built first assert orch.ledger_unreported(slot) r = orch.tick(brief, canon, now=AFTER + _dt.timedelta(minutes=3), **kw) diff --git a/tests/test_orchestrator_mind_writer.py b/tests/test_orchestrator_mind_writer.py index 04ebb435..66ccb293 100644 --- a/tests/test_orchestrator_mind_writer.py +++ b/tests/test_orchestrator_mind_writer.py @@ -81,9 +81,11 @@ def mind(tmp_path): return bare, canon, other -def _queue(slot, *argv, mind_repo): - env = {**os.environ, "PYAUTO_SHIFT_LEDGER_DIR": str(slot / "ledger"), - "PYAUTO_MIND": str(mind_repo)} +def _queue(slot, *argv, mind_repo, worker=False): + env = {k: v for k, v in os.environ.items() if k != "PYAUTO_SHIFT_WORKER"} + env.update({"PYAUTO_SHIFT_LEDGER_DIR": str(slot / "ledger"), "PYAUTO_MIND": str(mind_repo)}) + if worker: + env["PYAUTO_SHIFT_WORKER"] = "1" return subprocess.run([sys.executable, str(BRAIN / "bin" / "shift_ledger.py"), *argv], capture_output=True, text=True, env=env) @@ -344,3 +346,207 @@ def test_a_tick_commits_what_the_workers_queued(tmp_path, mind): spawner=orch.FakeSpawner(), records=[]) assert r["ledger"]["ops"] == 1 and r["ledger"]["committed"] assert "## t9" in _remote_tree(bare, "active.md").stdout + + +# --- M3.6d (PyAutoBrain#660): the edit op, a task's ops land together ---------------- + +def _push_from(other, path, text, message): + """Another session changes one Mind file on main.""" + git(other, "pull", "-q", "origin", "main") + f = other / path + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(text) + git(other, "add", "-A") + git(other, "commit", "-qm", message) + git(other, "push", "-q", "origin", "HEAD:main") + + +def test_a_write_on_a_path_on_main_is_refused_at_queue_time(tmp_path, mind): + """Shift 2026-11-16-pm: `write` edits to existing drafts were set aside + after the worker had ended. Now the worker is told when it queues.""" + bare, canon, _ = mind + slot = tmp_path / "slot" + res = _queue(slot, "--task", "t1", "write", "draft/feature/x/t1.md", "--text", "# t1 v2\n", + mind_repo=canon, worker=True) + assert res.returncode == 1, res.stderr + assert "already exists on Mind origin/main" in res.stderr and "edit" in res.stderr + assert mw.pending_ops(slot) == [] + # A path a pending op of this shift creates is refused the same way. + assert _queue(slot, "--task", "t1", "write", "complete/2026/11/t1.md", "--text", "a\n", + mind_repo=canon, worker=True).returncode == 0 + res = _queue(slot, "--task", "t1", "write", "complete/2026/11/t1.md", "--text", "b\n", + mind_repo=canon, worker=True) + assert res.returncode == 1 and "edit" in res.stderr + # An edit whose base is not there, and a table-append with no heading. + res = _queue(slot, "--task", "t1", "edit", "draft/feature/x/t1.md", "--old", "# nope\n", + "--new", "# t1 v2\n", mind_repo=canon, worker=True) + assert res.returncode == 1 and "expected base" in res.stderr + res = _queue(slot, "--task", "t1", "table-append", "active.md", "## Calibration runs", + "--text", "| a | b |", mind_repo=canon, worker=True) + assert res.returncode == 1 and "Calibration runs" in res.stderr + # A shift worker must name its task. + res = _queue(slot, "append", "active.md", "--text", "\n## t9\n- x\n", mind_repo=canon, + worker=True) + assert res.returncode != 0 and "--task" in res.stderr + assert len(mw.pending_ops(slot)) == 1 + + +def test_the_edit_op_applies_on_a_matching_base_and_is_set_aside_on_a_moved_one( + tmp_path, mind): + bare, canon, other = mind + slot = tmp_path / "slot" + for task, path, old, new in (("t1", "draft/feature/x/t1.md", "# t1\n", "# t1\n\nMore.\n"), + ("t2", "active/t2.md", "# t2\n", "# t2 done\n")): + res = _queue(slot, "--task", task, "edit", path, "--old", old, "--new", new, + mind_repo=canon, worker=True) + assert res.returncode == 0, res.stderr + # Someone else changes t2's file between the queue and the commit. + _push_from(other, "active/t2.md", "# t2 by someone else\n", "someone else's t2") + res = mw.commit_ledger(slot, canon, "edits") + assert res["committed"] and res["ops"] == 1 + assert _remote_tree(bare, "draft/feature/x/t1.md").stdout == "# t1\n\nMore.\n" + assert _remote_tree(bare, "active/t2.md").stdout == "# t2 by someone else\n" # not clobbered + [aside] = res["set_aside"] + assert aside["op"] == "edit" and aside["task"] == "t2" and aside["needs"] == "human" + assert "expected base not found" in aside["why"] + # The same edit again is already true on main: mechanical, not the human's. + mw.queue_op(slot / "ledger", {"op": "edit", "path": "draft/feature/x/t1.md", "task": "t1", + "old": "# t1\n", "new": "# t1\n\nMore.\n"}) + res = mw.commit_ledger(slot, canon, "again") + assert res["committed"] is None and res["set_aside"][0]["needs"] == "mechanical" + assert _remote_tree(bare, "draft/feature/x/t1.md").stdout == "# t1\n\nMore.\n" + + +def _close_out_t2(slot, canon): + for argv in (["write", "complete/2026/11/t2.md", "--text", "## t2\n- completed: x\n"], + ["drop-section", "active.md", "t2"]): + res = _queue(slot, "--task", "t2", *argv, mind_repo=canon, worker=True) + assert res.returncode == 0, res.stderr + + +@pytest.mark.parametrize("when", ["same-commit", "earlier-commit"]) +def test_a_worker_with_an_op_set_aside_has_its_complete_record_held(tmp_path, mind, when): + """Shift 2026-11-16-pm: three edits were set aside but the complete/ record + committed, so Mind recorded the task shipped. Now the record is withheld.""" + bare, canon, other = mind + slot = tmp_path / "slot" + assert _queue(slot, "--task", "t2", "edit", "active/t2.md", "--old", "# t2\n", "--new", + "# t2 done\n", mind_repo=canon, worker=True).returncode == 0 + _push_from(other, "active/t2.md", "# t2 by someone else\n", "someone else's t2") + if when == "same-commit": + _close_out_t2(slot, canon) # queued after the edit: still applied last + else: + first = mw.commit_ledger(slot, canon, "first") + assert [a["kind"] for a in first["set_aside"]] == ["set-aside"] + _close_out_t2(slot, canon) + assert _queue(slot, "--task", "t1", "move", "draft/feature/x/t1.md", "active/t1.md", + mind_repo=canon, worker=True).returncode == 0 # another task's op + res = mw.commit_ledger(slot, canon, "close") + assert res["committed"] # t1's claim landed + assert _remote_tree(bare, "active/t1.md").returncode == 0 + assert _remote_tree(bare, "complete/2026/11/t2.md").returncode != 0 + assert "## t2" in _remote_tree(bare, "active.md").stdout + withheld = [a for a in res["set_aside"] if a["kind"] == "withheld"] + assert sorted(a["op"] for a in withheld) == ["drop-section", "write"] + assert all(a["task"] == "t2" and a["needs"] == "human" for a in withheld) + assert all("held with its task" in a["why"] and "not recorded shipped" in a["why"] + for a in withheld) + aside = slot / "ledger" / mw.SET_ASIDE_DIR + assert len(list(aside.glob("*.json"))) == 3 and not mw.pending_ops(slot) + import _digest + assert any("withheld" in ln and "ledger/set_aside/" in ln + for ln in _digest.report_lines(slot)) + + +AUTONOMY_LOG = """# Autonomy calibration log + +Append-only record of `--auto` workflow runs. + +## Calibration runs + +| date | task | effective level | gates (tests/smoke/review/heart) | outcome | +|------|------|-----------------|----------------------------------|---------| +| 2026-11-13 | a | supervised | ok | merged-unchanged | + +| 2026-11-15 | b | supervised | ok | merged-unchanged | + +The calibration row goes in the table above, at the end of its last segment. + +## Shadow window — the tier-`glance` merge decision + +| date | task | human action | +|------|------|--------------| +| 2026-11-01 | s | merged | +""" + + +def test_shift_ledger_table_append_reaches_the_first_autonomy_log_table(tmp_path, mind): + """Five workers of shift 2026-11-16-pm could not queue their calibration + row: `table-append` needs a `## ` heading, and the CLI never set one.""" + bare, canon, other = mind + _push_from(other, "autonomy_log.md", AUTONOMY_LOG, "log") + git(canon, "fetch", "-q", "origin") + slot = tmp_path / "slot" + row = "| 2026-11-17 | t1 (PR) | supervised | ok | parked |" + res = _queue(slot, "--task", "t1", "table-append", "autonomy_log.md", "## Calibration runs", + "--text", row, mind_repo=canon, worker=True) + assert res.returncode == 0, res.stderr + res = mw.commit_ledger(slot, canon, "row") + assert res["committed"] and not res["set_aside"] and not res["held"] + lines = _remote_tree(bare, "autonomy_log.md").stdout.splitlines() + at = lines.index(row) + assert lines[at - 1].startswith("| 2026-11-15 | b ") + assert at < lines.index("## Shadow window — the tier-`glance` merge decision") + # The real Mind log beside this Brain has the heading above its first table. + live = BRAIN.parent / "PyAutoMind" / "autonomy_log.md" + if not live.is_file(): + pytest.skip("no PyAutoMind checkout beside this Brain") + text = live.read_text(encoding="utf-8") + out = mw.table_append(text, "## Calibration runs", row).splitlines() + first_table = next(i for i, ln in enumerate(text.splitlines()) if ln.startswith("|")) + assert text.splitlines().index("## Calibration runs") < first_table + at = out.index(row) + assert out[at - 1].startswith("|") + assert at < next(i for i, ln in enumerate(out) if ln.startswith("## Shadow window")) + + +def _events_of(slot, ledger): + import _events + slot.mkdir(parents=True, exist_ok=True) + return _events.record_tick(slot, _dt.datetime(2026, 11, 17, 9, 0, tzinfo=_dt.timezone.utc), + {"action": "ticked", "ledger": ledger}, counters={}) + + +def test_a_mechanical_set_aside_is_a_digest_line_not_a_needs_you_event(tmp_path, mind): + bare, canon, _ = mind + slot = tmp_path / "slot" + # Already true on main: a remove of a file that is gone, a write of the + # text the file already has. + mw.queue_op(slot / "ledger", {"op": "remove", "path": "active/gone.md", "task": "t2"}) + mw.queue_op(slot / "ledger", {"op": "write", "path": "active/t2.md", "text": "# t2\n", + "task": "t2"}) + mw.queue_op(slot / "ledger", {"op": "write", "path": "complete/2026/11/t2.md", + "text": "## t2\n", "task": "t2"}) + res = mw.commit_ledger(slot, canon, "mechanical") + assert {a["needs"] for a in res["set_aside"]} == {"mechanical"} and len(res["set_aside"]) == 2 + assert _remote_tree(bare, "complete/2026/11/t2.md").stdout == "## t2\n" # not withheld + events = _events_of(slot, res) + assert not [e for e in events if e["needs_you"]], events + import _digest + lines = [ln for ln in _digest.report_lines(slot) if ln] + assert len(lines) == 2 and all("mechanical" in ln and ln.startswith("- note:") + for ln in lines) + + +def test_two_human_set_asides_for_one_task_are_one_needs_you_event(tmp_path, mind): + bare, canon, _ = mind + slot = tmp_path / "slot" + for path in ("draft/feature/x/t1.md", "active/t2.md"): + mw.queue_op(slot / "ledger", {"op": "edit", "path": path, "task": "t3", + "old": "# nope\n", "new": "# t3\n"}) + res = mw.commit_ledger(slot, canon, "human") + assert [a["needs"] for a in res["set_aside"]] == ["human", "human"] + needs = [e for e in _events_of(slot, res) if e["needs_you"]] + assert len(needs) == 1 and needs[0]["key"] == "impaired:ledger:task:t3" + assert "`t3`" in needs[0]["line"] and "2 ops" in needs[0]["line"] + assert "active/t2.md" in needs[0]["line"] and "draft/feature/x/t1.md" in needs[0]["line"] From 0c3f21f517a341857a07e245d5ada4ae44897ff0 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:06:07 +0000 Subject: [PATCH 2/3] =?UTF-8?q?fix:=20shift=20ledger=20review=20findings?= =?UTF-8?q?=20=E2=80=94=20empty=20edits,=20closing=20groups,=20held=20sibl?= =?UTF-8?q?ings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of the M3.6d branch: - an edit to empty text no longer reads an absent base as already applied; - a task's closing ops apply as one group: a part-way failure rolls the group back and withholds the rest, so the record never lands alone; - an op on a path the group creates (edit of the complete/ record) is part of the group and keeps its order; - while a sibling op is held, the group stays pending beside it; - queue-time checks replay only pending ops over origin/main; - the NEEDS YOU line says "held" only when a record was withheld, and "already on main" when the task's record landed earlier (digest too); - shift_ledger names a missing Mind checkout instead of a traceback; - batch AGENTS.md states the two limits (earlier record, sticky block). Refs #660 Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 9 +- agents/conductors/batch/_digest.py | 5 +- agents/conductors/batch/_events.py | 7 +- agents/conductors/batch/_mind_writer.py | 172 +++++++++++++++++------- bin/shift_ledger.py | 8 +- tests/test_orchestrator_mind_writer.py | 108 +++++++++++++++ 6 files changed, 257 insertions(+), 52 deletions(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 7545f2f2..89653993 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -347,7 +347,14 @@ task's ops land together (#660): its closing ops (the `complete/` record, `drop-section`, the `active/` prompt's `remove`, `queue-retire`, `question-retire`) apply last, and are *withheld* — set aside, not retried — when any op of that task was set aside for a human this shift, so Mind never -records it shipped with a change missing. An op that is already true on main +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 +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 +is withheld too, for the rest of the shift. An op that is already true on main (an edit already applied, a write of the same text, a remove of a gone file) is set aside as *mechanical*: a digest line, never a NEEDS YOU; a task's human set-asides are one NEEDS YOU event naming the task. The diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 5c9c2bb2..b8ae4a9b 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -599,7 +599,10 @@ def report_line(e: dict) -> str: head = _REPORT_WORDS.get(kind, f"warning: Mind ledger {e.get('kind')}") where = f" (`ledger/set_aside/{e.get('file')}`)" if e.get("kind") in ( "set-aside", "conflict", "withheld") else "" - return f"- {head} — {e.get('op') or '?'} {e.get('path') or '?'}: {e.get('why')}{where}" + note = (f" — `{e.get('task')}`'s complete record is already on main" + if e.get("record") == "on-main" else "") + return (f"- {head} — {e.get('op') or '?'} {e.get('path') or '?'}: {e.get('why')}" + f"{where}{note}") def report_lines(slot: Path) -> list[str]: diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index ad7a0f9d..6f321a1c 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -376,10 +376,13 @@ def _impaired(b: _Batch, result: dict) -> None: for task, xs in sorted(by_task.items()): paths = ", ".join(sorted({str(x.get("path") or x.get("op") or "?") for x in xs})) n = len(xs) + tail = ("; its completion record is held — not shipped to Mind" + if any(x.get("kind") == "withheld" for x in xs) else + "; its completion record is already on main — check it" + if any(x.get("record") == "on-main" for x in xs) else "") b.add("impaired", f"impaired:ledger:task:{task}", f"Mind write set aside for `{task}`: {n} op{'s' if n != 1 else ''} " - f"({paths}); its completion record is held — not shipped to Mind.", - needs_you=True, task=task) + f"({paths}){tail}.", needs_you=True, task=task) per_op += [("held", x) for x in ledger.get("held") or []] for word, x in per_op: op = x.get("op") if isinstance(x, dict) else str(x) diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index 2ff14317..f57ff0bb 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -69,11 +69,13 @@ A worker's ops carry their `task` (`shift_ledger.py --task`). A task's *closing* ops (`_closing`: its `complete/` record, `drop-section`, the -`active/` prompt's `remove`, `queue-retire`, `question-retire`) apply after -every other op, and are *withheld* — set aside with the task, never retried — -when any sibling op of that task was set aside for a human, this run or -earlier in the shift: 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 +`active/` prompt's `remove`, `queue-retire`, `question-retire`, and any op on +a path one of them creates) apply after every other op, one group per task, +and are *withheld* — set aside with the task, never retried — when any +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 (`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 @@ -495,9 +497,10 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None: def edit_text(text: str, path: str, old: str, new: str) -> str: """`text` with its one `old` replaced by `new`. `MechanicalError` when the - edit is already there (`new` present and every `old` inside it); + edit is already there (a non-empty `new` present and every `old` inside + it); `MindWriteError` when `old` is not there exactly once (the base moved).""" - n, done = text.count(old), text.count(new) + n, done = text.count(old), (text.count(new) if new else 0) if done and n == done * new.count(old): raise MechanicalError(f"edit: {path} already has the new text on main") if n != 1: @@ -517,10 +520,10 @@ def _main_text(mind: Path, path: str, ref: str = "origin/main") -> str | None: def _ledger_ops(ledger_dir: Path) -> list[dict]: - """This shift's committed then pending ops, in order.""" - d = Path(ledger_dir) - files = sorted((d / COMMITTED_DIR).glob("*.json")) + sorted(d.glob("*.json")) - return [op for f in files if (op := _op_of(f))] + """This shift's pending ops, in order. Committed ops are already on + origin/main (the writer fetches each tick, and its push moves the + tracking ref): replaying them would undo a later change by someone else.""" + return [op for f in sorted(Path(ledger_dir).glob("*.json")) if (op := _op_of(f))] def _expected(mind: Path, path: str, ops: list[dict]) -> str | None: @@ -885,6 +888,67 @@ def committed_ops(slot: Path) -> list[dict]: if (op := _op_of(f))] if d.is_dir() else [] +def _apply_one(tree: Path, op: dict, lm, ctx: dict) -> tuple[str, object]: + """Apply one op: ("ok", note), ("held", entry) or ("failed", entry), an + entry being (kind, why, needs).""" + crit = is_critical(op) + try: + return "ok", apply_op(tree, op, lm, ctx) + except ConflictError as e: + out = ("held" if crit else "conflict", str(e), NEEDS_HUMAN) + except GoneError as e: + return "failed", ("set-aside", str(e), NEEDS_HUMAN) + except MechanicalError as e: + out = ("held" if crit else "set-aside", str(e), NEEDS_MECHANICAL) + except (MindWriteError, OSError, KeyError, TypeError, ValueError) as e: + out = ("held" if crit else "set-aside", str(e) or type(e).__name__, NEEDS_HUMAN) + return ("held" if crit else "failed"), out + + +def _withheld(task: str, cause: str) -> tuple: + return ("withheld", f"{task}: held with its task — {cause} set aside; not " + "recorded shipped", NEEDS_HUMAN) + + +def _apply_group(tree: Path, task: str, group: list, lm, ctx: dict, + failed: dict, held: dict, deferred: set) -> list: + """Apply one task's closing ops as a unit; returns their notes. If one + fails for a human (or is held), every file the group touched is put back + as it was and the rest are withheld (or kept pending): the record never + lands alone. A mechanical failure is a note-like set-aside and does not + stop the group.""" + paths = {op["path"] for _f, op in group} + before = {p: ((tree / p).read_bytes() if (tree / p).is_file() else None) for p in paths} + notes = [] + for i, (f, op) in enumerate(group): + where, out = _apply_one(tree, op, lm, ctx) + if where == "ok": + if out: + notes.append((f, op, out)) + continue + if where == "failed" and out[2] == NEEDS_MECHANICAL: + failed[f] = out + continue + for p, data in before.items(): # roll the group back + target = tree / p + if data is None: + if target.exists(): + target.unlink() + else: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + (held if where == "held" else failed)[f] = out + for g, _op in group: + if g == f or (g in failed and failed[g][2] == NEEDS_MECHANICAL): + continue + if where == "held": + deferred.add(g) + else: + failed[g] = _withheld(task, f.name) + return [] + return notes + + def commit_ledger(slot: Path, mind_repo: Path, message: str, remote: str = "origin", branch: str = "main", own_tasks=()) -> dict: @@ -898,9 +962,13 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, `conflict`); a critical op is held pending instead. Only a push rejected `PUSH_TRIES` times raises, with every op left pending. - A task's closing ops (`_closing`) apply after every other op; when one of - its ops was set aside for a human (this run or in an earlier `report`) or - is in conflict, they are `withheld` — set aside with it, not retried. + A task's closing ops (`_closing`, and any op on a path one of them + creates) apply after every other op, task by task, as one group: when one + of the task's ops was set aside for a human (this run or in an earlier + `report`) or is in conflict, the group is `withheld` — set aside with it, + not retried; when one of them is *held* (retried), the group stays pending + beside it. A group that fails part-way is rolled back, so a record never + lands without the rest of its group. """ mind_repo = Path(mind_repo) files = pending_ops(slot) @@ -921,8 +989,20 @@ 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 task's ops land together: its closing ops go last (stable). - ops = [x for x in ops if not _closing(x[1])] + [x for x in ops if _closing(x[1])] + # A task's ops land together: its closing ops go last, grouped by task. + creates: dict = {} + for _f, op in ops: + if _closing(op) and op.get("op") == "write": + creates.setdefault(op["task"], set()).add(op["path"]) + closing = {f for f, op in ops + if _closing(op) or op.get("path") in creates.get(op.get("task"), ())} + groups: dict = {} + for f, op in ops: + if f in closing: + groups.setdefault(op["task"], []).append((f, op)) + ops = [x for x in ops if x[0] not in closing] + recorded = {op["task"] for op in ctx["prior"] if isinstance(op.get("task"), str) + and op.get("op") == "write" and str(op.get("path", "")).startswith("complete/")} earlier = report(slot) seen_held = {(e.get("file"), e.get("kind")) for e in earlier} blocked_before = {e["task"]: e.get("file") for e in earlier @@ -937,41 +1017,37 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, try: _git(mind_repo, "worktree", "add", "-q", "--detach", str(tree), f"{remote}/{branch}") - notes, failed, held = [], dict(invalid), dict(unready) + notes, failed, held, deferred = [], dict(invalid), dict(unready), set() blocked = dict(blocked_before) for f in invalid: task = _op_of(f).get("task") if isinstance(task, str): blocked.setdefault(task, f.name) for f, op in ops: - task = op.get("task") - if _closing(op) and task in blocked: - failed[f] = ("withheld", f"{task}: held with its task — " - f"{blocked[task]} set aside; not recorded shipped", - NEEDS_HUMAN) + where, out = _apply_one(tree, op, lm, ctx) + if where == "ok": + if out: + notes.append((f, op, out)) continue - try: - note = apply_op(tree, op, lm, ctx) - except ConflictError as e: - (held if is_critical(op) else failed)[f] = ( - "held" if is_critical(op) else "conflict", str(e), NEEDS_HUMAN) - except GoneError as e: - failed[f] = ("set-aside", str(e), NEEDS_HUMAN) - except MechanicalError as e: - (held if is_critical(op) else failed)[f] = ( - "held" if is_critical(op) else "set-aside", str(e), - NEEDS_MECHANICAL) - except (MindWriteError, OSError, KeyError, TypeError, ValueError) as e: - (held if is_critical(op) else failed)[f] = ( - "held" if is_critical(op) else "set-aside", - str(e) or type(e).__name__, NEEDS_HUMAN) - else: - if note: - notes.append((f, op, note)) + (held if where == "held" else failed)[f] = out + if where == "failed" and out[2] != NEEDS_MECHANICAL \ + and isinstance(op.get("task"), str): + blocked.setdefault(op["task"], f.name) + waiting = {_op_of(f).get("task") for f in held} - {None} + for task, group in groups.items(): + if task in blocked: + for f, _op in group: + failed[f] = _withheld(task, blocked[task]) continue - if f in failed and failed[f][2] != NEEDS_MECHANICAL \ - and isinstance(task, str): - blocked.setdefault(task, f.name) + if task in waiting: # a sibling is held: wait beside it + deferred.update(f for f, _op in group) + continue + notes += _apply_group(tree, task, group, lm, ctx, failed, held, deferred) + for f in failed: + task = _op_of(f).get("task") + kind, why, needs = failed[f] + if task in recorded and needs != NEEDS_MECHANICAL: + failed[f] = (kind, why, needs, "on-main") _git(tree, "add", "-A") if not _git(tree, "status", "--porcelain").stdout.strip(): sha = None # every op was already true on main (or set aside) @@ -982,8 +1058,9 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, if pushed.returncode != 0: continue # main moved: replay the ops on the new origin/main aside = [] - for f, (kind, why, needs) in sorted(failed.items()): - aside.append({**_set_aside(slot, f, why, needs), "kind": kind}) + for f, (kind, why, needs, *record) in sorted(failed.items()): + aside.append({**_set_aside(slot, f, why, needs), "kind": kind, + **({"record": record[0]} if record else {})}) held_out = [{"file": f.name, "op": _op_of(f).get("op"), "path": _op_of(f).get("path"), "why": why, "kind": "held"} for f, (_k, why, _n) in sorted(held.items())] @@ -995,9 +1072,10 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, done = Path(slot) / LEDGER_DIR / COMMITTED_DIR done.mkdir(parents=True, exist_ok=True) for f in files: - if f not in failed and f not in held: + if f not in failed and f not in held and f not in deferred: f.replace(done / f.name) - return {"committed": sha, "ops": len(files) - len(failed) - len(held), + return {"committed": sha, + "ops": len(files) - len(failed) - len(held) - len(deferred), "tries": attempt, "skipped": [n for _f, _o, n in notes], "set_aside": aside, "held": held_out} finally: diff --git a/bin/shift_ledger.py b/bin/shift_ledger.py index bbb3fc01..abbfe92f 100755 --- a/bin/shift_ledger.py +++ b/bin/shift_ledger.py @@ -102,7 +102,13 @@ def main(argv=None) -> int: op["unique"] = op["row"] if a.unique is True else a.unique mind = _mind(a.mind) if mind: - errs = mw.validate_op(op, mw._ledger_merge(mind)) + try: + lm = mw._ledger_merge(mind) + except mw.MindWriteError as e: + print(f"shift_ledger: cannot check against Mind — {e} (set --mind or " + "$PYAUTO_MIND to a PyAutoMind checkout)", file=sys.stderr) + return 2 + errs = mw.validate_op(op, lm) errs = errs or mw.queue_refusals(mind, op, Path(ledger)) if errs: print("shift_ledger: refused — " + "; ".join(errs), file=sys.stderr) diff --git a/tests/test_orchestrator_mind_writer.py b/tests/test_orchestrator_mind_writer.py index 66ccb293..aadf8863 100644 --- a/tests/test_orchestrator_mind_writer.py +++ b/tests/test_orchestrator_mind_writer.py @@ -550,3 +550,111 @@ def test_two_human_set_asides_for_one_task_are_one_needs_you_event(tmp_path, min assert len(needs) == 1 and needs[0]["key"] == "impaired:ledger:task:t3" assert "`t3`" in needs[0]["line"] and "2 ops" in needs[0]["line"] assert "active/t2.md" in needs[0]["line"] and "draft/feature/x/t1.md" in needs[0]["line"] + + +# --- M3.6d review findings (PyAutoBrain#660) ---------------------------------------- + +def _q(slot, **op): + mw.queue_op(slot / "ledger", op) + + +def test_an_edit_to_empty_text_on_a_moved_base_is_the_humans(tmp_path, mind): + """`new == ""` must not make an absent base look already applied.""" + bare, canon, other = mind + slot = tmp_path / "slot" + res = _queue(slot, "--task", "t2", "edit", "active/t2.md", "--old", "# nope\n", "--new", "", + mind_repo=canon, worker=True) + assert res.returncode == 1 and "expected base not found" in res.stderr, res.stderr + _push_from(other, "active/t2.md", "# t2 by someone else\n", "someone else's t2") + _q(slot, op="edit", path="active/t2.md", task="t2", old="# t2\n", new="") + _q(slot, op="write", path="complete/2026/11/t2.md", text="## t2\n", task="t2") + res = mw.commit_ledger(slot, canon, "empty edit") + kinds = sorted((a["kind"], a["needs"]) for a in res["set_aside"]) + assert kinds == [("set-aside", "human"), ("withheld", "human")] + assert _remote_tree(bare, "complete/2026/11/t2.md").returncode != 0 + + +@pytest.mark.parametrize("order", ["record-first", "record-last"]) +def test_a_failing_closing_op_holds_the_record_it_closes_with(tmp_path, mind, order): + bare, canon, _ = mind + slot = tmp_path / "slot" + record = dict(op="write", path="complete/2026/11/t2.md", text="## t2\n", task="t2") + drop = dict(op="drop-section", path="active.md", section="nope", task="t2") + for op in ((record, drop) if order == "record-first" else (drop, record)): + _q(slot, **op) + res = mw.commit_ledger(slot, canon, "closing") + assert _remote_tree(bare, "complete/2026/11/t2.md").returncode != 0 + by = {a["op"]: a for a in res["set_aside"]} + assert by["drop-section"]["kind"] == "set-aside" and by["write"]["kind"] == "withheld" + [e] = [e for e in _events_of(slot, res) if e["needs_you"]] + assert "completion record is held" in e["line"] + + +def test_the_needs_you_line_says_held_only_when_a_record_was_withheld(tmp_path, mind): + _, canon, _ = mind + slot = tmp_path / "slot" + _q(slot, op="edit", path="active/t2.md", task="t3", old="# nope\n", new="# t3\n") + res = mw.commit_ledger(slot, canon, "no record") + [e] = [e for e in _events_of(slot, res) if e["needs_you"]] + assert "`t3`" in e["line"] and "held" not in e["line"] + + +def test_a_committed_op_is_not_replayed_over_main_at_queue_time(tmp_path, mind): + bare, canon, other = mind + slot = tmp_path / "slot" + assert _queue(slot, "--task", "t1", "write", "draft/feature/x/n.md", "--text", "v1\n", + mind_repo=canon, worker=True).returncode == 0 + assert mw.commit_ledger(slot, canon, "v1")["committed"] + _push_from(other, "draft/feature/x/n.md", "v2\n", "someone else's v2") + git(canon, "fetch", "-q", "origin") + res = _queue(slot, "--task", "t1", "edit", "draft/feature/x/n.md", "--old", "v2\n", + "--new", "v3\n", mind_repo=canon, worker=True) + assert res.returncode == 0, res.stderr + + +def test_a_task_may_edit_the_complete_record_it_writes(tmp_path, mind): + bare, canon, _ = mind + slot = tmp_path / "slot" + _q(slot, op="write", path="complete/2026/11/t2.md", text="a\n", task="t2") + _q(slot, op="edit", path="complete/2026/11/t2.md", old="a\n", new="b\n", task="t2") + _q(slot, op="append", path="active.md", text="\n## t6\n- x\n", task="t6") + res = mw.commit_ledger(slot, canon, "record then edit") + assert res["committed"] and not res["set_aside"] + assert _remote_tree(bare, "complete/2026/11/t2.md").stdout == "b\n" + + +def test_a_held_sibling_keeps_its_tasks_record_pending(tmp_path, mind): + """A held op is retried, so its task's record waits beside it — never + withheld for good, never landing alone.""" + bare, canon, _ = mind + slot = tmp_path / "slot" + entry = {"task": "t2", "issue": "https://example.invalid/issues/2", "kind": "choice", + "ask": "which?", "options": ["a", "b"], "shift": "s", "asked": "2026-11-17", + "worker": "w"} + _q(slot, op="question-add", path="questions.md", entry=entry, task="t2") # no script: held + _q(slot, op="write", path="complete/2026/11/t2.md", text="## t2\n", task="t2") + for _ in range(2): + res = mw.commit_ledger(slot, canon, "held") + assert [h["op"] for h in res["held"]] == ["question-add"] and not res["set_aside"] + assert _remote_tree(bare, "complete/2026/11/t2.md").returncode != 0 + assert len(mw.pending_ops(slot)) == 2 + + +def test_a_set_aside_after_the_record_landed_says_it_is_on_main(tmp_path, mind): + bare, canon, _ = mind + slot = tmp_path / "slot" + _q(slot, op="write", path="complete/2026/11/t2.md", text="## t2\n", task="t2") + assert mw.commit_ledger(slot, canon, "record")["committed"] + _q(slot, op="edit", path="active/t2.md", task="t2", old="# nope\n", new="# t2 v2\n") + res = mw.commit_ledger(slot, canon, "late edit") + [e] = [e for e in _events_of(slot, res) if e["needs_you"]] + assert "already on main" in e["line"] + import _digest + assert any("already on main" in ln for ln in _digest.report_lines(slot)) + + +def test_shift_ledger_names_a_missing_mind_checkout_cleanly(tmp_path): + res = _queue(tmp_path / "slot", "--task", "t1", "append", "active.md", "--text", "x", + 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 From 1a24b3506c7b74f566552bdb305f25b7147dd8d3 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Tue, 17 Nov 2026 14:43:18 +0000 Subject: [PATCH 3/3] test: split the real autonomy_log check; skip until Mind has the heading CI checks out Mind main, which gains `## Calibration runs` only when PyAutoMind#581 merges. The fixture-log witness stays unconditional; the check against the sibling Mind log is its own test and skips while that log lacks the heading. Refs #660 Co-Authored-By: Claude Opus 5.5 --- tests/test_orchestrator_mind_writer.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/test_orchestrator_mind_writer.py b/tests/test_orchestrator_mind_writer.py index aadf8863..3cf2eb62 100644 --- a/tests/test_orchestrator_mind_writer.py +++ b/tests/test_orchestrator_mind_writer.py @@ -497,11 +497,17 @@ def test_shift_ledger_table_append_reaches_the_first_autonomy_log_table(tmp_path at = lines.index(row) assert lines[at - 1].startswith("| 2026-11-15 | b ") assert at < lines.index("## Shadow window — the tier-`glance` merge decision") - # The real Mind log beside this Brain has the heading above its first table. + + +def test_the_sibling_autonomy_log_has_the_calibration_runs_heading(): + """The real Mind log beside this Brain has the heading above its first table.""" + row = "| 2026-11-17 | t1 (PR) | supervised | ok | parked |" live = BRAIN.parent / "PyAutoMind" / "autonomy_log.md" if not live.is_file(): pytest.skip("no PyAutoMind checkout beside this Brain") text = live.read_text(encoding="utf-8") + if "## Calibration runs" not in text.splitlines(): + pytest.skip("sibling Mind autonomy_log.md lacks the heading — lands with PyAutoMind#581") out = mw.table_append(text, "## Calibration runs", row).splitlines() first_table = next(i for i, ln in enumerate(text.splitlines()) if ln.startswith("|")) assert text.splitlines().index("## Calibration runs") < first_table