diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 5c48ca6a..ac68808e 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -208,6 +208,56 @@ 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 yanked or unparseable floor, URL lint, Lifecycle Drift | files a bug draft; picks it only on opt-in | +| `local-checkout` | behind, dirty, on a branch, worktree drift, every manifest-drift leg (they read the checkouts on disk, other sessions' worktrees included; `MANIFEST_FIXABLE` allowlists a leg that judges `main`) | reports only: another session's work may be in progress | +| `release-scope` | release integrate failed, install check F, rehearsal stale, a floor above the newest release | 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 not re-filed while +Heart keeps listing it; a fresh, valid read without the reason clears the +row, so a later recurrence files again). It files at most `--green-cap` (3) +new drafts per brief — `Consequence: judge`, a `Lane:`, a re-check-first +note, the quoted reason, a Witness, `Difficulty:` from the sizing faculty and +no `Unattended:` (the lane never grades its own drafts ready) — red first; +the rest wait for the next brief. + +**Where it writes.** Modes are `--green off|report|file|pick` (or +`$PYAUTO_HEART_GREEN`); the default is `file`. It writes drafts and its state +only when `brief --new` has `--out` (a stdout preview writes nothing) and +`--mind` names a Mind that is not the canonical shared checkout — a temp +worktree on `origin/main`, committed and pushed from there. Otherwise it +reports what it would file and says why. `pick` is the human's opt-in: a filed +or existing `draft/` prompt whose `Lane:` the brief allows and that sizing +grades `Unattended: ready` becomes a named task under a last `heart-green` +goal. An active quarantine's bug task is picked only when a prompt carries the +lane's key mark or has the entry's bug ref as its `Issue:`; it is 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..1ab7be01 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,11 +2901,13 @@ 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") - ap.add_argument("--mind", type=Path, default=BODY_MAP_PATH.parent) + ap.add_argument("--mind", type=Path, default=None, + help="the PyAutoMind checkout (default: the canonical one)") ap.add_argument("--budget", type=int, default=DEFAULT_REVIEW_BUDGET, help="review-minutes available in the slot") ap.add_argument("--awaiting-review", type=int, default=None, @@ -2926,6 +2929,19 @@ 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; opt-in). Default: ${_green.MODE_ENV}, else " + f"{_green.DEFAULT_MODE} for brief --new, report for green. " + "It writes only with --out and an explicit, non-canonical " + "--mind") + 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)") @@ -2988,7 +3004,8 @@ def main(argv=None) -> int: a = ap.parse_args(argv) lane = a.lane or detect_lane() - mind = a.mind.resolve() + a.mind_explicit = a.mind is not None + mind = (a.mind or BODY_MAP_PATH.parent).resolve() if a.prompt and a.verb not in ("slice", "premise"): print(f"batch {a.verb}: unexpected argument {a.prompt!r}", file=sys.stderr) return RC_USAGE @@ -3008,6 +3025,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 +3277,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 +3317,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 +3327,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 +3361,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 +3381,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 +3423,13 @@ 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, + preview=not a.out) + 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 +3473,81 @@ def _main_brief(mind: Path, a) -> int: return RC_OK if res["ok"] else RC_FINDINGS +#: Where the lane may not write: the shared, canonical Mind checkout other +#: sessions work in (memory: shared-Mind writes go through a temp worktree). +SHARED_MIND_HOLD = ("--mind is not a linked worktree ({}) — a main checkout is the " + "shared canonical Mind; the lane writes drafts only into a " + "Mind the caller names that is a temp " + "worktree on origin/main (`git -C worktree add " + "origin/main`), passed as --mind, committed and pushed from there") + + +def is_linked_worktree(path: Path) -> bool: + """True only for a LINKED git worktree (`--git-dir` differs from + `--git-common-dir`). The main checkout of any clone, wherever it lives, + is False — so is anything git cannot read.""" + dirs = [] + for flag in ("--git-dir", "--git-common-dir"): + try: + out = subprocess.run(["git", "-C", str(path), "rev-parse", flag], + capture_output=True, text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + return False + if out.returncode != 0 or not out.stdout.strip(): + return False + dirs.append((path / out.stdout.strip()).resolve()) + return dirs[0] != dirs[1] + + +def write_hold(mind: Path, a, preview: bool) -> str: + """Why the lane may not write here, or "" (review of #625): never in a + preview, never into an implicit Mind, and only into a linked worktree — + the main checkout of any Mind clone is the shared one.""" + if preview: + return "a preview (no --out) writes nothing" + if not getattr(a, "mind_explicit", False) or not is_linked_worktree(mind): + return SHARED_MIND_HOLD.format(mind) + return "" + + +def green_lane(mind: Path, a, default_mode: str, preview: bool = False) -> dict: + """Run the keep-Heart-green lane for `brief --new` / `green` (`_green`). + It reads Heart and may write NEW drafts and its state file — only when + `write_hold` allows; 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, + hold=write_hold(mind, a, preview)) + + +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..fe72b14d --- /dev/null +++ b/agents/conductors/batch/_green.py @@ -0,0 +1,508 @@ +"""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, on the human's opt-in (`pick`), 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 and its state file — +only when the caller allows it (never in a preview, never into the shared +canonical Mind: `_batch.write_hold`); 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" +#: `file` by default; `pick` (naming drafts as the brief's tasks) is the +#: human's opt-in, `--green pick` or `$PYAUTO_HEART_GREEN=pick` (review of #625). +DEFAULT_MODE = "file" +DEFAULT_CAP = 3 +MAX_AGE_HOURS = 6.0 +STATE_NAME = "heart_green.json" +GOAL_PREFIX = "heart-green" +KEY_MARK = "" + +#: Manifest legs that judge TRACKED repo content on main, and so are a dev fix. +#: Empty on purpose: every leg Heart reports today runs `repos_sync.py` over +#: the checkouts on disk, other sessions' worktrees included (the 2026-11-13 +#: "tenant firewall — 40 mismatch(es)" were all in one session's worktree). +MANIFEST_FIXABLE: tuple[str, ...] = () + +_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-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-main", "fixable-dev", + r"^manifest drift: (?P