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
44 changes: 42 additions & 2 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,37 @@ tests and the targeted smoke (leg 2), and opens the PR as soon as they pass

Outside a shift (an `--auto` chat) nothing changes.

Later rulings from the same review (S4, S7) are added to this section.
- **S7, `decision-taken` at PR-open** (M3.7c, PyAutoBrain#690). The
watcher refuses a `decision-taken` PR when it first sees it, from the
label alone. No close-out session starts, no merge slot is taken and CI
is not read. It reads the label once per PR per shift; a label it cannot
read is asked again next tick, never taken as absent, and after 3 misses
over 15 minutes the PR goes to the human's `/prm` and the digest counts it. The PR keeps its
place as an earlier PR in the merge order (M3.6j ruling c, unchanged), so
later unattended merges on that library wait for the human's `/prm`. The
digest names the PRs that waited behind a `/prm`-bound PR, one line per
library. The close-out's own label check stays as a second layer.

Watcher latency (M3.7c, the human's plan decisions of 2026-11-19):

- The watcher ticks every 60 seconds. A worker writes its `.done`, and a
close-out or branch update its `.closeout`, then appends a line to the
kick file (`$PYAUTO_SHIFT_KICK`, `~/.local/state/pyauto/orchestrator.kick`).
A systemd path unit starts a tick when it changes. The kick is best
effort. A kick that lands while a tick runs is dropped (the path unit is
edge-triggered), and the timer picks it up within 60 seconds.
- **Early close.** A shift posts its digest on the tick that leaves nothing
to do: no worker live, no re-dispatch owed, no close-out or branch update
running, every PR judged, no task that could still start, and nothing
this tick could not read (the steering comments, Mind `origin/main`). A PR waiting
behind a `/prm`-bound PR does not hold the shift open. The digest says
"closed early at <time>; review-at was <time>", and merges count up to the
close. A paused shift never closes early (decision 2). A task parked on a
question does not hold the shift open (decision 3); an answer after the
close resumes it in a later shift. A shift that never started anything,
or a shadow shift, stays open to `review-at:`.

A later ruling from the same review (S4) is added to this section.

## Merge authority follows Consequence — 2026-10-02

Expand Down Expand Up @@ -941,7 +971,10 @@ 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.
window has closed, it stops ticking the slot and renews no lease. A shift
with nothing left to do posts its digest early (M3.7c, "Shift speed —
2026-11-19"); from then on it is treated as after `review-at:`: no spawn, no
close-out, no second digest, and the late sweep only while something is owed.

*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 @@ -1240,6 +1273,13 @@ that library. It reads each PR's list at most once per shift and keeps it.
A repeat read for the same PR in one shift falls under the existing revert
condition.

**Amendment — 2026-11-19 (M3.7c, PyAutoBrain#690), approved by the human.**
For ruling S7 the watcher reads `labels` as one more field of the `gh pr
view` it already makes for its own workers' PRs: kept once read, once per PR
per shift. When GitHub cannot say it reads again, at most once a tick; after
3 misses over 15 minutes from first seeing the PR, the PR goes to `/prm`. The
kick file that starts a tick early is local and adds no network act.

**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)
Expand Down
46 changes: 46 additions & 0 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,52 @@ 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 tick, the kick and the early close (M3.7c, PyAutoBrain#690).** The timer
ticks every 60 seconds. `worker_env` sets `PYAUTO_SHIFT_KICK` to the kick file
(`kick_path`: `$XDG_STATE_HOME/pyauto/orchestrator.kick`, else
`~/.local/state/pyauto/orchestrator.kick`, systemd's `%S`). A worker appends a
line to it after its `.done`, and a close-out or branch update after its
`.closeout`, best effort. `bin/systemd/pyauto-orchestrator.path` starts a tick
when the file changes. `PathChanged` is edge-triggered: a kick that lands
while a tick runs is dropped, not queued, and the timer picks it up within 60
seconds. The service has no start limit (`StartLimitIntervalSec=0`) and the
path unit allows 20 triggers in 10 s. The
shift closes early on the tick that leaves nothing to do (`early_close_ready`):
not paused, not shadow, something started, no live lease, no re-dispatch owed,
no close-out or update running or waiting on its new head, every PR judged
(refused, merged, or waiting in merge order), and no task that could still
start (`startable`: a failed launch, an unreadable spend, an expired login).
Nothing this tick could not read: the steering comments (`commands_unread`)
or Mind `origin/main` (a draft held as `fail closed`) keeps it open. A
task held by a library, `max-sessions` or the token budget cannot start, and a
task parked on a question does not hold the shift open. `close_early` records
`counters["closed_early"]` and runs `finish_shift` with that time as the end.
The digest opens with `Closed early at <time>; review-at was <time>`. Later
ticks in the window run the late sweep while something is owed, else idle;
they read no steering, so an `/add` after the close does nothing.

**S7: `decision-taken` at PR-open (M3.7c).** `_start_closeouts` reads a new
PR's labels right after the tier check (`labels` in `gh_pr_state`, kept in
`counters["pr_labels"]`, once per PR per shift, after the carried-PR check;
unreadable means wait, at most one read a tick; after 3 misses over 15
minutes from first seen (`LABEL_READ_GRACE_S`) the PR goes to `/prm` as
`labels unreadable`, counted in the digest). A
`decision-taken` PR is refused (`decision-taken — the human's /prm`) with no
close-out, no merge slot and no CI read. It stays an earlier PR in the merge
order, so later PRs on its library wait until GitHub says MERGED or CLOSED.
The digest's `### Waited behind your /prm` names them, one line per library.

**Deploy.** Installing the units is the human's step, when no shift is live:

cp bin/systemd/pyauto-orchestrator.{service,timer,path} ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user restart pyauto-orchestrator.timer
systemctl --user enable --now pyauto-orchestrator.path

If the path unit ever shows failed (trigger limit hit, systemd 250 or later),
run `systemctl --user restart pyauto-orchestrator.path`. On systemd 249 the
`TriggerLimit` keys are ignored with a warning.

**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
Expand Down
66 changes: 65 additions & 1 deletion agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
import ci_verdict # noqa: E402

DIGEST_HEADING = "## Digest"
#: The tail of a watcher plan reason for a draft held because Mind
#: origin/main could not be read (`_orchestrator.on_origin`).
FAIL_CLOSED = "fail closed"
SECTIONS = ("### Brief work", "### Backlog picks", "### Proof packets", "### Counters")
#: Every counter, always printed — a zero is a fact, an absent line is a finding.
COUNTERS = ("merges", "glance-auto-merges", "reverts", "pushes", "drafts-filed",
Expand Down Expand Up @@ -354,6 +357,65 @@ def number(u):
return out


#: The heading of the PRs that waited behind a /prm-bound PR (S7, M3.7c).
WAITED_HEADING = "### Waited behind your /prm"


def _hhmm(iso: str) -> str:
"""`2026-11-04T09:01Z` from an ISO time; the text itself otherwise."""
iso = str(iso or "")
return iso[:16] + "Z" if len(iso) >= 16 and iso[10:11] == "T" else (iso or "?")


def closed_early_lines(counters: dict) -> list[str]:
"""One line when the shift closed before `review-at:` (M3.7c, #690)."""
at = counters.get("closed_early")
if not at:
return []
return [f"Closed early at {_hhmm(at)}; review-at was {_hhmm(counters.get('review_at'))} "
"— nothing was left to run, start or judge.", ""]


def waited_lines(counters: dict) -> list[str]:
"""The PRs that waited in merge order behind an earlier PR bound for the
human's /prm (S7, M3.7c, PyAutoBrain#690): one line per library repo and
set of blockers, from `merge_waits` at close and the refused close-outs —
`autogalaxy: #8, #9 waited behind #7 (/prm-bound: decision-taken)` — after
a count; and how many PRs were refused because their labels could not be
read (S7). Empty when there is neither."""
cos = counters.get("closeouts") or {}
refused = {u: co for u, co in cos.items() if co.get("state") == "refused"}
groups: dict[tuple, list[str]] = {}
for url, info in (counters.get("merge_waits") or {}).items():
bound = [b for b in info.get("behind") or [] if b in refused]
if not bound:
continue
m = _PR_REF_RE.match(url)
repo = m.group(1) if m else "?"
groups.setdefault((repo, tuple(bound)), []).append(url)
unread = [u for u, co in refused.items()
if str(co.get("why") or "").startswith("labels unreadable")]
if not groups and not unread:
return []

def num(u):
m = _PR_REF_RE.match(u)
return int(m.group(2)) if m else 0
n = sum(len(v) for v in groups.values())
out = ["", WAITED_HEADING] + ([f"- {n} PR(s) waited behind a /prm-bound PR"] if n else [])
if unread: # review round 1: label reads that never succeeded (S7)
out.append(f"- {len(unread)} PR(s) refused: labels unreadable (at most one read a "
"tick, refused after 3 misses over 15 minutes) — "
+ ", ".join(pr_ref(u) for u in unread))
for (repo, bound), urls in groups.items():
whys = "; ".join(dict.fromkeys(str(refused[b].get("why") or "?").split(" — ", 1)[0]
for b in bound))
out.append(f"- {repo}: " + ", ".join(f"#{num(u)}" for u in sorted(urls, key=num))
+ " waited behind " + ", ".join(f"#{num(b)}" for b in bound)
+ f" (/prm-bound: {whys})")
return out


def has_slot(counters: dict, task: str, url: str) -> bool:
"""Whether the shift's merge-slot file (as last synced into `counters`
as `slot_holders`) shows a slot for this PR held for this task."""
Expand Down Expand Up @@ -664,6 +726,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None,
backlog = [t for t in picks if t not in named]

lines = [DIGEST_HEADING, ""]
lines += closed_early_lines(counters)
# The one notice of the shift's parked questions (M3.5, #645, Decision
# H7 a): no @mention mid-shift, one line here; the asks live in the inbox.
inbox = [x for x in [_questions.inbox_line(counters, Path(slot).name, mind)]
Expand All @@ -681,6 +744,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None,
for t in backlog] or [NO_PICKS]
lines += backlog_gate_lines(counters)
lines += merge_order_lines(counters)
lines += waited_lines(counters)

started = [t for t in named + backlog
if t in counters.get("outcomes", {}) or t in counters.get("parked", [])
Expand Down Expand Up @@ -776,7 +840,7 @@ def backlog_gate_lines(counters: dict) -> list[str]:
out.append("Backlog dip stopped: queue.md is empty, so the shift took the "
"brief's named tasks only.")
origin = gates.get("origin") or {}
closed = {p: w for p, w in origin.items() if w.endswith("fail closed")}
closed = {p: w for p, w in origin.items() if w.endswith(FAIL_CLOSED)}
repo_held = {p: w for p, w in origin.items() if w.startswith("repo ") and p not in closed}
claimed = sorted(p for p in origin if p not in closed and p not in repo_held)

Expand Down
6 changes: 4 additions & 2 deletions agents/conductors/batch/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,11 +439,13 @@ def _digest_event(b: _Batch, result: dict, counters: dict) -> None:
if filed else
f" {len(parked)} task{'s' if len(parked) != 1 else ''} parked on a question."
if parked else "")
# An early close (M3.7c, #690) says so: the shift ended before review-at.
closed = "Shift closed early." if counters.get("closed_early") else "Shift closed."
if post.get("url"):
b.add("digest", "digest", f"Shift closed. Digest: {post['url']}.{tail}", url=post["url"])
b.add("digest", "digest", f"{closed} Digest: {post['url']}.{tail}", url=post["url"])
else:
why = post.get("error") or "not posted"
b.add("digest", "digest", f"Shift closed. Digest written to the record; its post: "
b.add("digest", "digest", f"{closed} Digest written to the record; its post: "
f"{why}.{tail}")


Expand Down
Loading
Loading