diff --git a/AUTONOMY.md b/AUTONOMY.md index fb8ba960..9a33b0c7 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -334,18 +334,25 @@ never an assumption: `claims to falsify`, CLEAN carries one disposition line per claim (basis-cited / idle / finding — faculty AGENTS.md step 2a); a bare CLEAN over a non-empty claims surface is malformed evidence, not CLEAN. -4. **Heart** — verdict **GREEN** or **STALE**, or **YELLOW whose reason set is - contained in the set the human acknowledged at launch**. Heart observes - organism state, not the branch (the audit confirmed its legs never see - feature branches). **STALE** is Heart's freshness tier (evidence missing or - expired, nothing known-bad — `PyAutoHeart/heart/readiness.py`): it passes - this leg because an evidence gap is organism-scope, not branch-scope, and - legs 1–3 gate the branch itself; the PR body lists the stale reasons. - Releases are unaffected — they always require GREEN. A verdict from a Heart - without the tier behaves as before. For YELLOW, the acknowledgement binds - to the *exact reason list* at launch, for that launch only — any new - reason, or RED, parks the run. Never ambient, never carried across - sessions. +4. **Heart** — the **scoped development-ship verdict** (changed 2026-11-12, + PyAutoHeart#340; ruling M2.1 in "M2 rulings — 2026-11-12" below): + `pyauto-heart readiness --dev --repos A,B --json`, with the repos taken + from the task's `repos:` in `PyAutoMind/active.md` + (`consult_vitals_verdict --repos "$(active_task_repos )"`). Only CI + on `main` of the touched repos and their dependants blocks; every other + reason comes back in `shown_reasons` and is listed in the PR body without + blocking. Only **GREEN** passes. **STALE** — in-scope evidence missing, + unfinished, or older than 6 h — **never passes**: re-check, or park. With + **no Heart CLI** (a web session) the one fallback is the *published* + organism-wide feed: GREEN and under 6 h old passes, because it is at least + as strict as any scope; anything else parks. Any other scoped read that + cannot be made (an empty `repos:`, a Heart without the gate, an unknown + repo name) is "unknown" and parks. Until this change the leg + read the whole-organism verdict and let STALE pass; the scoped verdict has + no YELLOW tier, so the YELLOW acknowledgement below (bound to the *exact + reason list* at launch, for that launch only) applies only if a YELLOW + verdict is ever returned. Releases are unaffected — they ask the unscoped + verdict and always require GREEN. 5. **Independent adversary** — **added 2026-08-30, required for a BATCH launch** (below) and for any run counting toward the multi-repo autonomy @@ -655,6 +662,80 @@ row suspends the actor rule — the count goes back to every in-window row, with doctrine edit citing the row. A `reverted` row still demotes `glance` as the ruling says. +## M2 rulings — 2026-11-12 + +Ruled by the human 2026-11-12 at the M1→M2 gate of the autonomous-orchestrators +programme, one ruling per M2 decision sheet; this section is the dated doctrine +record of all six. Each quotes, verbatim, the recommendation the human adopted +from the sheets' index, then names the build issue or the human act it awaits, +and the condition that reverts it. It records the rulings; the doctrine text +each one changes elsewhere in this file is edited by its own build, not here. + +**M2.1 Heart branch scope.** *"Yes: enforce library CI for touched repos and +their dependants; show the rest. Feed: 6 h maximum age plus event triggers, +built first. Rule that an over-age feed re-checks or parks, never passes."* A +STALE feed never passes a development ship: over the maximum age the door +re-reads the touched repos' `main` CI at ship time, and an unattended run that +cannot parks. The override row stays, with its reason machine-readable. +Build: PyAutoHeart#340. *Revert condition:* any ship passed by the branch scope +that breaks `main` of a touched repo or a dependant, where the organism-wide RED +would have stopped it — return to the full verdict by dated doctrine edit. + +**M2.2 Server-side merge gate.** *"Yes, staged: libraries and tested organs +first, workspaces after a week, Mind after M4.3. Require status checks, not +reviews. `--auto` for notify and glance only. A separate worker identity at +M4."* `judge` stays a human merge; the ban under the corrective-RED path stays. +Awaits a human act: the rulesets are applied by the human with their admin +credential. *Revert condition:* a ruleset that blocks a release, or leaves PRs +pending with no failing check more than twice in a week — set that repo's +ruleset to `disabled` and fix the check list; an auto-merge found to have +passed a never-auto-merge rule withdraws `--auto` by doctrine edit. + +**M2.3 Lane fails closed; queue.md is the ranked list.** *"Fail closed in +unattended and cloud sessions only. Keep `queue.md` as a short ranked list, +validated; an empty list stops a shift; sort priority before review-minutes."* +As built: every plan `pyauto-brain batch plan` composes, and every watcher +tick, is unattended, and excludes a backlog draft with no valid `Lane:`, saying +so in the plan and the digest; `batch plan --attended` (a human picking for +their own session) reads an absent Lane as `any`. A brief's named tasks are the +human's own pick and are not gated. Intake refuses to file a new draft whose +lane is neither declared (a `Lane:` header, or the filer's `--lane`) nor +inferred from a resource signal, and says how to declare one. `lifecycle.py check` +fails on a `queue.md` prompt ref that resolves to no draft or active prompt +(`lifecycle.py close` retires a completed task's entry to the footer); an +empty or absent `queue.md` stops an unattended shift's backlog dip (named tasks +still run); below the queue the planner sorts priority, then review-minutes. +Build: PyAutoBrain#614. *Revert condition:* if fail-closed excludes more than a +handful of valid drafts in a week for a missing header, re-run +`bin/lane_backfill.py`; if that does not fix it, return to `any` for attended +filing. If `queue.md` goes two weeks without an edit, replace it with a +per-draft rank header set in a weekly review. + +**M2.4 Release builds the rehearsed SHAs.** *"Yes: release the rehearsed +commits even if `main` moved; move the Colab bump off `main`."* The release log +prints the rehearsed commit, the released commit and `identical`. Build: +PyAutoHands#337. *Revert condition:* a release whose tag does not match the +rehearsed commit, or a Colab notebook that installs the wrong version because +the bump is off `main` — return to `ref: main` plus the freeze flag until fixed. + +**M2.5 Always-apply rules.** *"Split the safety rules into a short file +imported by the home `CLAUDE.md`; set a size budget for the memory index +(21.8 KB today)."* +Awaits a human act: these are the human's home-folder files — a session may +draft the edits, the human applies them. *Revert condition:* if a new session's +loaded-file list does not show the rules file, or sessions lose the routing +they need, restore the previous files and fall back to importing the whole +workspace guidance file from the home `CLAUDE.md`. + +**Quarantine (side ruling).** *"Yes: one retry; quarantine needs a bug task, +expires in 7 days, at most 3, shows YELLOW."* The nightly may retry a failing +script once. A script may be quarantined only with a filed bug task, for at +most 7 days, at most 3 entries at once, never a unit test or an install check; +while any entry is live the release shows Heart YELLOW and the digest lists +them. Build: to build. *Revert condition:* a release that ships with a +quarantined script hiding a real user-facing break — quarantine returns to +human-only. + ## Shift briefs and unattended `glance` — 2026-11-03 Approved by the human 2026-11-03 as the rulings of the autonomous-orchestrators diff --git a/ORGANISM.md b/ORGANISM.md index 16b33357..d61d15e7 100644 --- a/ORGANISM.md +++ b/ORGANISM.md @@ -94,7 +94,9 @@ Brain → Heart (gate) → Build (execute) The Brain asks `pyauto-heart readiness --json`, reasons over the verdict, and only on **GREEN** triggers Build. Heart never triggers Build; Build never -re-derives a decision the Brain already made. +re-derives a decision the Brain already made. A development ship asks the +scoped gate instead, `pyauto-heart readiness --dev --repos A,B --json` (the +branch's repos and their dependants; STALE never passes — PyAutoHeart#340). ## Agents: conductors and faculties diff --git a/agents/_common.sh b/agents/_common.sh index e0325a2a..c8f85140 100755 --- a/agents/_common.sh +++ b/agents/_common.sh @@ -116,20 +116,48 @@ _agents_dir() { # gate); release-grade work uses this, ordinary build work does not. # --profile P evaluate under a readiness evidence profile (e.g. `release-ci` # for the scheduled-nightly gate — heart/readiness.py "Profiles"). +# --repos A,B the DEVELOPMENT-SHIP gate (PyAutoHeart#340, AUTONOMY.md leg 4): +# `pyauto-heart readiness --dev --repos A,B --json`, scoped to the +# repos the branch touches and their dependants, with a 6 h +# evidence age. Its verdict is green | red | stale, and only +# green passes. Take the repos from the task's `repos:` in +# PyAutoMind/active.md (`active_task_repos`). Release callers +# (release conductor, nightly, pre_build) never pass this. +# `--repos ""` (no scope) is "unknown", never an unscoped read. +# Without a Heart CLI that has the gate (a web session), the +# one safe fallback: the PUBLISHED organism-wide feed, GREEN +# and under 6 h old (`bin/heart_feed.py`), passes as "green" — +# it is at least as strict as the scoped verdict. Anything +# else is "unknown". # -# Echoes one of: green | yellow | red | unknown. Never fails the caller — an -# unresolvable/again-unknown verdict is reported as "unknown" (treated as YELLOW -# by callers), never silently as green. +# Echoes one of: green | yellow | red | stale | unknown. Never fails the caller — +# an unresolvable/again-unknown verdict is reported as "unknown" (treated as +# YELLOW by callers, and as a park by the dev-ship gate), never silently as green. consult_vitals_verdict() { - local refresh=0 profile="" + local refresh=0 profile="" repos="" scoped=0 while [[ $# -gt 0 ]]; do case "$1" in --refresh) refresh=1; shift ;; --profile) profile="$2"; shift 2 ;; --profile=*) profile="${1#*=}"; shift ;; + --repos) scoped=1; repos="${2:-}"; shift; shift || true ;; + --repos=*) scoped=1; repos="${1#*=}"; shift ;; *) shift ;; esac done + # A scope was asked for but is empty (a task with no `repos:` block): there + # is nothing to scope to, and an unscoped read would answer a different + # question. Unknown parks. + if [[ "$scoped" -eq 1 && -z "${repos//[ ,]/}" ]]; then + echo "unknown" + return 0 + fi + # No Heart CLI here (a web session): the scoped gate cannot be asked, so + # the published-feed fallback is the only answer. + if [[ "$scoped" -eq 1 ]] && ! resolve_heart >/dev/null 2>&1; then + _published_green_fallback + return 0 + fi local vitals vitals="$(_agents_dir)/faculties/vitals/vitals.sh" if [[ ! -f "$vitals" ]]; then @@ -143,20 +171,52 @@ consult_vitals_verdict() { # `set -o pipefail`, under which a non-zero exit from the (possibly # Heart-less) vitals faculty would otherwise double-fire a fallback. The python # below always prints exactly one token, even on empty/garbage input. - local args=(readiness --json) - [[ -n "$profile" ]] && args+=(--profile "$profile") + local args + args=($(_vitals_readiness_args "$profile" "$repos")) local out - out="$(bash "$vitals" "${args[@]}" 2>/dev/null | python3 -c ' -import json, sys + # A scoped read must come back as Heart's dev-ship verdict: a faculty with no + # Heart CLI answers from the published, organism-wide board, which cannot + # judge the scope — that is "unknown" (park), never a pass. + out="$(bash "$vitals" "${args[@]}" 2>/dev/null | SCOPED="$scoped" python3 -c ' +import json, os, sys try: - v = json.load(sys.stdin).get("verdict", "unknown") - print(v or "unknown") + d = json.load(sys.stdin) + if os.environ.get("SCOPED") == "1" and d.get("gate") != "dev-ship": + print("unknown") + else: + print(d.get("verdict", "unknown") or "unknown") except Exception: print("unknown") ' 2>/dev/null)" printf '%s\n' "${out:-unknown}" } +# _published_green_fallback — the dev-ship gate's one fallback when there is +# no Heart CLI to ask (a web session; a Heart that answers but errors is +# "unknown", never this fallback): the PUBLISHED +# organism-wide feed, read by bin/heart_feed.py, which already applies the 6 h +# maximum age. GREEN there means every repo is green, which is at least as +# strict as any scope, so it echoes "green"; anything else (an older, undated, +# non-green or unpublished feed) echoes "unknown", which parks. +_published_green_fallback() { + local feed + feed="$(cd "$(_agents_dir)/.." && pwd)/bin/heart_feed.py" + [[ -f "$feed" ]] || { echo "unknown"; return 0; } + # Captured, not piped out: heart_feed exits non-zero on any non-green + # status, which under a caller's pipefail must not add a second token. + local out + out="$(python3 "$feed" --json 2>/dev/null | python3 -c ' +import json, sys +try: + s = json.load(sys.stdin) + ok = s.get("source") == "published" and s.get("status") == "green" and s.get("pass") is True + print("green" if ok else "unknown") +except Exception: + print("unknown") +' 2>/dev/null)" + [[ "$out" == "green" ]] && echo "green" || echo "unknown" +} + # Back-compat alias for the pre-rename name (faculty: health -> vitals). consult_health_agent_verdict() { consult_vitals_verdict "$@"; } @@ -165,27 +225,90 @@ consult_health_agent_verdict() { consult_vitals_verdict "$@"; } # authorize proceeding despite specific, named RED reasons. Reads the SAME # read-only faculty as consult_vitals_verdict — Heart's verdict is never # mutated; the override is a Brain-level, recorded decision. +# +# `--repos A,B` reads the scoped dev-ship verdict instead (see +# consult_vitals_verdict); `--field stale_reasons|shown_reasons` prints that +# list of it instead of `red_reasons` (the PR body lists the shown reasons). consult_vitals_red_reasons() { - local profile="" + local profile="" repos="" field="red_reasons" scoped=0 while [[ $# -gt 0 ]]; do case "$1" in --profile) profile="$2"; shift 2 ;; --profile=*) profile="${1#*=}"; shift ;; + --repos) scoped=1; repos="${2:-}"; shift; shift || true ;; + --repos=*) scoped=1; repos="${1#*=}"; shift ;; + --field) field="$2"; shift 2 ;; + --field=*) field="${1#*=}"; shift ;; *) shift ;; esac done + # An empty scope reads nothing (never the unscoped verdict's reasons). + [[ "$scoped" -eq 1 && -z "${repos//[ ,]/}" ]] && return 0 local vitals vitals="$(_agents_dir)/faculties/vitals/vitals.sh" [[ -f "$vitals" ]] || return 0 - local args=(readiness --json) - [[ -n "$profile" ]] && args+=(--profile "$profile") - bash "$vitals" "${args[@]}" 2>/dev/null | python3 -c ' -import json, sys + local args + args=($(_vitals_readiness_args "$profile" "$repos")) + bash "$vitals" "${args[@]}" 2>/dev/null | FIELD="$field" python3 -c ' +import json, os, sys try: - for r in (json.load(sys.stdin).get("red_reasons") or []): + for r in (json.load(sys.stdin).get(os.environ["FIELD"]) or []): if str(r).strip(): print(str(r).strip()) except Exception: pass ' 2>/dev/null } + +# _vitals_readiness_args — the `pyauto-heart` argument words +# for one readiness read: the release verdict (optionally under a profile), or, +# with repos, the scoped development-ship gate. Repo names carry no spaces. +_vitals_readiness_args() { + local profile="$1" repos="$2" + if [[ -n "$repos" ]]; then + echo "readiness --dev --repos $repos --json" + elif [[ -n "$profile" ]]; then + echo "readiness --json --profile $profile" + else + echo "readiness --json" + fi +} + +# active_task_repos [active.md] — the repos a task's branch +# touches, comma-joined, from its `- repos:` block in PyAutoMind/active.md +# (` - : ` lines). This is the dev-ship gate's `--repos`. +# Prints nothing (exit 1) when the task or its repos are not found — the caller +# must then stop, never ship against an unscoped or empty scope. +active_task_repos() { + local slug="$1" ledger="${2:-}" + if [[ -z "$ledger" ]]; then + local mind; mind="$(resolve_mind 2>/dev/null)" || return 1 + ledger="$mind/active.md" + fi + [[ -f "$ledger" ]] || return 1 + SLUG="$slug" python3 - "$ledger" <<'PY' +import os, re, sys +slug, repos, inside, in_repos = os.environ["SLUG"].strip(), [], False, False +for line in open(sys.argv[1], encoding="utf-8", errors="replace"): + line = line.rstrip("\n") + if line.startswith("## "): + inside = line[3:].strip() == slug + in_repos = False + continue + if not inside: + continue + if re.match(r"^-\s+repos:\s*$", line): + in_repos = True + continue + if in_repos: + m = re.match(r"^\s+-\s+([^:\s]+)\s*(?::.*)?$", line) + if m: + if m.group(1) not in repos: + repos.append(m.group(1)) + continue + in_repos = False +if not repos: + sys.exit(1) +print(",".join(repos)) +PY +} diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 615665cf..2d2588f7 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -51,6 +51,8 @@ consulting a conductor. If a rule here starts needing to *judge* rather than | **One slice per epic per batch** | epic phases are ordered, so two members could not run in parallel anyway — and this is what interleaves small pieces of long programmes with standalone work | | **`Unattended: ready` only** | `needs-slicing` goes to the decomposition pass (`batch slice`); `never` never enters a batch | | **Lane match** | a session detects its own lane and plans only that one | +| **No Lane, no unattended pick** | a backlog draft with no valid `Lane:` is excluded from every unattended plan (the default, and the watcher) and the plan says so; `--attended` reads it as `any`. A lane-less draft that needs the laptop, RAL or private data would otherwise reach a cloud worker (M2.3, `AUTONOMY.md` "M2 rulings — 2026-11-12") | +| **Empty queue, no dip** | an empty or absent `queue.md` stops an unattended shift's backlog dip; a brief's named tasks still run (M2.3) | | **Not `looks-shipped`** | a draft the close-out guard (`intake looks-shipped`) flagged with strong evidence that its work already shipped waits until a human closes it or lists it in `PyAutoMind/looks_shipped_dismissed.md`; the flags are read from `PyAutoMind/looks_shipped.json` at plan time, so a dismissal takes effect at once. The 2026-11-05-am batch proposed two shipped drafts. | | **Backpressure** | see below | | **Brief scope** | under a shift brief, only its named tasks and the backlog its dip policy covers run; anything else is a dispatch outside the launch, which "What a batch launch is" forbids (`AUTONOMY.md`, 2026-11-03) | @@ -94,8 +96,12 @@ an entry up *is* the act of prioritising it. 3. the review-queue depth, derived from `active.md` as above. A queued prompt outranks an unqueued one; among queued ones the file's order -wins; below the queue the old rule stands — cheapest first, because that list -is read when there is a slot to fill and the question is what fits in it. A +wins; below the queue a declared `Priority:` comes first and cheapest review +second (M2.3, 2026-11-12 — cheapest-first let the cheapest review win and broke +ties by filename). An unattended plan with an **empty or absent** `queue.md` +dips into no backlog at all: only a brief's named tasks run, and the plan and +the digest say so. `lifecycle.py check` (Mind) fails on a `kind: prompt` ref +that resolves to no draft or active prompt, so the list stays honest. A queue entry written against `draft/…` still matches its prompt after it moves to `active/` (matched on the basename), so an entry never silently loses its priority. `retired`, `epic-slice` and `theme-sweep` entries are skipped rather @@ -132,7 +138,11 @@ work it cannot run. A session reports the other lane's ready count rather than hiding it, by resource: *"4 laptop-lane task(s) are ready (3 ral, 1 local-dev) — run `batch plan` from the laptop."* A task's `Lane:` is `any`, `local-dev`, or one of the resource lanes `ral` / `gpu` / `wsl-data`, each of which implies -`local-dev` (`lane_is_local` in the sizing faculty is the one test). +`local-dev` (`lane_is_local` in the sizing faculty is the one test). A draft +with **no** valid `Lane:` fails closed in an unattended plan +(`lane_absent_why`) and reads as `any` only under `batch plan --attended`; +intake refuses to file a draft whose lane is neither declared (`Lane:` header +or `--lane`) nor inferred. ## The premise check (`premise`) — before a run is spent @@ -290,8 +300,8 @@ title, size and repos, and the digest names it as from the brief's `issue:` repository; a pick recorded without a title falls back to the bare slug, and `validate` reads the backticked slug either way. The `why:` is the brief's admission rule plus `_brief.rank_note`, which is the -planner's actual order: `queue.md #k`, or `not in queue.md · ~N review-min · -priority P` (then the path, so a tie is alphabetical), plus `epic E phase X`. +planner's actual order: `queue.md #k`, or `not in queue.md · priority P · +~N review-min` (then the path, so a tie is alphabetical), plus `epic E phase X`. Shadow shift 1 (2026-11-04) showed why: six bare slugs, each `why: scoped tier notify`, could not be reviewed. A shadow digest prints its counters as one line (`- all counters 0 — shadow shift, nothing dispatched · review-minutes-planned: N`), diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 3edd626d..bac38479 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -91,10 +91,27 @@ def detect_lane() -> str: def _lane_ok(record_lane: str, session_lane: str) -> bool: """A laptop-lane task (`local-dev`, `ral`, `gpu`, `wsl-data`) runs only in - a `local-dev` session; `any` runs anywhere.""" + a `local-dev` session; `any` runs anywhere. An ABSENT lane passes here: it + is the unattended gate in `plan` (`lane_absent_why`) that excludes it.""" return not lane_is_local(record_lane) or session_lane == "local-dev" +def lane_absent_why(r: dict) -> str: + """Why an unattended pick refuses this record for want of a lane, or "". + + Fail closed (M2.3, human ruling 2026-11-12): a draft with no valid `Lane:` + is excluded from every unattended or cloud pick, because a lane-less draft + that needs the laptop, RAL or private data would otherwise reach a cloud + worker and burn its run. An attended session still reads it as `any`. + Worded without a colon: `emit` groups rejections on the text before one.""" + if r.get("lane"): + return "" + if r.get("lane_invalid"): + return (f"lane invalid ({r['lane_invalid']!r}) — unattended picks fail " + "closed; declare a valid Lane") + return "lane absent — unattended picks fail closed; declare a Lane" + + def grade(path: Path, mind: Path) -> dict: """Everything the planner needs about one prompt, from the faculty.""" p = parse_prompt(path, mind) @@ -110,7 +127,12 @@ def grade(path: Path, mind: Path) -> dict: "difficulty": level, "score": score, "consequence": tier, "witness": p.get("witness"), "review_minutes": minutes, "unattended": ready, "why": (why or [""])[0], - "ready_why": ready_why, "epic": None, "lane": p.get("lane") or "any", + "ready_why": ready_why, "epic": None, + # The DECLARED lane, or None when the header has no valid `Lane:`. + # Absence is no longer read as `any` here (M2.3, AUTONOMY.md "M2 + # rulings — 2026-11-12"): `plan` excludes a lane-less draft from an + # unattended pick and reads it as `any` only when `attended=True`. + "lane": p.get("lane"), "lane_invalid": p.get("lane_invalid"), "priority": p.get("priority") or "normal", "blocked": bool(p.get("blocked_by")), } @@ -221,7 +243,7 @@ def read_queue(mind: Path) -> list[str]: except OSError: return [] out: list[str] = [] - kind, ref, fenced = "", "", False + kind, ref, fenced, entry = "", "", False, False def flush() -> None: if kind == "prompt" and ref and ref not in out: out.append(ref) @@ -231,12 +253,17 @@ def flush() -> None: continue if fenced: continue - if QUEUE_HEAD_RE.match(line): + if line.startswith("#"): + # Any heading ends the entry above it. Only a numbered `## .` + # one starts a new entry: the `## Retired` footer's `### …` + # entries carry `- ref:` lines too, and until 2026-11-12 the last + # of them overwrote the final live entry's ref. flush() kind, ref = "", "" + entry = bool(QUEUE_HEAD_RE.match(line)) continue m = QUEUE_FIELD_RE.match(line) - if not m: + if not m or not entry: continue value = m.group(2).split("#")[0].strip() if m.group(1) == "kind": @@ -314,7 +341,8 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, session_lane: str = "web-github", awaiting_review: int = 0, cap: int = DEFAULT_BACKPRESSURE_CAP, queue: list[str] | None = None, awaiting_source: str = "given", carried: list[str] | None = None, - carried_from: str = "", brief: dict | None = None) -> dict: + carried_from: str = "", brief: dict | None = None, + attended: bool = False) -> dict: """Compose the next batch — a BatchDecision. Every constraint states itself in `rejected`, because a planner that @@ -326,10 +354,30 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, from `active.md` by the caller (`derive_awaiting_review`) unless the human passed the flag; `awaiting_source` says which, because a number nobody can trace is a number nobody trusts. + + `attended` is False for every shift this planner composes (the batch it + proposes runs unattended, and the watcher picks unattended). Two M2.3 rules + (AUTONOMY.md "M2 rulings — 2026-11-12") apply only then: + + - a backlog draft with no valid `Lane:` is excluded (`lane_absent_why`); + - an EMPTY queue stops the backlog dip: the brief's named tasks still run, + nothing else is picked. `queue=[]` is "queue.md was read and is empty or + absent" (`read_queue` returns that); `queue=None` means the caller read + no queue at all and is left ungated — every Mind-reading caller passes a + list. + + With `attended=True` (`batch plan --attended`, a human at the keyboard + picking for this session) an absent Lane reads as `any` and an empty queue + falls back to the backlog order, as before. """ rejected: list[tuple[str, str]] = [] + queue_given = queue is not None queue = queue or [] + # Read BEFORE a brief folds its named tasks into the order: an empty + # queue.md is the human saying nothing is wanted beyond the brief. + queue_stop = not attended and queue_given and not queue all_records = records + named_names: set[str] = set() # Under a shift brief the brief IS the human's composition (AUTONOMY.md, # "Shift briefs and unattended `glance`"): its named tasks outrank the # queue, then only the backlog its dip policy covers. The brief's @@ -337,6 +385,7 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, if brief is not None: records, out_of_scope, named = _brief.scope(records, brief) rejected += out_of_scope + named_names = {Path(t).name for t in named} queue = named + [q for q in queue if q not in named] minutes = _brief._nonneg_int(brief.get("review-minutes", {}).get("value", "")) if minutes is not None: @@ -359,27 +408,37 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # run, not which. next_phase = next_phases(records) - pool = [] + pool, lane_absent = [], [] for r in records: + # A brief's named task is the human's own pick, not a backlog dip: + # neither M2.3 gate below applies to it (the brief's `lanes:` still does). + backlog = Path(r["path"]).name not in named_names why = pool_gate(r, next_phase) if why: rejected.append((r["path"], why)) elif not _lane_ok(r["lane"], session_lane): rejected.append((r["path"], f"lane {r['lane']}, session {session_lane}")) + elif not attended and backlog and lane_absent_why(r): + rejected.append((r["path"], lane_absent_why(r))) + lane_absent.append(r["path"]) + elif queue_stop and backlog: + rejected.append((r["path"], "queue.md empty — no backlog dip " + "(named tasks only)")) else: pool.append(r) - # The queue first, cheapest first within it. `queue.md` is the human's - # order and outranks everything: a queued prompt beats an unqueued one, and - # among queued ones the file's order wins, because moving an entry up IS - # the act of prioritising it. Below the queue the old rule stands — - # cheapest first, since this list is read when there is a slot to fill and - # the question is what fits in it. + # The queue first; below it priority, THEN review-minutes. `queue.md` is + # the human's order and outranks everything: a queued prompt beats an + # unqueued one, and among queued ones the file's order wins, because moving + # an entry up IS the act of prioritising it. Below the queue a declared + # `Priority:` outranks cost (M2.3, 2026-11-12): sorting cheapest first let + # the cheapest review win and broke ties by filename, which picked work the + # human did not want. Cheapest first still decides within a priority. for r in pool: r["queue_rank"] = queue_rank(r, queue) r["queued"] = r["queue_rank"] < len(queue) - pool.sort(key=lambda r: (r["queue_rank"], r["review_minutes"], - priority_rank(r), r["path"])) + pool.sort(key=lambda r: (r["queue_rank"], priority_rank(r), + r["review_minutes"], r["path"])) members, spent, seen_epics, libs = [], 0, set(), set() for r in pool: @@ -430,13 +489,17 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, "lane_counts": _lane_counts(r for r in all_records if r["unattended"] == "ready" and not r.get("done")), "brief": brief is not None, + "attended": attended, + # The two M2.3 gates, stated rather than buried in `rejected`. + "lane_absent": lane_absent, + "queue_stop": queue_stop, } def _lane_counts(records) -> dict[str, int]: counts: dict[str, int] = {} for r in records: - lane = r.get("lane") or "any" + lane = r.get("lane") or "absent" counts[lane] = counts.get(lane, 0) + 1 return dict(sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))) @@ -472,6 +535,17 @@ def emit(d: dict) -> None: f"(queued members marked q)") print(f"Planned: {d['review_minutes_planned']} review-minutes over " f"{len(d['members'])} member(s)") + if d.get("attended"): + print("Mode: attended (--attended) — an absent Lane reads as " + "any, an empty queue.md falls back to the backlog order") + if d.get("queue_stop"): + # M2.3: an empty queue is the human saying nothing beyond the brief. + print("Backlog dip: STOPPED — queue.md is empty, so this unattended " + "shift takes the brief's named tasks only") + if d.get("lane_absent"): + n = len(d["lane_absent"]) + print(f"Lane absent: {n} draft(s) excluded — no valid `Lane:`, and an " + "unattended pick fails closed (declare one; bin/lane_backfill.py)") if d.get("carried"): # Read first, because a carried member is work the human is already # holding: it costs review-minutes in THIS slot that no new member @@ -2836,6 +2910,11 @@ def main(argv=None) -> int: "default: derived from active.md") ap.add_argument("--cap", type=int, default=DEFAULT_BACKPRESSURE_CAP) ap.add_argument("--lane", default="", help="override the detected session lane") + ap.add_argument("--attended", action="store_true", + help="plan: a human at the keyboard picks for THIS session — " + "an absent Lane reads as any and an empty queue.md " + "does not stop the backlog dip (default: unattended, " + "both fail closed; AUTONOMY.md M2 rulings)") ap.add_argument("--json", action="store_true", dest="as_json") # brief / plan ap.add_argument("--check", default="", metavar="FILE", @@ -3149,7 +3228,7 @@ def _main_plan(mind: Path, a, lane: str) -> int: d = plan(survey(mind), budget=a.budget, session_lane=lane, awaiting_review=awaiting, cap=a.cap, queue=read_queue(mind), awaiting_source=source, carried=carried, carried_from=carried_from, - brief=brief) + brief=brief, attended=a.attended) if a.as_json: print(json.dumps(d, indent=2)) return RC_OK diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index e06d22f0..af5d6fa5 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -376,16 +376,16 @@ def pick_reason(record: dict, brief: dict) -> str: def rank_note(record: dict) -> str: """The planner's order, as it applied to this record (`_batch.plan`): - queue.md position first; below the queue, cheapest review first, then - priority, then the path — so a tie is alphabetical, and says so.""" + queue.md position first; below the queue, priority, then cheapest review + (M2.3, 2026-11-12), then the path — so a tie is alphabetical, and says so.""" parts = [] if record.get("queued"): parts.append(f"queue.md #{record['queue_rank'] + 1}") elif "queue_rank" in record: parts.append("not in queue.md") + parts.append(f"priority {record.get('priority') or 'normal'}") if record.get("review_minutes") is not None: parts.append(f"~{record['review_minutes']} review-min") - parts.append(f"priority {record.get('priority') or 'normal'}") if record.get("epic"): phase = record.get("phase") parts.append(f"epic {record['epic']}" + (f" phase {phase:g}" if isinstance(phase, (int, float)) diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 2af41eae..c905143f 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -243,6 +243,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, lines += ["", "### Backlog picks"] lines += [_line(t, counters, tiers.get(t, picks[t].get("tier", "?")), health, base) + f" — why: {picks[t].get('why') or 'NOT RECORDED'}" for t in backlog] or [NO_PICKS] + lines += backlog_gate_lines(counters) started = [t for t in named + backlog if t in counters.get("outcomes", {}) or t in counters.get("parked", []) @@ -262,6 +263,23 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, return "\n".join(lines) + "\n" +def backlog_gate_lines(counters: dict) -> list[str]: + """What the M2.3 gates kept out of the backlog dip (AUTONOMY.md "M2 + rulings — 2026-11-12"), as of the watcher's last tick. Not bullets: a + `- ` line in this section is read as a pick and must carry a `why:`.""" + gates = counters.get("backlog_gates") or {} + out = [] + if gates.get("queue_stop"): + out.append("Backlog dip stopped: queue.md is empty, so the shift took the " + "brief's named tasks only.") + absent = gates.get("lane_absent") or [] + if absent: + out.append(f"Lane absent: {len(absent)} draft(s) excluded — no valid `Lane:`, " + "and an unattended pick fails closed: " + + ", ".join(f"`{Path(a).stem}`" for a in absent)) + return [""] + out if out else [] + + # --- per-worker exits, GitHub merges, tokens (PyAutoBrain#610) ----------------- WORKERS_HEADING = "### Workers" diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index b4ed5137..ce27139a 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -233,13 +233,31 @@ def worker_prompt(task: str, prompt_path: str, brief_path: Path, lease_dir: Path shift_ledger=SHIFT_LEDGER, brain_cli=BRAIN_CLI) +#: The Brain helpers a close-out sources for the scoped Heart gate. +COMMON_SH = Path(__file__).resolve().parents[2] / "_common.sh" + + +def pr_repos(pr_url: str) -> str: + """The repo a PR belongs to, as the dev-ship gate's `--repos` (bare name). + Empty for a URL that is not a GitHub pull request — the gate then cannot + be scoped, and the close-out refuses.""" + m = re.match(r"^https://github\.com/[^/]+/([^/]+)/pull/\d+", pr_url or "") + return m.group(1) if m else "" + + def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, lease_dir: Path) -> str: - """The close-out session template filled in for one PR (phase 4b).""" + """The close-out session template filled in for one PR (phase 4b). Its + Heart check is the scoped development-ship gate for the PR's repo (leg 4, + PyAutoHeart#340): only `green` merges.""" + repos = pr_repos(pr_url) + heart_cmd = (f"bash -c 'source \"{COMMON_SH}\"; consult_vitals_verdict --repos {repos}'" + if repos else "") return CLOSEOUT_TEMPLATE.read_text(encoding="utf-8").format( task=task, pr_url=pr_url, task_path=prompt_path, brief_path=brief_path, lease_dir=lease_dir, ledger_dir=Path(lease_dir).parent / _mind_writer.LEDGER_DIR, - shift_ledger=SHIFT_LEDGER) + shift_ledger=SHIFT_LEDGER, pr_repos=repos or "(none — not a GitHub PR URL)", + heart_cmd=heart_cmd or "(cannot be scoped — refuse)") def closeout_command(task: str, pr_url: str, prompt_path: str, brief_path: Path, @@ -904,7 +922,13 @@ def _tick_locked(slot, brief, mind, now, spawner, grace_s, records, agents, import _batch # noqa: E402 — deferred: _batch imports this module's sibling if records is None: records = _batch.survey(mind) - d = _batch.plan(records, session_lane="local-dev", brief=brief) + # Unattended by construction: an absent Lane is excluded and an empty + # queue.md stops the backlog dip (M2.3, AUTONOMY.md "M2 rulings — + # 2026-11-12"). Recorded each tick so the digest can say so. + d = _batch.plan(records, session_lane="local-dev", brief=brief, + queue=_batch.read_queue(mind)) + counters["backlog_gates"] = {"lane_absent": sorted(d["lane_absent"]), + "queue_stop": d["queue_stop"]} if _brief.is_shadow(brief): proposed = _propose(d["members"], brief, counters, max_sessions) _write_counters(slot, counters) diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index f96d7c10..14c927d8 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -16,8 +16,14 @@ outcome — the human merges by `/prm` at check-in. error message, a removed or weakened test, a renamed public thing, or a wrong docs claim. Any one of them → refuse. 3. Refuse if the PR carries the `decision-taken` label, if its tier is not - `glance`, or if Heart is RED (`python3 $PYAUTO_BRAIN/bin/heart_feed.py`, - exit 2). + `glance`, or unless Heart's **scoped development-ship verdict** for the + PR's repo ({pr_repos}) is `green` (AUTONOMY.md leg 4, PyAutoHeart#340): + + {heart_cmd} + + It prints `green`, `red`, `stale` or `unknown`. Only `green` passes: `stale` + never does, and `unknown` (a reply that is not Heart's dev-ship gate, or no + Heart here) parks — refuse with the word it printed. 4. If everything passed, use the prm skill on {pr_url}: the full close-out, judged exactly as a human-typed `/prm`. Never commit to PyAutoMind yourself — a hook refuses it; queue each Mind change with diff --git a/agents/conductors/build/build.sh b/agents/conductors/build/build.sh index 9106c085..cb0d2f38 100755 --- a/agents/conductors/build/build.sh +++ b/agents/conductors/build/build.sh @@ -38,6 +38,14 @@ # is NOT changed — it still reports RED; this records that a # human accepted those exact reasons. Never ambient: it must # be passed explicitly per invocation. +# --rehearsal-run-id release mode, pre_build: the successful release.yml +# rehearsal whose recorded commits the release publishes +# (PyAutoHands#337). Else $REHEARSAL_RUN_ID, else Heart's +# validated stages.rehearse.run_id +# ($HEART_STATE_DIR/validation_report.json); a given id +# that differs from Heart's refuses. Forwarded as +# `autohands pre_build `; with none the agent +# refuses (exit 5) before consulting anything. # --dry-run reason + plan only; emit the BuildDecision, do not execute. # --json emit the BuildDecision as JSON only (machine-readable). # @@ -66,6 +74,8 @@ json_only=0 action="" forward=() accept_red=() +rehearsal_run_id="${REHEARSAL_RUN_ID:-}" +heart_run_note="" while [[ $# -gt 0 ]]; do case "$1" in @@ -78,6 +88,10 @@ while [[ $# -gt 0 ]]; do [[ $# -ge 2 ]] || { echo "build agent: --accept-red needs a verbatim RED reason" >&2; exit 5; } accept_red+=("$2"); shift 2 ;; --accept-red=*) accept_red+=("${1#*=}"); shift ;; + --rehearsal-run-id) + [[ $# -ge 2 ]] || { echo "build agent: --rehearsal-run-id needs a run id" >&2; exit 5; } + rehearsal_run_id="$2"; shift 2 ;; + --rehearsal-run-id=*) rehearsal_run_id="${1#*=}"; shift ;; --dry-run) dry_run=1; shift ;; --json) json_only=1; shift ;; -h|--help) sed -n '2,40p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;; @@ -107,6 +121,45 @@ if [[ " $allowed " != *" $action "* ]]; then exit 5 fi +# ----- a release publishes the REHEARSED commits (PyAutoHands#337) ----- +# `pre_build `: release.yml refuses a live dispatch +# without the run id, so the door refuses first, before any gate or workspace +# is touched. A second positional forwarded after `--` is the run id already. +if [[ "$mode" == "release" && "$action" == "pre_build" ]]; then + if [[ ${#forward[@]} -ge 2 ]]; then + rehearsal_run_id="${forward[1]}" + fi + heart_run_id="$(python3 - "${HEART_STATE_DIR:-$HOME/.pyauto-heart}/validation_report.json" <<'PY' 2>/dev/null +import json, sys +try: + print(((json.load(open(sys.argv[1])).get("stages") or {}).get("rehearse") or {}).get("run_id") or "") +except Exception: + print("") +PY +)" + if [[ -z "$rehearsal_run_id" ]]; then + rehearsal_run_id="$heart_run_id" + [[ -n "$rehearsal_run_id" ]] && heart_run_note="rehearsal run id $rehearsal_run_id from Heart's validated stages.rehearse.run_id" + elif [[ -n "$heart_run_id" && "$heart_run_id" != "$rehearsal_run_id" ]]; then + # A given id (flag, positional or a lingering $REHEARSAL_RUN_ID) that is + # not the rehearsal Heart validated would publish unvalidated commits. + echo "build agent: refused — rehearsal run id $rehearsal_run_id (given) is not the" >&2 + echo " rehearsal Heart validated: stages.rehearse.run_id $heart_run_id" >&2 + echo " (${HEART_STATE_DIR:-$HOME/.pyauto-heart}/validation_report.json). Pass the validated" >&2 + echo " id, or validate the intended rehearsal first (release validate)." >&2 + exit 5 + fi + if ! [[ "$rehearsal_run_id" =~ ^[0-9]+$ ]]; then + echo "build agent: refused — a release publishes the commits of a successful release.yml" >&2 + echo " rehearsal (PyAutoHands#337), and no rehearsal run id was given." >&2 + echo " Pass --rehearsal-run-id (pyauto-brain release --rehearsal-run-id )," >&2 + echo " set REHEARSAL_RUN_ID, or ingest the rehearsal into Heart (release validate)" >&2 + echo " so its validation_report.json carries stages.rehearse.run_id." >&2 + exit 5 + fi + forward=("${forward[0]:-1}" "$rehearsal_run_id") +fi + # ----- consult the sibling vitals faculty (not Heart directly) ----- [[ "$json_only" -eq 1 ]] || echo "== build agent ($mode): consulting vitals faculty for readiness ==" if [[ "$mode" == "release" ]]; then @@ -122,6 +175,7 @@ eff="$verdict" decision="" ; decision_code=0 warnings=() ; blockers=() ; follow_up=() +[[ -n "${heart_run_note:-}" ]] && warnings+=("Using the ${heart_run_note}.") [[ "$verdict" == "unknown" ]] && warnings+=("Readiness verdict unknown; treated as YELLOW. Run 'pyauto-brain vitals' to refresh.") diff --git a/agents/conductors/health/AGENTS.md b/agents/conductors/health/AGENTS.md index 03b4757a..995e6a3f 100644 --- a/agents/conductors/health/AGENTS.md +++ b/agents/conductors/health/AGENTS.md @@ -85,7 +85,7 @@ Deterministically, given the adopted verdict and triage: | **GREEN** | none — a release conductor may proceed | | **RED** (real blockers) | resolve the top blocker; cite `pyauto-heart fix …` where one exists, else flag it as human/Release-Agent work. **Do not** dispatch a release while RED — the release preflight (Stage 0/1) aborts on it anyway | | **YELLOW**, a real warning present | clear the warning (cite its `fix`), then re-assess | -| **STALE** (the freshness tier) | refresh the top evidence gap — `pyauto-brain release validate` when the release-validation report is one of them (the hard gate), else the capability's own refresh entry point. Nothing is known-bad, so this is never a code fix. A release still requires GREEN; the dev-ship gate (`AUTONOMY.md` leg 4) treats STALE as passing | +| **STALE** (the freshness tier) | refresh the top evidence gap — `pyauto-brain release validate` when the release-validation report is one of them (the hard gate), else the capability's own refresh entry point. Nothing is known-bad, so this is never a code fix. A release still requires GREEN, and since 2026-11-12 the scoped dev-ship gate (`AUTONOMY.md` leg 4, PyAutoHeart#340) never passes STALE either | | **YELLOW**, only baseline gaps | `pyauto-brain release validate` — the leg that flips "no release validation" and makes GREEN reachable | | **UNKNOWN** | `pyauto-brain vitals` to refresh, then re-run | @@ -121,9 +121,8 @@ Exit codes mirror the adopted verdict so a caller (and the loop) can branch: `0` green · `2` yellow · `3` red · `4` unknown · `6` stale. A CLI usage error (unknown subcommand) exits `5`, kept distinct so misuse is never read as a real YELLOW. STALE takes `6` rather than the free slot `1` for the same fail-safe -reason: `1` is the shell's own generic failure, and STALE is the tier -`AUTONOMY.md` leg 4 treats as **passing** the dev-ship gate — so a crash must -never be readable as a passing verdict. That separation is the whole point: a +reason: `1` is the shell's own generic failure, and STALE (which the dev-ship +gate passed until 2026-11-12) must never be confused with a crash. That separation is the whole point: a machine caller can tell "Heart says STALE" from "Heart unreachable" (`4`). ## Prerequisites / caveats diff --git a/agents/conductors/health/health.sh b/agents/conductors/health/health.sh index b64141ed..db3a4fb3 100755 --- a/agents/conductors/health/health.sh +++ b/agents/conductors/health/health.sh @@ -57,8 +57,8 @@ # # STALE takes 6 rather than the free slot 1 for the same fail-safe reason: the # shell's own generic failure is 1 (a missing `_common.sh`, a failed `readlink`), -# and STALE is the tier AUTONOMY.md leg 4 treats as PASSING the dev-ship gate — -# so a crash must never be readable as a passing verdict. 6 sits outside the 0-5 +# and a crash must never be readable as a passing verdict (STALE passed the dev-ship +# gate until 2026-11-12; the scoped gate, PyAutoHeart#340, never passes it). 6 sits outside the 0-5 # block and is never produced by bash or python here, which is what lets a # machine caller tell "Heart says STALE" from "Heart unreachable" (4). @@ -365,9 +365,9 @@ elif verdict == "stale" or evidence: "rehearsal + wheel integration -> Heart ingests -> " "re-judge), DELEGATED to the release conductor, which owns " "the MCP GitHub boundary. ") - detail += ("A release still requires GREEN; the dev-ship gate " - "(AUTONOMY.md leg 4) treats STALE as passing, because an " - "evidence gap is organism-scope, not branch-scope.") + detail += ("A release still requires GREEN, and the scoped dev-ship " + "gate (AUTONOMY.md leg 4) never passes STALE either: " + "refresh, or park.") rec = {"action": "refresh-evidence", "command": cmd, "headline": "STALE — refresh the expired evidence: " + t["reason"], "detail": detail, "checkpoint": CHECKPOINT} @@ -414,8 +414,8 @@ _exit_code_for() { green) return 0 ;; yellow) return 2 ;; red) return 3 ;; - # 6, not the free slot 1: bash itself exits 1 on a generic failure, and STALE - # PASSES the dev-ship gate — a crash must never be readable as a pass. See + # 6, not the free slot 1: bash itself exits 1 on a generic failure — a + # crash must never be readable as a verdict. See # the exit-code table in this file's header. stale) return 6 ;; *) return 4 ;; diff --git a/agents/conductors/intake/AGENTS.md b/agents/conductors/intake/AGENTS.md index 537ebbc1..180767e9 100644 --- a/agents/conductors/intake/AGENTS.md +++ b/agents/conductors/intake/AGENTS.md @@ -121,8 +121,8 @@ with or without it. Unknown keywords are counted in the page's Hygiene section. | Mode | Command | What it does | |------|---------|--------------| -| **classify** | `intake ""` / `intake classify --file P` | classify one raw input; `--apply` writes the prompt | -| **ideas** | `intake ideas` | scan `ideas.md`, propose one prompt per bullet; `--apply` writes them | +| **classify** | `intake ""` / `intake classify --file P [--lane L]` | classify one raw input; `--apply` writes the prompt — and **refuses** (exit 6) when no lane is decided: no `--lane`, no `Lane:` header in the text, no resource signal (M2.3, `AUTONOMY.md` "M2 rulings — 2026-11-12") | +| **ideas** | `intake ideas [--lane L]` | scan `ideas.md`, propose one prompt per bullet; `--apply` writes them, refusing (and not marking) any bullet with no decided lane | | **census** | `intake census` | inventory every filed prompt (work-type/target/difficulty/status + hygiene flags); always read-only | | **dashboard** | `intake dashboard` | render the census as the Mind **task** page — picks, in flight, pending release, planned, backlog (including human review), recent, epics; `--apply` writes `PyAutoMind/dashboard.md` + `dashboard.html` + `state.json` (the organ-cockpit feed, `board/_state.py` v1: red when a task awaits input/is blocked or prompts drift, yellow when work waits on a merge/release/review or picks exist; items carry the page's own copy payloads), `--check` exits 1 on drift (ignoring the page date and the feed's `updated`) | | **formalise** | `intake formalise [prefix]` | retroactively header the prompts census flags — derive the missing fields, insert in place, prose untouched; `--apply` writes | diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 5d99da61..7ce8b9fa 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -475,13 +475,18 @@ def infer_autonomy(level: str, factors: dict) -> str: return "safe" -def analyse(text: str, source: str, themes=None): +def analyse(text: str, source: str, themes=None, lane=None): """Classify raw text into a full IntakeDecision (never writes). `themes` is the optional `Themes:` keyword list the caller assigns at formalisation (primary first). Absent, any `Themes:` block the raw input already carries is kept; absent that too, the prompt is simply un-themed — formalisation never waits on a theme. + + `lane` is an EXPLICIT lane from the filer (`classify --lane any`). With + none, a `Lane:` header in the text, else a lane inferred from a resource + signal. With none of the three the decision carries `lane: None` and a + `lane_refusal`, and `write_prompt` refuses to file it (M2.3). """ # A pasted prompt's own header block (PyAutoBrain#472): read its raw # Type/Target/Repos so a value the faculty does not recognise is reported, @@ -586,17 +591,28 @@ def analyse(text: str, source: str, themes=None): # `Type:` matches the destination folder (PyAutoMind convention). For a # low-confidence triage filing that means `Type: triage`, not the provisional # guess — the guess still rides in the IntakeDecision's `work_type` field. - # A declared lane wins; otherwise the text's resource signals. `any` is - # the default and is not written — absence already means it. - lane = header.get("lane") or infer_lane(text) + # The filer's explicit lane wins, then a `Lane:` header in the text, then + # a resource signal the text names. "No signal" is NOT `any` (M2.3, + # AUTONOMY.md "M2 rulings — 2026-11-12": a new draft filed without a Lane + # is rejected): an unattended planner excludes a draft with no `Lane:`, so + # where the work can run must be decided at filing, by a person or by a + # signal — never defaulted. `write_prompt` refuses a decision with none. + if lane: + lane, lane_source = lane.lower(), "explicit" + elif header.get("lane"): + lane, lane_source = header["lane"], "declared" + else: + lane = infer_lane(text) + lane, lane_source = (lane, "inferred") if lane != "any" else (None, None) header = _render_header(title, folder, target_display, repos, level, autonomy, priority, themes, consequence=consequence, witness=p["witness"], review_minutes=review_minutes, unattended=unattended, passthrough=_declared_passthrough(header_lines), - lane=(lane if lane != "any" - or header.get("lane") else None)) + lane=lane) + decision_lane = {"lane": lane, "lane_source": lane_source, + "lane_refusal": "" if lane else LANE_REFUSAL} return { "source": source, "title": title, @@ -641,9 +657,24 @@ def analyse(text: str, source: str, themes=None): consequence=consequence), "next_action": _next_action(proposed, confidence, folder), "slice_offer": slice_offer(proposed, unattended), + **decision_lane, } +#: Why intake will not file a draft whose lane nobody decided, and how to +#: decide it (M2.3, AUTONOMY.md "M2 rulings — 2026-11-12"). +LANE_REFUSAL = ( + "refused — no Lane: the text names no resource (RAL, GPU, /mnt data, " + "private data), so where this can run is undecided, and an unattended " + "shift excludes a draft with no Lane. Declare one: add a header line " + f"`Lane: <{' | '.join(LANE_VALUES)}>` to the text, or pass " + "`--lane any` (or another lane) to `intake classify` / `intake ideas`.") + + +class LaneRequired(ValueError): + """`write_prompt` was handed a decision with no lane (M2.3).""" + + # Optional header keys a raw input may declare that classification never # derives, so they are carried through verbatim (PyAutoBrain#553). Dropping them # filed an epic member as a standalone pick and dated it by file mtime. Written @@ -1025,7 +1056,12 @@ def _with_memory(header: str, pages: list, target: str | None = None) -> str: def write_prompt(mind: Path, decision: dict, body_text: str, source_note: str): - """Write the formal prompt file. Returns the path written (relative to mind).""" + """Write the formal prompt file. Returns the path written (relative to mind). + + Refuses (`LaneRequired`) a decision with no lane — declared, explicit or + inferred — before anything touches the disk (M2.3).""" + if not decision.get("lane"): + raise LaneRequired(LANE_REFUSAL) rel = Path(decision["proposed_path"]) dest = mind / rel if dest.exists(): @@ -1506,8 +1542,9 @@ def recent_events(c: dict, limit: int = RECENT_MAX) -> list: def _lane_of(header: dict) -> str: - """The prompt's lane as the planner reads it: a value the sizing faculty - does not accept counts as `any`, exactly as `parse_prompt` treats it.""" + """The prompt's lane for the census: a value the sizing faculty does not + accept counts as `any`. That is the ATTENDED reading only; an unattended + planner excludes a draft with no valid lane (`_batch.lane_absent_why`).""" lane = (header.get("lane") or "any").lower() return lane if lane in LANE_VALUES else "any" @@ -1585,8 +1622,8 @@ def census(mind: Path) -> dict: "witness": header.get("witness", ""), "review_minutes": header.get("review-minutes", "-"), "unattended": header.get("unattended", "-"), - # Where it can run. Absent means `any` — the common case, and a - # missing lane must never be read as "nowhere". + # Where it can run. Absent reads as `any` here (the attended + # reading); an unattended pick excludes it (M2.3, 2026-11-12). "lane": _lane_of(header), "priority": header.get("priority", "-"), "status": header.get("status", "-"), @@ -4172,10 +4209,16 @@ def emit_human(d: dict): for r in d["risks"]: print(f" - {r}") print(f"Next action: {d['next_action']}") + if d.get("lane_refusal"): + print(f"Lane: {d['lane_refusal']}") if d.get("slice_offer"): print(f"Offer: {d['slice_offer']}") +#: `classify --apply` / `ideas --apply` refused a draft with no lane (M2.3). +RC_LANE_REQUIRED = 6 + + def main(argv=None): ap = argparse.ArgumentParser(prog="intake", add_help=True) ap.add_argument("--mind", required=True) @@ -4190,8 +4233,13 @@ def main(argv=None): cl.add_argument("--themes", default="", help="comma-separated Themes: keywords, primary first " "(vocabulary: PyAutoMind/themes.md)") + lane_help = ("declare where the work can run; required when the text has " + "no `Lane:` header and names no resource (M2.3)") + cl.add_argument("--lane", default="", choices=("",) + LANE_VALUES, help=lane_help) - sub.add_parser("ideas", help="scan ideas.md and propose one prompt per bullet") + idp = sub.add_parser("ideas", help="scan ideas.md and propose one prompt per bullet") + idp.add_argument("--lane", default="", choices=("",) + LANE_VALUES, + help=lane_help + "; applies to every bullet without one") sub.add_parser("census", help="inventory all filed prompts (always read-only)") @@ -4364,7 +4412,11 @@ def main(argv=None): print("intake: no input text to classify.", file=sys.stderr) return 4 decision = analyse(text, source, [t for t in ( - getattr(a, "themes", "") or "").split(",") if t.strip()]) + getattr(a, "themes", "") or "").split(",") if t.strip()], + lane=a.lane or None) + if a.apply and not decision["lane"]: + print(f"intake: {decision['lane_refusal']}", file=sys.stderr) + return RC_LANE_REQUIRED if a.apply: written = write_prompt(mind, decision, text, source) decision["written"] = written @@ -4385,10 +4437,13 @@ def main(argv=None): return 4 results = [] formalised = {} + refused: list[str] = [] for text, ctx in bullets: ctx_text = f"{ctx}: {text}" if ctx else text - d = analyse(ctx_text, f"ideas.md ({ctx or 'top'})") - if a.apply: + d = analyse(ctx_text, f"ideas.md ({ctx or 'top'})", lane=a.lane or None) + if a.apply and not d["lane"]: + refused.append(d["title"]) + elif a.apply: d["written"] = write_prompt(mind, d, ctx_text, d["source"]) d["slice_offer"] = slice_offer(d["written"], d["unattended"]) formalised[text] = d["written"] @@ -4400,7 +4455,8 @@ def main(argv=None): else: print(f"== Intake: {len(results)} idea(s) from ideas.md ==") for d in results: - mark = f" -> WROTE {d['written']}" if a.apply else "" + mark = (f" -> WROTE {d['written']}" if d.get("written") + else " -> REFUSED (no Lane)" if a.apply else "") print(f" [{d['work_type']}/{d['target']}, {d['difficulty']}, " f"conf {d['classification_confidence']}] {d['title']}" f" => {d['proposed_path']}{mark}") @@ -4409,6 +4465,12 @@ def main(argv=None): if not a.apply: print("\n(dry-run — re-run `intake ideas --apply` to write these + " "mark the bullets in ideas.md)") + if refused: + print(f"intake: {len(refused)} idea(s) not filed — {LANE_REFUSAL}", + file=sys.stderr) + for t in refused: + print(f" - {t}", file=sys.stderr) + return RC_LANE_REQUIRED return 0 return 5 diff --git a/agents/conductors/release/AGENTS.md b/agents/conductors/release/AGENTS.md index 39a38a9f..d5b46486 100644 --- a/agents/conductors/release/AGENTS.md +++ b/agents/conductors/release/AGENTS.md @@ -20,8 +20,13 @@ Brain → Heart (gate) → Build (execute) *and* execution to the Build Agent's release mode (`build.sh --mode release`), the **single** gate implementation — GREEN proceeds, YELLOW needs `--force`, RED blocks; on a pass `autohands - pre_build` dispatches `release.yml`. This conductor holds no second copy of - that gate. + pre_build ` dispatches `release.yml`. This + conductor holds no second copy of that gate. **A release publishes the + rehearsed commits** (PyAutoHands#337): the door forwards the rehearsal run + id — `--rehearsal-run-id `, else `$REHEARSAL_RUN_ID`, else Heart's + validated `stages.rehearse.run_id` (`$HEART_STATE_DIR/validation_report.json`) + — and refuses (exit 5) with none, or when a given id differs from the one + Heart validated. ## Run @@ -29,6 +34,7 @@ Brain → Heart (gate) → Build (execute) bin/pyauto-brain release # release door → Build Agent release mode bin/pyauto-brain release --force # also proceed on yellow (cautions ack'd) bin/pyauto-brain release -- 2 # forward `2` (minor_version) to pre_build +bin/pyauto-brain release --rehearsal-run-id 12345678901 # publish that rehearsal's commits ``` Gate outcomes and exit codes are the Build Agent's (release mode). @@ -57,7 +63,7 @@ ingest+verdict (phase 2): # 1. print the MCP dispatch/poll/download plan (the agent executes it via MCP): bin/pyauto-brain release rehearse [--ref main] [--minor N] [--json] -# 2. after downloading the artifact + capturing the library main HEADs, +# 2. after downloading the artifact (rehearsal.json carries the rehearsed commit_shas + run_id), # ingest into Heart and get the verdict: bin/pyauto-brain release rehearse --ingest --commit-shas /commit_shas.json bin/pyauto-brain release rehearse --ingest --force # accept a YELLOW @@ -66,8 +72,11 @@ bin/pyauto-brain release rehearse --ingest --force # accept a YELLOW Phase 1 emits the steps: `mcp__github__actions_run_trigger` on `PyAutoLabs/PyAutoHands` `release.yml` with `{rehearsal: true}` (M1 mode) → poll `mcp__github__actions_get` to completion → download the -`testpypi-rehearsal-version` artifact → `mcp__github__get_commit` each library's -`main` HEAD into `commit_shas.json`. Phase 2 hands the artifacts to +`testpypi-rehearsal-version` artifact → copy `rehearsal.json`'s `commit_shas` +(the commits the rehearsal **built**, PyAutoHands#337) into `commit_shas.json` +and keep its `run_id` — never `main` HEADs re-read later. Phase 2 does that +copy itself when `rehearsal.json` is present, and refuses a `--commit-shas` +file that disagrees with it. Phase 2 hands the artifacts to `pyauto-heart validate --ingest` (Heart writes `validation_report.json`), then calls `consult_vitals_verdict --refresh` so the **read-only vitals faculty** reports GREEN/YELLOW/RED from the freshly-ingested report. @@ -111,7 +120,7 @@ bin/pyauto-brain release validate --ingest --force # accept a YELLOW abort). Stage 1 reuses the cached CI conclusion; dispatching a fresh unit run if stale is the spec's optional path, deferred for M4's first cut. - **Stage 2 (rehearse)** is `rehearse.sh`'s phase-1 plan, reused verbatim via its - `--next-plan-cmd` hook so its dispatch/poll/download/capture-heads plan stays + `--next-plan-cmd` hook so its dispatch/poll/download/commit-shas-from-record plan stays defined in ONE place; only the "continue" step is redirected into phase B. - **Stage 3 (integrate)** dispatches PyAutoHeart's `release-integrate.yml` channel with `testpypi_version` + `commit_shas` (a JSON *string*) read diff --git a/agents/conductors/release/_nightly_lib.sh b/agents/conductors/release/_nightly_lib.sh index 5543ded0..f4b5d0d1 100644 --- a/agents/conductors/release/_nightly_lib.sh +++ b/agents/conductors/release/_nightly_lib.sh @@ -73,3 +73,103 @@ print(r["status"], r.get("conclusion") or "")' 2>>"$err")"; then sleep "$interval" done } + +# dispatch_and_await [ ] +# Dispatches, resolves the run id, polls it to completion (await_run, which +# keeps the token fresh), and optionally downloads an artifact. Returns 0 ok, +# 1 dispatch failed, 2 run red, 3 artifact missing, 4 lost the watch (the run +# was never judged — callers treat it as a driver error). +dispatch_and_await() { + local repo="$1" wf="$2" inputs="$3" artifact="${4:-}" dest="${5:-}" + local before run_id rc + # The step 6 dispatch comes hours in: never dispatch on a stale token. + refresh_gh_token + before="$(date -u +%Y-%m-%dT%H:%M:%SZ)" + local fargs=() + while IFS=$'\t' read -r k v; do + [[ -z "$k" ]] && continue + fargs+=(-f "$k=$v") + done < <(printf '%s' "$inputs" | python3 -c ' +import json, sys +for k, v in (json.load(sys.stdin) or {}).items(): + print(f"{k}\t{str(v).lower() if isinstance(v, bool) else v}") +') + gh workflow run "$wf" -R "$repo" --ref main "${fargs[@]}" || return 1 + run_id="" + for _ in $(seq 1 18); do + sleep 10 + run_id="$(gh run list -R "$repo" --workflow "$wf" --created ">=$before" \ + -L 1 --json databaseId --jq '.[0].databaseId // empty' 2>/dev/null)" + [[ -n "$run_id" ]] && break + done + if [[ -z "$run_id" ]]; then + echo "nightly: dispatched $repo/$wf but could not find the run" >&2 + return 1 + fi + echo "https://github.com/$repo/actions/runs/$run_id" >&2 + LAST_RUN_URL="https://github.com/$repo/actions/runs/$run_id" + LAST_RUN_ID="$run_id" + await_run "$repo" "$run_id" + rc=$? + [[ $rc -eq 4 ]] && return 4 + if [[ $rc -ne 0 ]]; then + # The report artifacts upload `if: always()`, so a FAILED run still carries + # the evidence of which scripts failed — fetch it so the page can name + # them. Best-effort: paging must never be blocked by a missing artifact. + if [[ -n "$artifact" ]]; then + refresh_gh_token + gh run download "$run_id" -R "$repo" -n "$artifact" -D "$dest" 2>/dev/null \ + || echo "nightly: failed run's artifact '$artifact' not downloadable" >&2 + fi + return 2 + fi + if [[ -n "$artifact" ]]; then + refresh_gh_token + gh run download "$run_id" -R "$repo" -n "$artifact" -D "$dest" || return 3 + fi + return 0 +} + +# rehearsal_record — the rehearsal's own +# record (PyAutoHands#337 "Caller contract"): writes rehearsal.json's +# `commit_shas` to as {bare repo: sha} and prints its run id. +# Returns 1, with the reason on stderr, when there is no usable record — no +# rehearsal.json, a pre-#337 one without `commit_shas`, or no digit run id. +rehearsal_record() { + python3 - "$1" "$2" <<'PY' +import json, re, sys +from pathlib import Path +d, out = Path(sys.argv[1]), Path(sys.argv[2]) +cands = ([d / "rehearsal.json"] if (d / "rehearsal.json").is_file() else []) \ + + sorted(p for p in d.rglob("rehearsal.json") if p != d / "rehearsal.json") +for p in cands: + try: + rec = json.loads(p.read_text()) + except (OSError, ValueError): + continue + shas, run = rec.get("commit_shas"), str(rec.get("run_id") or "") + if isinstance(shas, dict) and shas and re.fullmatch(r"\d+", run): + out.write_text(json.dumps(shas, indent=2, sort_keys=True) + "\n") + print(run) + sys.exit(0) +print(f"nightly: no rehearsal record (rehearsal.json with run_id and commit_shas) under {d}", + file=sys.stderr) +sys.exit(1) +PY +} + +# live_release_inputs — the +# live release.yml inputs: `rehearsal_run_id` (required by #337) and the +# compact `commit_shas` JSON string the run cross-checks against the record. +live_release_inputs() { + python3 - "$1" "$2" "$3" <<'PY' +import json, re, sys +minor, run, path = sys.argv[1:4] +if not re.fullmatch(r"\d+", run): + sys.exit(f"nightly: rehearsal run id {run!r} is not a run id") +shas = json.loads(open(path).read()) +print(json.dumps({"rehearsal": "false", "minor_version": minor, + "rehearsal_run_id": run, + "commit_shas": json.dumps(shas, separators=(",", ":"), sort_keys=True)})) +PY +} diff --git a/agents/conductors/release/nightly.sh b/agents/conductors/release/nightly.sh index 509bb657..806a6123 100644 --- a/agents/conductors/release/nightly.sh +++ b/agents/conductors/release/nightly.sh @@ -21,7 +21,10 @@ # --profile release-ci` — GREEN only; STALE/YELLOW/ # RED stop and page; there is NO force input # step 6 live release dispatch Build's release.yml (rehearsal=false, -# minor_version=1) — or a log line under dry-run. +# minor_version=1, rehearsal_run_id + commit_shas +# from the Stage 2 rehearsal.json — PyAutoHands#337: +# the release builds the REHEARSED commits) — or a +# log line under dry-run. # A red run whose release tag nevertheless landed # (the post-publish smoke leg failed) is SHIPPED, # reported with a warning, never a stop @@ -321,60 +324,7 @@ print($2) " } -# dispatch_and_await [ ] -# Dispatches, resolves the run id, polls it to completion (await_run, which -# keeps the token fresh), and optionally downloads an artifact. Returns 0 ok, -# 1 dispatch failed, 2 run red, 3 artifact missing, 4 lost the watch (the run -# was never judged — callers treat it as a driver error). -dispatch_and_await() { - local repo="$1" wf="$2" inputs="$3" artifact="${4:-}" dest="${5:-}" - local before run_id rc - # The step 6 dispatch comes hours in: never dispatch on a stale token. - refresh_gh_token - before="$(date -u +%Y-%m-%dT%H:%M:%SZ)" - local fargs=() - while IFS=$'\t' read -r k v; do - [[ -z "$k" ]] && continue - fargs+=(-f "$k=$v") - done < <(printf '%s' "$inputs" | python3 -c ' -import json, sys -for k, v in (json.load(sys.stdin) or {}).items(): - print(f"{k}\t{str(v).lower() if isinstance(v, bool) else v}") -') - gh workflow run "$wf" -R "$repo" --ref main "${fargs[@]}" || return 1 - run_id="" - for _ in $(seq 1 18); do - sleep 10 - run_id="$(gh run list -R "$repo" --workflow "$wf" --created ">=$before" \ - -L 1 --json databaseId --jq '.[0].databaseId // empty' 2>/dev/null)" - [[ -n "$run_id" ]] && break - done - if [[ -z "$run_id" ]]; then - echo "nightly: dispatched $repo/$wf but could not find the run" >&2 - return 1 - fi - echo "https://github.com/$repo/actions/runs/$run_id" >&2 - LAST_RUN_URL="https://github.com/$repo/actions/runs/$run_id" - await_run "$repo" "$run_id" - rc=$? - [[ $rc -eq 4 ]] && return 4 - if [[ $rc -ne 0 ]]; then - # The report artifacts upload `if: always()`, so a FAILED run still carries - # the evidence of which scripts failed — fetch it so the page can name - # them. Best-effort: paging must never be blocked by a missing artifact. - if [[ -n "$artifact" ]]; then - refresh_gh_token - gh run download "$run_id" -R "$repo" -n "$artifact" -D "$dest" 2>/dev/null \ - || echo "nightly: failed run's artifact '$artifact' not downloadable" >&2 - fi - return 2 - fi - if [[ -n "$artifact" ]]; then - refresh_gh_token - gh run download "$run_id" -R "$repo" -n "$artifact" -D "$dest" || return 3 - fi - return 0 -} +# dispatch_and_await lives in _nightly_lib.sh (tested there with a fake gh). log "step 4 — validate (Stages 0-3 via validate.sh)" phase_a="$(bash "$HERE/validate.sh" --json)" @@ -392,7 +342,6 @@ s2_repo="$(plan_field "$phase_a" "plan['stage2_plan']['steps'][0]['repo']")" s2_wf="$(plan_field "$phase_a" "plan['stage2_plan']['steps'][0]['workflow']")" s2_inputs="$(plan_field "$phase_a" "json.dumps(plan['stage2_plan']['steps'][0]['inputs'])")" s2_artifact="$(plan_field "$phase_a" "[s for s in plan['stage2_plan']['steps'] if s['step']=='download'][0]['artifact']")" -head_repos="$(plan_field "$phase_a" "chr(10).join([s for s in plan['stage2_plan']['steps'] if s['step']=='capture-heads'][0]['repos'])")" log "step 4a — Stage 2 rehearsal: dispatch $s2_repo/$s2_wf" dispatch_and_await "$s2_repo" "$s2_wf" "$s2_inputs" "$s2_artifact" "$ART_DIR" @@ -405,22 +354,21 @@ elif [[ $rc -ne 0 ]]; then exit 2 fi -# capture-heads: {bare repo name: main HEAD sha} — Stage 2's commit_shas.json -# is the single source of truth downstream (validate.sh header). -refresh_gh_token -python3 - "$ART_DIR/commit_shas.json" <; cannot release rehearsed commits" + exit 1 +} +if [[ -n "$s2_run_id" && "$rehearsal_run_id" != "$s2_run_id" ]]; then + page "rehearsal record is for run $rehearsal_run_id, but this night rehearsed run $s2_run_id — refusing to release" + exit 1 +fi +log "rehearsal record: run $rehearsal_run_id, commit_shas $(cat "$ART_DIR/commit_shas.json" | tr -d ' \n')" log "step 4b — Stage 3 integrate: emitting + executing the dispatch plan" phase_b="$(bash "$HERE/validate.sh" --stage3-plan "$ART_DIR" --json)" || { @@ -493,9 +441,14 @@ if [[ "$DRY_RUN" == "true" ]]; then exit 0 fi -log "step 6 — dispatching the LIVE release ($version)" -dispatch_and_await "$BUILD_REPO" "$RELEASE_WORKFLOW" \ - '{"rehearsal": "false", "minor_version": "1"}' +log "step 6 — dispatching the LIVE release ($version) of rehearsal run $rehearsal_run_id" +# release.yml refuses a live dispatch without `rehearsal_run_id` (M2.4); the +# commit_shas cross-check must equal the record exactly. +live_inputs="$(live_release_inputs 1 "$rehearsal_run_id" "$ART_DIR/commit_shas.json")" || { + page "could not compose the live release inputs (rehearsal run $rehearsal_run_id)" + exit 1 +} +dispatch_and_await "$BUILD_REPO" "$RELEASE_WORKFLOW" "$live_inputs" rc=$? if [[ $rc -eq 4 ]]; then # Unjudged, not failed: the release may well have published, so not page() diff --git a/agents/conductors/release/rehearse.sh b/agents/conductors/release/rehearse.sh index c0b3f336..33e8b1fd 100755 --- a/agents/conductors/release/rehearse.sh +++ b/agents/conductors/release/rehearse.sh @@ -123,11 +123,12 @@ print(json.dumps({ "until": "status == completed", "note": "artifact exists IFF all 5 wheels built+installed"}, {"step": "download", "artifact": os.environ["ART"], "note": "download into an artifacts dir (rehearsal.json + testpypi_version.txt)"}, - {"step": "capture-heads", "mcp_tool": "mcp__github__get_commit", - "repos": [f"{owner}/{lib}" for lib in libs], - "note": "write {repo: sha} of each library main HEAD to commit_shas.json in the dir, " - "keyed by the BARE repo name (e.g. PyAutoNerves, not owner/repo) - " - "matches heart/readiness.py commit_shas convention"}, + {"step": "commit-shas-from-record", "source": "rehearsal.json", + "note": "write rehearsal.json commit_shas (the commits the rehearsal BUILT, " + "keyed by BARE repo name) to commit_shas.json in the dir, and keep " + "its run_id: a live release.yml needs rehearsal_run_id " + "(PyAutoHands#337). Never re-read main HEADs - main may have moved. " + "The ingest phase does this itself when rehearsal.json is present."}, {"step": "next", "cmd": os.environ["NEXT_CMD"]}, ], }, indent=2)) @@ -155,12 +156,12 @@ Bash cannot call GitHub; execute these steps with Brain's MCP GitHub tools 3. DOWNLOAD the '$REHEARSAL_ARTIFACT' artifact into an artifacts directory (it contains rehearsal.json + testpypi_version.txt). -4. CAPTURE the current main HEAD sha of each library and write them as - {bare_repo_name: sha} to /commit_shas.json (keys are bare names, e.g. - "PyAutoNerves" — matches heart/readiness.py's commit_shas convention, NOT - "owner/repo") — so Heart can confirm the report is for THIS source - (readiness matches them against the live main HEADs): - mcp__github__get_commit for: ${LIBRARIES[*]/#/$LIBRARIES_OWNER/} +4. RECORD the rehearsed commits: copy rehearsal.json's "commit_shas" object + ({bare_repo_name: sha}, e.g. "PyAutoNerves") to /commit_shas.json, and + keep its "run_id" — the live release.yml needs it as rehearsal_run_id + (PyAutoHands#337: a release builds the rehearsed commits). Never re-read the + library main HEADs: main may have moved since the rehearsal. (The ingest + phase writes commit_shas.json itself when rehearsal.json is in .) 5. NEXT (continue the pipeline): $next_cmd @@ -181,6 +182,24 @@ fi heart="$(resolve_heart)" || exit $? +# The rehearsal's own record is the commit_shas authority (PyAutoHands#337): +# when rehearsal.json is in the artifacts, commit_shas.json is written from it, +# and a --commit-shas file that disagrees with it refuses. +if [[ -d "$ingest_dir" ]]; then + source "$HERE/_nightly_lib.sh" + if record_run="$(rehearsal_record "$ingest_dir" "$ingest_dir/.commit_shas.record.json" 2>/dev/null)"; then + if [[ -n "$commit_shas_file" && "$commit_shas_file" != "$ingest_dir/commit_shas.json" ]] \ + && ! python3 -c 'import json,sys; sys.exit(json.load(open(sys.argv[1])) != json.load(open(sys.argv[2])))' \ + "$commit_shas_file" "$ingest_dir/.commit_shas.record.json"; then + echo "release rehearse: --commit-shas $commit_shas_file disagrees with rehearsal.json (run $record_run) — the record is the authority" >&2 + exit 1 + fi + mv "$ingest_dir/.commit_shas.record.json" "$ingest_dir/commit_shas.json" + commit_shas_file="$ingest_dir/commit_shas.json" + [[ "$json_only" -eq 1 ]] || echo "== release agent: commit_shas from rehearsal.json (run $record_run) ==" + fi +fi + ingest_args=(validate --ingest "$ingest_dir") [[ -n "$commit_shas_file" ]] && ingest_args+=(--commit-shas "$commit_shas_file") [[ -n "$profile" ]] && ingest_args+=(--profile "$profile") diff --git a/agents/conductors/release/release.sh b/agents/conductors/release/release.sh index e509ff7d..3561d3fb 100755 --- a/agents/conductors/release/release.sh +++ b/agents/conductors/release/release.sh @@ -16,6 +16,10 @@ # explicit, per-invocation human decision # that does NOT alter Heart's verdict); # forward to pre_build. +# release [--rehearsal-run-id ] — the rehearsal whose recorded commits +# the release publishes (PyAutoHands#337); +# forwarded to build.sh, which refuses +# without one (see build.sh). # # This conductor holds no second copy of the gate logic — one gate # implementation lives in the Build Agent; this door routes through it. @@ -54,6 +58,7 @@ fi force=0 forward=() accept_red=() +rehearsal_run_id="" while [[ $# -gt 0 ]]; do case "$1" in --force) force=1; shift ;; @@ -61,6 +66,10 @@ while [[ $# -gt 0 ]]; do [[ $# -ge 2 ]] || { echo "release conductor: --accept-red needs a verbatim RED reason" >&2; exit 5; } accept_red+=("$2"); shift 2 ;; --accept-red=*) accept_red+=("${1#*=}"); shift ;; + --rehearsal-run-id) + [[ $# -ge 2 ]] || { echo "release conductor: --rehearsal-run-id needs a run id" >&2; exit 5; } + rehearsal_run_id="$2"; shift 2 ;; + --rehearsal-run-id=*) rehearsal_run_id="${1#*=}"; shift ;; --) shift; forward=("$@"); break ;; *) forward+=("$1"); shift ;; esac @@ -74,4 +83,5 @@ echo "== release conductor: delegating gate + execution to the Build Agent (rele args=(--mode release) [[ "$force" -eq 1 ]] && args+=(--force) for _a in ${accept_red[@]+"${accept_red[@]}"}; do args+=("--accept-red=$_a"); done +[[ -n "$rehearsal_run_id" ]] && args+=("--rehearsal-run-id=$rehearsal_run_id") exec bash "$HERE/../build/build.sh" "${args[@]}" -- "${forward[@]}" diff --git a/agents/conductors/release/validate.sh b/agents/conductors/release/validate.sh index b6e857ae..d394b993 100755 --- a/agents/conductors/release/validate.sh +++ b/agents/conductors/release/validate.sh @@ -15,8 +15,9 @@ # preflight blocker. (A fresh dispatch-if-stale run is the # spec's optional path — deferred for M4's first cut.) # Stage 2 (rehearse) dispatch Build's release.yml rehearsal, poll, download -# the testpypi-rehearsal-version artifact, capture each -# library's main HEAD -> commit_shas.json. Reused AS-IS +# the testpypi-rehearsal-version artifact, write its +# rehearsal.json commit_shas -> commit_shas.json (the +# commits it BUILT, PyAutoHands#337). Reused AS-IS # from rehearse.sh (called into, not re-implemented). # Stage 3 (integrate) dispatch PyAutoHeart's release-integrate.yml channel # with the Stage-2 testpypi_version + commit_shas, poll, @@ -58,8 +59,9 @@ # 1 could-not-ingest — i.e. the same convention rehearse.sh's phase 2 uses, held # consistent across the now-longer pipeline. Plan-emission phases exit 0. # -# commit_shas authority. Stage 2's commit_shas.json (the library main HEADs the -# Release Agent read straight from GitHub) is the SINGLE source of truth. Stage 3 +# commit_shas authority. Stage 2's commit_shas.json (the commits the rehearsal +# built, from its own rehearsal.json — PyAutoHands#337, never main HEADs re-read +# afterwards) is the SINGLE source of truth. Stage 3 # merely echoes it back: the same JSON is passed as release-integrate.yml's # `commit_shas` input, which emit_release_report writes out and embeds into # stage_report.json. So the phase-C `--commit-shas` flag and the stage report's @@ -182,6 +184,14 @@ def find_shas(): continue if isinstance(data, dict): return data.get("commit_shas") if "commit_shas" in data else data + # No commit_shas.json yet: the rehearsal record itself (PyAutoHands#337). + for p in sorted(d.rglob("rehearsal.json")): + try: + data = json.loads(p.read_text()) + except (OSError, json.JSONDecodeError): + continue + if isinstance(data, dict) and isinstance(data.get("commit_shas"), dict): + return data["commit_shas"] return {} version = find_version() @@ -210,7 +220,7 @@ print(shas_json) # then emit a phase-C `--commit-shas /commit_shas.json` step pointing at a # file that may not exist. Better to stop here than dispatch a blind run. if [[ -z "$commit_shas_json" || "$commit_shas_json" == "{}" ]]; then - echo "release validate: no Stage-2 commit_shas found in '$stage3_dir' (expected a non-empty commit_shas.json — the authoritative library main HEADs). Cannot dispatch Stage 3 without them." >&2 + echo "release validate: no Stage-2 commit_shas found in '$stage3_dir' (expected a non-empty commit_shas.json, or rehearsal.json with commit_shas — the rehearsed commits). Cannot dispatch Stage 3 without them." >&2 exit 1 fi diff --git a/agents/faculties/sizing/_sizing.py b/agents/faculties/sizing/_sizing.py index a6120d02..eb478a5e 100755 --- a/agents/faculties/sizing/_sizing.py +++ b/agents/faculties/sizing/_sizing.py @@ -436,7 +436,10 @@ def empty_discovery_reason(mind: Path, work_type: str) -> str: # `skills/WORKFLOW.md` already defines (`local-dev` / `web-github` / `ci-only` / # `analysis-only`) rather than a parallel cloud/laptop one — `local-dev` means # the work needs the local dataset and output trees, an SSH endpoint, or the -# human at the machine. Default `any`. +# human at the machine. An absent `Lane:` is `any` only in an ATTENDED +# session; every unattended or cloud pick excludes it (M2.3, AUTONOMY.md "M2 +# rulings — 2026-11-12"; `_batch.lane_absent_why`), and intake refuses to file a +# draft whose lane is neither declared nor inferred. # # `ral`, `gpu` and `wsl-data` (2026-11-03, autonomous-orchestrators phase 2) # name the resource the work needs: RAL test runs, the laptop GPU, data under @@ -447,7 +450,9 @@ def empty_discovery_reason(mind: Path, work_type: str) -> str: def lane_is_local(lane) -> bool: - """True for every lane but `any` (a missing lane is `any`).""" + """True for every lane but `any`. A missing lane is not local here — the + question this answers is "laptop or not?"; whether a missing lane may run + at all is the planner's call (unattended: no, M2.3).""" return (lane or "any") != "any" # Surfaces that make a change a PI's decision whatever repo it lives in: a diff --git a/agents/faculties/vitals/AGENTS.md b/agents/faculties/vitals/AGENTS.md index 18cfb748..45aa11cf 100644 --- a/agents/faculties/vitals/AGENTS.md +++ b/agents/faculties/vitals/AGENTS.md @@ -157,9 +157,9 @@ faculty every cycle.) Red dominates yellow, which dominates stale — the structural precedence in `PyAutoHeart/heart/readiness.py`. A release still requires **GREEN** (STALE - blocks it exactly as YELLOW does), while the dev-ship gate (`AUTONOMY.md` - leg 4) treats STALE as **passing**, because an evidence gap is organism-scope, - not branch-scope. A verdict from an older Heart carries no `stale_reasons` + blocks it exactly as YELLOW does). The development-ship gate (`AUTONOMY.md` + leg 4) asks the scoped `readiness --dev --repos A,B` verdict instead + (PyAutoHeart#340), and STALE never passes it. A verdict from an older Heart carries no `stale_reasons` key at all and behaves exactly as before. 5. **Explain and recommend.** Produce the structured report below. Recommendations diff --git a/bin/README.md b/bin/README.md index cc7bfc84..904bd4f2 100644 --- a/bin/README.md +++ b/bin/README.md @@ -8,8 +8,10 @@ Executable tooling for the PyAuto organism. skill `.md` files must stay < 200 lines). - **`heart_feed.py`** — "Heart at the door": reads the Heart's published `state.json` (fallback: local `pyauto-heart readiness --json`), read-only, - never ticks; exit 0 green · 1 yellow/stale · 2 red · 3 grey. Run first by - `start_dev` step 0a and `route`. + never ticks; exit 0 green · 1 yellow/stale · 2 red · 3 grey. A feed older + than 6 h is never GREEN (STALE, `pass: false`); `--repos A,B` asks the local + Heart's scoped dev-ship gate (PyAutoHeart#340). Run first by `start_dev` + step 0a and `route`. - **`lane_backfill.py`** — proposes a `Lane:` for every lane-less draft in the planner pool, from intake's own lane signals, as a table for a human to skim; `--apply [--from ]` writes the headers (commits nothing). diff --git a/bin/heart_feed.py b/bin/heart_feed.py index 64fd6cc9..ab3afe86 100755 --- a/bin/heart_feed.py +++ b/bin/heart_feed.py @@ -23,6 +23,17 @@ reader at the door must be fast and must not mutate state. The vitals faculty remains the live, authoritative read at ship time. +MAXIMUM AGE (PyAutoHeart#340, AUTONOMY.md "M2 rulings — 2026-11-12"). A feed +older than 6 h, or of unknown age, is never GREEN: it reads STALE (a YELLOW or +RED feed keeps its worse colour) with an age row, and `pass` is true only for +GREEN. STALE never passes. + +SCOPE (`--repos A,B`). Asks the local Heart's development-ship gate, +`pyauto-heart readiness --dev --repos A,B --json` — only CI on `main` of those +repos and their dependants blocks; other reasons are shown as info. The +published feed is organism-wide and cannot be scoped, so without a local Heart +the door reads it unscoped and says so (`scope_applied: false`). + Output: `Heart: RED — (updated 2h ago)` then one line per red/yellow item (info items too when the status is not green and nothing is red/yellow). `--json` prints the same summary as one JSON object for the skill seams. @@ -50,6 +61,7 @@ FALLBACK_TIMEOUT = 30 STATUSES = ("green", "yellow", "red", "stale", "grey") +MAX_FEED_AGE_HOURS = 6.0 EXIT = {"green": 0, "yellow": 1, "stale": 1, "red": 2, "grey": 3} SEVERITY_ORDER = {"red": 0, "yellow": 1, "info": 2} @@ -154,27 +166,37 @@ def resolve_heart_cli(): def from_readiness(r): - """Map `pyauto-heart readiness --json` into the state.json shape.""" + """Map `pyauto-heart readiness --json` (or its `--dev` dev-ship verdict) + into the state.json shape. A dev-ship verdict's `shown_reasons` are info + rows (shown, never blocking) and its age is the snapshot's (`feed_ts`).""" verdict = str(r.get("verdict", "")).lower() status = verdict if verdict in STATUSES else "grey" items = ([{"severity": "red", "text": t} for t in r.get("red_reasons") or []] + [{"severity": "yellow", "text": t} for t in r.get("yellow_reasons") or []] - + [{"severity": "info", "text": t} for t in r.get("stale_reasons") or []]) + + [{"severity": "info", "text": t} for t in r.get("stale_reasons") or []] + + [{"severity": "info", "text": f"shown (not in scope): {t}"} + for t in r.get("shown_reasons") or []]) headline = items[0]["text"] if items else ( "all checks green" if status == "green" else f"verdict {verdict or 'unknown'}") - return {"status": status, "headline": headline, "updated": r.get("ts"), - "items": items} + return {"status": status, "headline": headline, + "updated": r.get("feed_ts") or r.get("ts"), "items": items} -def read_local(timeout=FALLBACK_TIMEOUT): - """(state, why) from the local Heart CLI's readiness verdict (no tick).""" +def read_local(timeout=FALLBACK_TIMEOUT, repos=None): + """(state, why) from the local Heart CLI's readiness verdict (no tick); + with `repos`, its scoped development-ship verdict.""" cli = resolve_heart_cli() if cli is None: return None, "no pyauto-heart on PATH or in the sibling checkout" + args = [cli, "readiness", "--json"] + if repos: + args = [cli, "readiness", "--dev", "--repos", ",".join(repos), "--json"] try: - proc = subprocess.run([cli, "readiness", "--json"], capture_output=True, - text=True, timeout=timeout) - return from_readiness(json.loads(proc.stdout)), None + proc = subprocess.run(args, capture_output=True, text=True, timeout=timeout) + out = json.loads(proc.stdout) + if repos and out.get("gate") != "dev-ship": + return None, "local pyauto-heart has no dev-ship gate (`readiness --dev`)" + return from_readiness(out), None except subprocess.TimeoutExpired: return None, f"pyauto-heart readiness timed out after {timeout}s" except (OSError, ValueError, AttributeError) as exc: @@ -203,6 +225,39 @@ def age_of(updated, now=None): return "just now" +def age_hours(updated, now=None): + """Hours since an ISO timestamp; None when unknown or in the future.""" + if not isinstance(updated, str) or not updated: + return None + try: + then = datetime.fromisoformat(updated.replace("Z", "+00:00")) + except ValueError: + return None + if then.tzinfo is None: + then = then.replace(tzinfo=timezone.utc) + hours = ((now or datetime.now(timezone.utc)) - then).total_seconds() / 3600 + return None if hours < -5 / 60 else max(hours, 0.0) + + +def apply_max_age(state, now=None, max_hours=MAX_FEED_AGE_HOURS): + """The 6 h rule: an over-age (or undated) GREEN feed reads STALE, and every + over-age feed carries the row that says why. Never makes a feed greener.""" + if not state: + return state + age = age_hours(state.get("updated"), now) + if age is not None and age <= max_hours: + return state + why = ("feed age unknown" if age is None + else f"feed {age:.1f} h old, over the {max_hours:g} h maximum") + state = dict(state) + state["items"] = [{"severity": "info", "text": f"{why} — re-check (STALE never passes)"}] \ + + list(state.get("items") or []) + if state.get("status") == "green": + state["status"] = "stale" + state["headline"] = why + return state + + def door_items(state): """The rows printed under the headline: red/yellow always; info only when the status is not green and nothing louder exists (a STALE door).""" @@ -213,11 +268,16 @@ def door_items(state): return sorted(loud, key=lambda i: SEVERITY_ORDER.get(i.get("severity"), 3)) -def summarise(state, source, url=None, fallback_reason=None): +def summarise(state, source, url=None, fallback_reason=None, repos=None, + scope_applied=False): + state = apply_max_age(state) status = state.get("status") if state else "grey" return { "status": status, + "pass": status == "green", "exit": EXIT.get(status, 3), + "repos": list(repos or []), + "scope_applied": bool(repos) and scope_applied, "headline": (state or {}).get("headline") or "", "updated": (state or {}).get("updated"), "age": age_of((state or {}).get("updated")), @@ -243,11 +303,27 @@ def render(s): if s["source"] == "local-readiness": lines.append(f" (from local `pyauto-heart readiness`; published feed: " f"{s['fallback_reason']})") + if s.get("repos"): + scope = ",".join(s["repos"]) + lines.append(f" (scoped to {scope} and dependants — local dev-ship gate)" + if s.get("scope_applied") else + f" (scope {scope} NOT applied — organism-wide feed; " + f"{s.get('scope_reason') or 'no local dev-ship gate'})") return "\n".join(lines) -def read(url=None, offline=False): - """The door's summary — published feed first, local readiness second.""" +def read(url=None, offline=False, repos=None): + """The door's summary — published feed first, local readiness second. + + With `repos`, the local dev-ship gate first (the only scoped source), then + the published feed unscoped.""" + if repos: + local, local_why = read_local(repos=repos) + if local is not None: + return summarise(local, "local-dev-ship", url, None, repos, True) + s = read(url=url, offline=offline) + s.update(repos=list(repos), scope_applied=False, scope_reason=local_why) + return s why = "--offline" if not offline: if url is None: @@ -270,8 +346,12 @@ def main(argv=None): p.add_argument("--url", help="read this state.json URL instead (tests, mirrors)") p.add_argument("--offline", action="store_true", help="skip the published feed; ask local pyauto-heart readiness") + p.add_argument("--repos", default="", + help="A,B: scope to these repos and their dependants via the " + "local Heart's dev-ship gate (PyAutoHeart#340)") args = p.parse_args(argv) - s = read(url=args.url, offline=args.offline) + repos = [r.strip() for r in args.repos.split(",") if r.strip()] + s = read(url=args.url, offline=args.offline, repos=repos or None) print(json.dumps(s, indent=2) if args.json else render(s)) return s["exit"] diff --git a/skills/WORKFLOW.md b/skills/WORKFLOW.md index 9f9612a0..b7dd9fac 100644 --- a/skills/WORKFLOW.md +++ b/skills/WORKFLOW.md @@ -67,9 +67,13 @@ user-facing output. Issue and lifecycle mechanics stay with Mind's continue. A light early read, never a tick; the ship-time gate stays authoritative. -Before `ship_*`, the vitals faculty gives the verdict: GREEN continues; YELLOW -shows exact reasons and needs the autonomy-contract acknowledgement; STALE may -pass for development only (still a release blocker); RED stops. After the exact +Before `ship_*`, the vitals faculty gives the **scoped** dev-ship verdict, +`pyauto-heart readiness --dev --repos A,B` with the task's `repos:` from +`active.md` (PyAutoHeart#340): only CI on `main` of those repos and their +dependants blocks, other reasons are shown; GREEN continues; STALE (evidence +over 6 h, missing or unfinished) never passes — re-check or park; RED stops. +`heart_feed.py --repos A,B` gives the door the same scope. Releases keep the +unscoped verdict. After the exact reason strings are quoted verbatim from the current Heart verdict and validation is shown, a live human may use `AUTONOMY.md` "Human override for Heart RED (development only)" or the narrower diff --git a/skills/batch/batch.md b/skills/batch/batch.md index 74c3ecba..797257fc 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -20,15 +20,15 @@ survive into your reply because they are the point of the whole surface: laptop-lane tasks are ready (3 ral, 1 local-dev) — run this from the laptop."* -An empty batch at the backpressure cap is a **finding, not a deadlock**: nothing -in the backlog costs zero review-minutes. Say which it is. +An empty batch is a **finding**: at the backpressure cap nothing costs zero +review-min; with an empty `queue.md` an unattended plan dips no backlog. Say which. **2. "Here are the ones I want."** — a paste of paths from the Mind dashboard, or a description ("something on the numba path", "the next euclid slice"). -Resolve what they gave you to prompt paths, then run the planner's constraints -over exactly that set. **Under a shift brief** (`AUTONOMY.md`, "Shift briefs -and unattended `glance`" — 2026-11-03) the brief *is* the human's composition: +Resolve it to prompt paths; plan exactly that set as a brief's named tasks, or +`batch plan --attended` (else an empty `queue.md` stops it). **Under a shift brief** +(`AUTONOMY.md`, "Shift briefs and unattended `glance`") the brief *is* the human's composition: its named tasks go first, then the backlog dip its policy allows (`none` | `fill-idle` | `scoped:` plus `exclude:`). Backlog the brief does not cover is never dipped, and every dipped pick carries a one-line reason in the digest. diff --git a/skills/ship_library/ship_library.md b/skills/ship_library/ship_library.md index b37f7d39..2d460df3 100644 --- a/skills/ship_library/ship_library.md +++ b/skills/ship_library/ship_library.md @@ -51,14 +51,17 @@ a release): ```bash bin/pyauto-brain vitals # reason over the readiness surface (vitals faculty → Heart) -pyauto-heart readiness --json # authoritative GREEN / YELLOW / RED +# the DEV-SHIP gate, scoped to the task's `repos:` in PyAutoMind/active.md +# (agents/_common.sh: consult_vitals_verdict --repos "$(active_task_repos )") +pyauto-heart readiness --dev --repos --json # GREEN / STALE / RED ``` -The library test suites are part of Heart's verdict — they run as the gate, not -as an ad-hoc step the skill re-judges. **GREEN** → proceed to step 4. -**YELLOW** → surface warnings, proceed only on explicit user acknowledgement. -**RED** → stop and report; an autonomous run parks. After surfacing the exact -current RED reasons verbatim from `pyauto-heart readiness` and passed applicable +Only CI on `main` of the touched repos and their dependants blocks; every other +reason comes back in `shown_reasons` — list them in the PR body, never block on +them (PyAutoHeart#340). **GREEN** → proceed to step 4. **STALE** (evidence over +6 h old, missing or unfinished) never passes: refresh (`pyauto-heart tick`) and +ask again, or park. **RED** → stop and report; an autonomous run parks. After +surfacing the exact current RED reasons verbatim from the scoped verdict and passed applicable tests/smoke/review, a live human may authorize the canonical `AUTONOMY.md` "Human override for Heart RED (development only)" or the narrower "Corrective-PR exception for Heart RED" for a causal fix. Follow the selected diff --git a/skills/ship_workspace/ship_workspace.md b/skills/ship_workspace/ship_workspace.md index 39e17429..a3cc5fd1 100644 --- a/skills/ship_workspace/ship_workspace.md +++ b/skills/ship_workspace/ship_workspace.md @@ -48,14 +48,17 @@ release): ```bash bin/pyauto-brain vitals # reason over the readiness surface (vitals faculty → Heart) -pyauto-heart readiness --json # GREEN / YELLOW / RED +# the DEV-SHIP gate, scoped to the task's `repos:` in PyAutoMind/active.md +pyauto-heart readiness --dev --repos --json # GREEN / STALE / RED ``` -Workspace **smoke tests** are part of Heart's verdict. **GREEN** → execute. -**YELLOW** → proceed only on explicit acknowledgement. **RED** → stop; an -autonomous run parks. After surfacing the exact current RED reasons and passed -applicable tests/smoke/review, including the reason strings verbatim from -`pyauto-heart readiness`, a live human may authorize the canonical +Only CI on `main` of the touched repos and their dependants blocks; other +reasons arrive as `shown_reasons` for the PR body (PyAutoHeart#340). **GREEN** → +execute. **STALE** (over 6 h, missing or unfinished evidence) never passes: +refresh and ask again, or park. **RED** → stop; an autonomous run parks. After +surfacing the exact current RED reasons and passed applicable +tests/smoke/review, including the reason strings verbatim from the scoped +verdict, a live human may authorize the canonical `AUTONOMY.md` "Human override for Heart RED (development only)" or the narrower "Corrective-PR exception for Heart RED" for a causal fix. Follow the selected canonical section's scope and four record sinks exactly. Neither path permits diff --git a/tests/test_batch_plan.py b/tests/test_batch_plan.py index 421b142b..80129bfa 100644 --- a/tests/test_batch_plan.py +++ b/tests/test_batch_plan.py @@ -116,10 +116,18 @@ def test_at_the_cap_the_batch_is_fill_only_and_still_composes(): assert paths(d) == ["b.md"] -def test_cheapest_first_because_the_question_is_what_fits(): +def test_priority_sorts_before_review_minutes(): + """M2.3 (2026-11-12): below the queue a declared `Priority:` outranks cost. + Cheapest-first let the cheapest review win and broke ties by filename.""" d = _batch.plan([rec("slow.md", minutes=20, priority="high"), rec("fast.md", minutes=2, priority="low")], budget=45) - assert paths(d)[0] == "fast.md" + assert paths(d) == ["slow.md", "fast.md"] + + +def test_cheapest_first_still_decides_within_a_priority(): + d = _batch.plan([rec("a_slow.md", minutes=20), rec("b_fast.md", minutes=2)], + budget=45) + assert paths(d) == ["b_fast.md", "a_slow.md"] def test_every_rejection_states_a_reason(): diff --git a/tests/test_dev_ship_gate.py b/tests/test_dev_ship_gate.py new file mode 100644 index 00000000..1ff5ec96 --- /dev/null +++ b/tests/test_dev_ship_gate.py @@ -0,0 +1,243 @@ +"""The scoped development-ship gate's Brain callers (PyAutoHeart#340, M2.1). + +`consult_vitals_verdict --repos A,B` asks `pyauto-heart readiness --dev --repos +A,B --json`; only GREEN passes and STALE never does. `active_task_repos` reads +the scope from the task's `repos:` in PyAutoMind/active.md. `heart_feed.py` +gains the 6 h maximum age and an optional `--repos` scope. Offline: a fake +`pyauto-heart` first on PATH; fictional repo names only. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest + +BRAIN_HOME = Path(__file__).resolve().parents[1] +COMMON = BRAIN_HOME / "agents" / "_common.sh" +sys.path.insert(0, str(BRAIN_HOME / "bin")) +import heart_feed # noqa: E402 + + +def _iso(hours_ago): + t = datetime.now(timezone.utc) - timedelta(hours=hours_ago) + return t.strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _dev(verdict="stale", **kw): + d = {"gate": "dev-ship", "verdict": verdict, "pass": verdict == "green", + "red_reasons": [], "yellow_reasons": [], + "stale_reasons": ["Heart snapshot 7.0 h old, over the 6 h maximum"], + "shown_reasons": ["WidgetWorkspace: smoke failing"], + "feed_ts": _iso(7), "ts": _iso(0)} + d.update(kw) + return d + + +@pytest.fixture +def heart(tmp_path): + """A fake pyauto-heart answering `readiness` with the JSON in a file, and + logging every argument line.""" + bindir = tmp_path / "bin" + bindir.mkdir() + payload, log = tmp_path / "readiness.json", tmp_path / "heart.log" + cli = bindir / "pyauto-heart" + cli.write_text("#!/usr/bin/env bash\n" + f'echo "$@" >> "{log}"\n' + f'if [[ "$1" == readiness ]]; then cat "{payload}"; fi\n') + cli.chmod(0o755) + empty = tmp_path / "no_heart_checkout" + empty.mkdir() + env = dict(os.environ, PATH=f"{bindir}{os.pathsep}{os.environ['PATH']}", + PYAUTO_HEART=str(empty)) + + def answer(obj): + payload.write_text(json.dumps(obj)) + return env, log + return answer + + +def _sh(env, body): + r = subprocess.run(["bash", "-c", f'source "{COMMON}"; {body}'], + capture_output=True, text=True, env=env, timeout=60) + return r.stdout.strip() + + +# --- agents/_common.sh ------------------------------------------------------------ + +def test_scoped_verdict_asks_the_dev_gate_and_stale_comes_back_stale(heart): + env, log = heart(_dev("stale")) + assert _sh(env, "consult_vitals_verdict --repos WidgetLib,GadgetLib") == "stale" + assert "readiness --dev --repos WidgetLib,GadgetLib --json" in log.read_text() + + +def test_unscoped_verdict_is_unchanged_for_release_callers(heart): + env, log = heart({"verdict": "green", "red_reasons": []}) + assert _sh(env, "consult_vitals_verdict") == "green" + assert _sh(env, "consult_vitals_verdict --profile release-ci") == "green" + lines = log.read_text().splitlines() + assert lines == ["readiness --json", "readiness --json --profile release-ci"] + + +def test_a_scoped_read_without_the_dev_gate_is_unknown_never_a_pass(heart): + """A Heart without `--dev` (or the published, organism-wide board) cannot + judge the scope: unknown parks, it does not pass.""" + env, _ = heart({"verdict": "green", "red_reasons": []}) + assert _sh(env, "consult_vitals_verdict --repos WidgetLib") == "unknown" + + +def test_scoped_reasons_by_field(heart): + env, _ = heart(_dev("red", red_reasons=["WidgetLib: main CI failing"])) + assert _sh(env, "consult_vitals_red_reasons --repos WidgetLib") \ + == "WidgetLib: main CI failing" + assert _sh(env, "consult_vitals_red_reasons --repos WidgetLib --field shown_reasons") \ + == "WidgetWorkspace: smoke failing" + + +ACTIVE = """\ +# Active + +## other-task +- repos: + - GadgetLib: feature/other-task + +## widget-polish +- status: library-dev +- repos: + - WidgetLib: feature/widget-polish + - widget_workspace: feature/widget-polish +- prompt: active/widget_polish.md + +## no-repos +- status: library-dev +""" + + +def test_active_task_repos_reads_the_tasks_repos_block(tmp_path): + ledger = tmp_path / "active.md" + ledger.write_text(ACTIVE) + env = dict(os.environ) + assert _sh(env, f'active_task_repos widget-polish "{ledger}"') \ + == "WidgetLib,widget_workspace" + r = subprocess.run(["bash", "-c", f'source "{COMMON}"; active_task_repos no-repos "{ledger}"'], + capture_output=True, text=True, env=env) + assert r.returncode == 1 and r.stdout == "" + + +# --- bin/heart_feed.py ------------------------------------------------------------------ + +def _feed(status, hours): + return {"status": status, "headline": "h", "updated": _iso(hours), "items": []} + + +def test_a_green_feed_over_six_hours_is_stale_and_never_passes(): + s = heart_feed.summarise(_feed("green", 7), "published") + assert s["status"] == "stale" and s["pass"] is False and s["exit"] == 1 + assert "over the 6 h maximum" in s["items"][0]["text"] + fresh = heart_feed.summarise(_feed("green", 1), "published") + assert fresh["status"] == "green" and fresh["pass"] is True + + +def test_age_never_makes_a_feed_greener(): + s = heart_feed.summarise(_feed("red", 9), "published") + assert s["status"] == "red" and s["pass"] is False + undated = heart_feed.summarise({"status": "green", "headline": "h", "items": []}, + "published") + assert undated["status"] == "stale" + + +def test_repos_asks_the_local_dev_gate(heart, monkeypatch, capsys): + env, log = heart(_dev("green", stale_reasons=[], feed_ts=_iso(1))) + monkeypatch.setenv("PATH", env["PATH"]) + monkeypatch.setattr(heart_feed, "fetch_feed", + lambda *a, **k: pytest.fail("a scoped read fetched the feed")) + assert heart_feed.main(["--repos", "WidgetLib", "--json"]) == 0 + s = json.loads(capsys.readouterr().out) + assert s["scope_applied"] is True and s["pass"] is True + assert s["repos"] == ["WidgetLib"] + assert "readiness --dev --repos WidgetLib --json" in log.read_text() + + +def test_repos_without_a_local_gate_reads_the_feed_unscoped_and_says_so( + tmp_path, monkeypatch, capsys): + monkeypatch.setattr(heart_feed, "resolve_heart_cli", lambda: None) + url = tmp_path / "state.json" + url.write_text(json.dumps(_feed("green", 1))) + assert heart_feed.main(["--url", url.as_uri(), "--repos", "WidgetLib"]) == 0 + out = capsys.readouterr().out + assert "scope WidgetLib NOT applied" in out + + +# --- the watcher's close-out: the same scoped gate for the PR's repo ------------------ + +def _closeout_heart_cmd(pr_url, tmp_path): + sys.path.insert(0, str(BRAIN_HOME / "agents" / "faculties" / "sizing")) + sys.path.insert(0, str(BRAIN_HOME / "agents" / "conductors" / "batch")) + import _orchestrator # noqa: PLC0415 + text = _orchestrator.closeout_prompt("t", pr_url, "draft/x/t.md", + tmp_path / "brief.md", tmp_path / "leases") + step = text.split("\n3. ", 1)[1].split("\n4. ", 1)[0] + cmd = next((l.strip() for l in step.splitlines() if l.strip().startswith("bash -c")), "") + return step, cmd + + +@pytest.mark.parametrize("reply,printed", [ + (_dev("green", stale_reasons=[]), "green"), + (_dev("stale"), "stale"), + ({"verdict": "green", "red_reasons": []}, "unknown"), # not the dev-ship gate +]) +def test_closeout_asks_the_scoped_gate_for_the_prs_repo(heart, tmp_path, reply, printed): + step, cmd = _closeout_heart_cmd("https://github.com/ExampleOrg/WidgetLib/pull/7", tmp_path) + assert "heart_feed.py" not in step + assert "Only `green` passes" in step and "(WidgetLib)" in step + env, log = heart(reply) + r = subprocess.run(cmd, shell=True, capture_output=True, text=True, env=env, timeout=60) + assert r.stdout.strip() == printed + assert "readiness --dev --repos WidgetLib --json" in log.read_text() + + +def test_closeout_without_a_pr_repo_cannot_be_scoped(tmp_path): + step, cmd = _closeout_heart_cmd("not-a-pr-url", tmp_path) + assert cmd == "" and "cannot be scoped — refuse" in step + + +# --- review items: an empty scope, and the no-Heart-CLI fallback ------------------------- + +def test_an_empty_scope_is_unknown_never_an_unscoped_read(heart): + env, log = heart({"verdict": "green", "red_reasons": ["x"]}) + assert _sh(env, 'consult_vitals_verdict --repos ""') == "unknown" + assert _sh(env, "consult_vitals_verdict --repos=") == "unknown" + assert _sh(env, 'consult_vitals_red_reasons --repos ""') == "" + assert not log.exists() # Heart was never asked the unscoped question + + +def _no_heart_env(tmp_path, feed): + """No pyauto-heart anywhere; the published feed is a file:// fixture.""" + path = [d for d in os.environ["PATH"].split(os.pathsep) + if d and not (Path(d) / "pyauto-heart").exists()] + empty = tmp_path / "no_heart_checkout" + empty.mkdir(exist_ok=True) + pages = tmp_path / "pages" / heart_feed.heart_board_repo() + pages.mkdir(parents=True) + if feed is not None: + (pages / "state.json").write_text(json.dumps( + {"schema_version": 1, "organ": "heart", "items": [], "headline": "h", **feed})) + return dict(os.environ, PATH=os.pathsep.join(path), PYAUTO_HEART=str(empty), + PYAUTO_ROOT=str(empty), BOARD_PAGES_BASE=(tmp_path / "pages").as_uri()) + + +@pytest.mark.parametrize("feed,printed", [ + ({"status": "green", "updated": _iso(1)}, "green"), # fresh organism GREEN + ({"status": "green", "updated": _iso(7)}, "unknown"), # over 6 h + ({"status": "stale", "updated": _iso(1)}, "unknown"), + ({"status": "red", "updated": _iso(1)}, "unknown"), + (None, "unknown"), # nothing published +]) +def test_without_a_heart_cli_only_a_fresh_published_green_passes(tmp_path, feed, printed): + env = _no_heart_env(tmp_path, feed) + assert _sh(env, "consult_vitals_verdict --repos WidgetLib") == printed diff --git a/tests/test_health_conductor.py b/tests/test_health_conductor.py index 8468118d..d6e04a3f 100644 --- a/tests/test_health_conductor.py +++ b/tests/test_health_conductor.py @@ -120,7 +120,7 @@ def test_stale_recommendation_is_refresh_not_unknown(tmp_path): def test_stale_detail_states_the_tier_semantics(tmp_path): """The remedy is re-running the check, never fixing code — and a release - still needs GREEN even though the dev-ship gate treats STALE as passing.""" + still needs GREEN, and the scoped dev-ship gate never passes STALE.""" t, _ = _triage(tmp_path, STALE_ONLY) detail = t["recommendation"]["detail"].lower() assert "missing or expired" in detail @@ -198,8 +198,8 @@ def test_usage_error_stays_five(tmp_path): def test_stale_exit_code_is_not_the_shell_generic_failure(): """1 is bash's own generic failure (a missing `_common.sh`, a failed - `readlink`). STALE passes the dev-ship gate, so a crash must never be - readable as a passing verdict — hence 6, not the free slot 1.""" + `readlink`). A crash must never be readable as a verdict — hence 6, not + the free slot 1.""" assert EXIT_STALE != 1 assert "stale) return 6 ;;" in HEALTH_SH assert "return 1" not in HEALTH_SH.split("_exit_code_for() {")[1].split("}")[0] diff --git a/tests/test_intake_declared_fields.py b/tests/test_intake_declared_fields.py index 482f1473..7e881042 100644 --- a/tests/test_intake_declared_fields.py +++ b/tests/test_intake_declared_fields.py @@ -148,7 +148,7 @@ def test_header_block_is_not_echoed_into_the_body(tmp_path, monkeypatch): monkeypatch.setattr(_intake, "memory_citations", lambda *a, **k: []) text = ("# Ellipse crash\n\nType: bug\nTarget: autogalaxy\nDifficulty: small\n\n" "Ellipse fitting crashes when the mask is empty.") - d = analyse(text, "test") + d = analyse(text, "test", lane="any") # M2.3: filing needs a lane rel = write_prompt(tmp_path, d, text, "test") written = (tmp_path / rel).read_text(encoding="utf-8") assert written.count("Type:") == 1 diff --git a/tests/test_intake_looks_shipped.py b/tests/test_intake_looks_shipped.py index 4ef662c9..df09fa71 100644 --- a/tests/test_intake_looks_shipped.py +++ b/tests/test_intake_looks_shipped.py @@ -81,6 +81,7 @@ def _init(repo: Path): Consequence: notify Review-minutes: 5 Unattended: ready +Lane: any Witness: {witness} """ diff --git a/tests/test_intake_memory.py b/tests/test_intake_memory.py index c3e99fe5..fdd7ca9b 100644 --- a/tests/test_intake_memory.py +++ b/tests/test_intake_memory.py @@ -62,7 +62,7 @@ def _memory(tmp_path: Path) -> Path: def _file_one(mind: Path, raw: str = RAW) -> str: - decision = _intake.analyse(raw, "test") + decision = _intake.analyse(raw, "test", lane="any") # M2.3: filing needs a lane rel = _intake.write_prompt(mind, decision, raw, "test") return (mind / rel).read_text(encoding="utf-8") @@ -164,7 +164,7 @@ def test_organ_target_gets_no_memory_line(tmp_path, monkeypatch): organs = organs + extra for organ in organs: raw = _declared(organ) - decision = _intake.analyse(raw, "test") + decision = _intake.analyse(raw, "test", lane="any") # M2.3: filing needs a lane assert decision["target_source"] == "declared", organ rel = _intake.write_prompt(mind, decision, raw, "test") text = (mind / rel).read_text(encoding="utf-8") @@ -180,7 +180,7 @@ def test_library_target_with_hits_still_gets_memory_line(tmp_path, monkeypatch): mind = _mind(tmp_path) _memory(tmp_path) raw = _declared(sorted(_intake.LIBRARY_REPOS)[0]) # any library, read from repos.yaml - decision = _intake.analyse(raw, "test") + decision = _intake.analyse(raw, "test", lane="any") # M2.3: filing needs a lane assert decision["target_source"] == "declared" rel = _intake.write_prompt(mind, decision, raw, "test") line = _memory_line((mind / rel).read_text(encoding="utf-8")) @@ -204,7 +204,7 @@ def test_organ_target_spellings_get_no_memory_line(tmp_path, monkeypatch): assert _intake._with_memory("Priority: normal", ["wiki/x.md"], spelling) == "Priority: normal", spelling raw = _declared(spelling) - decision = _intake.analyse(raw, "test") + decision = _intake.analyse(raw, "test", lane="any") # M2.3: filing needs a lane rel = _intake.write_prompt(mind, decision, raw, "test") text = (mind / rel).read_text(encoding="utf-8") assert "Memory:" not in text, spelling @@ -255,7 +255,7 @@ def test_vocabulary_only_overlap_gets_no_memory_line(tmp_path, monkeypatch): raw = _declared_raw(TOOLING) ranked = _intake._memory.digest(TOOLING, mem, None, None, 3)["pages"] assert ranked[0]["page"].endswith("massive-ellipticals.md") - decision = _intake.analyse(raw, "test") + decision = _intake.analyse(raw, "test", lane="any") # M2.3: filing needs a lane assert _intake._cites_memory(decision["target"]) rel = _intake.write_prompt(mind, decision, raw, "test") assert "Memory:" not in (mind / rel).read_text(encoding="utf-8") @@ -270,7 +270,7 @@ def test_distinctive_terms_still_get_memory_line(tmp_path, monkeypatch): _floor_memory(tmp_path) raw = _declared_raw("Fix the expectation propagation cavity moment matching " "for a loggaussian factor so the model fit converges.") - decision = _intake.analyse(raw, "test") + decision = _intake.analyse(raw, "test", lane="any") # M2.3: filing needs a lane rel = _intake.write_prompt(mind, decision, raw, "test") line = _memory_line((mind / rel).read_text(encoding="utf-8")) assert line == "Memory: wiki/methods/concepts/expectation-propagation.md" diff --git a/tests/test_lane_fail_closed_queue.py b/tests/test_lane_fail_closed_queue.py new file mode 100644 index 00000000..5f5a976e --- /dev/null +++ b/tests/test_lane_fail_closed_queue.py @@ -0,0 +1,238 @@ +"""M2.3 (PyAutoBrain#614; AUTONOMY.md "M2 rulings — 2026-11-12"). + +(a) An absent `Lane:` fails closed in an unattended pick and reads as `any` in +an attended one; intake always writes a Lane. (b) `queue.md` is the ranked +list: an empty one stops a shift's backlog dip (named tasks still run), and the +planner sorts priority before review-minutes. Fictional fixtures only. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "intake")) +sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) +import _intake # noqa: E402 + +_spec = importlib.util.spec_from_file_location( + "_batch_m23", BRAIN / "agents" / "conductors" / "batch" / "_batch.py") +_batch = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_batch) +_brief = _batch._brief +import _digest # noqa: E402 + +DRAFT = """\ +# {title} + +Type: feature +Target: PyAutoBrain +Repos: +- PyAutoBrain +Difficulty: small +Autonomy: safe +Priority: normal +Status: formalised +Consequence: notify +Witness: tests pass +Review-minutes: 2 +Unattended: ready +{lane} + +Tidy one docstring. +""" + + +def _mind(tmp_path: Path, drafts: dict[str, str]) -> Path: + mind = tmp_path / "mind" + folder = mind / "draft" / "feature" / "pyautobrain" + folder.mkdir(parents=True) + for name, lane in drafts.items(): + (folder / f"{name}.md").write_text( + DRAFT.format(title=name, lane=lane), encoding="utf-8") + return mind + + +def _paths(d): + return [m["path"] for m in d["members"]] + + +def _rec(path, lane="any", **kw): + r = {"path": path, "repos": [], "work_type": "feature", "difficulty": "small", + "score": 1, "consequence": "notify", "witness": "w", "review_minutes": 2, + "unattended": "ready", "why": "", "ready_why": "", "epic": None, + "lane": lane, "priority": "normal", "blocked": False, + "autonomy": "safe", "autonomy_cap": "safe", "declared_autonomy": None, + "done": False, "themes": []} + r.update(kw) + return r + + +# --- (a) an absent Lane fails closed unattended ---------------------------------- + +def test_unattended_plan_excludes_an_absent_lane_attended_includes_it(tmp_path): + """The witness: graded from real files, the lane-less draft is refused by + the unattended plan with a stated reason and taken by the attended one.""" + mind = _mind(tmp_path, {"declared": "Lane: any", "absent": ""}) + records = _batch.survey(mind) + absent = "draft/feature/pyautobrain/absent.md" + declared = "draft/feature/pyautobrain/declared.md" + assert {r["path"]: r["lane"] for r in records} == {absent: None, declared: "any"} + + for lane in ("web-github", "local-dev"): + d = _batch.plan(records, session_lane=lane, budget=45) + assert _paths(d) == [declared] + assert dict(d["rejected"])[absent].startswith("lane absent") + assert d["lane_absent"] == [absent] + + d = _batch.plan(records, session_lane="web-github", budget=45, attended=True) + assert sorted(_paths(d)) == [absent, declared] + assert d["lane_absent"] == [] + + +def test_an_invalid_lane_is_absent_to_an_unattended_pick(): + d = _batch.plan([_rec("draft/x.md", lane=None, lane_invalid="any | local-dev")]) + assert _paths(d) == [] + assert "lane invalid" in dict(d["rejected"])["draft/x.md"] + + +def test_a_brief_named_task_is_not_a_backlog_dip(): + """The lane gate guards the backlog. A task the human NAMED in the brief is + their own pick; the brief's `lanes:` still applies to it.""" + brief = _brief.parse(BRIEF)["brief"] + d = _batch.plan([_rec("draft/named.md", lane=None), + _rec("draft/dip.md", lane=None)], + session_lane="local-dev", brief=brief, queue=["draft/q.md"]) + assert _paths(d) == ["draft/named.md"] + assert dict(d["rejected"])["draft/dip.md"].startswith("lane absent") + + +def test_the_plan_output_says_so(capsys): + d = _batch.plan([_rec("draft/a.md", lane=None)], queue=[]) + _batch.emit(d) + out = capsys.readouterr().out + assert "Lane absent: 1 draft(s) excluded" in out + assert "Backlog dip: STOPPED" in out + + +CLOUD_TEXT = "Tidy a docstring in @PyAutoBrain." + + +def test_intake_refuses_a_draft_whose_lane_nobody_decided(tmp_path, capsys): + """The ruling: a new draft filed without a Lane is rejected. No signal, no + `Lane:` header and no `--lane` writes nothing and says how to declare one.""" + mind = tmp_path / "mind" + (mind / "draft").mkdir(parents=True) + d = _intake.analyse(CLOUD_TEXT, "test") + assert d["lane"] is None and "Lane:" not in d["header"] + import pytest + with pytest.raises(_intake.LaneRequired, match="--lane any"): + _intake.write_prompt(mind, d, CLOUD_TEXT, "test") + rc = _intake.main(["--mind", str(mind), "--apply", "classify", CLOUD_TEXT]) + assert rc == _intake.RC_LANE_REQUIRED + err = capsys.readouterr().err + assert "Lane: Path: (folder / "named.md").write_text(PROMPT.format(name="named", epic="")) (folder / "picked.md").write_text(PROMPT.format(name="picked", epic="Epic: e1\n")) (folder / "outside.md").write_text(PROMPT.format(name="outside", epic="")) + (root / "queue.md").write_text(QUEUE) return root @@ -416,7 +423,7 @@ def run(argv, **kw): ("fill-idle", {"path": "x/a.md", "queue_rank": 2, "queued": True}, "backlog: fill-idle · queue.md #3"), ("scoped", {"path": "x/a.md", "consequence": "notify", "queue_rank": 4, "queued": False, "review_minutes": 3, "priority": "high", "epic": "e1", "phase": 2.0}, - "scoped tier notify · not in queue.md · ~3 review-min · priority high · epic e1 phase 2"), + "scoped tier notify · not in queue.md · priority high · ~3 review-min · epic e1 phase 2"), ("scoped", {"path": "x/a.md", "themes": ["jax"]}, "scoped tag jax"), ("scoped", {"path": "x/a.md", "consequence": "notify"}, "scoped tier notify"), ("scoped", {"path": "x/named.md"}, "named task"), diff --git a/tests/test_orchestrators_lane_brief.py b/tests/test_orchestrators_lane_brief.py index 713d5eb6..545c9018 100644 --- a/tests/test_orchestrators_lane_brief.py +++ b/tests/test_orchestrators_lane_brief.py @@ -248,9 +248,11 @@ def test_intake_proposes_gpu_and_wsl_data(text, lane): assert f"\nLane: {lane}" in _intake.analyse(text, "test")["header"] -def test_intake_writes_no_lane_for_cloud_runnable_text(): - assert "Lane:" not in _intake.analyse("Tidy a docstring in @PyAutoBrain.", - "test")["header"] +def test_intake_writes_no_lane_when_nothing_decides_one(): + """M2.3 (2026-11-12): with no signal, no header and no `--lane`, intake + leaves the lane undecided and refuses to file (`test_lane_fail_closed_queue`).""" + d = _intake.analyse("Tidy a docstring in @PyAutoBrain.", "test") + assert "Lane:" not in d["header"] and d["lane"] is None and d["lane_refusal"] DECLARED = """\ diff --git a/tests/test_release_rehearsed_shas.py b/tests/test_release_rehearsed_shas.py new file mode 100644 index 00000000..20d8ac5f --- /dev/null +++ b/tests/test_release_rehearsed_shas.py @@ -0,0 +1,225 @@ +"""M2.4 callers (PyAutoHands#337 "Caller contract"): a release publishes the +REHEARSED commits. + +The nightly reads `commit_shas` and the run id from the rehearsal's own +`rehearsal.json` (never `main` re-read), feeds the same file to Heart, and the +live dispatch carries `rehearsal_run_id`; the manual door forwards the run id +to `autohands pre_build` and refuses without one. Offline throughout: fake +`gh`, `pyauto-heart` and `autohands` on PATH, fictional repo names. +""" + +from __future__ import annotations + +import json +import os +import subprocess +from pathlib import Path + +import pytest + +BRAIN_HOME = Path(__file__).resolve().parents[1] +REL = BRAIN_HOME / "agents" / "conductors" / "release" +LIB = REL / "_nightly_lib.sh" +NIGHTLY = (REL / "nightly.sh").read_text() +BUILD = BRAIN_HOME / "agents" / "conductors" / "build" / "build.sh" +RELEASE = REL / "release.sh" +REHEARSE = REL / "rehearse.sh" + +SHAS = {"WidgetLib": "a" * 40, "GadgetLib": "b" * 40} +RECORD = {"mode": "rehearsal", "index": "testpypi", "version": "2026.11.12.1.dev1", + "run_id": "12345", "run_attempt": "1", "commit_shas": SHAS} + + +def _bin(tmp_path, name, body): + d = tmp_path / "bin" + d.mkdir(exist_ok=True) + f = d / name + f.write_text("#!/usr/bin/env bash\n" + body) + f.chmod(0o755) + return d + + +def _env(tmp_path, **extra): + empty = tmp_path / "empty" + empty.mkdir(exist_ok=True) + env = dict(os.environ, PATH=f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}", + PYAUTO_HEART=str(empty), PYAUTO_HANDS=str(empty), + HEART_STATE_DIR=str(tmp_path / "heart-state"), + NIGHTLY_POLL_SECONDS="0", TMPDIR=str(tmp_path)) + env.pop("REHEARSAL_RUN_ID", None) + env.update(extra) + return env + + +def _lib(tmp_path, body, env=None): + return subprocess.run(["bash", "-c", f'set -uo pipefail; source "{LIB}"; {body}'], + capture_output=True, text=True, env=env or _env(tmp_path), + timeout=60) + + +# --- the rehearsal record ------------------------------------------------------------- + +def test_commit_shas_and_run_id_come_from_rehearsal_json(tmp_path): + art = tmp_path / "art" + art.mkdir() + (art / "rehearsal.json").write_text(json.dumps(RECORD)) + r = _lib(tmp_path, f'rehearsal_record "{art}" "{art}/commit_shas.json"') + assert r.returncode == 0 and r.stdout.strip() == "12345" + assert json.loads((art / "commit_shas.json").read_text()) == SHAS + + +@pytest.mark.parametrize("record", [None, {k: v for k, v in RECORD.items() + if k != "commit_shas"}, + dict(RECORD, run_id="")]) +def test_no_usable_record_refuses(tmp_path, record): + art = tmp_path / "art" + art.mkdir() + if record is not None: + (art / "rehearsal.json").write_text(json.dumps(record)) + r = _lib(tmp_path, f'rehearsal_record "{art}" "{art}/commit_shas.json"') + assert r.returncode == 1 and "no rehearsal record" in r.stderr + assert not (art / "commit_shas.json").exists() + + +def test_live_dispatch_payload_carries_the_run_id_and_the_record(tmp_path): + """dispatch_and_await turns the inputs into `gh workflow run -f k=v`: the + live release carries rehearsal_run_id and the record's commit_shas.""" + shas = tmp_path / "commit_shas.json" + shas.write_text(json.dumps(SHAS)) + log = tmp_path / "gh.log" + _bin(tmp_path, "gh", f'''echo "$@" >> "{log}" +case "$1 $2" in + "run list") echo 777 ;; + "run view") echo '{{"status":"completed","conclusion":"success"}}' ;; +esac +''') + _bin(tmp_path, "sleep", "exit 0\n") + r = _lib(tmp_path, f'inputs="$(live_release_inputs 1 12345 "{shas}")" && ' + 'dispatch_and_await Org/Hands release.yml "$inputs" && echo "$LAST_RUN_ID"') + assert r.returncode == 0, r.stderr + assert r.stdout.strip().endswith("777") + run = next(l for l in log.read_text().splitlines() if l.startswith("workflow run")) + assert "-f rehearsal=false" in run and "-f minor_version=1" in run + assert "-f rehearsal_run_id=12345" in run + compact = json.dumps(SHAS, separators=(",", ":"), sort_keys=True) + assert f"-f commit_shas={compact}" in run + + +def test_a_missing_run_id_refuses_to_compose_the_live_inputs(tmp_path): + shas = tmp_path / "commit_shas.json" + shas.write_text(json.dumps(SHAS)) + r = _lib(tmp_path, f'live_release_inputs 1 "" "{shas}"') + assert r.returncode != 0 and not r.stdout.strip() + + +def test_nightly_uses_the_record_not_main_heads(): + assert "commits/main" not in NIGHTLY + assert "capture-heads" not in NIGHTLY + assert 'rehearsal_record "$ART_DIR" "$ART_DIR/commit_shas.json"' in NIGHTLY + assert '--commit-shas "$ART_DIR/commit_shas.json"' in NIGHTLY + assert 'live_release_inputs 1 "$rehearsal_run_id"' in NIGHTLY + # The pre-#337 payload a merged release.yml would refuse. + assert '{"rehearsal": "false", "minor_version": "1"}' not in NIGHTLY + + +# --- rehearse.sh ingest: the record is the commit_shas authority ----------------------- + +def _fake_heart(tmp_path, log): + _bin(tmp_path, "pyauto-heart", f'''echo "$@" >> "{log}" +case "$1" in + readiness) echo '{{"verdict":"green","red_reasons":[]}}' ;; +esac +exit 0 +''') + + +def test_ingest_writes_commit_shas_from_the_record(tmp_path): + art = tmp_path / "art" + art.mkdir() + (art / "rehearsal.json").write_text(json.dumps(RECORD)) + log = tmp_path / "heart.log" + _fake_heart(tmp_path, log) + r = subprocess.run(["bash", str(REHEARSE), "--ingest", str(art), "--json"], + capture_output=True, text=True, env=_env(tmp_path), timeout=120) + assert r.returncode == 0, r.stderr + assert json.loads((art / "commit_shas.json").read_text()) == SHAS + assert f"validate --ingest {art} --commit-shas {art}/commit_shas.json" in log.read_text() + + +def test_ingest_refuses_a_commit_shas_file_that_disagrees(tmp_path): + art = tmp_path / "art" + art.mkdir() + (art / "rehearsal.json").write_text(json.dumps(RECORD)) + other = tmp_path / "heads.json" + other.write_text(json.dumps(dict(SHAS, WidgetLib="c" * 40))) + _fake_heart(tmp_path, tmp_path / "heart.log") + r = subprocess.run(["bash", str(REHEARSE), "--ingest", str(art), + "--commit-shas", str(other), "--json"], + capture_output=True, text=True, env=_env(tmp_path), timeout=120) + assert r.returncode == 1 and "disagrees with rehearsal.json" in r.stderr + + +# --- the manual door ---------------------------------------------------------------- + +def _door(tmp_path, argv, **env): + log = tmp_path / "hands.log" + _bin(tmp_path, "autohands", f'echo "$@" >> "{log}"\n') + _fake_heart(tmp_path, tmp_path / "heart.log") + r = subprocess.run(["bash", *argv], capture_output=True, text=True, + env=_env(tmp_path, **env), timeout=120) + return r, (log.read_text().strip() if log.exists() else "") + + +def test_the_door_refuses_without_a_rehearsal_run_id(tmp_path): + r, hands = _door(tmp_path, [str(BUILD), "--mode", "release", "pre_build"]) + assert r.returncode == 5 + assert "--rehearsal-run-id" in r.stderr and "PyAutoHands#337" in r.stderr + assert hands == "" + assert not (tmp_path / "heart.log").exists() # refused before any gate + + +def test_the_door_forwards_the_run_id_to_pre_build(tmp_path): + r, hands = _door(tmp_path, [str(BUILD), "--mode", "release", + "--rehearsal-run-id", "4242", "pre_build", "--", "2"]) + assert r.returncode == 0, r.stderr + assert hands == "pre_build 2 4242" + + +def test_release_conductor_forwards_the_run_id(tmp_path): + r, hands = _door(tmp_path, [str(RELEASE), "--rehearsal-run-id=31337"]) + assert r.returncode == 0, r.stderr + assert hands == "pre_build 1 31337" + + +def test_the_door_takes_hearts_validated_rehearsal_run_id(tmp_path): + state = tmp_path / "heart-state" + state.mkdir() + (state / "validation_report.json").write_text(json.dumps( + {"stages": {"rehearse": {"run_id": "9001", "status": "pass"}}})) + r, hands = _door(tmp_path, [str(RELEASE)]) + assert r.returncode == 0, r.stderr + assert hands == "pre_build 1 9001" + assert "stages.rehearse.run_id" in r.stdout + + +def _heart_validated(tmp_path, run_id): + state = tmp_path / "heart-state" + state.mkdir(exist_ok=True) + (state / "validation_report.json").write_text(json.dumps( + {"stages": {"rehearse": {"run_id": run_id, "status": "pass"}}})) + + +def test_a_stale_env_run_id_that_heart_never_validated_refuses(tmp_path): + _heart_validated(tmp_path, "9001") + r, hands = _door(tmp_path, [str(RELEASE)], REHEARSAL_RUN_ID="111") + assert r.returncode == 5 and hands == "" + assert "111" in r.stderr and "9001" in r.stderr + + +def test_a_given_run_id_matching_hearts_proceeds(tmp_path): + _heart_validated(tmp_path, "9001") + r, hands = _door(tmp_path, [str(RELEASE), "--rehearsal-run-id", "9001"]) + assert r.returncode == 0, r.stderr + assert hands == "pre_build 1 9001" + r, hands = _door(tmp_path, [str(RELEASE), "--rehearsal-run-id", "9002"]) + assert r.returncode == 5 and "9002" in r.stderr and "9001" in r.stderr