diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 51643211..dabf768f 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -33,6 +33,7 @@ import html import importlib.util import json +import os import re import shutil import subprocess @@ -53,7 +54,7 @@ # `CORTEX_BOARD_STATES`) so existing importers of `_batch` keep working. sys.path.insert(0, str(Path(__file__).resolve().parent)) from _status import ( # noqa: E402 - PENDING_RE, RULING_WORDS, CORTEX_BOARD_STATES, _carried_slugs, + PENDING_RE, RULING_WORDS, CORTEX_BOARD_STATES, _carried_slugs, freeze_line, ) # One slot's worth of the human's attention, and only the DEFAULT: the human @@ -1593,6 +1594,11 @@ def collect(mind: Path, slot: str, *, evidence: dict | None = None, "review": review, "not_delivered": [s["slug"] for s in scored if s["health"] == "NOT-DELIVERED"], + # Heart's release freeze, read at collect time: the packet is where a + # human decides what to merge, so the window has to be on the page. + # Empty whenever nothing is frozen (or Heart's state is absent — this + # runs on a laptop, in CI and in a web container). + "freeze": freeze_line(heart_freeze()), "rulings": [(s["slug"], _ruling_line(s)) for s in scored], "unparsable": rec["unparsable"], # `members` above is sorted by HEALTH, so it cannot drive a merge @@ -1685,6 +1691,42 @@ def _integration_report(d: dict) -> list: return L + [""] +#: PyAutoHeart's freeze flag, read straight off its sidecar. Brain never +#: writes it — Heart owns the file (`PyAutoHeart/heart/freeze.py`), and this is +#: a read of state that lives on the same box, in the same spirit as the +#: profiling conductor's read of `~/.pyauto-heart`. A shell-out to +#: `pyauto-heart freeze --show --json` would say the same thing; the file read +#: keeps `collect` runnable where Heart is not on PATH. +HEART_STATE_DIR = Path(os.environ.get("HEART_STATE_DIR") + or Path.home() / ".pyauto-heart") + + +def heart_freeze(now: _dt.datetime | None = None, + state_dir: Path | None = None) -> dict: + """`{"state": clear|active|expired, ...}` — Heart's reading, re-derived. + + Expiry is applied here rather than trusted from the file, so a flag whose + window has passed reads as thawed even if nobody cleared it. Anything + unreadable reads as clear: a freeze nobody can parse must not be able to + stop a batch from being collected. + """ + path = (state_dir or HEART_STATE_DIR) / "freeze.json" + try: + rec = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {"state": "clear"} + if not isinstance(rec, dict): + return {"state": "clear"} + try: + until = _dt.datetime.fromisoformat(str(rec.get("until", "")).replace("Z", "+00:00")) + except ValueError: + return {"state": "clear"} + if until.tzinfo is None: + until = until.replace(tzinfo=_dt.timezone.utc) + ref = now or _dt.datetime.now(_dt.timezone.utc) + return {**rec, "state": "active" if ref < until else "expired"} + + def collect_report(d: dict) -> str: L = [f"# Batch collect {d['slot']}", ""] if d["not_delivered"]: @@ -1696,6 +1738,13 @@ def collect_report(d: dict) -> str: f"{slug} ({_short(by_slug[slug]['legs']['pr'][1] if by_slug[slug]['legs']['pr'][0] == FAIL else _evidence_line(by_slug[slug]))})" for slug in d["not_delivered"]) L += [f"**NOT DELIVERED — {n} of {total}**: {why}", ""] + if d.get("freeze"): + # One line, above the members: whoever reads this packet is deciding + # what to merge, and a library merge landing inside a validation window + # restales the whole rehearsal. `/prm` is what actually stops. + L += [f"**{d['freeze']}** — library `main`s are frozen; `/prm` will " + "refuse a library PR until it clears (`--thaw` overrides, " + "logged).", ""] L += _integration_report(d) L += _merge_order_report(d) for s in d["members"]: @@ -1748,6 +1797,8 @@ def emit_collect(d: dict, out: str = "") -> None: n, total = d["delivered"] print(f"collect {d['slot']}: {len(d['members'])} members, " f"delivered {n}/{total}") + if d.get("freeze"): + print(d["freeze"]) body = collect_report(d) if out: Path(out).write_text(body, encoding="utf-8") diff --git a/agents/conductors/batch/_status.py b/agents/conductors/batch/_status.py index f6162642..4cf7ae2f 100644 --- a/agents/conductors/batch/_status.py +++ b/agents/conductors/batch/_status.py @@ -131,6 +131,21 @@ def _first_word(text: str) -> str: return words[0].strip("(,.").upper() if words else "" +def freeze_line(rec: dict | None) -> str: + """The Heart freeze flag as one line — `""` when nothing is frozen. + + `rec` is PyAutoHeart's own reading (`pyauto-heart freeze --show --json`, or + the `freeze.json` sidecar read straight off disk). Heart owns the flag and + is its only writer; this is the Brain-side copy of the *wording*, kept + byte-identical to `PyAutoHeart/heart/freeze.py::render_line` so the batch + box, `vitals` and `/prm` all say the same sentence. `expired` reads as + thawed, exactly as Heart reads it. + """ + if not rec or rec.get("state") != "active": + return "" + return f"FROZEN: {rec.get('reason', 'unspecified')} until {rec.get('until', '?')}" + + def _carried_slugs(keys: dict, members: list) -> set: """The members a `- carried:` line hands to the next slot. @@ -151,7 +166,7 @@ def _carried_slugs(keys: dict, members: list) -> set: def dev_status(slot: str, keys: dict, members: list, review_exists: bool, - pages: str) -> dict | None: + pages: str, freeze: str = "") -> dict | None: """The Mind's (development) reading — today's behaviour, unchanged. A dev batch is dispatched at once and reviewed at once: it is open until @@ -174,11 +189,12 @@ def dev_status(slot: str, keys: dict, members: list, review_exists: bool, rows.append({"slug": m.get("slug", ""), "state": state, "detail": detail}) return _status(slot, "dev", keys, rows, - reviewable=bool(_one(keys, "collected")), pages=pages) + reviewable=bool(_one(keys, "collected")), pages=pages, + freeze=freeze) def cortex_status(slot: str, keys: dict, members: list, states: dict, - live: dict, pages: str) -> dict | None: + live: dict, pages: str, freeze: str = "") -> dict | None: """The Cortex's (science) reading — a rolling board, not one sitting. A science slot stays open while anything is still ON the board: members @@ -210,11 +226,20 @@ def cortex_status(slot: str, keys: dict, members: list, states: dict, return None return _status(slot, "cortex", keys, rows, reviewable=any(r["state"] == AWAITING for r in rows), - pages=pages) + pages=pages, freeze=freeze) def _status(slot: str, kind: str, keys: dict, rows: list, reviewable: bool, - pages: str) -> dict: + pages: str, freeze: str = "") -> dict: + """`freeze` is a caller-supplied FACT, and defaults to nothing on purpose. + + The flag lives in the dev box's `~/.pyauto-heart/`, which is machine state + and not in any checkout — so a surface that renders a **committed** + artifact must not pass it. The Mind's dashboard is regenerated in CI, where + that state does not exist, and a freeze folded into the page would read as + dashboard drift on the next `--check`. `batch collect`, which runs on the + box that holds the state and prints to a terminal, passes it. + """ return { "slot": slot, "kind": kind, @@ -225,6 +250,7 @@ def _status(slot: str, kind: str, keys: dict, rows: list, reviewable: bool, "reviewable": reviewable, "url": review_url(pages, slot) if reviewable else "", "packet": f"batches/packets/{slot}.html", + "freeze": freeze, } @@ -261,6 +287,8 @@ def render_html(st: dict | None) -> str: esc = _html.escape tone = "warn" if st["reviewable"] else "ok" H = [f'
{esc(_headline(st))}'] + if st.get("freeze"): + H.append(f'

