Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -804,6 +804,19 @@ not open.
scoped` dip takes `queue.md` first, then only `Difficulty: small` single-repo
backlog tasks; anything bigger must be queued by the human.

**Launch preflight — 2026-11-17 (M3.6a, PyAutoBrain#659), approved by the
human.** A live brief (not `shadow: yes`) names its shift **`issue:`**: `batch
brief --new --out` creates it on PyAutoMind and writes it, and `batch brief
--check` refuses a live brief without it, and refuses the launch while the CLI
login has expired or expires before `review-at:`. **Only a pushed brief
opens:** the watcher finds the brief itself on Mind `origin/main`, read
locally and never fetched for this, taking the one whose `dispatched:` has
passed and whose `review-at:` has not. Two open briefs grant nothing: the
watcher idles and says so. `PYAUTO_SHIFT_BRIEF` (or `--brief`) is only an
override, honoured inside that brief's own window. **The watcher's part in a
shift ends at `review-at:` + 45 min:** once the digest is posted and that late
window has closed, it stops ticking the slot and renews no lease.

*Revert condition:* one dispatch found outside a brief's scope returns batching
to per-task `--auto` until the cause is found.

Expand Down Expand Up @@ -1055,6 +1068,8 @@ The revert condition also covers these: an @mention for a parked question,
or any read of `questions.md` other than that local one, retires the watcher
to fake mode.

**Login probe — 2026-11-17.** The watcher runs `claude auth status --json` (local, no model call) on a shift's first tick and when a worker shows as blocked. `loggedIn: false`, or a `loginExpiresAt` already passed, is a `login-expired` event, never "blocked on a person", and no worker starts until it passes.

## Human override for Heart RED (development only)

Heart RED still parks every autonomous run and blocks every release. After the
Expand Down Expand Up @@ -1318,6 +1333,8 @@ Codex hook list.
their revert condition are "The watcher's network surface — 2026-11-03"
above.

A fourth exception, added 2026-11-17: `batch brief --new --out <file>` makes one `gh issue create` on PyAutoMind for the shift issue and writes its URL as `issue:`. It runs in the launch chat, never in the watcher; `--issue <url>` or `PYAUTO_BRIEF_ISSUE=off` skips it.

Any *further* network surface in the Brain is a new decision, not covered by
this line.
- The `Autonomy:` header is a model's own estimate. The caps, the explicit
Expand Down
62 changes: 58 additions & 4 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,24 @@ is copied as their word; `--new` also prints on stderr how the goals changed
since the newest brief. `brief --check` warns when `goals.md`'s goal 1 is
missing from a brief (PyAutoMind#565; readers in `_steer.py`).

**The launch preflight (M3.6a, PyAutoBrain#659).** With `--out`, `brief --new`
first makes the shift issue: one `gh issue create` on the Mind's `origin` repo
(`create_shift_issue`), written as `- issue: <url>`. It runs in the launch
chat, never in the watcher (AUTONOMY.md, the 2026-11-17 exception to "The
Brain reads no network"). A file that already names an `issue:` keeps it, so
a re-run never makes a second; `--issue <url>` names one by hand;
`PYAUTO_BRIEF_ISSUE=off` skips it. The issue is made last, just before the
write: if `gh` fails, no brief is written (exit 1), and if the write fails
after it, the URL is printed to re-run with `--issue <url>`.
`brief --check` then adds what only a launch needs (`_brief.launch_errors`,
`login_findings`): a live brief (not `shadow: yes`) without a GitHub issue URL
is refused (`issue: missing — …`), and so is a CLI login that has expired
("login: CLI login expired: run `claude /login`") or that expires before
`review-at:`. The login is read by `_login.probe`: `claude auth status
--json` (`loggedIn`, `loginExpiresAt`), no model call; a probe that cannot
tell only warns, and `PYAUTO_LOGIN_PROBE=off` skips it. `_brief.check` itself
is unchanged: the watcher's open-brief gate does not require `issue:`.

## The keep-Heart-green lane (`_green.py`, PyAutoBrain#625)

The human, 2026-11-13: "having the autonomous agent constantly trying to
Expand Down Expand Up @@ -258,8 +276,8 @@ pin that and record every process a full brief run starts.

## The watcher (phases 3a–3d)

`bin/orchestrator_watch.py --brief <record> --mind <PyAutoMind>` runs **one
tick**: `STOP` first, then the open-brief gate, the tick lock, the lease reap,
`bin/orchestrator_watch.py --mind <PyAutoMind>` finds the brief and runs **one
tick** of it (finding it is below, "Which brief"); `STOP` first, then the open-brief gate, the tick lock, the lease reap,
the plan inside the brief, the caps (`max-workers:`, default 4;
`max-sessions:`, default 8) and an exclusive-create lease per spawn. The plan
is checked against Mind `origin/main` (#632): a draft not under its `draft/` or
Expand Down Expand Up @@ -290,6 +308,41 @@ opened the moment it landed (pilot shadow shift 1 opened a day early;
PyAutoBrain#589). `batch watch` says `not yet open — opens in …` before the
start.

**Which brief (M3.6a, PyAutoBrain#659).** The watcher reads the briefs itself
from Mind `origin/main` (`shift_briefs`: a local `git ls-tree` / `git show`,
never a fetch), so only a pushed brief opens. It ticks the one open brief
(`dispatched:` <= now < `review-at:`) and every late one (`review-at:` <= now
< + 45 min, for the digest and the late sweep). Two open briefs tick neither:
the tick prints `idle: two open briefs on origin/main (a, b)`. A pushed brief
missing from the checkout's working tree is not ticked (`pushed, but the Mind
checkout is behind`). A brief past its late window is still ticked, for up
to a day, while its slot owes something (`late_owed`: no digest yet, a post
retry due, a queued Mind op), so a laptop that was off catches up. Past that
day it is not ticked again; the first tick after says once (`abandoned: <slot>
past catch-up (<what it owes>; N leases)`, marker `abandoned.noted`) so the
human runs `batch digest` and closes it by hand. The tick
reads the local `origin/main` ref and never fetches it: the Mind checkout it
reads must be fetched (or the brief pushed from it) before launch, or the
tick idles `no open brief`. `--brief` or `$PYAUTO_SHIFT_BRIEF` is an override:
while that brief is open it takes the open brief's place; in its late window
it is one more late brief, ticked beside the open one; otherwise it is
ignored, so a stale env file never displaces the next shift.

**The end: `review-at:` + 45 min.** Once the late window
(`_brief.LATE_WINDOW_S`) has closed and nothing is owed (the digest posted, no
post retry due, no queued Mind op), a tick of that brief returns
`idle: late window closed at …` before the lock: no reap, no lease renewed, no
`tick.log` line. A worker still out by then is in the digest, for the human.

**The login hold.** A real spawner probes the CLI login (`_login.probe`) when a
member waits to start and the last probe was not `ok` (the shift's first
spawning tick, and each tick after an expiry), and again whenever a worker
shows `blocked`. An expired login holds every spawn and is its own
`login-expired` event ("CLI login expired: run `claude /login`. No worker
starts until it passes."), a needs-you comment on the shift issue, never a
worker "blocked on a person". It is kept in `counters["login"]` and in the
tick's result.

**Real workers (phase 3b).** Without `PYAUTO_ORCHESTRATOR_FAKE=1` each spawn is
`claude --bg --name shift:<task> --permission-mode <worker-mode> <prompt>`, the
prompt filled from `worker_template.md` (the `/start_dev <path> --auto` line,
Expand Down Expand Up @@ -622,8 +675,9 @@ workers are ever launched there.

**Installing the timer is the human's act** — no session runs these. Copy
`bin/systemd/pyauto-orchestrator.{service,timer}` to `~/.config/systemd/user/`,
write `~/.config/pyauto/orchestrator.env` with `PYAUTO_BRAIN`, `PYAUTO_MIND`,
`PYAUTO_SHIFT_BRIEF` (and `PYAUTO_ORCHESTRATOR_FAKE=1` until 3b), then
write `~/.config/pyauto/orchestrator.env` with `PYAUTO_BRAIN`, `PYAUTO_MIND`
(and `PYAUTO_ORCHESTRATOR_FAKE=1` until 3b; `PYAUTO_SHIFT_BRIEF` only as an
override, see "Which brief"), then
`systemctl --user daemon-reload && systemctl --user enable --now
pyauto-orchestrator.timer`. The service carries `KillMode=process`: under the
default (`control-group`) systemd killed every process a tick started when the
Expand Down
137 changes: 130 additions & 7 deletions agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from _status import PENDING_RE, RULING_WORDS, freeze_line # noqa: E402
import _brief # noqa: E402
import _green # noqa: E402 — the keep-Heart-green lane (PyAutoBrain#625)
import _login # noqa: E402 — the CLI login probe (M3.6a, PyAutoBrain#659)
# The human's goals (goals.md, PyAutoMind#565): `brief --new` copies them.
from _steer import read_goals # noqa: E402,F401 — re-exported beside read_queue
# The close-out guard's reader (intake `looks-shipped`): the live flags minus
Expand Down Expand Up @@ -2966,6 +2967,11 @@ def main(argv=None) -> int:
"--mind")
ap.add_argument("--green-cap", type=int, default=_green.DEFAULT_CAP,
help="brief --new / green: at most this many new drafts")
ap.add_argument("--issue", default="", metavar="URL",
help="brief --new: the shift issue to write as `issue:` instead "
"of creating one (with --out, `brief --new` makes one "
"`gh issue create` on PyAutoMind unless this is given or "
"$PYAUTO_BRIEF_ISSUE=off)")
ap.add_argument("--heart-json", default="", metavar="FILE",
help="brief --new / green: read this saved `readiness --json` "
"or state.json instead of Heart (a replay; --at sets now)")
Expand Down Expand Up @@ -3315,7 +3321,7 @@ def goals_report(mind: Path) -> list[str]:


def new_brief(mind: Path, slot: str, review_at: str, now=None,
heart: dict | None = None) -> str:
heart: dict | None = None, issue: str = "") -> str:
"""A skeleton shift brief whose `goals:` are `goals.md`'s, in order.

`goals.md` has one kind of writer, the human (by hand or in chat), so
Expand All @@ -3327,7 +3333,10 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None,

`heart` is the keep-Heart-green lane's result (`_green.run`): its picks
become a last `heart-green` goal plus named `tasks:`, and its report the
record's `## Heart` section (PyAutoBrain#625)."""
record's `## Heart` section (PyAutoBrain#625).

