diff --git a/AUTONOMY.md b/AUTONOMY.md index bd79bdb..ea859f5 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -804,6 +804,19 @@ not open. scoped` dip takes `queue.md` first, then only `Difficulty: small` single-repo backlog tasks; anything bigger must be queued by the human. +**Human rulings R5 and R2 — 2026-11-17 (M3.6b, PyAutoBrain#667).** R5 +(option a): the one-slice-per-epic limit and phase order bind only tasks with +a `Phase:` number; a side task of the epic shares the shift and orders itself +by `Blocked-by:`. Every named task that will not start is listed with its +reason at `batch brief --check` and in the digest. R2: the planner never +dispatches a task whose repo another active task claims, named or backlog; a +`coordination:` / `conflict-override:` line frees a repo only for the task it +names. Also approved: a shift dips only witnessed drafts (counted in the +digest); `brief --new` with no goal epic or tag writes `backlog: scoped` with +`tiers: notify, glance`; and `brief --check` applies the organ rule to named +tasks — refused when the prompt names the shift's own code (`_brief.SELF_PATHS`), +passed with a line when it names only other paths, a warning when it names none. + **Launch preflight — 2026-11-17 (M3.6a, PyAutoBrain#659), approved by the human.** A live brief (not `shadow: yes`) names its shift **`issue:`**: `batch brief --new --out` creates it on PyAutoMind and writes it, and `batch brief diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index a714d55..fc52448 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -48,7 +48,7 @@ consulting a conductor. If a rule here starts needing to *judge* rather than |---|---| | **Review-minute budget** | the human's hour is the binding resource; see above | | **One member per *library* repo per shift** | concurrent members do not collide at dispatch (separate worktrees) — they collide at **merge**, because the first `/prm` moves `main` and invalidates the others' test and smoke evidence. Workspace, docs and organ repos are exempt: two docs changes in one shift cost nothing. Work concentrates in four repos (PyAutoFit 118/332 August records, PyAutoArray 98, PyAutoGalaxy 82, PyAutoLens 78), so effective parallelism is two or three, not six. | -| **One slice per epic per batch** | epic phases are ordered, so two members could not run in parallel anyway — and this is what interleaves small pieces of long programmes with standalone work | +| **One `Phase:` task per epic per batch** | epic phases are ordered, so two members could not run in parallel anyway — and this is what interleaves small pieces of long programmes with standalone work. A side task of the epic (no `Phase:`) is not counted and orders itself by `Blocked-by:` (ruling R5, M3.6b) | | **`Unattended: ready` only** | `needs-slicing` goes to the decomposition pass (`batch slice`); `never` never enters a batch | | **Lane match** | a session detects its own lane and plans only that one | | **No Lane, no unattended pick** | a backlog draft with no valid `Lane:` is excluded from every unattended plan (the default, and the watcher) and the plan says so; `--attended` reads it as `any`. A lane-less draft that needs the laptop, RAL or private data would otherwise reach a cloud worker (M2.3, `AUTONOMY.md` "M2 rulings — 2026-11-12") | @@ -198,7 +198,8 @@ whole grant (`AUTONOMY.md`, "Shift briefs and unattended `glance`"). `batch brief --new --review-at ` composes that writing: a skeleton brief whose `goals:` are `PyAutoMind/goals.md`'s, in order, with -`backlog: scoped` to their `epics:`/`tags:` (else `fill-idle`) and +`backlog: scoped` to their `epics:`/`tags:` (else `scoped` by `tiers: notify, +glance`, M3.6b) and `merge-cap: 0`. It prints to stdout (`--out FILE` writes it) and never writes a record into `batches/` — saving it there is the human's dispatch. `goals.md` is written by the human alone (by hand or in chat), so every goal @@ -285,8 +286,11 @@ claimed in its `active.md` is excluded unless this shift picked it, read from th local `origin/main` ref after one `git fetch` per shift through the one Mind writer's own fetch (never a pull); an unreadable ref fails closed. From PyAutoBrain#637 the same read also skips a task whose declared repo (`Repos:` -header and target) a claim in that `active.md` holds, unless the claim records -`coordination:` or `conflict-override:`; a task an earlier shift in the same +header and target) a claim in that `active.md` holds, unless the claim's +`coordination:` or `conflict-override:` line names that task (ruling R2, M3.6b; +a shift's dip also skips a draft with no `Witness:`, counted in the digest, and +`brief --check` lists each named task that will not start and applies the +organ rule to it); a task an earlier shift in the same home left parked on a question is not startable until a later shift finishes it or a brief names it again; a dip never takes a Brain, Mind or Hands target; a `backlog: scoped` dip beyond `queue.md` takes only small single-repo tasks diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 34afdbe..ea6531e 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -162,6 +162,9 @@ def grade(path: Path, mind: Path, text: str | None = None) -> dict: "declared_repos": declared_repos(p), "priority": p.get("priority") or "normal", "blocked": bool(p.get("blocked_by")), + # What it waits for, so a rejection names it (M3.6b: a side task + # orders itself after its epic's phase by `Blocked-by:`). + "blocked_by": list(p.get("blocked_by") or []), } @@ -206,10 +209,15 @@ def _is_done(text: str) -> bool: def _phase_of(text: str) -> float: """`Phase: ` as a sortable number; phase-less members sort last.""" raw = _header_of(text, "phase") - try: - return float(raw.rstrip("abcdefgh") or "inf") - except ValueError: - return float("inf") + # The leading number: `5a`/`5A` → 5, `6b2` → 6 (M3.6b review). A label + # with no leading number (`C2`) sorts last but is still a declared phase + # (`_phase_declared`), so the per-epic limit counts it. + m = re.match(r"\s*(\d+(?:\.\d+)?)", raw) + return float(m.group(1)) if m else float("inf") + + +def _phase_declared(text: str) -> bool: + return bool(_header_of(text, "phase")) def survey(mind: Path) -> list[dict]: @@ -228,6 +236,7 @@ def survey(mind: Path) -> list[dict]: g["looks_shipped"] = f.relative_to(mind).as_posix() in flagged g["epic"] = _epic_of(text) g["phase"] = _phase_of(text) + g["phase_declared"] = _phase_declared(text) g["done"] = _is_done(text) g["themes"] = _themes_of(text) g["title"] = _title_of(text) @@ -244,6 +253,7 @@ def grade_text(text: str, rel: str, mind: Path) -> dict: g["looks_shipped"] = rel in _shipped.flagged_paths(mind) g["epic"] = _epic_of(text) g["phase"] = _phase_of(text) + g["phase_declared"] = _phase_declared(text) g["done"] = _is_done(text) g["themes"] = _themes_of(text) g["title"] = _title_of(text) @@ -307,18 +317,35 @@ def pool_gate(r: dict, next_phase: dict[str, float]) -> str: if r.get("looks_shipped"): return ("looks shipped — confirm (close) or " f"dismiss it ({_shipped.DISMISS_FILE}) first") - if r.get("epic") and r.get("phase", float("inf")) > next_phase.get( + # Phase order binds only a task with a `Phase:` number (ruling R5, option + # a, 2026-11-17): a side task of the epic (no `Phase:`) is not a later + # phase, and orders itself by `Blocked-by:` below. + if r.get("epic") and has_phase(r) and r["phase"] == float("inf") \ + and next_phase.get(r["epic"], float("inf")) < float("inf"): + return f"epic {r['epic']} phase (unnumbered) is not next" + if r.get("epic") and has_phase(r) and r["phase"] > next_phase.get( r["epic"], float("inf")): - return f"epic {r['epic']} phase {r.get('phase')} is not next" + return f"epic {r['epic']} phase {r['phase']:g} is not next" if r["autonomy"] == "human-required": return f"autonomy {r['autonomy']} — would park at ship" if r["unattended"] != "ready": return f"unattended: {r['unattended']}" if r["blocked"]: - return "declares Blocked-by:" + waits = "; ".join(r.get("blocked_by") or []) + return f"waits for {waits} (its Blocked-by)" if waits else "declares Blocked-by:" return "" +def has_phase(r: dict) -> bool: + """Whether a record declares a `Phase:` (`phase_declared`, from the + survey); else whether its phase is a number (`_phase_of` reads a missing + one as infinity, so phase-less side tasks sort last).""" + if "phase_declared" in r: + return bool(r["phase_declared"]) + phase = r.get("phase", float("inf")) + return isinstance(phase, (int, float)) and phase != float("inf") + + def self_organ_why(r: dict) -> str: """Why a shift never dips this draft, or "" (PyAutoBrain#637, item 7): it targets an organ the shift runs on — its watcher, writer or release path @@ -430,7 +457,7 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, shift_dip = brief is not None and not attended scoped_dip = shift_dip and brief.get("backlog", {}).get("value") == "scoped" - pool, lane_absent, reach = [], [], [] + pool, lane_absent, reach, witness_absent = [], [], [], [] for r in records: # A brief's named task is the human's own pick, not a backlog dip: # neither M2.3 gate below applies to it (the brief's `lanes:` still does). @@ -448,6 +475,13 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, "(named tasks only)")) elif shift_dip and backlog and self_organ_why(r): rejected.append((r["path"], self_organ_why(r))) + elif shift_dip and backlog and not r.get("witness") and not r.get("resume"): + # A shift dips only witnessed drafts (M3.6b): one without a + # `Witness:` is reviewed as `judge`, so it is never cheap fill. + # Counted for the digest; a named task is the human's pick. + rejected.append((r["path"], "no Witness — a shift dips only witnessed " + "drafts (declare one to make it pickable)")) + witness_absent.append(r["path"]) elif scoped_dip and backlog and queue_rank(r, queue) >= len(queue) \ and scoped_reach_why(r): rejected.append((r["path"], scoped_reach_why(r))) @@ -470,8 +504,11 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, members, spent, seen_epics, libs = [], 0, set(), set() for r in pool: - if r["epic"] and r["epic"] in seen_epics: - rejected.append((r["path"], f"epic {r['epic']} already in this batch")) + # One slice per epic counts only `Phase:` tasks (ruling R5, option a, + # 2026-11-17): a side task of the epic shares the shift with its phase. + if r["epic"] and has_phase(r) and r["epic"] in seen_epics: + rejected.append((r["path"], f"epic {r['epic']} already has a phase task in " + "this batch (one Phase: task per epic)")) continue # Concurrent members do not collide at dispatch (separate worktrees) — # they collide at MERGE, because the first /prm moves main and @@ -489,7 +526,7 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, continue members.append(r) spent += cost - if r["epic"]: + if r["epic"] and has_phase(r): seen_epics.add(r["epic"]) libs.update(x for x in r["repos"] if x in LIBRARY_REPOS) @@ -523,6 +560,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, "queue_stop": queue_stop, # The 2026-11-16 backlog-reach ruling (#637, item 6), stated likewise. "scoped_reach": reach, + # Backlog drafts with no `Witness:`, kept out of a shift's dip (M3.6b). + "witness_absent": witness_absent, } @@ -3320,13 +3359,19 @@ def goals_report(mind: Path) -> list[str]: return L +#: `brief --new`'s scope when no goal names an epic or tag (M3.6b): the tiers +#: a shift may merge, under the 2026-11-16 backlog-reach ruling. +NEW_BRIEF_SCOPED_TIERS = ("notify", "glance") + + def new_brief(mind: Path, slot: str, review_at: str, now=None, heart: dict | None = None, issue: str = "") -> str: """A skeleton shift brief whose `goals:` are `goals.md`'s, in order. `goals.md` has one kind of writer, the human (by hand or in chat), so every goal is copied as their word. `backlog: scoped` covers the union of - the goals' `epics:`/`tags:`; with none named, `fill-idle`. Every other required key + the goals' `epics:`/`tags:`; with none named, `scoped` by the tiers a shift + may merge (`NEW_BRIEF_SCOPED_TIERS`). Every other required key gets a default the human edits. Writing the record (with its `review-at:`) is the dispatch, so this only composes the text (batches/AGENTS.md "Shift brief"). @@ -3370,7 +3415,14 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, if tags: L.append(f" - tags: {', '.join(tags)}") else: - L.append(" - backlog: fill-idle # no goal names an epic or tag") + # No goal names an epic or tag: the backlog-reach ruling (2026-11-16, + # PyAutoBrain#637 item 6) is the default, not `fill-idle` (M3.6b) — + # under `scoped` the planner dips queue.md first, then only small + # single-repo tasks, and these tiers are the ones a shift may merge. + L += [" - backlog: scoped # tiers a shift may merge; beyond " + "queue.md small single-repo only (ruling 2026-11-16)", + " - scoped:", + f" - tiers: {', '.join(NEW_BRIEF_SCOPED_TIERS)}"] L += [f" - review-minutes: {NEW_BRIEF_DEFAULTS['review-minutes']}", f" - lanes: {NEW_BRIEF_DEFAULTS['lanes']}", f" - merge-cap: {NEW_BRIEF_DEFAULTS['merge-cap']}" @@ -3380,6 +3432,49 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, return text + "\n" + _green.section(heart) if heart else text +#: `brief --check`'s word for a named task whose prompt is in `active/`. +NAMED_IN_ACTIVE = ("its prompt is in active/ — already issued: a shift starts it only " + "as a resume after an answered question (or it has started)") + + +def named_skips(brief: dict, mind: Path) -> tuple[dict[str, str], str]: + """({named task: why it will not start}, a note when the claims on Mind + origin/main could not be read) — the watcher's own gates, run at + `brief --check` (M3.6b, ruling R5): the claim gate against Mind's local + `origin/main` (never a fetch), then `plan` under this brief, unattended, + on the watcher's lane. A task the planner keeps is not listed; one that + resolves to no prompt is `_brief.check`'s warning already.""" + import _orchestrator as orch # noqa: E402 — deferred: it imports this module + named = _brief.tasks_of(brief) + if not named: + return {}, "" + recs = survey(mind) + note = "" + claims = orch.origin_claims(mind) + held: dict[str, str] = {} + if claims is not None and "error" in claims: + note = (f"brief.tasks: claims on Mind origin/main not read ({claims['error']}) — " + "the watcher fails closed on that; repo claims not checked here") + elif claims is not None: + recs, held = orch.on_origin(recs, mind, own=set()) + d = plan(recs, session_lane="local-dev", brief=brief, queue=read_queue(mind)) + rejected = {Path(p).name: w for p, w in d["rejected"]} + rejected.update({Path(p).name: w for p, w in held.items()}) + members = {Path(m["path"]).name for m in d["members"]} + out = {} + for t in named: + name = Path(t).name + if name in rejected: + out[t] = rejected[name] + elif name not in members and _brief._resolve(mind, t) is not None: + # In active/ (already issued): `_brief.check` resolves it, so no + # warning came from there, and no survey of draft/ holds it. A + # shift resumes it only once its question is answered, and on a + # record re-checked after launch it is a task that started. + out[t] = NAMED_IN_ACTIVE + return out, note + + #: `PYAUTO_BRIEF_ISSUE=off`: `brief --new --out` makes no shift issue. BRIEF_ISSUE_ENV = "PYAUTO_BRIEF_ISSUE" _GITHUB_REMOTE_RE = re.compile(r"github\.com[:/]([\w.-]+)/([\w.-]+?)(?:\.git)?/?$") @@ -3555,6 +3650,23 @@ def _main_brief(mind: Path, a) -> int: warn = goal_one_warning(Path(a.check), mind) if warn: res["warnings"].append(warn) + # M3.6b: every named task that will not start, with the planner's own + # reason, and the organ rule for each one, before the shift opens. + res["notes"] = [] + if rec is not None and rec["brief"] is not None: + why_not, claim_note = named_skips(rec["brief"], mind) + res["warnings"] += [f"brief.tasks: {Path(t).stem} will not start — {w}" + for t, w in why_not.items()] + if claim_note: + res["warnings"].append(claim_note) + for t in _brief.tasks_of(rec["brief"]): + f = _brief._resolve(mind, t) + if f is not None: + errs, warns, notes = _brief.organ_findings(Path(t).stem, f, mind) + res["errors"] += errs + res["warnings"] += warns + res["notes"] += notes + res["ok"] = not res["errors"] # The premise leg: a named task whose premise is gone on main is flagged # here, before the shift pays a worker to discover it. A warning, not a # refusal — the check is mechanical, and the human reads the evidence. @@ -3573,6 +3685,8 @@ def _main_brief(mind: Path, a) -> int: print(f" ✗ {e}") for w in res["warnings"]: print(f" ! {w}") + for n in res.get("notes") or []: + print(f" · {n}") for p in res["premise"]: print(f" premise {p['status']}: {p['task']}") return RC_OK if res["ok"] else RC_FINDINGS diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index cc9f189..25e316d 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -404,6 +404,177 @@ def launch_errors(top: dict, brief: dict | None) -> list[str]: return [] +# --- the organ rule for a named task (M3.6b) ------------------------------------- + +#: The shift's own code, per organ it runs on: its watcher and planner (Brain), +#: its one Mind writer and lifecycle (Mind) and its release path (all of Hands, +#: so the empty prefix). A named task that names a path here is refused at +#: `brief --check`: a shift never changes what runs it. +SELF_PATHS = { + "PyAutoBrain": ("agents/conductors/batch/",), + "PyAutoMind": ("scripts/", ".github/workflows/"), + "PyAutoHands": ("",), +} +#: Self prefixes no other repo has: unprefixed, they still name that organ's +#: code (`.github/workflows/` and `scripts/` are every repo's). +DISTINCT_PREFIXES = ("agents/conductors/batch/",) +_SELF_PREFIXES = {pre.lower() for pres in SELF_PATHS.values() for pre in pres if pre} +#: Path candidates in a prompt: any backticked token, and an unbackticked +#: token that looks like a file path (segments and a lettered extension). +_TICKED_RE = re.compile(r"`([^`\s]+)`") +_BARE_PATH_RE = re.compile(r"(? tuple[list[str], bool] | None: + """(lower-cased path segments, glob) of a token, or None when it is not a + file path: a URL, `Repo#N`, an `action@ref`, a slash command (`/prm`), a + bare `/`, or a two-segment token with no extension (`origin/main`). A + `:line` suffix and a leading `@` or `./` are dropped; a glob keeps the + segments before its first `*`.""" + t = token.strip().rstrip(".,;)").removeprefix("@") + if "://" in t or "#" in t or "@" in t: + return None + t = re.sub(r":\d[\d,-]*$", "", t).removeprefix("./") + glob = "*" in t + if glob: + t = t.split("*", 1)[0].rsplit("/", 1)[0] + "/" + parts = [x.lower() for x in t.split("/") if x and x not in (".", "..")] + # A self prefix written without its slash (`.github/workflows`, `scripts`) + # is still that directory. + if "/".join(parts) + "/" in _SELF_PREFIXES or "/".join(parts[1:]) + "/" in _SELF_PREFIXES: + t = t.rstrip("/") + "/" + is_dir = t.endswith("/") + if not parts or (len(parts) == 1 and not is_dir): + return None + if len(parts) == 2 and not is_dir and not glob and "." not in parts[-1]: + return None + return parts + ([""] if is_dir else []), glob + + +def _own_files(mind: Path) -> dict[str, set[str]]: + """File names of the shift's own code, per organ, for a prompt that names + one bare (`_orchestrator.py`, `worker_template.md`): this conductor's + directory (bar its AGENTS.md) and Mind's `scripts/`.""" + def names(d: Path, keep) -> set[str]: + return {f.name for f in d.iterdir() if f.is_file() and keep(f)} if d.is_dir() else set() + return {"PyAutoBrain": names(Path(__file__).parent, lambda f: f.name != "AGENTS.md"), + "PyAutoMind": names(Path(mind) / "scripts", lambda f: f.suffix in (".py", ".sh"))} + + +def _classify(parts: list[str], hit: list[str], only_self: bool, organs: dict, + known, declared: set[str]) -> str: + """"own" | "maybe" | "other" | "neutral" for one path's segments.""" + from _sizing import normalise_repo # noqa: E402 + # `parts` ends in "" for a directory token: its last name may then be a + # repo (`PyAutoBrain/`), which the attribution below reads. + rel = "/".join(x for x in parts if x) + "/" + if rel.startswith(MIND_DOCS): + return "neutral" # a Mind record, wherever its folder is named + # An explicit repo segment (never the file name itself) attributes the path. + at = next((i for i, seg in enumerate(parts[:-1]) + if normalise_repo(seg) in organs or normalise_repo(seg) in known), None) + if at is not None: + organ = organs.get(normalise_repo(parts[at])) + rest = "/".join(x for x in parts[at + 1:] if x) + "/" + if rest == "/": + return "neutral" # the repo itself, not a path in it + if organ and any(rest.startswith(pre.lower()) for pre in SELF_PATHS[organ]): + return "own" + if organ == "PyAutoMind" and rest.startswith(MIND_DOCS): + return "neutral" + # A path in a repo the task declares shows what it changes; one in a + # repo it does not declare shows nothing either way. + return "other" if normalise_repo(parts[at]) in declared else "neutral" + # A multi-segment self prefix found anywhere (a worktree or absolute path). + # Inside a longer path only (a worktree or an absolute path), and only + # for an organ this task targets: at the start it is plainly unprefixed, + # which `cands` judges below (another repo's `.github/workflows/` is not + # Mind's). + # A prefix only that organ has (`DISTINCT_PREFIXES`) is its code at the + # start of a path too, whatever else the task declares. + deep = any(rel.startswith(pre) or f"/{pre}" in rel[1:] for pre in DISTINCT_PREFIXES) \ + or any(f"/{pre.lower()}" in rel[1:] + for o in hit for pre in SELF_PATHS[o] if pre.count("/") > 1) + cands = [o for o in hit if any(rel.startswith(pre.lower()) for pre in SELF_PATHS[o])] + if deep or (cands and only_self): + return "own" + return "maybe" if cands else "other" + + +def organ_findings(name: str, path: Path, mind: Path) -> tuple[list[str], list[str], list[str]]: + """(errors, warnings, notes) of the organ rule for one named task. + + The organ rule was a dip rule only (`_batch.self_organ_why`); a named task + is the human's pick, and in shift 2026-11-16-pm the human had to rule in + chat that a renderer is not the watcher, writer or release path. This says + it at launch instead (M3.6b), for a task that targets an organ the shift + runs on: + + - refused when it names the shift's own code: a path under an organ's + `SELF_PATHS` with that organ written in it, under a multi-segment self + prefix anywhere in the path, unprefixed when the task declares only + self organs, or a bare file name of that code; + - a warning when an unprefixed path could be a self organ's own code but + the task also declares another repo (the human's call), or when it names + no path that shows what it changes; + - otherwise passed, with a line saying so. A path in an undeclared repo, + a repo name alone and a Mind record (`MIND_DOCS`) show nothing either way.""" + from _sizing import KNOWN_REPOS, normalise_repo # noqa: E402 — on sys.path + p = parse_prompt(path, mind) + text = p.get("text") or "" + organs = {normalise_repo(o): o for o in SELF_ORGANS} + # The `Target:` header (every repo it names), else `parse_prompt`'s + # target (the draft's folder); then the `Repos:` block. + head = re.search(r"(?m)^Target:[ \t]*(.+)$", text) + targets = re.findall(r"[\w.-]+", head.group(1)) if head else [p.get("target") or ""] + declared = {normalise_repo(x) for x in [*targets, + *re.findall(r"(?m)^- (\S+)", _repos_block(p))] if x} + hit = [organs[k] for k in organs if k in declared] + if not hit: + return [], [], [] + only_self = declared <= set(organs) + own_files = _own_files(mind) + bare_names = {n for o in hit for n in own_files.get(o, ())} + own, maybe, paths = [], [], [] + for n in sorted(bare_names): + if re.search(rf"(? 3 else "") + + " — not the watcher, writer or release path; passes"] + + +def _repos_block(p: dict) -> str: + m = re.search(r"^Repos:\n((?:- .+\n)+)", p.get("text") or "", re.M) + return m.group(1) if m else "" + + # --- scope --------------------------------------------------------------------- def scope(records: list[dict], brief: dict) -> tuple[list[dict], list[tuple[str, str]], list[str]]: diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index c5721c2..738da4a 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -290,9 +290,11 @@ def no_slot_merges(counters: dict) -> list[str]: def gate_why(task: str, counters: dict) -> str: """Why the watcher's last plan kept this task out — a claim or a held - repo on Mind origin/main, or a park in an earlier shift (#637) — or "".""" + repo on Mind origin/main, a park in an earlier shift (#637), or the + planner's own reason for a named task (M3.6b: epic, budget, Blocked-by) — + or "".""" gates = counters.get("backlog_gates") or {} - for key in ("origin", "parked"): + for key in ("origin", "parked", "named"): for path, why in (gates.get(key) or {}).items(): if Path(path).stem == task: return why @@ -714,6 +716,11 @@ def names(paths): "their old standing — " + "; ".join( f"`{t}` ({', '.join(v.get('ids') or [])} answered)" for t, v in sorted(resumed.items())[:SUMMARY_NAMES])) + bare = gates.get("witness_absent") or [] + if bare: + out.append(f"No Witness: {len(bare)} draft(s) not dipped — a shift dips only " + "witnessed drafts; declare a Witness: to make one pickable: " + + names(bare)) reach = gates.get("scoped_reach") or [] if reach: out.append(f"Backlog reach (ruling 2026-11-16): {len(reach)} unqueued draft(s) not " diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index d84e848..384c51a 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -1317,6 +1317,23 @@ def git(*args): #: A claim that records human-authorized sharing of its repos (#637, item 4). _COORDINATION_RE = re.compile(r"^- (coordination|conflict-override):\s*\S", re.M) _CLAIM_REPO_RE = re.compile(r"^\s+- ([A-Za-z0-9_.-]+)") +_COORDINATION_LINE_RE = re.compile(r"(?m)^- (?:coordination|conflict-override):(.*)$") + + +def _slug_form(text: str) -> str: + return re.sub(r"[-_]+", "-", text.lower()) + + +def coordinated_for(sec: dict, task: str) -> bool: + """Whether a claim's `coordination:` / `conflict-override:` line frees its + repos for `task` (ruling R2, 2026-11-17): only when it names the task, by + its slug or prompt stem (`-` and `_` alike). Such a line records sharing + the human approved with one named task — in shift 2026-11-16-pm a task was + dispatched onto a claim whose override named another task — never a free + pass for any.""" + text = _slug_form(sec.get("coordination") or "") + name = _slug_form(task or "") + return bool(name) and bool(re.search(rf"(? dict[str, dict]: @@ -1347,6 +1364,8 @@ def flush(): keys = dict(re.findall(r"(?m)^- (session|prompt):[ \t]*(.*?)\s*$", "\n".join(body))) out[slug] = {"repos": repos, "coordinated": bool(_COORDINATION_RE.search("\n".join(body))), + "coordination": " ".join(m.group(1) for m in + _COORDINATION_LINE_RE.finditer("\n".join(body))), "session": keys.get("session", ""), "prompt": keys.get("prompt", "")} for ln in active_text.splitlines(): if ln.startswith("## "): @@ -1442,7 +1461,7 @@ def on_origin(records: list[dict], mind: Path, own: set[str], "is not this home's shift worker's (session: " f"{(sec.get('session') or 'none')[:60]}) — left to the human") elif held := next(((repo, other) for other, sec2 in claims["sections"].items() - if other != slug and not sec2["coordinated"] + if other != slug and not coordinated_for(sec2, task) for repo in sec2["repos"] if _repo_key(repo) in mine), None): # Every other claim on the repo counts, not only the first # (`claimed_repos` keeps one per repo): its own does not. @@ -1454,9 +1473,8 @@ def on_origin(records: list[dict], mind: Path, own: set[str], out[r["path"]] = "not in draft/ on Mind origin/main (claimed or retired)" elif task in claims["active"]: out[r["path"]] = "claimed in active.md on Mind origin/main" - elif held := next((claims["repos"][_repo_key(x)] - for x in r.get("declared_repos") or r.get("repos") or [] - if _repo_key(x) in claims.get("repos", {})), None): + elif held := _held_for(claims.get("sections") or {}, task, + r.get("declared_repos") or r.get("repos") or []): out[r["path"]] = (f"repo {held[0]} claimed by `{held[1]}` in active.md on " "Mind origin/main") else: @@ -1464,6 +1482,16 @@ def on_origin(records: list[dict], mind: Path, own: set[str], return kept, out +def _held_for(sections: dict[str, dict], task: str, repos) -> tuple[str, str] | None: + """(repo as written, claiming slug) of the first claim on one of `repos` + that does not free it for `task` (R2: a coordination line frees a repo + only for the task it names), or None.""" + mine = {_repo_key(x) for x in repos} + return next(((repo, slug) for slug, sec in sections.items() + if not coordinated_for(sec, task) + for repo in sec["repos"] if _repo_key(repo) in mine), None) + + def parked_elsewhere(slot: Path, inbox: dict | None = None, resumes: dict | None = None) -> dict[str, str]: """{task: why} for every task an earlier shift in this watcher's home left @@ -1594,7 +1622,8 @@ def resume_records(records: list[dict], mind: Path, resumes: dict, g = _batch.grade(f, Path(tmp)) text = shown.stdout g.update(looks_shipped=False, epic=_batch._epic_of(text), - phase=_batch._phase_of(text), done=_batch._is_done(text), + phase=_batch._phase_of(text), + phase_declared=_batch._phase_declared(text), done=_batch._is_done(text), themes=_batch._themes_of(text), title=_batch._title_of(text)) out = [r for r in out if task_id(r["path"]) != task] + [g] for r in out: @@ -1631,6 +1660,24 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, return out +#: A named task the plan never saw: not in the survey of `draft/`. +NAMED_NO_DRAFT = "no draft prompt for it (already issued to active/, retired or never pushed)" + + +def _named_reasons(brief: dict, d: dict, planned: dict) -> dict[str, str]: + """{named task: why it did not start} for the digest (M3.6b): the plan's + rejection, or — for a named task neither picked, rejected, held by a claim + nor parked — that it has no draft prompt to start.""" + named = _brief.tasks_of(brief) + names = {Path(t).name for t in named} + out = {p: w for p, w in d["rejected"] if Path(p).name in names} + seen = {Path(p).name for p in [*out, *(m["path"] for m in d["members"]), + *(planned.get("claimed") or {}), + *(planned.get("parked") or {})]} + out.update({t: NAMED_NO_DRAFT for t in named if Path(t).name not in seen}) + return out + + def _tick_body(slot, brief, mind, now, spawner, grace_s, records, agents, tokens, health=None, pr_state=None, *, poster=None, shift=None, token_reserve=None, whoami=None, github=None) -> dict: @@ -1736,7 +1783,12 @@ def known(task: str) -> bool: "origin": planned.get("claimed") or {}, "parked": planned.get("parked") or {}, "resumed": planned.get("resume") or {}, - "scoped_reach": sorted(d.get("scoped_reach") or [])} + "scoped_reach": sorted(d.get("scoped_reach") or []), + # M3.6b: why each named task did not start (the + # digest's "Not started" reason), and the backlog + # drafts kept out for want of a `Witness:`. + "named": _named_reasons(brief, d, planned), + "witness_absent": sorted(d.get("witness_absent") or [])} paused = bool(counters.get("paused")) if _brief.is_shadow(brief): proposed = [] if paused else _propose( diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 7a59dd3..72e20c6 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -32,6 +32,7 @@ Resolve it to prompt paths; plan exactly that set as a brief's named tasks, or its named tasks go first, then the backlog dip its policy allows (`none` | `fill-idle` | `scoped:` plus `exclude:`). Backlog the brief does not cover is never dipped, and every dipped pick carries a one-line reason in the digest. +`brief --check` says why any named task will not start (AUTONOMY.md, R5 and R2). Report, per task they named: - **taken** — with its tier and review-minutes; diff --git a/tests/test_batch_brief_goals.py b/tests/test_batch_brief_goals.py index 03ff6a5..3077efe 100644 --- a/tests/test_batch_brief_goals.py +++ b/tests/test_batch_brief_goals.py @@ -123,10 +123,13 @@ def test_new_writes_the_5m_token_budget_and_leaves_the_caps_to_the_code(tmp_path assert "max-workers:" not in out and "max-sessions:" not in out -def test_goals_without_epics_or_tags_fill_idle(tmp_path): +def test_goals_without_epics_or_tags_take_the_reach_scope(tmp_path): + """M3.6b: no longer `fill-idle` — the 2026-11-16 backlog-reach ruling, + scoped by the tiers a shift may merge.""" mind = _mind(tmp_path, "# Goals\n\n## 1. Ship it\n") text = _batch.new_brief(mind, "2026-11-14-am", "2099-01-01T12:00Z") - assert " - backlog: fill-idle" in text and "scoped:" not in text + assert "fill-idle" not in text + assert " - backlog: scoped" in text and " - tiers: notify, glance" in text def test_no_goals_still_composes_but_check_refuses(tmp_path, capsys): diff --git a/tests/test_batch_named_tasks.py b/tests/test_batch_named_tasks.py new file mode 100644 index 0000000..e6d810c --- /dev/null +++ b/tests/test_batch_named_tasks.py @@ -0,0 +1,422 @@ +"""M3.6b (PyAutoBrain#667): named tasks and the planner's skips. + +Human rulings 2026-11-17 (PyAutoMind `active/shift_named_tasks_and_planner_skips.md`): + +- R5 (option a): the per-epic limit is for `Phase:` tasks only; a side task + orders itself by `Blocked-by:`; every named task that will not start is + listed with its reason at `brief --check` and in the digest. +- R2: the planner never dispatches a task whose repo another active task + claims; the digest counts those skipped. A `coordination:` / + `conflict-override:` line frees a repo only for the task it names. + +One test per Witness clause (1-7); each fails on main 8f36ae6. Fictional +fixtures only. +""" + +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_dispatch as d # noqa: E402 — the real-spawner fixtures +from test_orchestrator_dispatch import _digest, orch # noqa: E402 +import _batch # noqa: E402 + +NOW = d.NOW +ISSUE = "https://github.com/example-org/PyAutoMind/issues/42" + +PROMPT = """\ +# {name} + +Type: feature +Target: {target} +Repos: +- {target} +Difficulty: small +Autonomy: safe +Priority: normal +Status: draft +{headers}Consequence: notify +{witness}Review-minutes: 3 +Unattended: ready +Lane: any + +{body} +""" + +SHIFT = """\ +# Batch 2026-11-04 am +- dispatched: 2026-11-04T08:30Z +- review-at: 2026-11-04T11:30Z +- issue: {issue} +- brief: + - goals: + - 1. a shift + - tasks: +{tasks} + - backlog: {backlog} + - review-minutes: 45 + - lanes: any local-dev + - merge-cap: 0 + - token-budget: 100000 + - max-workers: 4 + - max-sessions: 8 +""" + + +def _write(mind: Path, name: str, *, target="PyAutoHeart", epic="", phase="", + blocked_by="", witness=True, body="Body.") -> str: + headers = "".join(f"{k}: {v}\n" for k, v in (("Epic", epic), ("Phase", phase), + ("Blocked-by", blocked_by)) if v) + rel = f"draft/feature/x/{name}.md" + f = mind / rel + f.parent.mkdir(parents=True, exist_ok=True) + f.write_text(PROMPT.format(name=name, target=target, headers=headers, body=body, + witness="Witness: a unit test\n" if witness else "")) + return rel + + +def _shift(tmp_path: Path, named=(), *, backlog="none") -> tuple[Path, Path, Path]: + mind = tmp_path / "mind" + mind.mkdir(parents=True, exist_ok=True) + (mind / "queue.md").write_text("# Queue\n\n## 1. q\n- kind: prompt\n" + "- ref: draft/feature/x/elsewhere.md\n") + tasks = "\n".join(f" - {t}" for t in named) or " - draft/feature/x/none.md" + brief = tmp_path / "shift.md" + brief.write_text(SHIFT.format(issue=ISSUE, tasks=tasks, backlog=backlog)) + return mind, brief, tmp_path / "home" + + +def _check(brief: Path, mind: Path, capsys) -> tuple[int, str]: + capsys.readouterr() + rc = _batch.main(["brief", "--check", str(brief), "--mind", str(mind), "--no-premise"]) + return rc, capsys.readouterr().out + + +def rec(path, *, epic="", phase=float("inf"), blocked_by=(), witness="a test"): + return {"path": path, "repos": [], "work_type": "feature", "difficulty": "small", + "score": 1, "consequence": "notify", "witness": witness, + "review_minutes": 3, "unattended": "ready", "why": "", "ready_why": [], + "epic": epic, "lane": "any", "priority": "normal", + "blocked": bool(blocked_by), "blocked_by": list(blocked_by), + "autonomy": "safe", "autonomy_cap": "safe", "declared_autonomy": "safe", + "done": False, "phase": phase} + + +# --- 1. a side task shares the shift with its epic's phase --------------------------- + +def test_1_a_named_phase_task_and_a_same_epic_side_task_both_dispatch(tmp_path): + mind, brief, home = _shift(tmp_path) + p5 = _write(mind, "p5a", epic="lifecycle", phase="5") + side = _write(mind, "wall_bug", epic="lifecycle") + brief.write_text(brief.read_text().replace(" - draft/feature/x/none.md", + f" - {p5}\n - {side}")) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert sorted(s["task"] for s in r["spawned"]) == ["p5a", "wall_bug"], r + + +# --- 2. two Phase tasks of one epic: the second says why it did not start ------------- + +def test_2_the_second_phase_task_of_an_epic_is_not_started_with_its_reason(tmp_path, capsys): + mind, brief, home = _shift(tmp_path) + a = _write(mind, "p5a", epic="lifecycle", phase="5a") + b = _write(mind, "p5b", epic="lifecycle", phase="5b") + brief.write_text(brief.read_text().replace(" - draft/feature/x/none.md", + f" - {a}\n - {b}")) + # At launch: `brief --check` names it, one line, with the reason. + rc, out = _check(brief, mind, capsys) + assert rc == 0, out + line = next(ln for ln in out.splitlines() if "p5b" in ln and "will not start" in ln) + assert "epic lifecycle" in line, out + assert not any("p5a" in ln and "will not start" in ln for ln in out.splitlines()) + # In the shift: the digest's "Not started" line gives the same reason. + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["p5a"], r + counters = orch.read_counters(orch.slot_dir(brief, home)) + state, _ = _digest.task_state("p5b", counters, lambda u: "?") + assert state.startswith("not started — skipped: ") and "epic lifecycle" in state, state + + +# --- 3. a side task with Blocked-by: waits for the phase it names ---------------------- + +def test_3_a_side_task_blocked_by_the_phase_prompt_waits_for_it(): + phase = "draft/feature/x/p5a.md" + dec = _batch.plan([rec(phase, epic="lifecycle", phase=5), + rec("draft/feature/x/side.md", epic="lifecycle", blocked_by=[phase])], + budget=100) + assert [m["path"] for m in dec["members"]] == [phase] + why = dict(dec["rejected"])["draft/feature/x/side.md"] + assert "p5a.md" in why and "waits" in why, why + + +# --- 4. the backlog dip skips a draft with no Witness: and counts it ------------------ + +def test_4_a_backlog_draft_with_no_witness_is_skipped_and_counted(tmp_path): + mind, brief, home = _shift(tmp_path, backlog="fill-idle") + _write(mind, "witnessed") + bare = _write(mind, "unwitnessed", witness=False) + r = d._tick(brief, mind, home, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["witnessed"], r + counters = orch.read_counters(orch.slot_dir(brief, home)) + assert counters["backlog_gates"]["witness_absent"] == [bare] + lines = _digest.backlog_gate_lines(counters) + assert any(ln.startswith("No Witness: 1 draft(s) not dipped") for ln in lines), lines + # A named task is the human's pick: no Witness: does not hold it back. + mind2, brief2, home2 = _shift(tmp_path / "named") + named = _write(mind2, "unwitnessed_named", witness=False) + brief2.write_text(brief2.read_text().replace("draft/feature/x/none.md", named)) + r = d._tick(brief2, mind2, home2, NOW, d.FakeClaude()) + assert [s["task"] for s in r["spawned"]] == ["unwitnessed_named"], r + + +# --- 5. R2: a repo another active task claims is never dispatched, and counted -------- + +def _git(cwd, *args): + res = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) + assert res.returncode == 0, (args, res.stderr) + + +def test_5_a_coordinated_claim_frees_its_repo_only_for_the_task_it_names(tmp_path): + if shutil.which("git") is None: + pytest.skip("needs git") + bare, mind = tmp_path / "mind.git", tmp_path / "mind" + _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare)) + _git(tmp_path, "clone", "-q", str(bare), str(mind)) + other = _write(mind, "grid_offset_roundtrip", target="PyAutoCortex") + sharer = _write(mind, "three_autos_public_framing", target="PyAutoCortex") + (mind / "active.md").write_text( + "# Active\n\n## ep-projected-model-shared-prior\n- status: library-dev\n" + "- repos:\n - PyAutoCortex: feature/ep-projected-model-shared-prior\n" + "- conflict-override: PyAutoCortex also claimed by three-autos-public-framing; " + "human approved a separate worktree\n") + _git(mind, "add", "-A") + _git(mind, "-c", "user.name=T", "-c", "user.email=t@example.invalid", "commit", "-q", + "-m", "seed") + _git(mind, "push", "-q", "origin", "HEAD:main") + _git(mind, "fetch", "-q", "origin") + records = [_batch.grade(mind / p, mind) for p in (other, sharer)] + kept, out = orch.on_origin(records, mind, own=set()) + assert [r["path"] for r in kept] == [sharer] + assert out == {other: "repo PyAutoCortex claimed by `ep-projected-model-shared-prior` " + "in active.md on Mind origin/main"} + lines = _digest.backlog_gate_lines({"backlog_gates": {"origin": out}}) + assert any(ln.startswith("Repo claimed on Mind origin/main: 1 draft(s) skipped") + for ln in lines), lines + + +# --- 6. `brief --new` defaults to the backlog-reach scope ------------------------------ + +def test_6_brief_new_writes_the_scoped_reach_default_not_fill_idle(tmp_path, capsys): + mind = tmp_path / "mind" + mind.mkdir() + (mind / "goals.md").write_text("# Goals\n\n## 1. Land the flywheel rework\n") + text = _batch.new_brief(mind, "2026-11-17-pm", "2099-01-01T12:00Z", issue=ISSUE) + assert "fill-idle" not in text + assert " - backlog: scoped" in text and " - tiers: notify, glance" in text, text + assert "2026-11-16" in text # the ruling it applies is named on the line + brief = tmp_path / "brief.md" + brief.write_text(text) + rc, out = _check(brief, mind, capsys) + assert rc == 0, out + + +# --- 7. the organ rule at `--check`: a renderer passes, saying why --------------------- + +def test_7_a_named_renderer_task_passes_the_organ_rule_with_a_line(tmp_path, capsys): + mind, brief, _ = _shift(tmp_path) + render = _write(mind, "dashboard_census", target="PyAutoBrain", + body="Fix the census in `agents/conductors/intake/_dashboard.py`.") + brief.write_text(brief.read_text().replace("draft/feature/x/none.md", render)) + rc, out = _check(brief, mind, capsys) + assert rc == 0, out + line = next(ln for ln in out.splitlines() if "dashboard_census" in ln and "organ" in ln) + assert "not the watcher, writer or release path" in line, out + # One that names the shift's own code is refused. + watcher = _write(mind, "tick_fix", target="PyAutoBrain", + body="Change `agents/conductors/batch/_orchestrator.py`.") + brief.write_text(brief.read_text().replace(f" - {render}", + f" - {render}\n - {watcher}")) + rc, out = _check(brief, mind, capsys) + assert rc != 0 + assert any("tick_fix" in ln and "✗" in ln and "watcher, writer or release path" in ln + for ln in out.splitlines()), out + # One that names no path at all is the human's call: a warning, not a refusal. + vague = _write(mind, "vague", target="PyAutoMind", body="Tidy it up.") + brief.write_text(brief.read_text().replace(f" - {watcher}\n", f" - {vague}\n")) + rc, out = _check(brief, mind, capsys) + assert rc == 0, out + assert any("vague" in ln and "!" in ln and "names no path" in ln + for ln in out.splitlines()), out + + +# --- review fixes (Fable 5.2, FINDINGS 1, 2, 3, 7, 8) ----------------------------------- + +def _organ(tmp_path, body, *, target="PyAutoBrain", repos=None): + """organ_findings for one prompt with `body`, declaring `repos` (default: the target).""" + mind = tmp_path / "mind" + (mind / "scripts").mkdir(parents=True, exist_ok=True) + (mind / "scripts" / "lifecycle.py").write_text("") + rel = _write(mind, "t", target=target, body=body) + if repos is not None: + f = mind / rel + f.write_text(f.read_text().replace(f"Repos:\n- {target}\n", + "Repos:\n" + "".join(f"- {r}\n" for r in repos))) + return _batch._brief.organ_findings("t", mind / rel, mind) + + +@pytest.mark.parametrize("body", [ + "Change `example-org/PyAutoBrain/agents/conductors/batch/_orchestrator.py`.", + "Change `./agents/conductors/batch/_orchestrator.py`.", + "Change `/home/u/PyAutoBrain/agents/conductors/batch/_orchestrator.py`.", + "Change `_orchestrator.py` and `agents/conductors/intake/_dashboard.py`.", + "Change agents/conductors/batch/_orchestrator.py and `docs/x.md`.", + "Change `PyAutoMind/scripts/lifecycle.py`.", + "Change `lifecycle.py` in Mind.", +]) +def test_review_the_shift_own_code_is_refused_however_it_is_written(tmp_path, body): + target = "PyAutoMind" if "lifecycle.py` in" in body else "PyAutoBrain" + errors, warnings, notes = _organ(tmp_path, body, target=target) + assert errors and "watcher, writer or release path" in errors[0], (errors, warnings, notes) + + +@pytest.mark.parametrize("body", [ + "Then run `/prm` and see `/`.", + "Touch `*/__init__.py` across `example-org/PyAutoEyes`.", + "Edit `PyAutoHeart/scripts/x.py`.", +]) +def test_review_non_paths_and_other_repos_paths_are_not_refused(tmp_path, body): + errors, _, _ = _organ(tmp_path, body, target="PyAutoBrain", + repos=["PyAutoBrain", "PyAutoHands", "PyAutoHeart"]) + assert errors == [] + + +def test_review_an_unprefixed_self_path_with_other_repos_declared_is_the_humans_call(tmp_path): + errors, warnings, _ = _organ(tmp_path, "Run `scripts/fit.py` on the cluster.", + target="PyAutoMind", repos=["PyAutoMind", "PyAutoHeart"]) + assert errors == [] and warnings and "the human decides" in warnings[0] + + +def test_review_a_phase_label_keeps_its_leading_number_and_counts_as_a_phase(): + assert _batch._phase_of("Phase: 5A\n") == 5 and _batch._phase_of("Phase: 6b2\n") == 6 + assert _batch._phase_of("Phase: C2\n") == float("inf") and _batch._phase_declared("Phase: C2\n") + a, b = rec("a.md", epic="e", phase=5), rec("b.md", epic="e", phase=float("inf")) + b["phase_declared"] = True # `Phase: C2`: a phase, not a side task + dec = _batch.plan([a, b], budget=100) + assert [m["path"] for m in dec["members"]] == ["a.md"] + assert dict(dec["rejected"])["b.md"] == "epic e phase (unnumbered) is not next" + + +@pytest.mark.parametrize("task", ["coordination", "conflict_override", "human"]) +def test_review_the_coordination_key_and_common_words_free_nothing_by_themselves(task): + sec = {"coordination": orch._COORDINATION_LINE_RE.search( + "- conflict-override: human approved sharing with three-autos-public-framing").group(1)} + assert not orch.coordinated_for(sec, task if task != "human" else "humans") + assert orch.coordinated_for(sec, "three_autos_public_framing") + + +def test_review_a_named_task_already_in_active_says_why_it_will_not_start(tmp_path, capsys): + mind, brief, _ = _shift(tmp_path) + issued = mind / "active" / "already.md" + issued.parent.mkdir(parents=True) + issued.write_text(PROMPT.format(name="already", target="PyAutoHeart", headers="", + witness="Witness: a unit test\n", body="Body.")) + brief.write_text(brief.read_text().replace("draft/feature/x/none.md", + "draft/feature/x/already.md")) + rc, out = _check(brief, mind, capsys) + assert any("already" in ln and "will not start" in ln and "in active/" in ln + for ln in out.splitlines()), out + + +def test_review_a_resumed_task_is_not_held_back_for_want_of_a_witness(): + r = rec("draft/feature/x/r.md", witness=None) + r["resume"] = ["Q3"] + brief = {"backlog": {"value": "fill-idle", "children": []}, + "lanes": {"value": "any", "children": []}} + dec = _batch.plan([r], budget=100, brief=brief, queue=["x"]) + assert [m["path"] for m in dec["members"]] == ["draft/feature/x/r.md"], dec["rejected"] + + +# --- second review (Fable 5.2) --------------------------------------------------------- + +@pytest.mark.parametrize("body,target", [ + ("Rework everything under `agents/conductors/batch/`.", "PyAutoBrain"), + ("Rework `PyAutoBrain/agents/conductors/batch/` and `docs/x.md`.", "PyAutoBrain"), + ("Edit `.github/workflows/` and `docs/x.md`.", "PyAutoMind"), + ("Edit `scripts/` and `docs/x.md`.", "PyAutoMind"), + ("Edit `agents/conductors/batch/_*.py` and `tests/test_x.py`.", "PyAutoBrain"), + ("Reword `worker_template.md` and `docs/x.md`.", "PyAutoBrain"), + ("Change _orchestrator.py and `docs/x.md`.", "PyAutoBrain"), + ("See `/home/u/worktrees/PyAutoBrain-foo/agents/conductors/batch/_batch.py`.", "PyAutoBrain"), + ("See `Agents/Conductors/Batch/_batch.py`.", "PyAutoBrain"), + ("See `agents/conductors/batch/autolens.py` and `docs/x.md`.", "PyAutoBrain"), +]) +def test_review2_self_code_is_refused_in_every_spelling(tmp_path, body, target): + errors, warnings, notes = _organ(tmp_path, body, target=target) + assert errors, (warnings, notes) + + +@pytest.mark.parametrize("body", [ + "Fires on `example-org/PyAutoPulse` and `example-org/PyAutoHands`.", + "Moves the watcher, as `draft/feature/pyautobrain/other.md` and `batches/2026-11-13-am.md` say.", + "From v1.2/v1.3.0 onwards.", +]) +def test_review2_repo_names_mind_records_and_versions_show_nothing(tmp_path, body): + errors, warnings, notes = _organ(tmp_path, body, target="PyAutoBrain") + assert errors == [] and notes == [] and "names no path" in warnings[0], (errors, warnings) + + +def test_review2_branch_names_are_not_hands_paths(tmp_path): + """Any real path in a Hands-only task is Hands code (the approved rule); + a branch name is not a path.""" + errors, warnings, _ = _organ(tmp_path, "Push `origin/main` from `feature/x`.", + target="PyAutoHands") + assert errors == [] and "names no path" in warnings[0] + + +def test_review2_a_target_header_naming_several_repos_is_read(tmp_path): + mind = tmp_path / "mind" + rel = _write(mind, "t", target="PyAutoHeart", + body="Change `agents/conductors/batch/_batch.py`.") + f = mind / rel + f.write_text(f.read_text().replace("Target: PyAutoHeart", "Target: PyAutoBrain, PyAutoMind")) + errors, _, _ = _batch._brief.organ_findings("t", f, mind) + assert errors + + +# --- third review (Fable 5.2) ---------------------------------------------------------- + +def test_review3_a_repos_own_ci_workflow_is_not_the_minds(tmp_path): + errors, _, notes = _organ(tmp_path, "Edit `.github/workflows/tests.yml`.", target="PyAutoBrain") + assert errors == [] and notes, notes + errors, warnings, _ = _organ(tmp_path, "Edit `.github/workflows/heart-health.yml`.", + target="PyAutoBrain", repos=["PyAutoBrain", "PyAutoHeart"]) + assert errors == [] + + +@pytest.mark.parametrize("body", ["Add a workflow under `.github/workflows` and update `docs/x.md`.", + "Add `scripts` and update `docs/x.md`."]) +def test_review3_a_self_directory_without_its_slash_is_still_read(tmp_path, body): + errors, _, _ = _organ(tmp_path, body, target="PyAutoMind") + assert errors + + +@pytest.mark.parametrize("body", ["See `PyAutoBrain/`.", "See `example-org/PyAutoBrain/`.", + "As `../../../active/foo.md` says."]) +def test_review3_repo_dirs_and_relative_records_show_nothing(tmp_path, body): + errors, warnings, notes = _organ(tmp_path, body, target="PyAutoBrain") + assert errors == [] and notes == [] and "names no path" in warnings[0], (warnings, notes) + + +def test_review4_the_batch_conductor_is_refused_whatever_the_task_declares(tmp_path): + errors, _, _ = _organ(tmp_path, "Edit `agents/conductors/batch/_orchestrator.py`.", + target="PyAutoMind") + assert errors + errors, _, _ = _organ(tmp_path, "Edit `PyAutoMind/scripts` and `docs/x.md`.", + target="PyAutoMind") + assert errors diff --git a/tests/test_batch_plan.py b/tests/test_batch_plan.py index 80129bf..5cd171f 100644 --- a/tests/test_batch_plan.py +++ b/tests/test_batch_plan.py @@ -75,7 +75,9 @@ def test_non_library_repos_do_not_claim_a_shift(): def test_one_slice_per_epic(): - d = _batch.plan([rec("a.md", epic="euclid"), rec("b.md", epic="euclid")], + """One `Phase:` task per epic (ruling R5, 2026-11-17); a side task with no + `Phase:` is not counted (tests/test_batch_named_tasks.py).""" + d = _batch.plan([rec("a.md", epic="euclid", phase=2), rec("b.md", epic="euclid", phase=2)], budget=100) assert paths(d) == ["a.md"] assert "epic euclid already" in why(d, "b.md") diff --git a/tests/test_m31_live_shift_findings.py b/tests/test_m31_live_shift_findings.py index 34c2f51..fd12f60 100644 --- a/tests/test_m31_live_shift_findings.py +++ b/tests/test_m31_live_shift_findings.py @@ -221,11 +221,13 @@ def test_4_a_task_on_a_repo_claimed_on_origin_is_skipped_unless_coordinated(tmp_ git(tmp_path, "clone", "-q", str(bare), str(mind)) paths = [_write(mind, n, repos=(r,)) for n, r in (("a1", "PyAutoEyes"), ("a2", "PyAutoPulse"), ("a3", "PyAutoCortex"))] + # The coordination line names a2: since ruling R2 (M3.6b) it frees the + # repo only for the task it names (tests/test_batch_named_tasks.py). (mind / "active.md").write_text( "# Active\n\n## earlier-pick\n- status: workspace-dev\n- repos:\n" " - PyAutoEyes: feature/earlier-pick\n- prompt: active/z.md\n\n" "## shared-claim\n- repos:\n - PyAutoPulse (feature/shared)\n" - "- coordination: human approved sharing this repo\n") + "- coordination: human approved sharing this repo with a2\n") _commit(mind, "seed") git(mind, "push", "-q", "origin", "HEAD:main") git(mind, "fetch", "-q", "origin") diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index c7f6021..91c7e54 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -181,7 +181,9 @@ def test_digest_separates_brief_work_from_backlog_picks_with_reasons(tmp_path): assert ("- **Merged with NO merge slot — needs you** — [named](https://github.com/o/r/pull/1)\n" " `named` · glance · small · pyautoheart · merged in-turn with NO merge slot" " — R3 revert-condition evidence") in work - assert "- **Not started** — never\n `never` · not started" in work + # The fixture writes no prompt for `never`: it says so (M3.6b, R5). + assert ("- **Not started** — never\n `never` · not started — skipped: no draft " + "prompt for it (already issued to active/, retired or never pushed)") in work assert "blob/main" not in d # Green and glance: since phase 4b its close-out is running at review time. assert ("- **Still running — close-out checking it** — [picked](https://github.com/o/r/pull/2)\n"