{esc(st["freeze"])}

') for r in st["members"]: line = (f'{esc(r["slug"])}' f'{pills((r["state"], _TONE.get(r["state"], "n")))}') @@ -286,6 +314,8 @@ def render_md(st: dict | None) -> str: if st is None: return f"> **{FIXTURE}**" L = [f"> **{_headline(st)}**", ">"] + if st.get("freeze"): + L += [f"> {st['freeze']}", ">"] for r in st["members"]: line = f"> - `{r['slug']}` — {r['state']}" if r["detail"]: diff --git a/agents/faculties/vitals/AGENTS.md b/agents/faculties/vitals/AGENTS.md index 5681a4b7..978ad174 100644 --- a/agents/faculties/vitals/AGENTS.md +++ b/agents/faculties/vitals/AGENTS.md @@ -78,6 +78,20 @@ faculty every cycle.) `~/.pyauto-heart/release_ready.json`; if neither exists, the verdict is **unknown -> treat as YELLOW** and recommend running `pyauto-heart tick`. +1b. **Read the freeze window.** The verdict does not carry it, deliberately: + + ```bash + pyauto-heart freeze --show --json # {state: clear|active|expired, reason, until, ...} + ``` + + While `state` is `active`, report `FROZEN: until ` as a warning + line (below). It is **not** a `yellow_reasons` entry and it does **not** + change Heart's verdict — a freeze is not a health problem, it is the release + validation saying the library `main`s should not move for now. `clear` and + `expired` both mean thawed; say nothing (an `expired` reading is worth one + line only when someone asks why it is still on disk). An older Heart with no + `freeze` verb prints nothing and that is not an error. + 2. **Collect detail for explanation.** Pull the full snapshot when you need to explain a reason or craft a recommendation: ```bash @@ -144,6 +158,9 @@ Status: (score <0-100>, snapshot ) ### Warnings - (or "None") +- FROZEN: until (only while the freeze flag is active; not a + verdict input — it says library `main`s should not move, and `/prm` is the + one surface that actually stops on it) ### Evidence Gaps - /dev/null | grep '^FROZEN:' || true + exit 0 fi exec "$heart" "$@" diff --git a/skills/prm/prm.md b/skills/prm/prm.md index c02a985c..c402cd4e 100644 --- a/skills/prm/prm.md +++ b/skills/prm/prm.md @@ -20,6 +20,7 @@ never hand-writing a generated page. /prm 380 # PR #380 in the current or inferred repo /prm PyAutoArray#42 # or Jammy2211/PyAutoArray#42, or the full PR URL /prm --no-wait # judge CI once and report; merge only if already green +/prm --thaw "" # merge a LIBRARY PR through an active Heart freeze (logged) ``` ## Environment: decide your GitHub surface first @@ -114,14 +115,44 @@ every run for the sha and every job in it, and treat anything not `completed` as Green on every leg → merge, in this order: -1. **Library PR first.** The workspace PR may not merge until its upstream +1. **The Heart freeze window — library PRs only.** A release validation is a + window in which the library `main`s must not move: a merge landing inside it + invalidates the evidence and restales the rehearsal (~75 minutes, measured + 2026-08-29). Heart's flag says whether one is open: + + ```bash + pyauto-heart freeze --show # exit 3 = frozen; 0 = clear or expired + ``` + + Active **and** a target PR is in a **library** repo (the `category: library` + entries of `PyAutoMind/repos.yaml`) → stop, report the `FROZEN: …` line + verbatim, and say when it expires. Organ and workspace repos are not gated; + a workspace PR whose library half is held waits on the library-first gate + below anyway. Where Heart is not installed (mobile, web, CI) there is + nothing to read — say so in one line; an absent flag is not a freeze. + + **`--thaw ""` is the only way past**, and it is loggable by + construction: merge, then append one row to `PyAutoMind/autonomy_log.md` + under a `## Freeze overrides` heading (create the section, with this header, + on first use) — + + ``` + | date | task / PR | freeze reason | until | thawed by | why | + ``` + + — in the same Mind push the close-out already makes (step 5.4). The override + exists because a freeze is advice about evidence, not a protected branch, + and an unloggable override is one people route around instead of recording. + Never thaw silently, and never thaw to get past a red check: this gate is + about *when*, and step 2 is about *whether*. +2. **Library PR first.** The workspace PR may not merge until its upstream library PR is `MERGED` — the library-first gate ([`../ship_workspace/reference.md`](../ship_workspace/reference.md)). Refuse otherwise; there is no `--auto`-flag workaround. -2. `gh pr merge --merge` per PR (`-R owner/repo` when you have no checkout), +3. `gh pr merge --merge` per PR (`-R owner/repo` when you have no checkout), then confirm the state is `MERGED` — queued or auto-merge is not merged. Never `--delete-branch`: it takes the local branch too, orphaning a task worktree. -3. **Clear anything an older run left armed.** Step 3 arms nothing, so this is +4. **Clear anything an older run left armed.** Step 3 arms nothing, so this is hygiene: if the harness's routine list shows a subscription or a `send_later` reminder on a target PR, drop it (`unsubscribe_pr_activity`, cancel the reminder). Never create one. @@ -224,6 +255,8 @@ the page is true. 5 and 6 are local-only — name 5 outstanding, say nothing of Stop and report instead of pressing on when: - a branch in the task is **unmerged** with no open PR (step 5.1) — the waves trap; +- Heart's **freeze** is active and a target PR is in a library repo (step 4), + and no `--thaw ""` was given; - `worktree_remove` **refuses** (dirty repo, stale claim) — fix the cause, never `PYAUTO_WT_FORCE=1` past it; - the worktree holds **gitignored data products** (reduced datasets, caches, @@ -238,7 +271,10 @@ Stop and report instead of pressing on when: exception is Mind's own close-out commit, which needs no PR at all: pushing the branch is what lands it (step 5.4). - It never bypasses the Heart readiness gate — that ran at ship time, and a red - Heart is not something a merge shortcut may re-judge. Nor does merge ever stop + Heart is not something a merge shortcut may re-judge. The **freeze** flag + (step 4) is a different thing and does not re-run anything: readiness answers + "is the organism healthy", the freeze answers "is a validation window open + right now". Nor does merge ever stop being human: `/prm` is a human-typed door, never invoked by the `--auto` queue. - A task with no issue, no Mind prompt, or no worktree (a direct wiring change, say) skips those sub-steps and says so — not an error. That licence does **not** diff --git a/skills/prm/reference.md b/skills/prm/reference.md index 4b71d6b4..fe2de776 100644 --- a/skills/prm/reference.md +++ b/skills/prm/reference.md @@ -92,6 +92,9 @@ re-run; `/prm` does not decide that for them. ## Merging in gate order ```bash +# 0. the freeze window — library PRs only; exit 3 means a validation is open +pyauto-heart freeze --show || echo "frozen: stop unless /prm --thaw \"\"" + # 1. library PR gh pr merge -R / --merge gh pr view -R / --json state --jq '.state' # must print MERGED @@ -105,6 +108,12 @@ The library-first gate is `../ship_workspace/reference.md` → "Library-first me gate": a workspace PR linked to an upstream library PR may only merge once that PR reads `MERGED`. There is no workaround — not `--auto`, not `--admin`. +The freeze gate is `PyAutoHeart/REFERENCE.md` → "The release freeze window": +Heart owns the flag, `/prm` is the one surface that stops on it, and it stops +only for **library** repos. `--thaw ""` merges anyway and appends the +override row to `PyAutoMind/autonomy_log.md` (`## Freeze overrides`). An +expired flag reads as clear, so a forgotten `--set` never blocks anyone. + ## The close-out ### 1. Prove every branch merged (before recording anything) diff --git a/tests/test_batch_freeze.py b/tests/test_batch_freeze.py new file mode 100644 index 00000000..10a3fff7 --- /dev/null +++ b/tests/test_batch_freeze.py @@ -0,0 +1,164 @@ +"""tests/test_batch_freeze.py — the Heart freeze flag, as Brain reads it. + +PyAutoHeart owns the flag (`PyAutoHeart/heart/freeze.py`); everything here is a +**read**. What these tests defend is that the read agrees with Heart on the two +things a wrong answer would cost something: + +- **expiry is re-derived, never trusted.** A window that has passed reads as + thawed even though nobody cleared the file, so a forgotten `--set` cannot + block merges indefinitely. +- **the box only carries the line when a caller supplies it.** The flag lives + in the dev box's `~/.pyauto-heart/`, which no checkout contains; a surface + that renders a *committed* artifact (the Mind dashboard, regenerated in CI) + must render byte-identically with and without it, or every freeze reads as + dashboard drift. +""" + +from __future__ import annotations + +import datetime as dt +import importlib.util +import json +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +_spec = importlib.util.spec_from_file_location( + "_status_under_freeze_test", + BRAIN / "agents" / "conductors" / "batch" / "_status.py") +_status = importlib.util.module_from_spec(_spec) +sys.modules["_status_under_freeze_test"] = _status +_spec.loader.exec_module(_status) + +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +_bspec = importlib.util.spec_from_file_location( + "_batch_under_freeze_test", + BRAIN / "agents" / "conductors" / "batch" / "_batch.py") +_batch = importlib.util.module_from_spec(_bspec) +sys.modules["_batch_under_freeze_test"] = _batch +_bspec.loader.exec_module(_batch) + +PAGES = "https://exampleorg.github.io/ExampleMind/" +ACTIVE_REC = {"state": "active", "reason": "release validation", + "until": "2026-09-03T19:30:00+00:00"} + + +def _write_flag(tmp_path: Path, until: str, reason: str = "release validation"): + (tmp_path / "freeze.json").write_text(json.dumps({ + "reason": reason, "set_at": "2026-09-03T18:00:00+00:00", + "until": until, "set_by": "pre-build"}), encoding="utf-8") + return tmp_path + + +# ------------------------------------------------------------ the wording --- +def test_the_line_is_heart_s_sentence_verbatim(): + assert _status.freeze_line(ACTIVE_REC) == ( + "FROZEN: release validation until 2026-09-03T19:30:00+00:00") + + +def test_nothing_frozen_is_the_empty_string_so_callers_can_just_test_it(): + assert _status.freeze_line(None) == "" + assert _status.freeze_line({}) == "" + assert _status.freeze_line({"state": "clear"}) == "" + # Expired reads as thawed — the same reading Heart gives it. + assert _status.freeze_line({**ACTIVE_REC, "state": "expired"}) == "" + + +# ---------------------------------------------------------------- the read --- +def test_an_unexpired_flag_reads_active(tmp_path): + _write_flag(tmp_path, "2026-09-03T19:30:00+00:00") + now = dt.datetime(2026, 9, 3, 18, 30, tzinfo=dt.timezone.utc) + assert _batch.heart_freeze(now=now, state_dir=tmp_path)["state"] == "active" + + +def test_expiry_is_re_derived_not_trusted(tmp_path): + """Nobody cleared it; the window still ended. The file says nothing about + its own state, so a stale flag cannot go on blocking merges.""" + _write_flag(tmp_path, "2026-09-03T19:30:00+00:00") + now = dt.datetime(2026, 9, 3, 21, 0, tzinfo=dt.timezone.utc) + rec = _batch.heart_freeze(now=now, state_dir=tmp_path) + assert rec["state"] == "expired" + assert _status.freeze_line(rec) == "" + + +def test_absent_or_unreadable_state_reads_as_clear(tmp_path): + # No Heart on this box at all (CI, a web container) — collect still runs. + assert _batch.heart_freeze(state_dir=tmp_path)["state"] == "clear" + (tmp_path / "freeze.json").write_text("{not json", encoding="utf-8") + assert _batch.heart_freeze(state_dir=tmp_path)["state"] == "clear" + (tmp_path / "freeze.json").write_text(json.dumps({"reason": "x"}), + encoding="utf-8") + assert _batch.heart_freeze(state_dir=tmp_path)["state"] == "clear" + _write_flag(tmp_path, "whenever") + assert _batch.heart_freeze(state_dir=tmp_path)["state"] == "clear" + + +def test_a_zoneless_until_is_read_as_utc(tmp_path): + _write_flag(tmp_path, "2026-09-03T19:30:00") + before = dt.datetime(2026, 9, 3, 18, 30, tzinfo=dt.timezone.utc) + after = dt.datetime(2026, 9, 3, 20, 30, tzinfo=dt.timezone.utc) + assert _batch.heart_freeze(now=before, state_dir=tmp_path)["state"] == "active" + assert _batch.heart_freeze(now=after, state_dir=tmp_path)["state"] == "expired" + + +# ----------------------------------------------------------------- the box --- +def _box(freeze=""): + return _status.dev_status( + "2026-09-03-pm", {"dispatched": ["2026-09-03T18:00Z"]}, + [{"slug": "resampling-info", "outcome": "RUNNING"}], + review_exists=False, pages=PAGES, freeze=freeze) + + +def test_the_box_is_byte_identical_when_no_caller_supplies_a_freeze(): + """The committed-artifact invariant: a dashboard regenerated in CI, where + Heart's state does not exist, must match one regenerated on the dev box.""" + st = _box() + assert st["freeze"] == "" + assert "FROZEN" not in _status.render_md(st) + assert "FROZEN" not in _status.render_html(st) + + +def test_the_box_carries_one_line_when_it_is_supplied(): + st = _box(_status.freeze_line(ACTIVE_REC)) + md, html = _status.render_md(st), _status.render_html(st) + line = "FROZEN: release validation until 2026-09-03T19:30:00+00:00" + assert f"> {line}" in md + assert line in html + # One line, and above the members — a human reading the box is deciding + # what to merge. + assert md.count("FROZEN") == 1 + assert md.index("FROZEN") < md.index("resampling-info") + + +def test_the_science_box_carries_it_too(): + st = _status.cortex_status( + "2026-09-03-night", {"dispatched": ["2026-09-03T18:00Z"]}, + [{"slug": "a-phase"}], states={"a-phase": "running"}, live={}, + pages=PAGES, freeze=_status.freeze_line(ACTIVE_REC)) + assert "FROZEN" in _status.render_md(st) + + +# ------------------------------------------------------------- the packet --- +def test_the_collect_packet_says_what_the_freeze_means_for_merging(): + d = {"slot": "2026-09-03-pm", "not_delivered": [], "members": [], + "delivered": (0, 0), "review": None, "notes": [], + "freeze": _status.freeze_line(ACTIVE_REC)} + body = _batch.collect_report(d) + assert "FROZEN: release validation" in body + assert "/prm" in body and "--thaw" in body + + +def test_the_collect_packet_says_nothing_when_nothing_is_frozen(): + d = {"slot": "2026-09-03-pm", "not_delivered": [], "members": [], + "delivered": (0, 0), "review": None, "notes": [], "freeze": ""} + assert "FROZEN" not in _batch.collect_report(d) + + +def test_the_collect_summary_line(capsys): + d = {"slot": "2026-09-03-pm", "not_delivered": [], "members": [], + "delivered": (0, 0), "review": None, "notes": [], + "freeze": _status.freeze_line(ACTIVE_REC)} + _batch.emit_collect(d) + out = capsys.readouterr().out + assert out.splitlines()[1] == ( + "FROZEN: release validation until 2026-09-03T19:30:00+00:00")