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
31 changes: 31 additions & 0 deletions AUTONOMY.md
Original file line number Diff line number Diff line change
Expand Up @@ -991,6 +991,37 @@ refuses the merge. A PR in any other repo makes no call at all. The revert
condition covers these the same way: any other call, or a repeat for the same
close-out, retires the watcher to fake mode.

**Amendment — 2026-11-16 (M3.4/M3.5; PyAutoBrain#644), approved by the human.**
The shift cockpit's engine (DESIGN `m3_4_m3_5_design`, rulings H4b, H5a, H6a,
H8a/a, H10a). The watcher's surface gains, and only:

1. **the per-shift `events.jsonl`** in its slot directory, appended inside the
tick lock from what the tick already did — local, no network, no LLM. `batch
watch --stream` reads it; it goes to neither Mind nor GitHub;
2. **`/add`** (one Mind `git fetch` per `/add` command, on top of the
once-per-shift fetch), **`/cap`**, and **`/kill`** (a local `claude stop` of a
worker the watcher started; not network). `/cap` lowers a cap, or raises it
back, never above the brief's own value. `/add` is refused within 30 minutes
of `review-at:`; it overrides the brief's `exclude:` and an earlier shift's
parked hold, never the organ rule. A worker stopped by `/kill` is
re-dispatched once, unless the human dropped the task first;
3. **needs-you event comments**, at most 5 + 1 per shift: one short comment on
the brief's `issue:` per event that needs the human (an ignored or refused
command, commands unread three ticks running, the watcher unable to post or
to write Mind, a dropped task's PR merged anyway), with no `@`, each claimed
by its marker before the post and counted in the digest apart from the
per-worker pushes; after the fifth, one last comment saying the rest are in
the status comment.

It makes no new CI read: `ci` lines come only from the `gh pr checks` the
close-outs already make (H10a). The 2026-11-13 `/drop` rule "a running worker is
not killed by the watcher" now reads "… unless the human commands `/kill`".
The revert condition now also covers a second Mind fetch for one `/add`
command, a `claude stop` of any session but a running worker of this shift the
human named in `/kill`, a needs-you comment beyond 5 + 1 in a shift or one with
an `@`, and any network call from writing or reading `events.jsonl`: any of
these retires the watcher to fake mode.

## Human override for Heart RED (development only)