`issue` is the shift issue (`create_shift_issue`), written as `issue:`
(M3.6a, PyAutoBrain#659): `brief --check` refuses a live brief without it."""
goals = read_goals(mind)
now = now or _dt.datetime.now(_dt.timezone.utc)
epics: list[str] = []
Expand All @@ -3339,9 +3348,11 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None,
L = [f"# Batch {slot.rsplit('-', 1)[0]} {slot.rsplit('-', 1)[-1]}",
f"- dispatched: {now.strftime('%Y-%m-%dT%H:%MZ')}",
f"- review-at: {review_at}",
f"- shift: {shift}",
"- brief:",
" - goals: # from goals.md, in order"]
f"- shift: {shift}"]
if issue:
L.append(f"- issue: {issue}")
L += ["- brief:",
" - goals: # from goals.md, in order"]
# A goal is one line of plain text (goals.md's own check); ` # ` would
# read as a trailing comment here, so it is spelled out.
L += [f" - {g['n']}. " + re.sub(r"\s#\s", " no. ", g["text"]) for g in goals]
Expand Down Expand Up @@ -3369,6 +3380,80 @@ def new_brief(mind: Path, slot: str, review_at: str, now=None,
return text + "\n" + _green.section(heart) if heart else text


#: `PYAUTO_BRIEF_ISSUE=off`: `brief --new --out` makes no shift issue.
BRIEF_ISSUE_ENV = "PYAUTO_BRIEF_ISSUE"
_GITHUB_REMOTE_RE = re.compile(r"github\.com[:/]([\w.-]+)/([\w.-]+?)(?:\.git)?/?$")


def mind_repo(mind: Path) -> str:
"""`owner/repo` of the Mind checkout's `origin` on GitHub, or ""."""
try:
res = subprocess.run(["git", "-C", str(mind), "remote", "get-url", "origin"],
capture_output=True, text=True, timeout=30)
except (OSError, subprocess.SubprocessError):
return ""
m = _GITHUB_REMOTE_RE.search(res.stdout.strip()) if res.returncode == 0 else None
return f"{m.group(1)}/{m.group(2)}" if m else ""


def create_shift_issue(mind: Path, slot: str, review_at: str, run=None) -> tuple[str, str]:
"""(issue URL, "") or ("", why not): the one `gh issue create` on the Mind
repo that `brief --new --out` makes (M3.6a, PyAutoBrain#659; AUTONOMY.md
"The Brain reads no network", the 2026-11-17 exception). It runs in the
launch chat, never in the watcher."""
repo = mind_repo(mind)
if not repo:
return "", f"no GitHub `origin` remote in {mind} to make the shift issue on"
body = (f"The shift issue for `batches/{slot}.md` (review at {review_at}).\n\n"
"The watcher keeps one live status comment here, reads the steering "
"commands (`/pause`, `/resume`, `/drop`, `/stop`, `/add`, `/cap`, `/kill`) "
"from comments here, and posts the digest here at `review-at:`.\n")
run = run or subprocess.run
try:
res = run(["gh", "issue", "create", "--repo", repo,
"--title", f"Shift {slot} (review at {review_at})", "--body", body],
capture_output=True, text=True, timeout=60)
except (OSError, subprocess.SubprocessError) as e:
return "", f"gh issue create failed ({e})"
m = _brief.ISSUE_RE.search(res.stdout or "") if res.returncode == 0 else None
if not m:
return "", (f"gh issue create on {repo} failed (exit {res.returncode}): "
+ ((res.stderr or res.stdout or "").strip()[:200] or "no issue URL"))
return m.group(0), ""


def _issue_in(path: Path) -> str:
"""The `issue:` an existing brief file already names, or ""."""
try:
top = _brief.parse(path.read_text(encoding="utf-8", errors="replace"))["top"]
except (OSError, _brief.BriefError):
return ""
return (top.get("issue") or {}).get("value", "").strip()


def login_findings(top: dict, brief: dict | None) -> tuple[dict, list[str], list[str]]:
"""(probe result, errors, warnings) of the CLI login for a launch (M3.6a):
an expired login, or one that lapses before `review-at:`, refuses it. A
shadow brief starts no worker and is not probed."""
if brief is None or _brief.is_shadow(brief):
return {"state": "skipped", "detail": "shadow shift", "expires_at": ""}, [], []
login = _login.probe()
errors, warnings = [], []
if login["state"] == "expired":
errors.append(f"login: {_login.EXPIRED_LINE} ({login['detail']})")
elif login["state"] == "unknown":
warnings.append(f"login: could not tell whether the CLI login holds "
f"({login['detail']})")
elif login["state"] == "ok":
review_at = _brief._iso((top.get("review-at") or {}).get("value", ""))
lapses = _login.expires(login)
if review_at is not None and lapses is not None and lapses < review_at:
errors.append(f"login: the CLI login expires at {login['expires_at']}, before "
f"review-at {top['review-at']['value']} — run `claude /login` "
"before the launch")
return login, errors, warnings


def goal_one_warning(path: Path, mind: Path) -> str:
"""A warning when `goals.md`'s goal 1 is missing from the brief at `path`."""
goals = read_goals(mind)
Expand Down Expand Up @@ -3405,17 +3490,42 @@ def _main_brief(mind: Path, a) -> int:
print("batch brief --new: --review-at <ISO time> is required — the "
"grant expires there, and it is yours to declare", file=sys.stderr)
return RC_USAGE
if a.issue and not _brief.ISSUE_RE.fullmatch(a.issue.strip()):
print(f"batch brief --new: --issue {a.issue!r} is not a GitHub issue URL",
file=sys.stderr)
return RC_USAGE
heart = green_lane(mind, a, os.environ.get(_green.MODE_ENV) or _green.DEFAULT_MODE,
preview=not a.out)
text = new_brief(mind, a.new, a.review_at, heart=heart)
if heart["filed"]:
print(f"batch brief --new: heart-green filed {len(heart['filed'])} "
f"draft(s) in {mind} (uncommitted — commit them with the "
"record): " + ", ".join(heart["filed"]), file=sys.stderr)
for line in goals_report(mind):
print(line, file=sys.stderr)
# The shift issue (M3.6a, PyAutoBrain#659) is made last, just before
# the write, so nothing that can still fail stands between the two. A
# file that already names one keeps it: a re-run never makes a second.
issue = a.issue.strip() or (_issue_in(Path(a.out)) if a.out else "")
made = False
if a.out and not issue and \
os.environ.get(BRIEF_ISSUE_ENV, "").strip().lower() != "off":
issue, why = create_shift_issue(mind, a.new, a.review_at)
if not issue:
print(f"batch brief --new: no shift issue, so no brief written — {why}. "
"Pass --issue <url> to name one by hand.", file=sys.stderr)
return RC_FINDINGS
made = True
print(f"batch brief --new: made the shift issue {issue}", file=sys.stderr)
text = new_brief(mind, a.new, a.review_at, heart=heart, issue=issue)
if a.out:
Path(a.out).write_text(text, encoding="utf-8")
try:
Path(a.out).write_text(text, encoding="utf-8")
except OSError as e:
hint = (f" The shift issue {issue} exists: re-run with `--issue {issue}` "
"so no second one is made." if made else "")
print(f"batch brief --new: could not write {a.out} ({e}).{hint}",
file=sys.stderr)
return RC_FINDINGS
print(f"batch brief --new: wrote {a.out} "
f"({len(read_goals(mind))} goal(s) from goals.md)")
else:
Expand All @@ -3429,6 +3539,19 @@ def _main_brief(mind: Path, a) -> int:
"(the digest is `batch digest --record <file>`)", file=sys.stderr)
return RC_USAGE
res = _brief.check(Path(a.check), mind)
# What only a launch needs (M3.6a, PyAutoBrain#659): the shift issue, and a
# CLI login that holds until review-at. `_brief.check` stays the watcher's.
try:
rec = _brief.parse(Path(a.check).read_text(encoding="utf-8", errors="replace"))
except (OSError, _brief.BriefError):
rec = None
if rec is not None:
res["errors"] += _brief.launch_errors(rec["top"], rec["brief"])
login, errs, warns = login_findings(rec["top"], rec["brief"])
res["login"] = login
res["errors"] += errs
res["warnings"] += warns
res["ok"] = not res["errors"]
warn = goal_one_warning(Path(a.check), mind)
if warn:
res["warnings"].append(warn)
Expand Down
Loading
Loading