diff --git a/AUTONOMY.md b/AUTONOMY.md index 6442f8e6..bd79bdb3 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -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. @@ -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 @@ -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 ` 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 ` 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 diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 1ea45dd7..a714d550 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -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: `. 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 ` 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 `. +`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 @@ -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 --mind ` runs **one -tick**: `STOP` first, then the open-brief gate, the tick lock, the lease reap, +`bin/orchestrator_watch.py --mind ` 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 @@ -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: +past catch-up (; 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: --permission-mode `, the prompt filled from `worker_template.md` (the `/start_dev --auto` line, @@ -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 diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 7fbea62c..34afdbed 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -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 @@ -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)") @@ -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 @@ -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] = [] @@ -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] @@ -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) @@ -3405,17 +3490,42 @@ def _main_brief(mind: Path, a) -> int: print("batch brief --new: --review-at 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 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: @@ -3429,6 +3539,19 @@ def _main_brief(mind: Path, a) -> int: "(the digest is `batch digest --record `)", 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) diff --git a/agents/conductors/batch/_brief.py b/agents/conductors/batch/_brief.py index f4eee823..cc9f189b 100644 --- a/agents/conductors/batch/_brief.py +++ b/agents/conductors/batch/_brief.py @@ -38,6 +38,12 @@ #: The one size `backlog: scoped` may dip beyond `queue.md` (human ruling #: 2026-11-16, PyAutoBrain#637, item 6): small and single-repo only. SCOPED_REACH_DIFFICULTY = "small" +#: The late window (human ruling H2): the watcher's digest and late sweep run +#: from `review-at:` to this long after it, and then it stops ticking the slot +#: (M3.6a, PyAutoBrain#659). `batch watch --stream` ends at the same time. +LATE_WINDOW_S = 45 * 60 +#: A shift issue: the brief's `issue:` value (M3.6a). +ISSUE_RE = re.compile(r"https://github\.com/[\w.-]+/[\w.-]+/issues/\d+") _ITEM_RE = re.compile(r"^(\s*)-\s+(.*?)\s*$") _KEY_RE = re.compile(r"^([a-z][a-z0-9-]*):\s*(.*)$") @@ -381,6 +387,23 @@ def check(path: Path, mind: Path) -> dict: return {"ok": not errors, "errors": errors, "warnings": warnings} +def launch_errors(top: dict, brief: dict | None) -> list[str]: + """What only a launch needs (M3.6a, PyAutoBrain#659): `batch brief --check` + adds these to `check`; the watcher does not. A live brief (not `shadow: + yes`) needs its shift issue: the status comment, the steering commands and + the digest all go there, and shift 2026-11-16-pm had none.""" + if brief is None or is_shadow(brief): + return [] + issue = (top.get("issue") or {}).get("value", "").strip() + if not issue: + return ["issue: missing — a live brief needs its shift issue " + "(batch brief --new creates it)"] + if not ISSUE_RE.fullmatch(issue): + return [f"issue: {issue!r} is not a GitHub issue URL — a live brief needs its " + "shift issue (batch brief --new creates it)"] + return [] + + # --- scope --------------------------------------------------------------------- def scope(records: list[dict], brief: dict) -> tuple[list[dict], list[tuple[str, str]], list[str]]: diff --git a/agents/conductors/batch/_events.py b/agents/conductors/batch/_events.py index 6f321a1c..9582984a 100644 --- a/agents/conductors/batch/_events.py +++ b/agents/conductors/batch/_events.py @@ -28,6 +28,7 @@ from pathlib import Path import _digest # noqa: E402 — the batch conductor puts this directory on sys.path +import _login # noqa: E402 — its wording only; the probe runs in the tick, not here EVENTS_FILE = "events.jsonl" STATE_FILE = "events.state.json" @@ -48,7 +49,7 @@ KINDS = ("shift-open", "spawned", "redispatched", "crashed", "pr-opened", "finished", "question", "parked", "ci", "closeout-started", "merged", "merged-outside", "refused", "cap", "steer", "steer-unread", "impaired", "late", "digest", - "stopped", "shift-end") + "stopped", "shift-end", "login-expired") #: The kinds after which the stream has nothing more to follow. FINAL_KINDS = ("shift-end", "stopped") @@ -392,6 +393,18 @@ def _impaired(b: _Batch, result: dict) -> None: f"Mind write {word}: {op}, {why}.", needs_you=True) +def _login_expired(b: _Batch, result: dict) -> None: + """The CLI login has expired (M3.6a, PyAutoBrain#659): its own needs-you + event, once per episode (keyed by when the tick first saw it) — never read + as a worker blocked on a person.""" + login = result.get("login") or {} + if login.get("state") != "expired": + return + since = login.get("since") or login.get("at") or b.now.isoformat() + b.add("login-expired", f"login-expired:{since}", + _login.EXPIRED_LINE + ". No worker starts until it passes.", needs_you=True) + + def _late(b: _Batch, result: dict) -> None: for line in result.get("late") or []: text = _LATE_TAIL_RE.sub("", str(line).removeprefix("- late: ").strip()) @@ -449,6 +462,7 @@ def record_tick(slot: Path, now: _dt.datetime, result: dict, counters: dict | No _spawned(b, result, counters) _refused(b, result) _impaired(b, result) + _login_expired(b, result) _late(b, result) if action in ("ticked", "shadow", "stopped"): if counters.get("commands_unread"): diff --git a/agents/conductors/batch/_login.py b/agents/conductors/batch/_login.py new file mode 100644 index 00000000..58fcab6e --- /dev/null +++ b/agents/conductors/batch/_login.py @@ -0,0 +1,84 @@ +"""The CLI login probe (M3.6a, PyAutoBrain#659). + +Shift 2026-11-16-pm lost its first workers to an expired `claude` login, and +the watcher read them as "blocked on a person". This asks the CLI itself, +with `claude auth status --json` — a local read of the stored login, no model +call — and says one of: + +- `ok` — logged in, and the login has not expired; +- `expired` — `loggedIn: false`, a `loginExpiresAt` already passed, or the CLI + saying "Login reached its time limit" / "not logged in"; +- `unknown` — the CLI could not be run or printed nothing it could read; +- `skipped` — `PYAUTO_LOGIN_PROBE=off` (the test suite; a machine without + the CLI on purpose). + +`batch brief --check` refuses a launch on `expired` (or a login that lapses +before `review-at:`); the watcher holds spawning on it (AUTONOMY.md "The +watcher's network surface", Login probe — 2026-11-17). +""" + +from __future__ import annotations + +import datetime as _dt +import json +import os +import subprocess + +PROBE_ENV = "PYAUTO_LOGIN_PROBE" +#: What the human reads, in the brief check, the event and its comment. +EXPIRED_LINE = "CLI login expired: run `claude /login`" +#: Phrases the CLI prints for a login it cannot use (lower-cased match). +EXPIRED_PHRASES = ("login reached its time limit", "not logged in") +ARGV = ["claude", "auth", "status", "--json"] + + +def _parse(value: str): + try: + t = _dt.datetime.fromisoformat(str(value).strip().replace("Z", "+00:00")) + except ValueError: + return None + return t if t.tzinfo else t.replace(tzinfo=_dt.timezone.utc) + + +def expires(result: dict): + """The probe's `expires_at` as a datetime, or None.""" + return _parse(result.get("expires_at") or "") + + +def probe(run=None, now: _dt.datetime | None = None) -> dict: + """{"state": ok|expired|unknown|skipped, "detail", "expires_at"}.""" + if os.environ.get(PROBE_ENV, "").strip().lower() in ("off", "0", "no"): + return {"state": "skipped", "detail": f"{PROBE_ENV}=off", "expires_at": ""} + run = run or subprocess.run + now = now or _dt.datetime.now(_dt.timezone.utc) + try: + res = run(ARGV, capture_output=True, text=True, timeout=30) + except FileNotFoundError: + return {"state": "unknown", "detail": "no `claude` on PATH", "expires_at": ""} + except (OSError, subprocess.SubprocessError) as e: + return {"state": "unknown", "detail": f"`claude auth status` failed ({e})"[:200], + "expires_at": ""} + text = f"{res.stdout or ''}\n{res.stderr or ''}" + low = text.lower() + for phrase in EXPIRED_PHRASES: + if phrase in low: + line = next((ln.strip() for ln in text.splitlines() if phrase in ln.lower()), + phrase) + return {"state": "expired", "detail": line[:200], "expires_at": ""} + try: + d = json.loads(res.stdout or "") + except ValueError: + d = None + if not isinstance(d, dict): + return {"state": "unknown", "detail": f"`claude auth status --json` exit " + f"{res.returncode}: " + (text.strip()[:160] or "no output"), "expires_at": ""} + at = str(d.get("loginExpiresAt") or "") + if d.get("loggedIn") is False: + return {"state": "expired", "detail": "loggedIn: false", "expires_at": at} + when = _parse(at) if at else None + if when is not None and when <= now: + return {"state": "expired", "detail": f"login expired at {at}", "expires_at": at} + if d.get("loggedIn") is True: + return {"state": "ok", "detail": "logged in", "expires_at": at} + return {"state": "unknown", "detail": "no loggedIn field in `claude auth status --json`", + "expires_at": at} diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 235d5a4a..d84e8487 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -50,6 +50,7 @@ import _brief # noqa: E402 import _digest # noqa: E402 import _events # noqa: E402 +import _login # noqa: E402 — the CLI login probe (M3.6a, PyAutoBrain#659) import _merge_slots # noqa: E402 — one merge-cap count per shift (R3, #661) import _mind_writer # noqa: E402 import _questions # noqa: E402 @@ -1127,6 +1128,29 @@ def brief_open(brief_path: Path, mind: Path, now: _dt.datetime) -> tuple[bool, s return True, "open", rec["brief"] +def late_owed(slot: Path) -> bool: + """What the watcher still owes a shift once its late window has closed + (M3.6a review): the digest not yet claimed, a digest or correction post + that failed with tries left, or a queued Mind op. Local reads only.""" + slot = Path(slot) + return (not (slot / DIGEST_MARKER).exists() or post_due(slot / DIGEST_MARKER) + or post_due(slot / CORRECTION_MARKER) or bool(_mind_writer.pending_ops(slot))) + + +def _late_closed(brief_path: Path, now: _dt.datetime) -> str: + """When the late window closed (`review-at:` + `_brief.LATE_WINDOW_S`) as + ISO, if it has; else "" (M3.6a, PyAutoBrain#659). Local reads only.""" + try: + top = _brief.parse(Path(brief_path).read_text(encoding="utf-8"))["top"] + except (OSError, _brief.BriefError): + return "" + at = _brief._iso((top.get("review-at") or {}).get("value", "")) + if at is None: + return "" + closes = at + _dt.timedelta(seconds=_brief.LATE_WINDOW_S) + return _iso(closes) if now >= closes else "" + + def _default_pr_state(): """GitHub's word on a PR at `review-at:` — none asked in a dry shift.""" return FakeSpawner().pr_state if os.environ.get(FAKE_ENV) == "1" else gh_pr_state @@ -1174,6 +1198,15 @@ def _tick(brief_path: Path, mind: Path, *, home: Path | None = None, is_open, why, brief = brief_open(brief_path, mind, now) if not is_open: + # The late window has closed and nothing is owed (M3.6a, + # PyAutoBrain#659): the digest is out with no retry due and no Mind op + # is queued. The shift is over for the watcher: no lock, no reap, no + # lease renewed, no log line — a worker still out is the human's, by + # the digest. Anything still owed is caught up first, below. + closed = _late_closed(brief_path, now) + if closed and not late_owed(slot): + return {"action": "idle", "reason": f"late window closed at {closed} " + "(review-at + 45 min); the digest is posted"} if why.startswith("review-at") and (slot / "leases").is_dir() \ and not (slot / DIGEST_MARKER).exists(): if not _take_lock(slot, now): @@ -1733,7 +1766,11 @@ def known(task: str) -> bool: # worker slot a killed task is waiting for. members = sorted(d["members"], key=lambda m: task_id(m["path"]) not in counters["pending_redispatch"]) - for member in [] if paused else members: + # The CLI login (M3.6a, #659): an expired one holds every spawn, as its + # own event — never a worker "blocked on a person". + login = _login_hold(counters, spawner, [] if paused else members, live, now) + hold = paused or (login or {}).get("state") == "expired" + for member in [] if hold else members: task = task_id(member["path"]) if task in live or task in counters["done"] or task in counters["abandoned"] \ or task in counters["parked"] or task in counters["dropped"]: @@ -1815,9 +1852,43 @@ def known(task: str) -> bool: "closeouts": closeouts} if mentions: out["mentions"] = mentions + if login: + out["login"] = login return _steered(out, commands, paused) +def _login_hold(counters: dict, spawner, members: list[dict], live: dict, + now: _dt.datetime, probe=None) -> dict | None: + """The CLI login as this tick sees it (M3.6a, PyAutoBrain#659), or None. + + Probed (`claude auth status --json`, local, no model call) only for a + real spawner, and only when a member is waiting to start while the last + probe was not `ok` — the shift's first tick, or one after an expiry — or + when a worker shows `blocked` this tick, which an expired login looks + like. `expired` holds every spawn until a probe passes; `unknown` holds + nothing. Kept in `counters["login"]`, with `since` the first tick of an + expiry (the event's key).""" + if not getattr(spawner, "real", False): + return None + last = counters.get("login") or {} + blocked = any(w.get("blocked_seen") == _iso(now) and w.get("task") not in counters["parked"] + for w in counters["workers"]) + held = (set(live) | set(counters["done"]) | set(counters["abandoned"]) + | set(counters["parked"]) | set(counters["dropped"])) + wanted = any(task_id(m["path"]) not in held for m in members) + if not (blocked or (wanted and last.get("state") != "ok")): + return last if last.get("state") == "expired" else None + res = (probe or _login.probe)() + if res.get("state") == "skipped": + return None + rec = {**res, "at": _iso(now)} + if res.get("state") == "expired": + rec["since"] = (last.get("since") if last.get("state") == "expired" else None) \ + or _iso(now) + counters["login"] = rec + return rec + + def _steered(out: dict, commands: list, paused: bool) -> dict: """A tick's result with what the human's commands did to it.""" if commands: @@ -3485,28 +3556,229 @@ def _propose(members: list[dict], brief: dict, counters: dict, max_sessions: int return out +# --- which brief: the one open on Mind origin/main (M3.6a, PyAutoBrain#659) ------- + +#: The env file's brief: now only an override, honoured inside its own window. +SHIFT_BRIEF_ENV = "PYAUTO_SHIFT_BRIEF" +ORIGIN_REF = "origin/main" + + +def shift_briefs(mind: Path, ref: str = ORIGIN_REF) -> list[dict] | None: + """Every shift brief on Mind's local `ref`: {name, rel, dispatched, + review_at} for each top-level `batches/*.md` with a `brief:` block and + both times. None when `mind` is not its own git checkout or has no such + ref. Local `git ls-tree` / `git show` only — never a fetch: only a pushed + brief opens, so pushing the brief stays the launch.""" + def git(*args): + try: + res = subprocess.run(["git", "-C", str(mind), *args], capture_output=True, + text=True, timeout=30) + except (OSError, subprocess.SubprocessError): + return None + return res.stdout if res.returncode == 0 else None + top = git("rev-parse", "--show-toplevel") + if top is None or Path(top.strip()).resolve() != Path(mind).resolve(): + return None + listing = git("ls-tree", "--name-only", ref, "batches/") + if listing is None: + return None + out = [] + for rel in listing.splitlines(): + name = Path(rel).name + if not name.endswith(".md") or name == "AGENTS.md": + continue + text = git("show", f"{ref}:{rel}") + try: + rec = _brief.parse(text or "") + except _brief.BriefError: + continue + top_keys = rec["top"] + start = _brief._iso((top_keys.get("dispatched") or {}).get("value", "")) + end = _brief._iso((top_keys.get("review-at") or {}).get("value", "")) + if rec["brief"] is None or start is None or end is None: + continue + out.append({"name": Path(rel).stem, "rel": rel, "dispatched": start, "review_at": end}) + return sorted(out, key=lambda b: b["name"]) + + +#: How long after `review-at:` + the late window a shift whose digest is still +#: owed is caught up (the laptop was off through the late window). Bounded, +#: so an old slot is never digested days later. +CATCH_UP_S = 24 * 3600 +#: Claimed in a slot the first time a tick finds it past `CATCH_UP_S` with +#: something still owed, so the "abandoned" line is printed once. +ABANDONED_MARKER = "abandoned.noted" + + +def _owes(slot: Path) -> str: + """What `late_owed` found, in words, with the leases still held.""" + slot = Path(slot) + bits = [] + if not (slot / DIGEST_MARKER).exists(): + bits.append("digest not posted") + elif post_due(slot / DIGEST_MARKER): + bits.append("digest post retry due") + if post_due(slot / CORRECTION_MARKER): + bits.append("correction post retry due") + ops = len(_mind_writer.pending_ops(slot)) + if ops: + bits.append(f"{ops} queued Mind op{'s' if ops != 1 else ''}") + n = len(list((slot / "leases").glob("*.json"))) + bits.append(f"{n} lease{'s' if n != 1 else ''}") + return "; ".join(bits) + + +def _override_state(path: Path, now: _dt.datetime) -> str: + """Where an override brief (`--brief`, `$PYAUTO_SHIFT_BRIEF`) is in its own + window: "open" (`dispatched:` <= now < `review-at:`), "late" (to + `review-at:` + the late window), else "".""" + try: + top = _brief.parse(Path(path).read_text(encoding="utf-8"))["top"] + except (OSError, _brief.BriefError): + return "" + start = _brief._iso((top.get("dispatched") or {}).get("value", "")) + end = _brief._iso((top.get("review-at") or {}).get("value", "")) + if start is None or end is None or now < start: + return "" + if now < end: + return "open" + return "late" if now < end + _dt.timedelta(seconds=_brief.LATE_WINDOW_S) else "" + + +def find_briefs(mind: Path, now: _dt.datetime, *, override: Path | None = None, + ref: str = ORIGIN_REF, home: Path | None = None) -> tuple[list[Path], str]: + """(the brief files to tick, why something is not ticked). + + The one open brief on `ref` (`dispatched:` <= now < `review-at:`), then + every late one (`review-at:` <= now < + 45 min, for its digest and late + sweep), then any past that window whose slot still has something owed + (`late_owed`: the laptop was off through the late window), up to + `CATCH_UP_S`. Two open briefs tick neither: which grant holds is the + human's word, not the watcher's guess. A brief is ticked from Mind's + working tree; one pushed but missing there is named, not ticked. + + An override takes the open brief's place only while it is open itself; + in its late window it is one more late brief, ticked beside the open one + (M3.6a review: a stale env file must never displace the next shift).""" + state = _override_state(override, now) if override is not None else "" + briefs = shift_briefs(mind, ref) + if briefs is None: + if state: + return [Path(override)], "" + return [], f"no {ref} in {mind} to find the shift brief on" + home = home or orchestrator_home() + late_s = _dt.timedelta(seconds=_brief.LATE_WINDOW_S) + catch_s = _dt.timedelta(seconds=CATCH_UP_S) + own = Path(override).stem if state else None + opened = [b for b in briefs if b["dispatched"] <= now < b["review_at"]] + late = [b for b in briefs if b["review_at"] <= now < b["review_at"] + late_s] + owed = [b for b in briefs if b["review_at"] + late_s <= now < b["review_at"] + late_s + catch_s + and (Path(home) / b["name"] / "leases").is_dir() + and late_owed(Path(home) / b["name"])] + # Past the catch-up with something still owed: never ticked again, so the + # human is told once which slot was left and what it owes (M3.6a review). + abandoned = [] + for b in briefs: + slot = Path(home) / b["name"] + if now >= b["review_at"] + late_s + catch_s and (slot / "leases").is_dir() \ + and late_owed(slot) and _create_exclusive(slot / ABANDONED_MARKER, + {"at": _iso(now)}): + abandoned.append(f"abandoned: {b['name']} past catch-up ({_owes(slot)}) — " + f"run `batch digest --record {b['rel']}` and close it by hand") + reasons: list[str] = [] + first: list[Path] = [] + if state == "open": + first.append(Path(override)) + picks = late + owed + else: + if len(opened) > 1: + count = "two" if len(opened) == 2 else str(len(opened)) + reasons.append(f"{count} open briefs on {ref} (" + + ", ".join(b["name"] for b in opened) + ")") + picks = (opened if len(opened) == 1 else []) + late + owed + paths: list[Path] = [] + for b in picks: + if b["name"] == own: + continue + path = Path(mind) / b["rel"] + if path.is_file(): + paths.append(path) + else: + reasons.append(f"{b['name']} is pushed, but the Mind checkout is behind " + f"(no {b['rel']} in {mind})") + if state == "late": + # After the open brief (if any), before the other late ones. + at = 1 if opened and len(opened) == 1 and paths and paths[0].stem == opened[0]["name"] \ + else 0 + paths.insert(at, Path(override)) + paths = first + paths + if not paths and not reasons: + reasons.append(f"no open brief on {ref}") + return paths, "; ".join(reasons + abandoned) + + +def watch(mind: Path, *, home: Path | None = None, now: _dt.datetime | None = None, + override: Path | None = None, **kw) -> dict: + """One timer firing (M3.6a, PyAutoBrain#659): find the brief(s) on Mind + `origin/main` and tick each. {"action": "idle", "reason"} when there is + none; else {"action": "watch", "ticked": {slot: tick result}} plus a + `reason` for what was left out.""" + now = now or _now() + paths, why = find_briefs(mind, now, override=override, home=home) + out: dict = {"action": "watch", "ticked": {}} + if override is not None and Path(override) not in paths: + out["override"] = (f"{override} not honoured: outside its window " + "(dispatched → review-at + 45 min)") + if not paths: + return {"action": "idle", "reason": why, **({"override": out["override"]} + if "override" in out else {})} + for path in paths: + try: + out["ticked"][path.stem] = tick(path, mind, home=home, now=now, **kw) + except OrchestratorError as e: + out["ticked"][path.stem] = {"action": "error", "reason": str(e)} + if why: + out["reason"] = why + return out + + +def _result_line(res: dict) -> str: + return f"{res['action']}: " + (res.get("reason") or + f"spawned {len(res.get('spawned', []))}, " + f"refused {len(res.get('refused', []))}, " + f"live {len(res.get('live', []))}") + + def main(argv=None) -> int: import argparse ap = argparse.ArgumentParser( prog="orchestrator_watch", description="One shift-watcher tick (run by a systemd user timer the " "human installs). Fake workers only until phase 3b.") - ap.add_argument("--brief", required=True, type=Path, - help="the shift brief record (PyAutoMind/batches/.md)") + ap.add_argument("--brief", type=Path, default=None, + help="override: tick this brief record instead of the one open " + "on Mind origin/main — honoured only inside its own window " + "(dispatched → review-at + 45 min); default " + f"${SHIFT_BRIEF_ENV}, else none") ap.add_argument("--mind", required=True, type=Path) ap.add_argument("--home", type=Path, default=None, help=f"state directory (default ${HOME_ENV}, else " ".orchestrator under the worktree root)") ap.add_argument("--json", action="store_true", dest="as_json") a = ap.parse_args(argv) - try: - res = tick(a.brief, a.mind.resolve(), home=a.home) - except OrchestratorError as e: + env_brief = os.environ.get(SHIFT_BRIEF_ENV, "").strip() + override = a.brief or (Path(env_brief) if env_brief else None) + res = watch(a.mind.resolve(), home=a.home, override=override) + ticked = res.get("ticked") or {} + if a.as_json: + one = len(ticked) == 1 and not res.get("reason") + print(json.dumps(next(iter(ticked.values())) if one else res, indent=2)) + else: + for name, r in ticked.items(): + print((f"{name}: " if len(ticked) > 1 else "") + _result_line(r)) + if res.get("reason"): + print(f"idle: {res['reason']}") + errors = [r["reason"] for r in ticked.values() if r.get("action") == "error"] + for e in errors: print(f"orchestrator_watch: {e}", file=sys.stderr) - return 2 - print(json.dumps(res, indent=2) if a.as_json else - f"{res['action']}: " + (res.get("reason") or - f"spawned {len(res.get('spawned', []))}, " - f"refused {len(res.get('refused', []))}, " - f"live {len(res.get('live', []))}")) - return 0 + return 2 if errors else 0 diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index f71f5b66..1eb4c17a 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -343,8 +343,8 @@ def watch(brief_path: Path, slot: Path, *, interval: float = MIN_INTERVAL_S, #: The stream may attach this long before `dispatched:` … ATTACH_BEFORE_S = 30 * 60 #: … and runs until this long after `review-at:` (the late-sweep window, -#: human ruling H2). -LATE_WINDOW_S = 45 * 60 +#: human ruling H2) — the watcher's own end (M3.6a, PyAutoBrain#659). +LATE_WINDOW_S = _brief.LATE_WINDOW_S #: Events printed on attach without `--from`. CATCH_UP = 5 #: Exit codes: done (shift over, STOP, window), refused, segment over. diff --git a/bin/systemd/pyauto-orchestrator.service b/bin/systemd/pyauto-orchestrator.service index f6832365..e8039e51 100644 --- a/bin/systemd/pyauto-orchestrator.service +++ b/bin/systemd/pyauto-orchestrator.service @@ -18,4 +18,7 @@ Type=oneshot # on a machine without systemd-run, is still spared. KillMode=process EnvironmentFile=%h/.config/pyauto/orchestrator.env -ExecStart=/usr/bin/env python3 ${PYAUTO_BRAIN}/bin/orchestrator_watch.py --brief ${PYAUTO_SHIFT_BRIEF} --mind ${PYAUTO_MIND} +# The tick finds the one open brief on PyAutoMind origin/main itself (M3.6a, +# PyAutoBrain#659). PYAUTO_SHIFT_BRIEF in the env file is only an override, +# honoured inside that brief's own window (dispatched -> review-at + 45 min). +ExecStart=/usr/bin/env python3 ${PYAUTO_BRAIN}/bin/orchestrator_watch.py --mind ${PYAUTO_MIND} diff --git a/skills/batch/batch.md b/skills/batch/batch.md index a19cdabc..7a59dd33 100644 --- a/skills/batch/batch.md +++ b/skills/batch/batch.md @@ -74,9 +74,8 @@ In order: `expected-effects:` and **`review-at:`** — **before** any session starts; that file makes the launch auditable. `review-at:` is when the human expects to be back and where the grant expires: **if they did not say, ask before - dispatching** — never infer it from a schedule, a previous batch, or the - time of day. **If they will want to *run* the batch, write - `- integration: yes` into the record** (collect then builds the worktree). + dispatching** — never infer it from a schedule, a previous batch, or the time of day. **If they will want to *run* the batch, write `- integration: yes` into the record** (collect then builds the worktree). + **A shift brief** (`brief --new … --out` makes its shift issue; `--check`; push = launch): [`reference.md`](reference.md) "Launching a shift brief". 3. Start one session per member, each carrying `/start_dev --auto` plus the member-session contract below (the batch record informs a member of the shift's grant at leg 4, not the dispatch line). Spawn them if this harness @@ -97,7 +96,7 @@ In order: 5. Confirm what was dispatched, and stop. Do not follow the runs. **Brief verbs** (`batch brief --check`, `batch plan --brief`, `batch digest`): -[`reference.md`](reference.md). Run the check before writing a brief's `review-at:`. `brief --new` also runs the keep-Heart-green lane: a `## Heart` section and up to 3 bug drafts for fixable Heart reasons (only with `--out` and a non-shared `--mind`; named as tasks only with `--green pick`); it never releases (`batch green` = dry run; `agents/conductors/batch/AGENTS.md`). +[`reference.md`](reference.md). Run the check before pushing a brief; it refuses a live brief without `issue:` or with an expired CLI login. `brief --new` also runs the keep-Heart-green lane: a `## Heart` section and up to 3 bug drafts for fixable Heart reasons (only with `--out` and a non-shared `--mind`; named as tasks only with `--green pick`); it never releases (`batch green` = dry run; `agents/conductors/batch/AGENTS.md`). ## The watcher (phases 3a–3d) diff --git a/skills/batch/reference.md b/skills/batch/reference.md index 609a5df0..210cf498 100644 --- a/skills/batch/reference.md +++ b/skills/batch/reference.md @@ -84,10 +84,31 @@ tasks first, then only the backlog its policy covers, against its `review-minutes:`. Run the check before writing a brief's `review-at:` into `batches/`. The check also runs `batch premise` on each named task and warns when one is **obsolete on main** (`--no-premise` skips it) — drop that task -before the shift pays a worker to find out. Dispatch is the watcher's (`batch.md`, "The watcher"), not a verb. `batch digest +before the shift pays a worker to find out. For a live brief (not `shadow: yes`) +the check also refuses a missing `issue:` and a CLI login that has expired or +expires before `review-at:` (`claude auth status --json`, no model call; the +human runs `claude /login`). `batch brief --new --review-at --out +` makes that shift issue on PyAutoMind (one `gh issue create`) and +writes it as `issue:`; `--issue ` names one instead, and a file that +already has one keeps it. Dispatch is the watcher's (`batch.md`, "The watcher"), not a verb: +it finds the one open brief on Mind `origin/main` (only a pushed brief opens; +two open briefs tick neither) and ends at `review-at:` + 45 min. `batch digest --record ` prints a shift's digest and writes nothing; the record append and the one issue comment are the watcher's, at `review-at:`. +## Launching a shift brief + +Compose it with `batch brief --new --review-at --out `, +which also makes the shift issue on PyAutoMind and writes `issue:` +(2026-11-17). Then run `batch brief --check `: it refuses a live brief +without `issue:`, and an expired CLI login (the human runs `claude /login`). +**Pushing the brief is the launch.** The watcher finds it on Mind +`origin/main` itself, ticks it from `dispatched:` to `review-at:`, and stops +45 min after `review-at:`. Never two open briefs at once. The watcher reads +the `origin/main` ref of the Mind checkout in its env file **without +fetching**, so push the brief from that checkout or `git fetch` it before +launch; otherwise the watcher idles with "no open brief". + ## Collect: gathering the evidence - **Gather the evidence, then hand it over.** Collect has no GitHub of its diff --git a/tests/conftest.py b/tests/conftest.py index 21c547eb..6593db70 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -27,6 +27,16 @@ def _no_real_heart_lane(monkeypatch): monkeypatch.setenv("PYAUTO_HEART_GREEN", "off") +@pytest.fixture(autouse=True) +def _no_real_launch_probes(monkeypatch): + """M3.6a (PyAutoBrain#659): `brief --check` and the watcher's first tick + run `claude auth status --json`, and `brief --new --out` makes one `gh + issue create`. Both off in tests; a test that wants them deletes the + variable and puts a fake `claude` / `gh` on PATH.""" + monkeypatch.setenv("PYAUTO_LOGIN_PROBE", "off") + monkeypatch.setenv("PYAUTO_BRIEF_ISSUE", "off") + + @pytest.fixture(autouse=True) def _no_real_github(monkeypatch): """The shift watcher's GitHub seams never reach GitHub from a test diff --git a/tests/test_batch_brief.py b/tests/test_batch_brief.py new file mode 100644 index 00000000..b7fc301c --- /dev/null +++ b/tests/test_batch_brief.py @@ -0,0 +1,189 @@ +"""Shift launch preflight (M3.6a, PyAutoBrain#659): `batch brief --new` makes +the shift issue, and `batch brief --check` refuses a live brief that has no +issue or whose CLI login has expired. + +`gh` and `claude` are fakes on PATH: no issue is created and no model is +called. Fictional fixtures only. +""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +BATCH = BRAIN / "agents" / "conductors" / "batch" +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +sys.path.insert(0, str(BATCH)) +import _batch # noqa: E402 + +ISSUE = "https://github.com/example-org/PyAutoMind/issues/42" +GOALS = "# Goals\n\n## 1. Land the flywheel rework\n- epics: flywheel-rework\n" +EXPIRED = "CLI login expired: run `claude /login`" + +BRIEF = """\ +# Batch 2026-11-17 pm +- dispatched: 2026-11-17T13:00Z +- review-at: 2099-01-01T12:00Z +{issue}- brief: + - goals: + - 1. Land the flywheel rework + - backlog: fill-idle + - review-minutes: 45 + - lanes: any + - merge-cap: 0 + - token-budget: 5000000 +{extra}""" + + +def _git(cwd, *args): + env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid") + subprocess.run(["git", "-C", str(cwd), *args], check=True, env=env, capture_output=True) + + +def _mind(tmp_path: Path) -> Path: + """A Mind checkout whose origin is a (fictional) GitHub PyAutoMind.""" + mind = tmp_path / "mind" + (mind / "draft" / "feature" / "x").mkdir(parents=True) + (mind / "batches").mkdir() + (mind / "goals.md").write_text(GOALS, encoding="utf-8") + _git(mind, "init", "-q") + _git(mind, "remote", "add", "origin", "https://github.com/example-org/PyAutoMind.git") + return mind + + +def _fake(tmp_path: Path, monkeypatch, name: str, out: str, rc: int = 0) -> Path: + """A fake `name` on PATH that logs its argv and prints `out` (from a file, + so a test can change it between calls).""" + bindir = tmp_path / "bin" + bindir.mkdir(exist_ok=True) + log, text, code = (tmp_path / f"{name}.log", tmp_path / f"{name}.out", + tmp_path / f"{name}.rc") + text.write_text(out) + code.write_text(str(rc)) + (bindir / name).write_text(f"#!/bin/sh\necho \"$@\" >> {log}\ncat {text}\n" + f"exit $(cat {code})\n") + (bindir / name).chmod(0o755) + monkeypatch.setenv("PATH", f"{bindir}:{os.environ['PATH']}") + return log + + +def _calls(log: Path) -> list[str]: + """One entry per `gh` call (the issue body spans lines).""" + return [ln for ln in log.read_text().splitlines() if ln.startswith("issue create")] + + +def _brief(tmp_path: Path, issue: str = ISSUE, extra: str = "") -> Path: + f = tmp_path / "brief.md" + f.write_text(BRIEF.format(issue=f"- issue: {issue}\n" if issue else "", extra=extra)) + return f + + +def _check(brief: Path, mind: Path, capsys, *more) -> tuple[int, str]: + capsys.readouterr() + rc = _batch.main(["brief", "--check", str(brief), "--mind", str(mind), + "--no-premise", *more]) + return rc, capsys.readouterr().out + + +# --- Witness 1: `--new` creates one shift issue and writes it -------------------- + +def test_new_creates_one_shift_issue_and_writes_it(tmp_path, monkeypatch, capsys): + monkeypatch.delenv("PYAUTO_BRIEF_ISSUE", raising=False) + mind = _mind(tmp_path) + log = _fake(tmp_path, monkeypatch, "gh", ISSUE + "\n") + out = tmp_path / "2026-11-17-pm.md" + argv = ["brief", "--new", "2026-11-17-pm", "--review-at", "2099-01-01T12:00Z", + "--mind", str(mind), "--out", str(out)] + assert _batch.main(argv) == 0 + assert f"- issue: {ISSUE}\n" in out.read_text() + calls = _calls(log) + assert len(calls) == 1, calls + assert calls[0].startswith("issue create --repo example-org/PyAutoMind --title Shift " + "2026-11-17-pm") + # Run again on the same file: the issue it names is reused, never a second. + assert _batch.main(argv) == 0 + assert len(_calls(log)) == 1 + assert out.read_text().count("- issue: ") == 1 + # The written brief passes the launch check (login probe off in tests). + assert _check(out, mind, capsys)[0] == 0 + + +def test_new_writes_nothing_when_gh_fails(tmp_path, monkeypatch, capsys): + monkeypatch.delenv("PYAUTO_BRIEF_ISSUE", raising=False) + mind = _mind(tmp_path) + _fake(tmp_path, monkeypatch, "gh", "", rc=1) + out = tmp_path / "2026-11-17-pm.md" + rc = _batch.main(["brief", "--new", "2026-11-17-pm", "--review-at", + "2099-01-01T12:00Z", "--mind", str(mind), "--out", str(out)]) + assert rc == _batch.RC_FINDINGS and not out.exists() + assert "shift issue" in capsys.readouterr().err + + +def test_new_takes_a_given_issue_and_makes_none(tmp_path, monkeypatch): + monkeypatch.delenv("PYAUTO_BRIEF_ISSUE", raising=False) + mind = _mind(tmp_path) + log = _fake(tmp_path, monkeypatch, "gh", "") + out = tmp_path / "2026-11-17-pm.md" + assert _batch.main(["brief", "--new", "2026-11-17-pm", "--review-at", + "2099-01-01T12:00Z", "--mind", str(mind), "--out", str(out), + "--issue", ISSUE]) == 0 + assert f"- issue: {ISSUE}\n" in out.read_text() and not log.exists() + + +# --- Witness 2: a live brief without `issue:` is refused --------------------------- + +def test_check_refuses_a_live_brief_without_issue(tmp_path, capsys): + mind = _mind(tmp_path) + rc, out = _check(_brief(tmp_path, issue=""), mind, capsys) + assert rc == _batch.RC_FINDINGS + assert ("issue: missing — a live brief needs its shift issue " + "(batch brief --new creates it)") in out + # A shadow shift spawns nothing and posts nothing: no issue needed. + rc, out = _check(_brief(tmp_path, issue="", extra=" - shadow: yes\n"), mind, capsys) + assert rc == 0, out + + +# --- Witness 3: an expired CLI login refuses the launch ------------------------------ + +def test_check_refuses_on_expired_login(tmp_path, monkeypatch, capsys): + monkeypatch.delenv("PYAUTO_LOGIN_PROBE", raising=False) + mind = _mind(tmp_path) + log = _fake(tmp_path, monkeypatch, "claude", + "Login reached its time limit. Run /login to sign in again.\n", rc=1) + brief = _brief(tmp_path) + rc, out = _check(brief, mind, capsys) + assert rc == _batch.RC_FINDINGS + assert f"login: {EXPIRED}" in out + assert log.read_text().splitlines() == ["auth status --json"] # no model call + + # Logged in, but the login lapses before review-at: refused, naming the expiry. + (tmp_path / "claude.out").write_text( + '{"loggedIn": true, "loginExpiresAt": "2098-06-01T00:00:00.000Z"}\n') + (tmp_path / "claude.rc").write_text("0") + rc, out = _check(brief, mind, capsys) + assert rc == _batch.RC_FINDINGS and "2098-06-01T00:00:00.000Z" in out + + # Logged in past review-at: the launch passes. + (tmp_path / "claude.out").write_text( + '{"loggedIn": true, "loginExpiresAt": "2099-06-01T00:00:00.000Z"}\n') + rc, out = _check(brief, mind, capsys) + assert rc == 0, out + + +def test_a_write_failure_after_the_issue_names_it_for_a_rerun(tmp_path, monkeypatch, capsys): + """The issue is made just before the write; if the write still fails, its + URL is printed so a re-run reuses it rather than making a second.""" + monkeypatch.delenv("PYAUTO_BRIEF_ISSUE", raising=False) + mind = _mind(tmp_path) + log = _fake(tmp_path, monkeypatch, "gh", ISSUE + "\n") + out = tmp_path / "no-such-dir" / "2026-11-17-pm.md" + rc = _batch.main(["brief", "--new", "2026-11-17-pm", "--review-at", "2099-01-01T12:00Z", + "--mind", str(mind), "--out", str(out)]) + assert rc == _batch.RC_FINDINGS and not out.exists() + err = capsys.readouterr().err + assert ISSUE in err and f"--issue {ISSUE}" in err + assert len(_calls(log)) == 1 diff --git a/tests/test_batch_brief_goals.py b/tests/test_batch_brief_goals.py index 376bde92..03ff6a5d 100644 --- a/tests/test_batch_brief_goals.py +++ b/tests/test_batch_brief_goals.py @@ -80,9 +80,12 @@ def test_new_prefills_goals_and_passes_check(tmp_path, capsys): mind = _mind(tmp_path) out = tmp_path / "brief.md" rc = _batch.main(["brief", "--new", "2026-11-14-am", "--review-at", - "2099-01-01T12:00Z", "--mind", str(mind), "--out", str(out)]) + "2099-01-01T12:00Z", "--mind", str(mind), "--out", str(out), + "--issue", "https://github.com/example-org/PyAutoMind/issues/1"]) assert rc == 0 text = out.read_text() + # A live brief needs its shift issue (M3.6a, PyAutoBrain#659). + assert "- issue: https://github.com/example-org/PyAutoMind/issues/1\n" in text assert (" - goals:" in text and " - 1. Land the flywheel rework\n" " - 2. Clear review-ready PRs\n" in text) assert " - backlog: scoped" in text @@ -147,7 +150,8 @@ def test_new_needs_a_slot_and_a_review_at(tmp_path): def test_check_warns_when_goal_one_is_missing_from_the_brief(tmp_path, capsys): mind = _mind(tmp_path) out = tmp_path / "brief.md" - text = _batch.new_brief(mind, "2026-11-14-am", "2099-01-01T12:00Z") + text = _batch.new_brief(mind, "2026-11-14-am", "2099-01-01T12:00Z", + issue="https://github.com/example-org/PyAutoMind/issues/1") out.write_text(text.replace("1. Land the flywheel rework", "1. Something else")) assert _batch.main(["brief", "--check", str(out), "--mind", str(mind), "--no-premise"]) == 0 diff --git a/tests/test_orchestrator_dispatch.py b/tests/test_orchestrator_dispatch.py index 5736e4eb..758975ad 100644 --- a/tests/test_orchestrator_dispatch.py +++ b/tests/test_orchestrator_dispatch.py @@ -849,5 +849,11 @@ def test_a_parked_worker_that_ends_without_a_done_is_released_not_a_crash(tmp_pa def test_main_prints_a_digest_tick_without_a_keyerror(tmp_path, monkeypatch, capsys): monkeypatch.setattr(orch, "tick", lambda *a, **k: {"action": "digest", "post": None}) + # `--brief` is an override honoured inside its own window (M3.6a, #659). + now = _dt.datetime.now(_dt.timezone.utc) + hours = lambda h: (now + _dt.timedelta(hours=h)).strftime("%Y-%m-%dT%H:%MZ") # noqa: E731 + (tmp_path / "b.md").write_text(BRIEF.format(tasks="", budget=1, extra="") + .replace("2026-11-04T08:30Z", hours(-1)) + .replace("2026-11-04T11:30Z", hours(1))) assert orch.main(["--brief", str(tmp_path / "b.md"), "--mind", str(tmp_path)]) == 0 assert capsys.readouterr().out.startswith("digest: spawned 0") diff --git a/tests/test_orchestrator_events.py b/tests/test_orchestrator_events.py index d815a456..0e335205 100644 --- a/tests/test_orchestrator_events.py +++ b/tests/test_orchestrator_events.py @@ -182,7 +182,8 @@ def _every_kind_results(): (6, {"action": "ticked", "closeouts": {"started": [], "merged": [PR], "refused": [PR2, "https://github.com/o/r/pull/4"], "merged_outside": [PR2]}}, c), - (9, {"action": "ticked"}, c), + (9, {"action": "ticked", "login": {"state": "expired", "since": "2026-11-04T09:09:00Z", + "detail": "loggedIn: false"}}, c), (12, {"action": "stopped", "reason": "STOP written by /stop"}, c), (180, {"action": "digest", "post": {"posted": True, "url": "https://github.com/o/m/issues/1#issuecomment-5"}}, c), (183, {"action": "late", "late": ["- late: t8 — https://github.com/o/r/pull/7 (after review-at, 2026-11-04T12:33:00Z)"]}, c), diff --git a/tests/test_orchestrator_preflight.py b/tests/test_orchestrator_preflight.py new file mode 100644 index 00000000..bc6e668d --- /dev/null +++ b/tests/test_orchestrator_preflight.py @@ -0,0 +1,303 @@ +"""Shift launch preflight in the watcher (M3.6a, PyAutoBrain#659). + +- an expired CLI login is its own `login-expired` event and holds spawning — + never "blocked on a person"; +- the watcher finds the one open brief on Mind `origin/main` itself (no + fetch), and idles when two are open; +- after `review-at:` + 45 min, with the digest posted, a tick does nothing: + no lock, no reap, no lease write, no log line. + +`claude` is a fake on PATH and workers are `FakeClaude` / fake-mode stubs; +nothing reaches GitHub or starts a session. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import os +import subprocess +from pathlib import Path + +import test_orchestrator_dispatch as d # noqa: E402 — the 3b fixtures +from test_orchestrator_dispatch import orch # noqa: E402 + +NOW = d.NOW # 2026-11-04T09:00Z +MIN = _dt.timedelta(minutes=1) + + +def _fake_claude(tmp_path: Path, monkeypatch, out: str, rc: int = 0) -> Path: + """A fake `claude` on PATH for `claude auth status --json` (the probe).""" + bindir = tmp_path / "bin" + bindir.mkdir(exist_ok=True) + log, text, code = tmp_path / "claude.log", tmp_path / "claude.out", tmp_path / "claude.rc" + text.write_text(out) + code.write_text(str(rc)) + (bindir / "claude").write_text(f"#!/bin/sh\necho \"$@\" >> {log}\ncat {text}\n" + f"exit $(cat {code})\n") + (bindir / "claude").chmod(0o755) + monkeypatch.setenv("PATH", f"{bindir}:{os.environ['PATH']}") + return log + + +OK_JSON = '{"loggedIn": true, "loginExpiresAt": "2099-01-01T00:00:00.000Z"}\n' +EXPIRED_LINE = "CLI login expired: run `claude /login`. No worker starts until it passes." + + +# --- Witness 3 (watcher half): the first tick logs login-expired ------------------ + +def test_first_tick_logs_login_expired_not_blocked(tmp_path, monkeypatch): + monkeypatch.delenv("PYAUTO_LOGIN_PROBE", raising=False) + log = _fake_claude(tmp_path, monkeypatch, + "Login reached its time limit. Run /login to sign in again.\n", rc=1) + mind, brief, home = d._shift(tmp_path) + claude = d.FakeClaude() + r = d._tick(brief, mind, home, NOW, claude) + assert r["spawned"] == [] and claude.calls == [], "no worker starts on an expired login" + assert r["login"]["state"] == "expired" + slot = orch.slot_dir(brief, home) + events = orch._events.read_events(slot) + ours = [e for e in events if e["kind"] == "login-expired"] + assert [e["line"] for e in ours] == [EXPIRED_LINE] and ours[0]["needs_you"] + assert not any("blocked on a person" in e["line"] or e["kind"] == "parked" + for e in events) + assert "blocked on a person" not in (slot / orch.LOG_FILE).read_text() + assert log.read_text().splitlines() == ["auth status --json"] + + # Logged in again: the next tick starts the worker; the event is not repeated. + (tmp_path / "claude.out").write_text(OK_JSON) + (tmp_path / "claude.rc").write_text("0") + r = d._tick(brief, mind, home, NOW + 3 * MIN, claude) + assert [s["task"] for s in r["spawned"]] == ["t1"] + assert [e["kind"] for e in orch._events.read_events(slot)].count("login-expired") == 1 + # Once it passed, it is not probed again while no worker shows blocked. + d._tick(brief, mind, home, NOW + 6 * MIN, claude, + agents=d._agents({"t1": "working"}, slot)) + assert len(log.read_text().splitlines()) == 2 + + +def test_a_blocked_worker_reprobes_the_login(tmp_path, monkeypatch): + monkeypatch.delenv("PYAUTO_LOGIN_PROBE", raising=False) + log = _fake_claude(tmp_path, monkeypatch, OK_JSON) + mind, brief, home = d._shift(tmp_path, names=("t1", "t2"), + extra=" - max-workers: 1\n") + claude = d.FakeClaude() + assert [s["task"] for s in d._tick(brief, mind, home, NOW, claude)["spawned"]] == ["t1"] + slot = orch.slot_dir(brief, home) + (tmp_path / "claude.out").write_text('{"loggedIn": false}\n') + r = d._tick(brief, mind, home, NOW + 3 * MIN, claude, + agents=d._agents({"t1": "blocked"}, slot)) + assert r["login"]["state"] == "expired" and r["spawned"] == [] + assert len(log.read_text().splitlines()) == 2 + assert [e["line"] for e in orch._events.read_events(slot) + if e["kind"] == "login-expired"] == [EXPIRED_LINE] + + +# --- Witness 4: the watcher finds the open brief on Mind origin/main ---------------- + +BRIEF = """\ +# Batch {name} +- dispatched: {dispatched} +- review-at: {review_at} +- brief: + - goals: + - 1. sandbox shift + - backlog: none + - review-minutes: 45 + - lanes: any local-dev + - merge-cap: 0 + - token-budget: 100000 + - sandbox: yes +""" + + +def _git(cwd, *args, check=True): + env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", + GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid") + return subprocess.run(["git", "-C", str(cwd), *args], check=check, env=env, + capture_output=True, text=True) + + +def _iso(t: _dt.datetime) -> str: + return t.strftime("%Y-%m-%dT%H:%MZ") + + +def _origin(tmp_path: Path, briefs: dict) -> tuple[Path, Path]: + """(seed clone, Mind clone): `briefs` {name: (dispatched, review_at)} pushed + to a bare origin, then cloned as the Mind checkout the watcher reads.""" + bare, seed, mind = tmp_path / "PyAutoMind.git", tmp_path / "seed", tmp_path / "mind" + _git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare)) + _git(tmp_path, "clone", "-q", str(bare), str(seed)) + (seed / "draft").mkdir() + (seed / "draft" / "README.md").write_text("drafts\n") + (seed / "batches").mkdir() + (seed / "batches" / "AGENTS.md").write_text("# batches\n") + _push(seed, briefs) + _git(tmp_path, "clone", "-q", str(bare), str(mind)) + return seed, mind + + +def _push(seed: Path, briefs: dict) -> None: + for name, (start, end) in briefs.items(): + (seed / "batches" / f"{name}.md").write_text( + BRIEF.format(name=name, dispatched=_iso(start), review_at=_iso(end))) + _git(seed, "add", "-A") + _git(seed, "commit", "-qm", "briefs") + _git(seed, "push", "-q", "origin", "HEAD:main") + + +def test_watch_ticks_the_one_open_brief_on_origin(tmp_path, monkeypatch): + monkeypatch.setenv(orch.FAKE_ENV, "1") + _, mind = _origin(tmp_path, { + "2026-11-04-am": (NOW - 30 * MIN, NOW + 150 * MIN), # open now + "2026-11-04-pm": (NOW + 240 * MIN, NOW + 420 * MIN)}) # not yet open + # Written but never pushed: only a pushed brief opens. + (mind / "batches" / "2026-11-04-x.md").write_text(BRIEF.format( + name="x", dispatched=_iso(NOW - 10 * MIN), review_at=_iso(NOW + 60 * MIN))) + home = tmp_path / "home" + r = orch.watch(mind, home=home, now=NOW) + assert list(r["ticked"]) == ["2026-11-04-am"], r + assert r["ticked"]["2026-11-04-am"]["action"] == "ticked" + assert (home / "2026-11-04-am" / orch.LOG_FILE).is_file() + assert not (home / "2026-11-04-pm").exists() and not (home / "2026-11-04-x").exists() + # A `--brief` override outside its own window is not honoured. + r = orch.watch(mind, home=home, now=NOW + 3 * MIN, + override=mind / "batches" / "2026-11-04-pm.md") + assert list(r["ticked"]) == ["2026-11-04-am"] + assert not (home / "2026-11-04-pm").exists() + + +def test_a_pushed_brief_the_checkout_lacks_idles(tmp_path, monkeypatch): + monkeypatch.setenv(orch.FAKE_ENV, "1") + seed, mind = _origin(tmp_path, {}) + _push(seed, {"2026-11-04-am": (NOW - 30 * MIN, NOW + 150 * MIN)}) + _git(mind, "fetch", "-q", "origin") # the ref moves; the tree does not + r = orch.watch(mind, home=tmp_path / "home", now=NOW) + assert r["action"] == "idle" + assert "pushed, but the Mind checkout is behind" in r["reason"] + + +def test_two_open_briefs_idle(tmp_path, monkeypatch, capsys): + monkeypatch.setenv(orch.FAKE_ENV, "1") + monkeypatch.delenv("PYAUTO_SHIFT_BRIEF", raising=False) + now = _dt.datetime.now(_dt.timezone.utc) + _, mind = _origin(tmp_path, {"2026-11-04-am": (now - 60 * MIN, now + 120 * MIN), + "2026-11-04-pm": (now - 30 * MIN, now + 180 * MIN)}) + home = tmp_path / "home" + assert orch.main(["--mind", str(mind), "--home", str(home)]) == 0 + assert capsys.readouterr().out.strip() == ( + "idle: two open briefs on origin/main (2026-11-04-am, 2026-11-04-pm)") + assert not home.exists() or not any(home.iterdir()), "no slot was ticked" + + +# --- Witness 5: after review-at + 45 min a tick does nothing ------------------------ + +def test_after_late_window_no_tick_and_lease_mtime_unchanged(tmp_path, monkeypatch): + monkeypatch.setenv("PYAUTO_LOGIN_PROBE", "off") + mind, brief, home = d._shift(tmp_path) # review-at 11:30Z + claude = d.FakeClaude() + assert d._tick(brief, mind, home, NOW, claude)["spawned"] + slot = orch.slot_dir(brief, home) + review_at = _dt.datetime(2026, 11, 4, 11, 30, tzinfo=_dt.timezone.utc) + r = d._tick(brief, mind, home, review_at + MIN, claude, + agents=d._agents({"t1": "working"}, slot)) + assert r["action"] == "digest" and (slot / orch.DIGEST_MARKER).exists() + lease_files = sorted((slot / "leases").glob("*.json")) + assert lease_files, "the worker is still out after the digest" + for f in lease_files: + os.utime(f, (1_000_000_000, 1_000_000_000)) + before = {f: f.stat().st_mtime for f in lease_files} + log_before = (slot / orch.LOG_FILE).read_text() + + r = d._tick(brief, mind, home, review_at + 46 * MIN, claude, + agents=d._agents({"t1": "working"}, slot)) + assert r["action"] == "idle" and "late window closed" in r["reason"], r + assert {f: f.stat().st_mtime for f in lease_files} == before + assert (slot / orch.LOG_FILE).read_text() == log_before + assert not (slot / orch.LOCK_FILE).exists() + json.dumps(r) + + +# --- review findings (M3.6a, #659): the override and the end ------------------------- + +def _names(paths) -> list[str]: + return [Path(p).stem for p in paths] + + +def test_a_stale_override_in_its_late_window_does_not_displace_the_open_brief(tmp_path): + """The env file still names shift A, ended 10 min ago; shift B is open. + B is ticked, and A alongside it as one more late brief.""" + _, mind = _origin(tmp_path, { + "2026-11-04-am": (NOW - 180 * MIN, NOW - 10 * MIN), + "2026-11-04-pm": (NOW - 5 * MIN, NOW + 180 * MIN)}) + paths, why = orch.find_briefs(mind, NOW, override=mind / "batches" / "2026-11-04-am.md", + home=tmp_path / "home") + assert _names(paths) == ["2026-11-04-pm", "2026-11-04-am"], (paths, why) + # An override that is itself open still takes the open brief's place. + paths, _ = orch.find_briefs(mind, NOW, override=mind / "batches" / "2026-11-04-pm.md", + home=tmp_path / "home") + assert _names(paths) == ["2026-11-04-pm", "2026-11-04-am"] + + +def test_a_brief_past_its_late_window_is_caught_up_until_its_digest_is_out(tmp_path): + """The laptop was off through the late window: the digest is still owed, + so the brief is still ticked; once it is posted and nothing is owed, not.""" + _, mind = _origin(tmp_path, {"2026-11-04-am": (NOW - 300 * MIN, NOW - 120 * MIN)}) + home = tmp_path / "home" + slot = home / "2026-11-04-am" + (slot / "leases").mkdir(parents=True) + assert _names(orch.find_briefs(mind, NOW, home=home)[0]) == ["2026-11-04-am"] + (slot / orch.DIGEST_MARKER).write_text(json.dumps({"state": "failed", "tries": 1})) + assert _names(orch.find_briefs(mind, NOW, home=home)[0]) == ["2026-11-04-am"] + (slot / orch.DIGEST_MARKER).write_text(json.dumps({"state": "posted", "tries": 1})) + assert orch.find_briefs(mind, NOW, home=home)[0] == [] + # A slot the watcher never touched is not caught up. + assert orch.find_briefs(mind, NOW, home=tmp_path / "other")[0] == [] + + +def _ended_shift(tmp_path, monkeypatch): + """Witness 5's shift: digest out at review-at, the worker still out.""" + monkeypatch.setenv("PYAUTO_LOGIN_PROBE", "off") + mind, brief, home = d._shift(tmp_path) + claude = d.FakeClaude() + d._tick(brief, mind, home, NOW, claude) + slot = orch.slot_dir(brief, home) + review_at = _dt.datetime(2026, 11, 4, 11, 30, tzinfo=_dt.timezone.utc) + d._tick(brief, mind, home, review_at + MIN, claude, agents=d._agents({"t1": "working"}, slot)) + return mind, brief, home, slot, claude, review_at + + +def test_the_late_window_stop_waits_for_a_due_digest_retry(tmp_path, monkeypatch): + mind, brief, home, slot, claude, review_at = _ended_shift(tmp_path, monkeypatch) + (slot / orch.DIGEST_MARKER).write_text(json.dumps( + {"state": "failed", "tries": 1, "issue": "", "at": "2026-11-04T11:31:00Z"})) + r = d._tick(brief, mind, home, review_at + 46 * MIN, claude, + agents=d._agents({"t1": "working"}, slot)) + assert "late window closed" not in str(r.get("reason")), r + + +def test_the_late_window_stop_waits_for_a_queued_mind_op(tmp_path, monkeypatch): + mind, brief, home, slot, claude, review_at = _ended_shift(tmp_path, monkeypatch) + orch._mind_writer.queue_op(slot / orch._mind_writer.LEDGER_DIR, + {"op": "append", "path": "batches/x.md", "text": "x"}) + r = d._tick(brief, mind, home, review_at + 46 * MIN, claude, + agents=d._agents({"t1": "working"}, slot)) + assert "late window closed" not in str(r.get("reason")), r + + +def test_a_slot_past_the_catch_up_cap_is_named_abandoned_once(tmp_path): + """Inside the 24 h catch-up a slot that owes its digest is ticked; past it + the tick does not, and says once which slot was left and what it owes.""" + review_at = NOW - 60 * MIN + _, mind = _origin(tmp_path, {"2026-11-04-am": (review_at - 180 * MIN, review_at)}) + home = tmp_path / "home" + (home / "2026-11-04-am" / "leases").mkdir(parents=True) + (home / "2026-11-04-am" / "leases" / "t1.json").write_text("{}") + cap = review_at + _dt.timedelta(seconds=orch._brief.LATE_WINDOW_S + orch.CATCH_UP_S) + assert _names(orch.find_briefs(mind, cap - MIN, home=home)[0]) == ["2026-11-04-am"] + paths, why = orch.find_briefs(mind, cap + MIN, home=home) + assert paths == [] + assert "abandoned: 2026-11-04-am past catch-up" in why, why + assert "digest not posted" in why and "1 lease" in why + # Named once, not every tick. + assert "abandoned" not in orch.find_briefs(mind, cap + 4 * MIN, home=home)[1] diff --git a/tests/test_premise_check.py b/tests/test_premise_check.py index a31a607b..f2297c21 100644 --- a/tests/test_premise_check.py +++ b/tests/test_premise_check.py @@ -399,6 +399,7 @@ def test_set_header_op_validates_and_applies(tmp_path): # Batch 2026-11-06 pm - dispatched: 2026-11-06T11:20Z - review-at: 2026-11-06T12:20Z +- issue: https://github.com/example-org/PyAutoMind/issues/1 - brief: - goals: - 1. replay