From 89647fe2f0b6d18e3c8b1e1601e05484b11913af Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Fri, 13 Nov 2026 19:35:35 +0000 Subject: [PATCH 1/3] feat(batch): keep-Heart-green lane at brief time (#625) `batch brief --new` now reads Heart's release verdict (local `pyauto-heart readiness --json` with its per-repo keys, else the published feed; the 6 h age rule applies, and a fresher feed wins over an over-age snapshot) and sorts every RED/YELLOW/STALE reason with a tested rule table (`_green.RULES`) into fixable-dev, local-checkout, release-scope or human-only. For fixable-dev reasons it files at most 3 bug drafts per brief (judge tier, Lane, re-check-first note, quoted reason, Witness, a heart-key mark), deduplicated against draft/, active/, queue.md and a state file in the orchestrator home, and names lane-matching drafts as tasks under a last `heart-green` goal. The record gets a `## Heart` section. `batch green` runs the lane alone (report by default). It runs at brief time only, never in the watcher tick. It never releases, rehearses, dispatches, forces, writes queue.md, edits another prompt or quarantines (it may propose one). `_green.py` imports no process or network module; heart_feed gains `local_readiness` (the raw verdict). Tests use real Heart reason strings (fixtures/heart_green/reasons.json). Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 40 +++ agents/conductors/batch/_batch.py | 82 ++++- agents/conductors/batch/_green.py | 450 ++++++++++++++++++++++++ bin/heart_feed.py | 18 +- skills/batch/batch.md | 2 +- tests/conftest.py | 8 + tests/fixtures/heart_green/reasons.json | 41 +++ tests/test_batch_green.py | 391 ++++++++++++++++++++ 8 files changed, 1020 insertions(+), 12 deletions(-) create mode 100644 agents/conductors/batch/_green.py create mode 100644 tests/fixtures/heart_green/reasons.json create mode 100644 tests/test_batch_green.py diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 5c48ca6a..0039d923 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -208,6 +208,46 @@ last edited " — and never reaches a worker unless the human adopts it; `brief --check` warns when `goals.md`'s goal 1 is missing from a brief, unless goal 1 came from the dashboard (PyAutoMind#565; readers in `_steer.py`). +## The keep-Heart-green lane (`_green.py`, PyAutoBrain#625) + +The human, 2026-11-13: "having the autonomous agent constantly trying to +ensure its green (without having it be overly eager doing releases)". So +`brief --new` reads Heart's release verdict first: the local +`pyauto-heart readiness --json` (it carries per-repo keys), else the published +feed, under `heart_feed.py`'s 6 h rule (a fresher feed wins over an over-age +snapshot). It runs at brief time, never in the watcher's tick, whose network +surface does not grow. + +Every RED, YELLOW and STALE reason is sorted by the `RULES` table in +`_green.py` (first match wins; Heart's `repository_reasons` key wins over the +text; no match is `human-only`, fail closed): + +| Class | Examples | The lane | +|---|---|---| +| `fixable-dev` | red CI on `main`, a failing workspace script, a red unit test, a dependency floor, manifest/URL lint, Lifecycle Drift | files a bug draft, picks it | +| `local-checkout` | behind, dirty, on a branch, worktree drift | reports only: another session's work may be in progress | +| `release-scope` | release integrate failed, install check F, rehearsal stale | reports, and names the human's release action | +| `human-only` | open PR, quarantine doctrine, parked scripts, timing, credentials | reports | + +For `fixable-dev` it dedupes on a key (`ci:`, `script:` …): +a prompt in `draft/`/`active/` carrying ``, quoting +the reason or naming the script, a `queue.md` line, or the lane's state file +(`/heart_green.json`: a key it filed is never re-filed, +even after its draft leaves the backlog). It files at most `--green-cap` +(3) new drafts per brief — `Consequence: judge`, a `Lane:`, a re-check-first +note, the quoted reason and a Witness — red first; the rest wait for the next +brief. In `pick` mode (the default; `--green off|report|file|pick`, +`$PYAUTO_HEART_GREEN`) a filed or existing `draft/` prompt whose `Lane:` is in +the brief's lanes becomes a named task under a last `heart-green` goal. An +active quarantine's bug task is picked if it is in the backlog, never filed. +The record gets a `## Heart` section: reasons by class, filed, picked, and what +needs the human. `batch green` is the same lane alone, `report` by default. + +It never releases, rehearses, dispatches a workflow, forces, touches a +freeze, writes `queue.md`, edits another prompt, or quarantines (it may +propose one). `_green.py` imports no process or network module; the tests +pin that and record every process a full brief run starts. + ## The watcher (phases 3a–3d) `bin/orchestrator_watch.py --brief --mind ` runs **one diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index e3227081..84d121fd 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -55,6 +55,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) from _status import PENDING_RE, RULING_WORDS, freeze_line # noqa: E402 import _brief # noqa: E402 +import _green # noqa: E402 — the keep-Heart-green lane (PyAutoBrain#625) # 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 @@ -2900,7 +2901,8 @@ def organ_for(kind: str, root: Path, slot: str) -> dict: def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="batch") ap.add_argument("verb", choices=["plan", "collect", "brief", "digest", "watch", - "slice", "premise"], nargs="?", default="plan") + "slice", "premise", "green"], nargs="?", + default="plan") ap.add_argument("prompt", nargs="?", default="", help="slice: the needs-slicing prompt to decompose; " "premise: the draft whose premise to check") @@ -2926,6 +2928,17 @@ def main(argv=None) -> int: help="brief: print a skeleton shift brief for SLOT (e.g. " "2026-11-14-am) whose goals: come from goals.md; " "needs --review-at; --out FILE writes it instead") + # the keep-Heart-green lane (PyAutoBrain#625): `brief --new` and `green` + ap.add_argument("--green", default="", choices=("",) + _green.MODES, + help="brief --new / green: the keep-Heart-green lane — off | " + "report | file (bug drafts) | pick (file, then name them " + f"as tasks). Default: ${_green.MODE_ENV}, else " + f"{_green.DEFAULT_MODE} for brief --new, report for green") + ap.add_argument("--green-cap", type=int, default=_green.DEFAULT_CAP, + help="brief --new / green: at most this many new drafts") + ap.add_argument("--heart-json", default="", metavar="FILE", + help="brief --new / green: read this saved `readiness --json` " + "or state.json instead of Heart (a replay; --at sets now)") ap.add_argument("--brief", default="", metavar="FILE", help="plan: compose inside this shift brief (named tasks " "first, then its backlog policy)") @@ -3008,6 +3021,8 @@ def main(argv=None) -> int: return _main_digest(mind, a) if a.verb == "watch": return _main_watch(a) + if a.verb == "green": + return _main_green(mind, a) return _main_plan(mind, a, lane) except BatchUsageError as e: print(e, file=sys.stderr) @@ -3258,8 +3273,9 @@ def _last_brief_goals(mind: Path) -> tuple[str, list[str]] | None: except (OSError, _brief.BriefError): continue if brief and brief.get("goals"): - return f.name, [re.sub(r"^\d+\.\s*", "", c["text"]) - for c in brief["goals"]["children"]] + goals = [re.sub(r"^\d+\.\s*", "", c["text"]) + for c in brief["goals"]["children"]] + return f.name, [g for g in goals if not g.startswith(_green.GOAL_PREFIX)] return None @@ -3297,7 +3313,7 @@ def goals_report(mind: Path, prov: list[dict] | None) -> list[str]: def new_brief(mind: Path, slot: str, review_at: str, now=None, - prov=_UNSET) -> str: + prov=_UNSET, heart: dict | None = None) -> str: """A skeleton shift brief whose `goals:` are `goals.md`'s, in order. A goal last written from the dashboard is emitted commented out, marked @@ -3307,7 +3323,11 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, `epics:`/`tags:`; with none named, `fill-idle`. 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").""" + "Shift brief"). + + `heart` is the keep-Heart-green lane's result (`_green.run`): its picks + become a last `heart-green` goal plus named `tasks:`, and its report the + record's `## Heart` section (PyAutoBrain#625).""" goals = read_goals(mind) prov = resolve_provenance(mind, goal_provenance(mind) if prov is _UNSET else prov) now = now or _dt.datetime.now(_dt.timezone.utc) @@ -3337,6 +3357,12 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, "not adopted; delete the '# ' to adopt") else: L.append(f" - {text}") + picks = (heart or {}).get("picks") or [] + if picks: + L.append(f" - {len(goals) + 1}. {_green.GOAL_PREFIX}: clear the " + "fixable Heart reasons the lane picked (see ## Heart)") + L.append(" - tasks: # the heart-green lane's picks") + L += [f" - {t}" for t in picks] if epics or tags: L += [" - backlog: scoped # the goals' epics and tags", " - scoped:"] @@ -3351,7 +3377,8 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None, f" - merge-cap: {NEW_BRIEF_DEFAULTS['merge-cap']}" " # unattended glance merges: raise deliberately", f" - token-budget: {NEW_BRIEF_DEFAULTS['token-budget']}"] - return "\n".join(L) + "\n" + text = "\n".join(L) + "\n" + return text + "\n" + _green.section(heart) if heart else text def goal_one_warning(path: Path, mind: Path) -> str: @@ -3392,7 +3419,12 @@ def _main_brief(mind: Path, a) -> int: "grant expires there, and it is yours to declare", file=sys.stderr) return RC_USAGE prov = goal_provenance(mind) - text = new_brief(mind, a.new, a.review_at, prov=prov) + heart = green_lane(mind, a, os.environ.get(_green.MODE_ENV) or _green.DEFAULT_MODE) + text = new_brief(mind, a.new, a.review_at, prov=prov, heart=heart) + if heart["filed"]: + print(f"batch brief --new: heart-green filed {len(heart['filed'])} " + f"draft(s) in {mind} (uncommitted — commit them with the " + "record): " + ", ".join(heart["filed"]), file=sys.stderr) for line in goals_report(mind, prov): print(line, file=sys.stderr) if a.out: @@ -3436,6 +3468,42 @@ def _main_brief(mind: Path, a) -> int: return RC_OK if res["ok"] else RC_FINDINGS +def green_lane(mind: Path, a, default_mode: str) -> dict: + """Run the keep-Heart-green lane for `brief --new` / `green` (`_green`). + It reads Heart and may write NEW drafts and its state file; nothing else.""" + mode = a.green or default_mode + if mode not in _green.MODES: + raise BatchUsageError(f"batch: --green {mode!r} — one of " + + " | ".join(_green.MODES)) + now = _brief._iso(a.at) if a.at else None + if now is not None and now.tzinfo is None: + now = now.replace(tzinfo=_dt.timezone.utc) + if mode == "off": + heart = {"status": "grey", "source": "not read", "reasons": []} + else: + heart = _green.read_heart(a.heart_json, now=now) + import _orchestrator # noqa: E402 — deferred: only the state path + home = a.home or _orchestrator.orchestrator_home() + lanes = NEW_BRIEF_DEFAULTS["lanes"].split() + return _green.run(mind, heart, mode=mode, cap=max(a.green_cap, 0), lanes=lanes, + state_path=Path(home) / _green.STATE_NAME, now=now) + + +def _main_green(mind: Path, a) -> int: + """`batch green [--green report|file|pick] [--heart-json F] [--json]` — + the lane on its own: classify Heart's reasons and (from `file`) file the + fixable ones. Defaults to `report`, which writes nothing.""" + if not (mind / "draft").is_dir(): + print(f"batch: no PyAutoMind backlog at {mind}", file=sys.stderr) + return RC_NO_MIND + res = green_lane(mind, a, os.environ.get(_green.MODE_ENV) or "report") + if a.as_json: + print(json.dumps(res, indent=2, default=str)) + else: + sys.stdout.write(_green.section(res)) + return RC_OK + + def _main_plan(mind: Path, a, lane: str) -> int: used = [f"--{f}" for f in COLLECT_ONLY if getattr(a, f)] if used: diff --git a/agents/conductors/batch/_green.py b/agents/conductors/batch/_green.py new file mode 100644 index 00000000..65b2001b --- /dev/null +++ b/agents/conductors/batch/_green.py @@ -0,0 +1,450 @@ +"""The keep-Heart-green lane (PyAutoBrain#625) — runs at brief time. + +The human, 2026-11-13: "having the autonomous agent constantly trying to +ensure its green (without having it be overly eager doing releases)". So at +`batch brief --new` (and `batch green`, its dry run) this reads Heart's +verdict, sorts every RED, YELLOW and STALE reason into one of four classes by +the transparent RULES table below, and for the `fixable-dev` ones files at +most `cap` bug drafts and offers them as the brief's named tasks. + +It runs at brief time, never in the watcher's tick: the tick's network +surface (AUTONOMY.md) does not read the Heart feed, and this lane must not +widen it. + +What it may do: read Heart; write NEW draft prompts into the Mind it was +given; write its own state file; return text for the brief. What it never +does: release, rehearse, dispatch any workflow, force, touch a freeze, add a +quarantine entry (that needs a human-filed bug task, ruling 2026-11-12 — it +may only PROPOSE one), write `queue.md`, or edit another prompt. It imports +no process or network module: Heart is read through `bin/heart_feed.py` +(published feed or `pyauto-heart readiness --json`, nothing else), and +`tests/test_batch_green.py` pins that. +""" + +from __future__ import annotations + +import datetime as _dt +import importlib.util +import json +import re +from pathlib import Path + +from _sizing import ( # noqa: E402 — the caller puts the faculty on sys.path + effective_difficulty, effective_unattended, normalise_repo, + parse_prompt, +) + +BRAIN = Path(__file__).resolve().parents[3] +CLASSES = ("fixable-dev", "local-checkout", "release-scope", "human-only") +MODES = ("off", "report", "file", "pick") +MODE_ENV = "PYAUTO_HEART_GREEN" +DEFAULT_MODE = "pick" +DEFAULT_CAP = 3 +MAX_AGE_HOURS = 6.0 +STATE_NAME = "heart_green.json" +GOAL_PREFIX = "heart-green" +KEY_MARK = "" + +_CI = r"(?Pfailure|cancelled|timed_out|startup_failure|action_required|error)" +_R = r"(?P[\w.-]+)" + +# (rule, class, regex, key template, lane, what the human or a worker does). +# First match wins. A class may be a {severity: class} map. `pick-only` rules +# never FILE a draft (their bug task already exists); they may pick it. +RULES = [ + # --- fixable-dev: a dev shift can make these go away --------------------- + ("ci-red", "fixable-dev", rf"^{_R}: CI {_CI}$", "ci:{repo}", "any", + "fix the red CI on main"), + ("ci-red-workflow", "fixable-dev", rf"^{_R}: (?P.+?) {_CI} on main$", + "ci:{repo}:{wf}", "any", "fix the red workflow on main"), + ("ci-red-legacy", "fixable-dev", rf"^{_R}/(?P[\w .-]+): {_CI}$", + "ci:{repo}:{wf}", "any", "fix the red workflow on main"), + ("unit-test", {"red": "fixable-dev", "*": "human-only"}, + rf"^{_R}/(?P[\w/.-]+\.py)::", "test:{repo}/{path}", "any", + "red: fix the failing test on main; yellow/warn: flaky-test triage is yours"), + ("workspace-script", "fixable-dev", + r"^workspace validation (?:not passing|failing) \((?P.*)\)$", + "script:{script}", "local-dev", "reproduce and fix the failing workspace script"), + ("floor-unsatisfiable", "fixable-dev", + r"^(?P[\w.-]+): floor \S+ exceeds newest (?P\S+) release", + "floor:{ws}:{lib}", "any", "fix the dependency floor"), + ("floor-pypi", "fixable-dev", + r"^(?P[\w.-]+): no installable (?P\S+) release on PyPI satisfies floor", + "floor:{ws}:{lib}", "any", "fix the dependency floor"), + ("floor-other", "fixable-dev", + r"^(?P[\w.-]+): (?:unparseable (?:version|floor)|floor \S+ names a yanked)", + "floor:{ws}", "any", "fix the dependency floor"), + ("workflow-missing", "fixable-dev", + rf"^{_R}: required workflow '(?P[^']+)' has no workflow file", + "workflow-missing:{repo}:{wf}", "any", "add or rename the required workflow"), + ("manifest-local", "local-checkout", + r"^manifest drift: (?P