Heart RED still parks every autonomous run and blocks every release. After the
Expand Down
22 changes: 20 additions & 2 deletions agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -492,14 +492,32 @@ task of this shift only, else "no such task in this shift"; `counters.json`
re-dispatched, its PR refused for close-out; a close-out already running checks
the marker just before merging and refuses, and a merge that lands anyway is
recorded as merged outside the close-out, with no stage-2 row; a live worker is
shown `dropped, still running` and stopping it is the human's, `claude stop
<id>`) and `/stop` (writes `STOP`; that tick commits nothing to Mind). Each comment acts once, by id, and is acknowledged
shown `dropped, still running` until the human stops it, by hand or by `/kill`)
and `/stop` (writes `STOP`; that tick commits nothing to Mind). PyAutoBrain#644
adds three, making seven: `/cap merges|workers|sessions|tokens <n>` (lowers a
cap for this shift, or raises it back, never above the brief's own value;
`_brief.effective` applies it from that tick), `/add <prompt>` (one Mind fetch
per command; the draft on origin/main becomes a named task, refused within 30
min of `review-at:`; it overrides `exclude:` and an earlier shift's parked hold,
never the organ rule) and `/kill <task>` (the watcher runs a local `claude stop`
on that task's running worker; the reap marks the exit `killed`, not crashed,
and it is re-dispatched once unless dropped first). Each comment acts once, by id, and is acknowledged
once in the status comment's `Commands` list. Without a login, nothing is read
and the comment says steering is off. The dashboard's copy is the record's `-
live:` line (`record-key` op, one Mind writer, on a change of state), shown in
the batch box. Doctrine: AUTONOMY.md watcher network surface, amendment
2026-11-13.

**The event stream (PyAutoBrain#644).** Every tick that does work appends what
it did to `<slot>/events.jsonl` (`_events.record_tick`, inside the tick lock,
local only), one plain line per event, deduplicated by key in the file itself;
`batch watch --stream` prints it until `shift-end`. A needs-you event (an
`ignored:`/`refused:` ack, commands unread three ticks running, the watcher
unable to post or write Mind, a dropped task's PR merged anyway) is also one
short comment on the brief's `issue:`, no `@`, marker `mentions/event.<seq>`,
at most 5 + 1 a shift, counted as `event_comments` apart from `pushes`.
Doctrine: AUTONOMY.md watcher network surface, amendment 2026-11-16 (#644).

**The watcher's GitHub identity (human rulings 2026-11-12, #611, and
2026-11-14, #630).** The watcher posts as its own minimal GitHub App,
`pyautolabs-watcher`, set by the human in the timer's environment
Expand Down
60 changes: 53 additions & 7 deletions agents/conductors/batch/_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,11 @@ def declared_repos(p: dict) -> list[str]:
return sorted(out) or list(p.get("repos") or [])


def grade(path: Path, mind: Path) -> dict:
"""Everything the planner needs about one prompt, from the faculty."""
p = parse_prompt(path, mind)
def grade(path: Path, mind: Path, text: str | None = None) -> dict:
"""Everything the planner needs about one prompt, from the faculty.
`text`, when given, is the prompt's content (`grade_text`): nothing else
is read by path."""
p = parse_prompt(path, mind, text=text)
level, score, factors, derived = effective_difficulty(p)
tier, why, _ = effective_consequence(p, factors)
ready, ready_why, _ = effective_unattended(p, level, factors, derived)
Expand Down Expand Up @@ -232,6 +234,21 @@ def survey(mind: Path) -> list[dict]:
return out


def grade_text(text: str, rel: str, mind: Path) -> dict:
"""One `survey` record from a prompt's text as Mind origin/main holds it
(`/add`, PyAutoBrain#644): the canonical working tree nobody pulls
mid-shift may not have it yet. `rel` is its Mind-relative path."""
g = grade(Path(mind) / rel, Path(mind), text=text)
g["path"] = rel
g["looks_shipped"] = rel in _shipped.flagged_paths(mind)
g["epic"] = _epic_of(text)
g["phase"] = _phase_of(text)
g["done"] = _is_done(text)
g["themes"] = _themes_of(text)
g["title"] = _title_of(text)
return g


def _title_of(text: str) -> str:
"""The prompt's first `# ` heading — what a human reads the pick by."""
for line in text.splitlines():
Expand Down Expand Up @@ -2931,9 +2948,10 @@ def main(argv=None) -> int:
"both fail closed; AUTONOMY.md M2 rulings)")
ap.add_argument("--json", action="store_true", dest="as_json")
# brief / plan
ap.add_argument("--check", default="", metavar="FILE",
ap.add_argument("--check", default="", metavar="FILE", nargs="?", const=True,
help="brief: validate this shift brief against "
"PyAutoMind/batches/AGENTS.md")
"PyAutoMind/batches/AGENTS.md; watch --stream: only say "
"whether the stream is attachable now (no FILE)")
ap.add_argument("--new", default="", metavar="SLOT",
help="brief: print a skeleton shift brief for SLOT (e.g. "
"2026-11-14-am) whose goals: come from goals.md; "
Expand Down Expand Up @@ -2971,6 +2989,14 @@ def main(argv=None) -> int:
help="watch: print one snapshot and exit")
ap.add_argument("--interval", type=float, default=30.0,
help="watch: seconds between refreshes (at least 30)")
ap.add_argument("--stream", action="store_true",
help="watch: print the shift's events, one plain line each, "
"until the shift ends (the cockpit's watch; local reads only)")
ap.add_argument("--from", type=int, default=None, dest="from_seq", metavar="SEQ",
help="watch --stream: print every event after this seq first")
ap.add_argument("--for", type=float, default=None, dest="for_min", metavar="MIN",
help="watch --stream: end this segment after MIN minutes "
"(prints `segment-end next=--from N`, exit 3)")
# premise (and the premise leg of `brief --check`)
ap.add_argument("--root", type=Path, default=None,
help="premise: the workspace root holding the repo checkouts "
Expand Down Expand Up @@ -3190,12 +3216,29 @@ def _main_digest(mind: Path, a) -> int:

def _main_watch(a) -> int:
"""`batch watch --record <file> [--once] [--interval N]` — a live view of a
running shift; writes nothing anywhere (`_watch`)."""
running shift; writes nothing anywhere (`_watch`). With `--stream`, the
shift's event stream (`_watch.stream`, PyAutoBrain#644)."""
import _watch
if isinstance(a.check, str) and a.check:
print("batch watch: --check takes no file (the record is --record)", file=sys.stderr)
return RC_USAGE
if a.stream or a.check is True:
env = _watch.env_file()
record = Path(a.record or env.get("PYAUTO_SHIFT_BRIEF") or "")
if not str(record) or not record.is_file():
print(f"batch watch --stream: no brief record ({record or 'none'}; pass --record "
"or set PYAUTO_SHIFT_BRIEF in the orchestrator env file)", file=sys.stderr)
return RC_USAGE
home = a.home or (Path(env["PYAUTO_ORCHESTRATOR_HOME"])
if env.get("PYAUTO_ORCHESTRATOR_HOME") else None)
import _orchestrator
return _watch.stream(record, _orchestrator.slot_dir(record, home),
from_seq=a.from_seq, for_min=a.for_min, as_json=a.as_json,
check=a.check is True)
if not a.record:
print("batch watch: --record <file> is required", file=sys.stderr)
return RC_USAGE
import _orchestrator
import _watch
record = Path(a.record)
if not record.is_file():
print(f"batch watch: no such brief record {record}", file=sys.stderr)
Expand Down Expand Up @@ -3327,6 +3370,9 @@ def _main_brief(mind: Path, a) -> int:
"""`batch brief --check <file>` — read-only; exit 0 valid, 1 refused.
`batch brief --new <slot> --review-at <ISO>` — print (or `--out`) a
skeleton brief whose goals come from goals.md."""
if a.check is True:
print("batch brief --check: name the brief FILE to check", file=sys.stderr)
return RC_USAGE
if a.new:
if a.check:
print("batch brief: --new and --check are separate runs", file=sys.stderr)
Expand Down
39 changes: 37 additions & 2 deletions agents/conductors/batch/_brief.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,39 @@ def cap_of(brief: dict, key: str) -> int:
return CAP_DEFAULTS[key] if value is None else value


#: The caps a `/cap` steering command may lower for one shift (#644).
CAP_KEYS = ("merge-cap", "max-workers", "max-sessions", "token-budget")


def effective(brief: dict, counters: dict | None) -> dict:
"""The brief as this shift now runs it (PyAutoBrain#644): a copy with each
`/cap` override's value (`counters["caps"]`) swapped in, and each task the
human `/add`ed (`counters["added"]`) appended to `tasks:` and taken out of
`exclude:` — the human's newer word, as a brief that names a task again.
The brief file is never changed; with nothing steered it is `brief` itself."""
caps = (counters or {}).get("caps") or {}
added = (counters or {}).get("added") or {}
if not brief or not (caps or added):
return brief
out = dict(brief)
for key, ov in caps.items():
if key in CAP_KEYS and isinstance(ov, dict) and "value" in ov:
out[key] = {**(brief.get(key) or {"children": []}), "value": str(ov["value"])}
prompts = [a["prompt"] for a in added.values() if isinstance(a, dict) and a.get("prompt")]
if prompts:
tasks = brief.get("tasks") or {"value": "", "children": []}
have = {Path(c["text"]).name for c in tasks["children"]}
out["tasks"] = {**tasks, "children": list(tasks["children"]) + [
{"text": p, "children": []} for p in prompts if Path(p).name not in have]}
names = {Path(p).name for p in prompts}
if brief.get("exclude"):
ex = brief["exclude"]
out["exclude"] = {**ex, "children": [c for c in ex["children"]
if Path(c["text"]).name not in names]}
out["added"] = {"value": " ".join(sorted(names)), "children": []}
return out


def worker_mode_of(brief: dict) -> str:
return brief.get("worker-mode", {}).get("value") or DEFAULT_WORKER_MODE

Expand Down Expand Up @@ -363,13 +396,15 @@ def scope(records: list[dict], brief: dict) -> tuple[list[dict], list[tuple[str,
ex_paths, ex_keyed = excluded_of(brief)
ex_names = {Path(p).name for p in ex_paths}
lanes = set(lanes_of(brief)) or {"any"}
# `/add`ed this shift (`effective`, #644): no `exclude:` rule holds it back.
added = set(_csv(brief.get("added", {}).get("value", "")))

kept, rejected = [], []
for r in records:
name = Path(r["path"]).name
themes = set(r.get("themes") or [])
if name in ex_names or r.get("epic") in ex_keyed.get("epics", []) \
or themes & set(ex_keyed.get("tags", [])):
if name not in added and (name in ex_names or r.get("epic") in ex_keyed.get("epics", [])
or themes & set(ex_keyed.get("tags", []))):
rejected.append((r["path"], "excluded by the brief"))
continue
if name not in named_names:
Expand Down
36 changes: 34 additions & 2 deletions agents/conductors/batch/_digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False,
return STILL_OUT, True
if task in counters.get("pending_redispatch", []):
if live:
return "crashed — awaiting re-dispatch", True
word = "killed by /kill" if task in (counters.get("killed") or {}) else "crashed"
return f"{word} — awaiting re-dispatch", True
return f"{NOT_REDISPATCHED}: {redispatch_why(task, counters)}", False
skipped = gate_why(task, counters)
return ("not started — skipped: " + skipped if skipped else "not started"), False
Expand Down Expand Up @@ -446,6 +447,7 @@ def label(task: str, pick: dict | None, url: str = "") -> str:
("blocked on a person", "Needs you — blocked on a person"),
("abandoned", "Abandoned — crashed twice"),
(NOT_REDISPATCHED, "Crashed — not re-dispatched"),
("killed by /kill", "Killed by /kill — waiting to be re-dispatched"),
("crashed", "Crashed — waiting to be re-dispatched"),
("ended", "Crashed"),
("obsolete", "Obsolete — nothing to do"),
Expand Down Expand Up @@ -563,6 +565,7 @@ def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None,
lines.append(f"{SHADOW_COUNTERS} · review-minutes-planned: {values['review-minutes-planned']}")
else:
lines += [f"- {k}: {values[k]}" for k in COUNTERS]
lines += cap_lines(counters)
lines += ["", WORKERS_HEADING] + (worker_lines(counters, links) or [NO_PICKS])
lines += ["", REFUSALS_HEADING] + (refusal_lines(counters) or [NO_PICKS])
lines += report_lines(slot)
Expand Down Expand Up @@ -664,7 +667,9 @@ def names(paths):
#: `spawned/parked/late/finished`. `launch-failed` stands alone: no session
#: started. `ended` is a parked worker that ended without a `.done`.
EXIT_WORDS = ("spawned", "finished", "crashed", "parked", "late", "ended",
"launch-failed")
"launch-failed", "killed")
#: `killed` is a worker the human stopped by `/kill` (#644): it is re-dispatched
#: as a crash is, but it is not a crash, so it is not in `CRASH_WORDS`.
CRASH_WORDS = ("crashed", "launch-failed")


Expand All @@ -690,6 +695,11 @@ def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]:
if pushes > 1:
out.append(f"- finding: {pushes} pushes this shift — the push test budgets "
"about one (AUTONOMY.md)")
events = int(counters.get("event_comments") or 0)
if events:
# Needs-you event comments (#644) have their own cap, 5 + 1 a shift,
# and are not pushes for the finding above.
out.append(f"- needs-you event comments: {events} (at most 5 + 1 a shift)")
return out


Expand All @@ -702,6 +712,14 @@ def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]:
r"\1: committed + \2 reserved per worker would pass it"),
(re.compile(r"^token usage unavailable\b"), "token usage unavailable"),
(re.compile(r"^spawn failed\b"), "spawn failed"),
# Close-out refusals, so the event stream's `cls` is stable (#644). The
# public-name check's wording is #641's (`bin/public_names.py` `reason`).
(re.compile(r"^public name added/renamed\b"), "public name added or renamed: a human /prm"),
(re.compile(r"^public-name check could not tell\b"),
"public-name check could not tell: a human /prm"),
(re.compile(r"^PR carries the decision-taken label\b"), "decision-taken label"),
(re.compile(r"^token spend \d+ \(committed\) reached (\S+× token-budget \d+)"),
r"token spend reached \1"),
)
#: Refusals whose reason is the shift's, not the task's — summarised in one
#: line for every task they held back (#632, F3 and review).
Expand Down Expand Up @@ -780,6 +798,20 @@ def refusal_lines(counters: dict) -> list[str]:
return out


def cap_lines(counters: dict) -> list[str]:
"""A cap the human lowered (or raised back) by `/cap` this shift (#644),
one line each: `merge-cap 2 → 1 (/cap by <login> at 18:02Z)`. Not a
counter column, so the pilot rows keep their shape."""
out = []
for key, ov in sorted((counters.get("caps") or {}).items()):
if not isinstance(ov, dict):
continue
at = str(ov.get("at") or "")
out.append(f"- cap override: {key} {ov.get('brief', '?')} → {ov.get('value', '?')} "
f"(/cap by {ov.get('by', '?')} at {at[11:16] + 'Z' if len(at) >= 16 else at})")
return out


def workers_crashed(counters: dict) -> int:
"""Workers whose exit path holds a crash (or whose launch failed); a slot
recorded before per-worker exits falls back to its crash tally."""
Expand Down
Loading
Loading