diff --git a/AUTONOMY.md b/AUTONOMY.md index 29259768..1a658b86 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -383,7 +383,9 @@ never an assumption: 5. **Independent adversary** — **added 2026-08-30, required for a BATCH launch** (below) and for any run counting toward the multi-repo autonomy experiment; optional elsewhere. A second reading of the same diff by a - **different model from the one that wrote it**, whose job is not to review + **different model from the one that wrote it** (since 2026-11-22 an + independent Opus session by default: "Adversary model default — + 2026-11-22" below), whose job is not to review the change but to **falsify its claims — the `Witness:` first**. Run it as `pyauto-brain review --task --witness "" --adversary`. @@ -819,6 +821,45 @@ ignored Heart state. The stage-2 window is how this is checked. `merged-after-substantive-change`, restores the different-model requirement for unattended merges at once, by dated doctrine edit citing the row. +## Adversary model default — 2026-11-22 + +Amends leg 5 of "The autonomous-ship gate" and extends the "Stage-2 adversary +amendment — 2026-11-04" above from the unattended close-out to every +adversary and independent-review pass the orchestrator starts. Ruled by the +human 2026-11-22, in the review of shifts 2026-11-19-pm, -pm2 and +2026-11-20-am: "I dont think I want fable used by orchestrator as default as +fable eats more usage. Opus review default is fine". This section is that +dated doctrine edit. + +**The default reader is Opus.** The independent review (leg 3) and the +adversary (leg 5) of shift work run on **Opus, in a fresh session or +sub-agent that did not write the branch** and shares none of the author's +context. That covers the worker's own review, the close-out session, and the +adversary pass a cockpit or review chat runs before the human's `/prm`. A +chat whose own model is Fable still starts the pass as an Opus sub-agent; it +does not read the diff adversarially itself. + +**Fable only when asked.** A more expensive model reads a branch as the +adversary only when the human asks for it, for that pass. Nothing in a brief, +a skill or a record makes it the default. + +**What keeps it the leg.** Independence of session, as in the 2026-11-04 +amendment: the reader did not write the PR, runs the `Witness:` itself and +tries to falsify the claims. **A self-run adversary leg is still an absent +leg**: the author's own session re-reading its diff is not this pass, +whatever model it is on. `batch collect` reads it so: an adversary row whose +`model` equals its `author_model` passes only with `independent_session: +true`. + +**What is given up** is what the 2026-11-04 amendment names: two runs of one +model share blind spots. Its revert condition stands for unattended merges and +is not widened here. + +*Revert condition:* a defect that reaches `main` through a PR whose only +adversary was a same-model session, and that the human judges a different +model would have caught, reopens this default by dated doctrine edit citing +the PR. + ## Merge actor and random audit — 2026-11-12 Amends "The `glance` Shadow-window ruling — 2026-11-04" above: it puts that @@ -1351,6 +1392,8 @@ run id beyond its tries retires the watcher to fake mode. **Login probe — 2026-11-17.** The watcher runs `claude auth status --json` (local, no model call) on a shift's first tick and when a worker shows as blocked. `loggedIn: false`, or a `loginExpiresAt` already passed, is a `login-expired` event, never "blocked on a person", and no worker starts until it passes. +**RAL probe — 2026-11-22.** `batch brief --check`, for a brief whose `lanes:` include `ral`, runs one `ssh -o BatchMode=yes -o ConnectTimeout=10 true` in the launch chat (`agents/conductors/batch/_ral.py`). It never prompts, sends nothing but `true`, and a failure is a warning, never a refusal. The watcher never runs it. The host comes from `PYAUTO_RAL_SSH_HOST` or the Mind's `policy/hpc_ral.md`; `PYAUTO_RAL_PROBE=off` skips it. Asked for by the human 2026-11-22 after shift 2026-11-20-am granted a lane its worker could not reach. + ## Human override for Heart RED (development only) Heart RED still parks every autonomous run and blocks every release. After the @@ -1644,6 +1687,9 @@ Codex hook list. need the adversary leg. - `batch` (the close-out session) — "Stage-2 adversary amendment" (2026-11-04): the independent close-out session is the adversary leg, same model allowed. +- `batch`, `cockpit`, `review`, `MODEL_DELEGATION.md` — "Adversary model + default" (2026-11-22): every review and adversary pass the orchestrator + starts is an independent Opus session; Fable only when the human asks. - `batch` (the watcher) — "The watcher's network surface" (2026-11-03): what the watcher may reach, and that it is opt-in, laptop-only and never writes; amended 2026-11-12 (mentions, #611) and 2026-11-13 (the live status comment diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 53a9487f..0657047e 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -230,6 +230,14 @@ a re-run never makes a second; `--issue ` names one by hand; `PYAUTO_BRIEF_ISSUE=off` skips it. The issue is made last, just before the write: if `gh` fails, no brief is written (exit 1), and if the write fails after it, the URL is printed to re-run with `--issue `. + +**The RAL probe (2026-11-22).** For a live brief whose `lanes:` include `ral`, +`brief --check` runs one `ssh -o BatchMode=yes true` (`_ral.py`) and +warns when unattended key auth fails — shift 2026-11-20-am granted `ral` and +its worker parked on "Too many authentication failures". A warning, never a +refusal; launch chat only, never the watcher. The host is +`PYAUTO_RAL_SSH_HOST`, else the "SSH alias" in the Mind's +`policy/hpc_ral.md`; `PYAUTO_RAL_PROBE=off` skips it. `brief --check` then adds what only a launch needs (`_brief.launch_errors`, `login_findings`): a live brief (not `shadow: yes`) without a GitHub issue URL is refused (`issue: missing — …`), and so is a CLI login that has expired @@ -706,7 +714,10 @@ interval. tick takes the newest earlier slot's late `glance`/`notify` PRs (never closed out, or refused only for going green too near `review-at:`) into its own close-out path under its own grant, and the digest names them ("Carried over -from …"). A task this shift parked on a question restarts this shift when the +from …"). A carried PR the human merged between the shifts is settled: no +close-out, no entry, no proof packet, one line ("… PR(s) you had already +merged — nothing to do"), and it drops out of the merge order with any earlier +PR GitHub reads MERGED or CLOSED (2026-11-22). A task this shift parked on a question restarts this shift when the inbox answers it with more than 30 minutes left (once per answer; a release waits for its spawn, else the park stays for the next shift); the writer's fetch repeats for that only while such a park is open, at most every 10 minutes. @@ -748,7 +759,8 @@ stays for other triggers). The reap queues one `question-add` op per issue (`land_question`): the task's prompt, the issue, `kind: question` (or `blocked`, filed on the shift issue), the ask and options from the worker's `{task}.question.json` sidecar (sanitised; `see the question on the issue` -without one), the shift, the time and the worker. The one Mind writer lands +without one; it sits in `leases/` and is never read as a lease — until +2026-11-22 each one held a worker slot to `review-at:`), the shift, the time and the worker. The one Mind writer lands it in PyAutoMind `questions.md` through Mind's own `questions_edit.add_text`. The digest gets one line under its heading (`Inbox: N questions added to your inbox this shift (Q17, Q18), M open in all — `), and the @@ -1020,8 +1032,10 @@ adversary (`AUTONOMY.md` leg 5). Run it before reading a PR: pyauto-brain review --task --witness "" --adversary ``` -in a session **using a different model from the one that wrote the branch**. A -self-run adversary leg is an absent leg, not a weak one. `collect` cannot run +in a session **that did not write the branch — by default a fresh Opus +session or sub-agent, even when your own chat is on Fable**; a more expensive +model reads only when the human asks (`AUTONOMY.md` "Adversary model default — +2026-11-22"). A self-run adversary leg is an absent leg, not a weak one. `collect` cannot run it for you and does not pretend to: with no `adversary` block in the evidence the leg is UNOBSERVABLE and the member reaches the human as SUSPECT — the honest state, rather than a gap that closes itself. The shift worker does not @@ -1059,10 +1073,13 @@ is unobservable and its member reaches the human as SUSPECT. Inventing PASS would be inventing evidence and FAIL would condemn healthy work — the same choice the Cortex conductor makes for the `delivered:` legs it cannot see. -`adversary` is the leg with a rule of its own: it passes only when the read ran -under a model that is not the branch's author. **A self-run adversary leg is an -absent leg, not a weak one** (`AUTONOMY.md` leg 5), so an equal or missing -`author_model` is FAIL, not PASS. +`adversary` is the leg with a rule of its own: it passes only when the read was +independent of the branch's author. **A self-run adversary leg is an absent +leg, not a weak one** (`AUTONOMY.md` leg 5), so a missing `model` or +`author_model` is FAIL, and so is an equal one unless the row carries +`"independent_session": true` — the default Opus reader of an Opus branch, in +a session that did not write it (`AUTONOMY.md` "Adversary model default — +2026-11-22"). ### Six health words, in the order the human reads them diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index c434537c..cc4870f7 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -57,6 +57,7 @@ import _brief # noqa: E402 import _green # noqa: E402 — the keep-Heart-green lane (PyAutoBrain#625) import _login # noqa: E402 — the CLI login probe (M3.6a, PyAutoBrain#659) +import _ral # noqa: E402 — the unattended-ssh probe for a granted `ral` lane # The human's goals (goals.md, PyAutoMind#565): `brief --new` copies them. from _steer import read_goals # noqa: E402,F401 — re-exported beside read_queue # The close-out guard's reader (intake `looks-shipped`): the live flags minus @@ -1516,13 +1517,17 @@ def leg_adversary(ev) -> tuple: if not isinstance(row, dict) or not row.get("ran"): return UNOBSERVABLE, "no adversary leg recorded" model, author = (row.get("model") or ""), (row.get("author_model") or "") - if not model or not author or model == author: - # AUTONOMY.md leg 5, verbatim in intent: the leg is a reading by a - # DIFFERENT model from the one that wrote the diff. + # AUTONOMY.md leg 5: the leg is a reading independent of the author. A + # different model is one; so is the same model in a session that did not + # write the branch ("Adversary model default — 2026-11-22": Opus reads + # Opus by default), which the row must say — it is never assumed. + independent = row.get("independent_session") is True + if not model or not author or (model == author and not independent): return FAIL, ("a self-run adversary leg is an absent leg, not a weak " "one (AUTONOMY.md leg 5)" + (f" — model {model}" if model else " — no model named")) - return PASS, f"{model} vs author {author}: {row.get('verdict') or 'read'}" + how = "independent session" if model == author else f"vs author {author}" + return PASS, f"{model} {how}: {row.get('verdict') or 'read'}" #: Health, in the order the packet shows members in: what failed, what did not @@ -3922,6 +3927,11 @@ def _main_brief(mind: Path, a) -> int: res["login"] = login res["errors"] += errs res["warnings"] += warns + # A granted `ral` lane a worker cannot reach (2026-11-20-am): one + # BatchMode ssh, a warning only. A shadow brief starts no worker. + if rec["brief"] is not None and not _brief.is_shadow(rec["brief"]): + res["ral"], warns = _ral.findings(_brief.lanes_of(rec["brief"]), mind) + res["warnings"] += warns res["ok"] = not res["errors"] warn = goal_one_warning(Path(a.check), mind) if warn: diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 5f219230..3d868d21 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -240,7 +240,17 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, return f"{word} — awaiting re-dispatch", True return f"{NOT_REDISPATCHED}: {redispatch_why(task, counters)}", False skipped = gate_why(task, counters) - return ("not started — skipped: " + skipped if skipped else "not started"), False + if skipped: + return "not started — skipped: " + skipped, False + # Neither claimed nor rejected, yet never started: the spawn gate + # refused it (2026-11-20-am: a named task waited on `max-workers` + # all shift and its entry said only "not started"). + last = max((r for r in counters.get("refusals", []) if r.get("task") == task), + key=lambda r: r.get("last") or r.get("at") or "", default=None) + if last: + return (f"not started — refused: {last.get('why') or last.get('class') or '?'} " + f"(last {last.get('last') or last.get('at') or '?'})"), False + return "not started", False urls = urls_of(out) if not urls and "obsolete" in out: return ("obsolete (premise check): " @@ -268,6 +278,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, state = wait_state(url, counters) # merge order (M3.6j, #683) elif url in (counters.get("sweep_waits") or {}): state = sweep_wait_state(url, counters) # unknown sweep (M3.7e, #694) + elif co.get("settled"): + state = co.get("why") or SETTLED elif co.get("state") == "refused": state = f"awaiting /prm — close-out refused: {co.get('why', '?')}" elif co.get("state") == "running": @@ -283,6 +295,26 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, return "; ".join(parts), True +#: A carried-over PR the human merged between shifts: nothing is left to do. +SETTLED = "already merged" + + +def settled_prs(counters: dict) -> set[str]: + """The carried-over PRs GitHub read MERGED when this shift first looked.""" + return {u for u, co in (counters.get("closeouts") or {}).items() + if isinstance(co, dict) and co.get("settled")} + + +def is_settled(task: str, counters: dict) -> bool: + """Whether a carried-over task has nothing left for anyone: every PR it + carried was already merged by the human. Such a task is named once, in + the carry-over line, and has no entry and no proof packet (its packet is + in the digest of the shift that ran it).""" + out = (counters.get("outcomes") or {}).get(task) or {} + urls = urls_of(out) + return bool(out.get("carried_from") and urls) and set(urls) <= settled_prs(counters) + + #: A PR's states in the merge order (M3.6j, PyAutoBrain#683). UPDATING = "close-out updating the branch from main" UPDATED = "branch updated from main" @@ -302,6 +334,8 @@ def _order_word(url: str, counters: dict) -> str: co = (counters.get("closeouts") or {}).get(url) or {} if url in (counters.get("merge_waits") or {}): return "itself waiting" + if co.get("settled"): + return SETTLED if co.get("state") == "refused": return f"needs your /prm: {refusal_class(co.get('why') or '?')}" if co.get("state") == "running": @@ -339,6 +373,9 @@ def merge_order_lines(counters: dict) -> list[str]: return [] merged = {u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict) for u in o.get("merged") or []} + # A PR GitHub read MERGED or CLOSED is no longer in the order: one the + # human merged between shifts, or an earlier PR a carried one waited on. + merged |= settled_prs(counters) | set(counters.get("pr_gone") or {}) known = list(dict.fromkeys( u for o in (counters.get("outcomes") or {}).values() if isinstance(o, dict) for u in [*(o.get("prs") or []), *(o.get("behind") or [])])) @@ -395,7 +432,8 @@ def waited_lines(counters: dict) -> list[str]: a count; and how many PRs were refused because their labels could not be read (S7). Empty when there is neither.""" cos = counters.get("closeouts") or {} - refused = {u: co for u, co in cos.items() if co.get("state") == "refused"} + refused = {u: co for u, co in cos.items() + if co.get("state") == "refused" and not co.get("settled")} groups: dict[tuple, list[str]] = {} for url, info in (counters.get("merge_waits") or {}).items(): bound = [b for b in info.get("behind") or [] if b in refused] @@ -620,6 +658,7 @@ def label(task: str, pick: dict | None, url: str = "") -> str: _PLAIN = ( (IN_TURN_NO_SLOT, "Merged with NO merge slot — needs you"), ("merged", "Merged"), + (SETTLED, "Already merged — nothing to do"), ("awaiting /prm — close-out refused: CI FAILED", "CI failed — needs you"), ("awaiting /prm — close-out refused: CI RED", "CI failed — needs you"), ("awaiting /prm", "Needs you — not merged unattended"), @@ -693,10 +732,14 @@ def held_leases(slot: Path) -> dict[str, dict]: because this module must not import the orchestrator.""" out = {} for f in sorted((Path(slot) / "leases").glob("*.json")): + if f.name.endswith(_questions.SIDECAR_SUFFIX): + continue # a parked worker's question sidecar, never a lease try: - out[f.stem] = json.loads(f.read_text()) + lease = json.loads(f.read_text()) except (OSError, ValueError): continue + if isinstance(lease, dict): + out[f.stem] = lease return out @@ -735,7 +778,9 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, pass picks = counters.get("picks", {}) named = [Path(p).stem for p in _brief.tasks_of(brief)] - backlog = [t for t in picks if t not in named] + # A carried-over task the human already merged is named once, in the + # carry-over line, never as an entry or an empty proof packet. + backlog = [t for t in picks if t not in named and not is_settled(t, counters)] lines = [DIGEST_HEADING, ""] lines += closed_early_lines(counters) @@ -957,11 +1002,18 @@ def names(paths): f"`{t}` ({', '.join(v.get('ids') or [])} answered)" for t, v in sorted(resumed.items())[:SUMMARY_NAMES])) carried = counters.get("carried_in") or {} - if carried.get("prs"): - out.append(f"Carried over from {carried['from']}: {len(carried['prs'])} late PR(s) " - "closed out under this shift's grant — " + ", ".join(carried["prs"][:SUMMARY_NAMES]) - + (f" +{len(carried['prs']) - SUMMARY_NAMES} more" - if len(carried["prs"]) > SUMMARY_NAMES else "")) + done = [u for u in carried.get("prs") or [] if u in settled_prs(counters)] + left = [u for u in carried.get("prs") or [] if u not in done] + + def names(urls): + return ", ".join(urls[:SUMMARY_NAMES]) + ( + f" +{len(urls) - SUMMARY_NAMES} more" if len(urls) > SUMMARY_NAMES else "") + if left: + out.append(f"Carried over from {carried['from']}: {len(left)} late PR(s) " + "closed out under this shift's grant — " + names(left)) + if done: + out.append(f"Carried over from {carried['from']}: {len(done)} PR(s) you had already " + "merged — nothing to do — " + names(done)) again = counters.get("inshift_released") or {} if again: out.append(f"Restarted in-shift after an answer: {len(again)} task(s) — " diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 0e36da3c..96f351b5 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -1068,13 +1068,24 @@ def task_id(prompt_path: str) -> str: return Path(prompt_path).stem +def lease_files(slot: Path) -> list[Path]: + """The lease files of a slot. A parked worker's `{task}.question.json` + sidecar shares the folder and is not a lease: read as one it had no pid, + `_alive(0)` called it running, and it held a worker slot to `review-at:` + (2026-11-20-am: four sidecars filled `max-workers 4`, 11 tasks waited).""" + return [f for f in sorted((Path(slot) / "leases").glob("*.json")) + if not f.name.endswith(_questions.SIDECAR_SUFFIX)] + + def leases(slot: Path) -> dict[str, dict]: out = {} - for f in sorted((slot / "leases").glob("*.json")): + for f in lease_files(slot): try: - out[f.stem] = json.loads(f.read_text()) + lease = json.loads(f.read_text()) except (OSError, ValueError): continue + if isinstance(lease, dict): + out[f.stem] = lease return out @@ -4416,6 +4427,10 @@ def _merge_blockers(counters: dict, pr: str, pr_state, cache: dict) -> list[str] continue gh = _gh_once(pr_state, cache, u) if (gh or {}).get("state") in ("MERGED", "CLOSED"): + # Remembered for the digest's merge order: an earlier PR the + # human merged or closed is no longer one to merge first + # (2026-11-19-pm2 listed one as "open" twenty minutes after its merge). + counters.setdefault("pr_gone", {})[u] = gh["state"] continue out.append(u) return out @@ -4635,6 +4650,17 @@ def refuse(pr: str, task: str, why: str, held: bool = False) -> None: if not gh: continue # GitHub unreadable: asked again next tick, never assumed state = gh.get("state") + if state == "MERGED": + # Merged by the human since its shift: settled, nothing left + # for anyone. Final like a refusal (no close-out, no count as + # an unattended merge), but the digest never lists it as + # needing the human (2026-11-19-pm2 and 2026-11-20-am did). + refuse(pr, task, f"{_digest.SETTLED} since {out['carried_from']}" + + (f" (by {gh['mergedBy']})" if gh.get("mergedBy") else ""), + held=again) + counters["closeouts"][pr].update(settled="merged", github=gh) + events.setdefault("merged_outside", []).append(pr) + continue if state != "OPEN": refuse(pr, task, f"carried over from {out['carried_from']}, but GitHub reads " f"it {state or '?'} — not closed out", held=again) @@ -4928,7 +4954,7 @@ def _owes(slot: Path) -> str: ops = len(_mind_writer.pending_ops(slot)) if ops: bits.append(f"{ops} queued Mind op{'s' if ops != 1 else ''}") - n = len(list((slot / "leases").glob("*.json"))) + n = len(lease_files(slot)) bits.append(f"{n} lease{'s' if n != 1 else ''}") return "; ".join(bits) diff --git a/agents/conductors/batch/_ral.py b/agents/conductors/batch/_ral.py new file mode 100644 index 00000000..01451e9c --- /dev/null +++ b/agents/conductors/batch/_ral.py @@ -0,0 +1,107 @@ +"""The unattended-ssh probe for a brief that grants the `ral` lane. + +Shift 2026-11-20-am ran with `lanes: any local-dev ral` and a +`ral-allowance:`, and its one worker that needed RAL could not reach it: +`Permission denied … Too many authentication failures`, key auth through the +jump host with nobody to answer. It spent a session and parked on a question. +Nothing at launch had said the lane was unusable. + +`batch brief --check` therefore asks once, for a brief whose `lanes:` include +`ral`: `ssh -o BatchMode=yes -o ConnectTimeout=10 true`. BatchMode +never prompts, so the answer is what a worker will get. The result is one of: + +- `ok` — the host answered; +- `failed` — ssh ran and exited non-zero (its last line is the detail); +- `unknown` — no `ssh` on PATH, the call timed out, or no host is named; +- `skipped` — `PYAUTO_RAL_PROBE=off` (the test suite; a machine with no RAL). + +Anything but `ok` and `skipped` is a **warning, never a refusal**: the human +may be about to fix it, and a brief with no RAL task loses nothing. It runs in +the launch chat only, never in the watcher (AUTONOMY.md "The watcher's network +surface", RAL probe — 2026-11-22). + +The host is the tenant's, so it is never written here. `PYAUTO_RAL_SSH_HOST` +names it; otherwise it is read from the Mind's own access note, +`policy/hpc_ral.md` ("SSH alias ``"). +""" + +from __future__ import annotations + +import os +import re +import subprocess +from pathlib import Path + +PROBE_ENV = "PYAUTO_RAL_PROBE" +HOST_ENV = "PYAUTO_RAL_SSH_HOST" +#: Where a Mind records how its cluster is reached. +POLICY_FILE = "policy/hpc_ral.md" +_ALIAS_RE = re.compile(r"SSH alias `([A-Za-z0-9][\w.-]*)`") +_HOST_RE = re.compile(r"^[A-Za-z0-9][\w.@-]*$") +CONNECT_TIMEOUT_S = 10 +TIMEOUT_S = 30 + + +def host_of(mind) -> str: + """The ssh host to probe: `PYAUTO_RAL_SSH_HOST`, else the first "SSH alias + ``" in the Mind's `policy/hpc_ral.md`; "" when neither names one. A + value that is not a plain host name (it would be read as an ssh option) + is not a host.""" + name = os.environ.get(HOST_ENV, "").strip() + if not name: + try: + text = (Path(mind) / POLICY_FILE).read_text(encoding="utf-8", errors="replace") + except OSError: + text = "" + m = _ALIAS_RE.search(text) + name = m.group(1) if m else "" + return name if _HOST_RE.match(name) else "" + + +def argv_for(host: str) -> list[str]: + return ["ssh", "-o", "BatchMode=yes", "-o", f"ConnectTimeout={CONNECT_TIMEOUT_S}", + host, "true"] + + +def probe(mind, run=None) -> dict: + """{"state": ok|failed|unknown|skipped, "host", "detail"}.""" + if os.environ.get(PROBE_ENV, "").strip().lower() in ("off", "0", "no"): + return {"state": "skipped", "host": "", "detail": f"{PROBE_ENV}=off"} + host = host_of(mind) + if not host: + return {"state": "unknown", "host": "", + "detail": f"no host named ({HOST_ENV}, or \"SSH alias ``\" in the " + f"Mind's {POLICY_FILE})"} + run = run or subprocess.run + try: + res = run(argv_for(host), capture_output=True, text=True, timeout=TIMEOUT_S, + stdin=subprocess.DEVNULL) + except FileNotFoundError: + return {"state": "unknown", "host": host, "detail": "no `ssh` on PATH"} + except subprocess.TimeoutExpired: + return {"state": "unknown", "host": host, + "detail": f"no answer in {TIMEOUT_S} s"} + except (OSError, subprocess.SubprocessError) as e: + return {"state": "unknown", "host": host, "detail": f"ssh failed to run ({e})"[:200]} + if res.returncode == 0: + return {"state": "ok", "host": host, "detail": "answered"} + lines = [ln.strip() for ln in f"{res.stderr or ''}\n{res.stdout or ''}".splitlines() + if ln.strip()] + return {"state": "failed", "host": host, + "detail": (lines[-1] if lines else f"exit {res.returncode}")[:200]} + + +def findings(lanes, mind, run=None) -> tuple[dict | None, list[str]]: + """(probe result, warnings) for a brief's `lanes:`. No `ral`, no probe and + no ssh call: (None, []).""" + if "ral" not in (lanes or []): + return None, [] + res = probe(mind, run) + if res["state"] in ("ok", "skipped"): + return res, [] + if res["state"] == "failed": + return res, [f"brief.lanes: ral is granted, but unattended ssh to `{res['host']}` " + f"fails ({res['detail']}) — a worker that needs RAL will park; fix the " + "key setup or drop `ral` from `lanes:`"] + return res, [f"brief.lanes: ral is granted, but unattended ssh could not be checked " + f"({res['detail']})"] diff --git a/agents/faculties/review/AGENTS.md b/agents/faculties/review/AGENTS.md index a1e252aa..4fe2c42e 100644 --- a/agents/faculties/review/AGENTS.md +++ b/agents/faculties/review/AGENTS.md @@ -87,7 +87,10 @@ Heart and the agent reasons over the verdict. of the claims surface and falsified **first**: if the witness does not hold, the work did not do what it promised and nothing else on the surface matters. Second, the reader must be a **different model from the one that wrote the - branch**. + branch** — or, since 2026-11-22, the default: **Opus in a fresh session or + sub-agent that did not write the branch** (`AUTONOMY.md` "Adversary model + default — 2026-11-22"). A more expensive model (Fable) reads only when the + human asks for it. That second rule is the whole leg. Step 2a is already adversarial in *procedure*, and it was still run, in practice, by the branch's own author — diff --git a/agents/faculties/review/_review.py b/agents/faculties/review/_review.py index 0621b2f2..cca75700 100755 --- a/agents/faculties/review/_review.py +++ b/agents/faculties/review/_review.py @@ -200,7 +200,10 @@ def resolve_repos(task: str | None, repos: list[str]) -> list[Path]: ADVERSARY_CONTRACT = """\ INDEPENDENT ADVERSARY MODE (autonomous-ship gate, leg 5) - Who may run this: NOT the session or model that wrote the branch. The leg's + Who may run this: NOT the session that wrote the branch. By default an Opus + session or sub-agent that shares none of the author's context (AUTONOMY.md + "Adversary model default — 2026-11-22"); a more expensive model only when + the human asked for it. The leg's entire value is independence — the organism's own audit found the review leg on autonomous ships was in practice the branch's own author, that "a healthy pass and a rote one write the identical ledger row", and that the one @@ -296,7 +299,7 @@ def main(argv=None) -> int: ap.add_argument("--adversary", action="store_true", help="independent-adversary mode (autonomous-ship gate leg " "5): print the independence contract. Must be run by a " - "different model from the one that wrote the branch") + "session that did not write the branch (Opus by default)") a = ap.parse_args(argv) if not a.task and not a.repo: print("review: pass --task or --repo ", file=sys.stderr) diff --git a/skills/MODEL_DELEGATION.md b/skills/MODEL_DELEGATION.md index 5fef4d0a..d99a7cf2 100644 --- a/skills/MODEL_DELEGATION.md +++ b/skills/MODEL_DELEGATION.md @@ -89,6 +89,11 @@ missing phase. close-outs) run Opus at medium effort unless the human asks otherwise, whatever the session's own effort. An independent reviewer on another model leaves effort unset. +- An independent review or adversary pass the orchestrator starts runs on + Opus by default, as a fresh session or sub-agent that did not write the + branch — also when the session that starts it is Fable. Fable reads a + branch as the adversary only when the human asks for it (`AUTONOMY.md` + "Adversary model default — 2026-11-22"). - Do not rerun an unchanged successful check unless inputs or its gate changed. - Prefer native completion events. Do not repeatedly poll unchanged pending state or agent lists; use bounded waits only when needed, and never arm a diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 37e16829..1d4d6f03 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -133,8 +133,8 @@ bin/pyauto-brain batch collect --slot - --evidence ev.json --apply **Before reading any PR from a batch, the independent adversary leg must have run** (`AUTONOMY.md` leg 5): `bin/pyauto-brain review --task --witness -"" --adversary`, **in a session using a different model -from the one that wrote the branch**. A self-run adversary leg is an absent +"" --adversary`, **in a fresh Opus session or sub-agent +that did not write the branch** (Fable only when the human asks). A self-run adversary leg is an absent leg, not a weak one, and recording it as run is a false ledger row. If it has not run, say so rather than reviewing as though it had. diff --git a/skills/cockpit/cockpit.md b/skills/cockpit/cockpit.md index 84deb9a1..91efad0b 100644 --- a/skills/cockpit/cockpit.md +++ b/skills/cockpit/cockpit.md @@ -118,7 +118,7 @@ within 3 ticks (about 3 min), or `steer-unread` arrives, say so once. | "fewer workers" (no number) | nothing yet: ask "how many workers at most?" | ask | | "keep it under 400k" | `/cap tokens 400000` | **yes**, with n shown | | "the red sweep is fine", "unblock merges" | `/clear-sweep` (clears the latest red workspace sweep only) | **yes**, naming the run | -| "merge #347" | not a comment: the `/prm` procedure on that PR, in this chat. If a close-out is `running` on it, say so and ask the human to wait or `/drop` first | /prm's own | +| "merge #347" | not a comment: the `/prm` procedure on that PR, in this chat. If a close-out is `running` on it, say so and ask the human to wait or `/drop` first. An adversary pass first, only if they ask: an Opus sub-agent, never this chat's model (`AUTONOMY.md` "Adversary model default — 2026-11-22"); a finding on the PR description alone is a note and does not hold the merge | /prm's own | | "put X on the queue", "move X up" | not a shift command: the `/queue` procedure | /queue's own | | "go through my questions", "answer Q17" | not a shift command: `/questions` (section 6) | n/a | diff --git a/tests/conftest.py b/tests/conftest.py index 7ace373b..8f8a3234 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -47,6 +47,8 @@ def _no_real_launch_probes(monkeypatch): variable and puts a fake `claude` / `gh` on PATH.""" monkeypatch.setenv("PYAUTO_LOGIN_PROBE", "off") monkeypatch.setenv("PYAUTO_BRIEF_ISSUE", "off") + # `brief --check` on a brief that grants `ral` runs one BatchMode ssh. + monkeypatch.setenv("PYAUTO_RAL_PROBE", "off") @pytest.fixture(autouse=True) diff --git a/tests/test_autonomy_doctrine.py b/tests/test_autonomy_doctrine.py index d515547a..76d09600 100644 --- a/tests/test_autonomy_doctrine.py +++ b/tests/test_autonomy_doctrine.py @@ -254,6 +254,31 @@ def test_amendment_names_its_revert_condition(): assert trigger in sec +# --- Adversary model default (2026-11-22) ------------------------------------- + +DEFAULT_HEADER = "## Adversary model default — 2026-11-22" + + +def test_the_adversary_default_is_an_independent_opus_session(): + assert AUTONOMY.count(DEFAULT_HEADER) == 1 + assert AUTONOMY.index(AMEND_HEADER) < AUTONOMY.index(DEFAULT_HEADER) + rest = AUTONOMY[AUTONOMY.index(DEFAULT_HEADER) + len(DEFAULT_HEADER):] + sec = _norm(rest[:rest.find("\n## ")]) + assert "the default reader is opus" in sec + assert "fable only when asked" in sec + assert "a self-run adversary leg is still an absent leg" in sec + assert sec.count("revert condition:") == 1 + assert "Adversary model default" in _norm_ws(AUTONOMY[AUTONOMY.index("## Consumers"):]) + brain = Path(__file__).resolve().parents[1] + for doc in ("skills/MODEL_DELEGATION.md", "agents/faculties/review/AGENTS.md", + "agents/conductors/batch/AGENTS.md", "skills/cockpit/cockpit.md"): + assert "Adversary model default" in _norm_ws((brain / doc).read_text()), doc + + +def _norm_ws(text: str) -> str: + return " ".join(text.split()) + + def test_unattended_rule_and_consumers_point_at_the_amendment(): shift = AUTONOMY[AUTONOMY.index(SHIFT_HEADER):] assert "Stage-2\nadversary amendment — 2026-11-04" in shift \ diff --git a/tests/test_batch_brief.py b/tests/test_batch_brief.py index b7fc301c..1fc728c2 100644 --- a/tests/test_batch_brief.py +++ b/tests/test_batch_brief.py @@ -187,3 +187,70 @@ def test_a_write_failure_after_the_issue_names_it_for_a_rerun(tmp_path, monkeypa err = capsys.readouterr().err assert ISSUE in err and f"--issue {ISSUE}" in err assert len(_calls(log)) == 1 + + +# --- the RAL probe: a granted `ral` lane a worker cannot reach (2026-11-20-am) ----- + +RAL = (" - lanes: any ral\n", " - lanes: any ral\n - ral-allowance:\n - packets: 2\n" + " - partition: ral\n - cpu-hours: 64\n") + + +def _ral_brief(tmp_path: Path, extra: str = "") -> Path: + f = _brief(tmp_path, extra=extra) + f.write_text(f.read_text().replace(" - lanes: any\n", RAL[1])) + return f + + +def test_check_warns_when_unattended_ssh_to_ral_fails(tmp_path, monkeypatch, capsys): + monkeypatch.delenv("PYAUTO_RAL_PROBE", raising=False) + monkeypatch.delenv("PYAUTO_RAL_SSH_HOST", raising=False) + mind = _mind(tmp_path) + (mind / "policy").mkdir() + (mind / "policy" / "hpc_ral.md").write_text( + "- Cluster: connect via SSH alias `example_jump` (→ hpc.example.invalid).\n") + log = _fake(tmp_path, monkeypatch, "ssh", + "Received disconnect: Too many authentication failures\n", rc=255) + brief = _ral_brief(tmp_path) + rc, out = _check(brief, mind, capsys) + assert rc == 0, out # a warning, never a refusal + warn = [ln for ln in out.splitlines() if "ral is granted" in ln] + assert len(warn) == 1 and "`example_jump`" in warn[0] + assert "Too many authentication failures" in warn[0] + assert log.read_text().splitlines() == [ + "-o BatchMode=yes -o ConnectTimeout=10 example_jump true"] + + # The host answers: no warning. The environment names the host first. + (tmp_path / "ssh.rc").write_text("0") + monkeypatch.setenv("PYAUTO_RAL_SSH_HOST", "other_jump") + rc, out = _check(brief, mind, capsys) + assert rc == 0 and "ral is granted" not in out + assert log.read_text().splitlines()[-1].endswith("other_jump true") + + +def test_check_runs_no_ssh_without_the_ral_lane_or_for_a_shadow_brief(tmp_path, monkeypatch, + capsys): + monkeypatch.delenv("PYAUTO_RAL_PROBE", raising=False) + monkeypatch.setenv("PYAUTO_RAL_SSH_HOST", "example_jump") + mind = _mind(tmp_path) + log = _fake(tmp_path, monkeypatch, "ssh", "denied\n", rc=255) + rc, out = _check(_brief(tmp_path), mind, capsys) # lanes: any + assert rc == 0 and "ral is granted" not in out and not log.exists() + rc, out = _check(_ral_brief(tmp_path, extra=" - shadow: yes\n"), mind, capsys) + assert "ral is granted" not in out and not log.exists() + + +def test_the_ral_probe_names_no_host_of_its_own(tmp_path, monkeypatch, capsys): + """No host named anywhere: one warning that it could not be checked, and + no ssh call. A value that would read as an ssh option is not a host.""" + import _ral + monkeypatch.delenv("PYAUTO_RAL_PROBE", raising=False) + monkeypatch.delenv("PYAUTO_RAL_SSH_HOST", raising=False) + mind = _mind(tmp_path) + log = _fake(tmp_path, monkeypatch, "ssh", "", rc=0) + rc, out = _check(_ral_brief(tmp_path), mind, capsys) + assert rc == 0 and "unattended ssh could not be checked (no host named" in out + assert not log.exists() + monkeypatch.setenv("PYAUTO_RAL_SSH_HOST", "-oProxyCommand=evil") + assert _ral.host_of(mind) == "" + res, warns = _ral.findings(["any", "ral"], mind) + assert res["state"] == "unknown" and len(warns) == 1 and not log.exists() diff --git a/tests/test_batch_collect.py b/tests/test_batch_collect.py index e1143541..52783bd3 100644 --- a/tests/test_batch_collect.py +++ b/tests/test_batch_collect.py @@ -219,6 +219,25 @@ def test_a_self_run_adversary_is_an_absent_leg(tmp_path): assert "absent leg, not a weak one" in why +def test_a_same_model_adversary_passes_only_as_an_independent_session(tmp_path): + """AUTONOMY.md "Adversary model default — 2026-11-22": Opus reads an Opus + branch by default, in a session that did not write it, and the row says so.""" + mind = mini_mind(tmp_path) + row = {"ran": True, "model": "claude-opus-4", "author_model": "claude-opus-4", + "verdict": "CLEAN"} + for flag in ("true", 1, False): # only the JSON `true` counts + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( + adversary={**row, "independent_session": flag})) + assert one(d)["legs"]["adversary"][0] == _batch.FAIL, flag + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( + adversary={**row, "independent_session": True})) + verdict, why = one(d)["legs"]["adversary"] + assert verdict == _batch.PASS and "independent session" in why + d = _batch.collect(mind, "2026-09-03-pm", evidence=evidence( + adversary={"ran": True, "model": "claude-opus-4", "independent_session": True})) + assert one(d)["legs"]["adversary"][0] == _batch.FAIL # no author named + + def test_a_missing_witness_is_unobservable_and_makes_the_member_suspect(tmp_path): (tmp_path / "mind").mkdir(parents=True, exist_ok=True) mind = mini_mind(tmp_path) diff --git a/tests/test_orchestrator_throughput.py b/tests/test_orchestrator_throughput.py index 0e5ef343..18e89b18 100644 --- a/tests/test_orchestrator_throughput.py +++ b/tests/test_orchestrator_throughput.py @@ -28,6 +28,7 @@ import test_orchestrator_dispatch as d # noqa: E402 — the real-spawner fixtures from test_orchestrator_digest import _brief, orch # noqa: E402 import _batch # noqa: E402 +import _digest # noqa: E402 import _questions # noqa: E402 import _watch # noqa: E402 @@ -280,8 +281,43 @@ def _carry_shift(tmp_path, prev_extra: dict, merged=()): def test_review_a_carried_pr_the_human_merged_since_is_not_closed_out(tmp_path): r, c = _carry_shift(tmp_path, {}, merged=(LATE,)) assert LATE not in r["closeouts"]["started"] and CUT in r["closeouts"]["started"] - assert c["closeouts"][LATE]["why"].endswith("GitHub reads it MERGED — not closed out") + late = c["closeouts"][LATE] + assert late["state"] == "refused" and late["settled"] == "merged" + assert late["why"].startswith("already merged since 2026-11-03-pm") assert c.get("glance_auto_merges", 0) == 0 + assert LATE in r["closeouts"]["merged_outside"] + + +def test_a_carried_pr_already_merged_is_not_listed_as_needing_the_human(tmp_path): + """2026-11-19-pm2 and 2026-11-20-am listed PRs the human had merged between + shifts as "Needs you — not merged unattended", each with an empty proof + packet. A settled carry-over is named once, in the carry-over line.""" + r, c = _carry_shift(tmp_path, {}, merged=(LATE,)) + assert _digest.is_settled("late", c) and not _digest.is_settled("cut", c) + state, _ = _digest.task_state("late", c, co._health({})) + assert _digest.plain_outcome(state) == "Already merged — nothing to do" + brief = tmp_path / "2026-11-04-am.md" + text = _digest.build(_brief.parse(brief.read_text())["brief"], + orch.slot_dir(brief, tmp_path / "home"), c, health=co._health({})) + assert "#### late" not in text and "`late`" not in text + assert "not closed out" not in text + line = [ln for ln in text.splitlines() if "you had already merged" in ln] + assert len(line) == 1 and LATE in line[0] and CUT not in line[0] + assert not [e for e in _digest.validate(text) if "late" in e] + + +def test_the_merge_order_drops_an_earlier_pr_github_reads_merged(): + """2026-11-19-pm2's merge order began with an earlier PR as "▶ … — open", twenty + minutes after the human merged it.""" + a, b, c3 = (f"https://github.com/example-org/widgets/pull/{n}" for n in (868, 872, 874)) + counters = {"outcomes": {"x": {"prs": [b], "merged": [], "behind": [a]}, + "y": {"prs": [c3], "merged": []}}, + "closeouts": {b: {"state": "refused", "why": "merge-cap 0 reached this shift"}}, + "merge_waits": {c3: {"behind": [b]}}, "pr_gone": {a: "MERGED"}} + lines = _digest.merge_order_lines(counters) + assert not [ln for ln in lines if a in ln] + assert [ln for ln in lines if ln.strip().startswith("- ▶")] and b in "".join( + ln for ln in lines if "▶" in ln) def test_review_a_question_parked_tasks_pr_is_not_carried(tmp_path): @@ -430,3 +466,16 @@ def test_review2_the_digest_names_an_in_shift_restart(tmp_path, monkeypatch): d._tick(brief, mind, home, NOW + _dt.timedelta(minutes=20), claude) lines = t._digest.backlog_gate_lines(orch.read_counters(slot)) assert "Restarted in-shift after an answer: 1 task(s) — `t1` (Q7)" in lines + + +def test_a_task_the_spawn_gate_refused_all_shift_says_why_it_never_started(): + """2026-11-20-am: a named task waited on `max-workers` to `review-at:` and + its digest entry said only "not started".""" + counters = {"refusals": [ + {"task": "t9", "class": "max-workers 4 reached", "why": "max-workers 4 reached", + "count": 157, "at": "2026-11-20T08:37:12Z", "last": "2026-11-20T09:28:26Z"}]} + state, tiered = _digest.task_state("t9", counters, health=None) + assert state == ("not started — refused: max-workers 4 reached " + "(last 2026-11-20T09:28:26Z)") and not tiered + assert _digest.plain_outcome(state) == "Not started" + assert _digest.task_state("t8", counters, health=None)[0] == "not started" diff --git a/tests/test_questions_inbox.py b/tests/test_questions_inbox.py index 4f536510..d6983798 100644 --- a/tests/test_questions_inbox.py +++ b/tests/test_questions_inbox.py @@ -823,3 +823,32 @@ def test_the_inbox_section_shows_a_ruling_by_its_gate_and_counts_it_apart(tmp_pa sec = md[md.index("**Questions**"):md.index("**Shift**")] assert sec.startswith("**Questions** (1 open, 1 deferred, 1 ruling") assert "- Q19 — Repo claimed: wait, coordinate or drop? (ruling claimed" in sec + + +# --- a question sidecar is never a lease (2026-11-20-am) --------------------------- + +def test_a_question_sidecar_is_not_a_lease_and_holds_no_worker_slot(tmp_path): + """Each parked worker's `{task}.question.json` was read as a lease with no + pid, `_alive(0)` called it running, and it held a worker slot until + `review-at:`: four of them filled `max-workers 4` and 11 tasks waited.""" + mind, brief, home, slot = _shift(tmp_path) + claude, gh = d.FakeClaude(), FakeGh() + _tick(brief, mind, home, NOW, claude, gh) + leases = slot / "leases" + for task, q in (("t1", Q1), ("t2", Q2)): + (leases / f"{task}.done").write_text(f"question: {q}\n") + (leases / f"{task}.question.json").write_text(json.dumps( + {"issue": q, "ask": "Brass or steel?", "options": ["brass", "steel"]})) + later = NOW + _dt.timedelta(minutes=5) + _tick(brief, mind, home, later, claude, gh, d._agents({"t1": "done", "t2": "done"}, slot)) + # The sidecars outlive the reap, and none of them is a lease. + assert sorted(f.name for f in leases.glob("*.question.json")) == [ + "t1.question.json", "t2.question.json"] + assert orch.leases(slot) == {} and _digest.held_leases(slot) == {} + c = orch.read_counters(slot) + assert not [w for w in c["workers"] if w["task"].endswith(".question")] + # A later tick refuses nothing on `max-workers` and adds no phantom worker. + r = _tick(brief, mind, home, later + _dt.timedelta(minutes=2), claude, gh) + assert not [x for x in r.get("refused") or [] if "max-workers" in str(x.get("why"))] + c = orch.read_counters(slot) + assert not [w for w in c["workers"] if w["task"].endswith(".question")] diff --git a/tests/test_review_adversary.py b/tests/test_review_adversary.py index 6ca89735..f68a0d38 100644 --- a/tests/test_review_adversary.py +++ b/tests/test_review_adversary.py @@ -62,7 +62,7 @@ def test_adversary_mode_states_who_may_not_run_it(capsys): """The independence rule is the leg. A surface that omits it invites the exact failure the leg exists to close.""" out = _emit(capsys, adversary=True) - assert "NOT the session or model that wrote the branch" in out + assert "NOT the session that wrote the branch" in out assert "A self-run adversary leg is not a weaker version" in out diff --git a/tests/test_watcher_latency.py b/tests/test_watcher_latency.py index 5291f9ff..b2a22725 100644 --- a/tests/test_watcher_latency.py +++ b/tests/test_watcher_latency.py @@ -433,7 +433,8 @@ def test_r1_a_carried_pr_the_human_merged_is_reported_by_its_github_state(tmp_pa _ltick(brief, mind, home, sp, 1, states={ga6: ("MERGED", "2026-11-04T08:00:00Z")}, labels={ga6: ["decision-taken"]}) c = orch.read_counters(slot) - assert c["closeouts"][ga6]["why"].startswith("carried over from 2026-11-03-pm") + assert c["closeouts"][ga6]["why"].startswith("already merged since 2026-11-03-pm") + assert c["closeouts"][ga6]["settled"] == "merged" assert "decision-taken" not in c["closeouts"][ga6]["why"] from test_orchestrator_digest import _digest assert "#6" not in "\n".join(_digest.waited_lines(c)) # never a /prm-bound blocker