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
11 changes: 10 additions & 1 deletion agents/conductors/batch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,16 @@ default (`control-group`) systemd killed every process a tick started when the
tick exited, including the `claude --bg` daemon the first worker launched, so
live shift 1 (2026-11-06) lost all three workers about 30 seconds after spawn
(PyAutoBrain#592). A copy installed before then must be copied again
(`daemon-reload`). Separately, a worker or close-out whose `claude agents`
(`daemon-reload`). Since PyAutoBrain#634 every worker and close-out is
launched through `systemd-run --user --scope` when the tick runs inside a
unit (`INVOCATION_ID` set) and `systemd-run` is on PATH
(`_orchestrator.scope_command`): the transient `claude daemon run` and its
`bg-pty-host` spares then live in their own `app.slice/run-*.scope`, not in
the unit's cgroup, so systemd no longer logs "Found left-over process" on
every tick (211 lines in the 2026-11-14-pm shift). The daemon still quits
on its own 5 s after its last client; nothing in the watcher stops it.
Outside a unit, without `systemd-run`, or when systemd-run cannot reach the
user bus, the session is launched plain, as before. Separately, a worker or close-out whose `claude agents`
state is in `_digest.ENDED_STATES` (`failed`, `killed`, `error`, …) is reaped
at once, as a crash (worker, re-dispatched once) or a refusal (close-out),
never read as alive. To stop a shift, `touch <slot>/STOP` (or comment `/stop` on
Expand Down
300 changes: 258 additions & 42 deletions agents/conductors/batch/_digest.py

Large diffs are not rendered by default.

70 changes: 69 additions & 1 deletion agents/conductors/batch/_mind_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@
{"op": "jsonl-upsert", "path": "batches/pilot/pilot.jsonl", "key": "slot", "row": {...}}
{"op": "table-upsert", "path": "batches/pilot/pilot.md", "key": "<slot>", "row": "| … |", "header": "…"}
{"op": "record-key", "path": "batches/<slot>.md", "key": "live", "value": "…"}
{"op": "queue-retire", "path": "queue.md", "prompt": "x.md", "shipped_as": "<PR> → complete/…"}

`queue-retire` moves every live `queue.md` entry whose `ref:` names the
prompt file `prompt` to the `## Retired` footer with `shipped-as:`, using
PyAutoMind's own `lifecycle.py` `queue_retire_text`, the function
`lifecycle.py close` runs. It is loaded from the tree being written, so
the rule is Mind's, never a copy. An unattended close-out queues it with
its complete record, and the watcher queues it again when it reaps the
merge (PyAutoBrain#634: after the first unattended merge its entry
stayed live, and `lifecycle.py check` then failed on the dangling ref). No
live entry naming the prompt is the usual case, and it is silent.

`jsonl-upsert` keeps one JSON line per `row[key]`: the line with that key is
replaced (its other fields kept), else the row is appended. `table-upsert`
Expand Down Expand Up @@ -75,7 +86,10 @@
from pathlib import Path

OPS = ("append", "write", "move", "remove", "drop-section", "table-append",
"set-header", "jsonl-upsert", "table-upsert", "record-key")
"set-header", "jsonl-upsert", "table-upsert", "record-key", "queue-retire")
#: What a watcher-run queue retirement says in the footer, in place of the
#: `lifecycle.py close` it did not run.
QUEUE_RETIRED_BY = "retired by the shift close-out (queue-retire)"
PUSH_TRIES = 3
LEDGER_DIR = "ledger"
COMMITTED_DIR = "committed"
Expand Down Expand Up @@ -182,6 +196,14 @@ def validate_op(op: dict, lm) -> list[str]:
errs.append("record-key: value must be one non-empty line")
if not (path.startswith("batches/") and path.endswith(".md")):
errs.append("record-key: path must be a batch record (batches/*.md)")
if kind == "queue-retire":
prompt, shipped = op.get("prompt"), op.get("shipped_as")
if op.get("path") != "queue.md":
errs.append("queue-retire: path must be queue.md")
if not isinstance(prompt, str) or not re.fullmatch(r"[^/\s]+\.md", prompt):
errs.append("queue-retire: prompt must be a bare prompt file name (x.md)")
if not isinstance(shipped, str) or not shipped.strip() or "\n" in shipped:
errs.append("queue-retire: shipped_as must be one non-empty line")
if kind == "set-header":
key, value = op.get("key"), op.get("value")
if not isinstance(key, str) or not re.fullmatch(r"[A-Z][A-Za-z-]*", key):
Expand Down Expand Up @@ -267,6 +289,22 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None:
# A row re-queued after a crash between queue and counters (#632).
return f"table-append: a row with {op['unique']!r} is already there — skipped"
target.write_text(table_append(text, op["heading"], op["row"]), encoding="utf-8")
elif kind == "queue-retire":
if not target.exists():
return None # no queue on this Mind: nothing can dangle
text = target.read_text(encoding="utf-8")
try:
new, moved = _mind_module(tree, "lifecycle").queue_retire_text(
text, op["prompt"], op["shipped_as"])
except MindWriteError:
raise
except Exception as exc: # Mind main's lifecycle.py is not ours: any
# failure in it (syntax, rename, its own bug) must stay this one
# op's failure, never a tick crash that strands every other op.
raise MindWriteError(f"queue-retire: lifecycle.queue_retire_text "
f"failed: {type(exc).__name__}: {exc}") from exc
if moved:
target.write_text(_retired_by(new, len(moved)), encoding="utf-8")
elif kind == "jsonl-upsert":
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(jsonl_upsert(target.read_text(encoding="utf-8")
Expand All @@ -280,6 +318,36 @@ def apply_op(tree: Path, op: dict, lm, ctx: dict | None = None) -> str | None:
encoding="utf-8")


def _mind_module(tree: Path, name: str):
"""A PyAutoMind `scripts/<name>.py`, compiled from `tree` (the temporary
worktree on origin/main) as `_ledger_merge` compiles its own: no import,
so no `__pycache__` is written anywhere."""
path = Path(tree) / "scripts" / f"{name}.py"
if not path.is_file():
raise MindWriteError(f"no scripts/{name}.py on Mind main")
mod_name = f"_mind_{name}"
mod = types.ModuleType(mod_name)
mod.__file__ = str(path)
sys.modules[mod_name] = mod
try:
exec(compile(path.read_text(encoding="utf-8"), str(path), "exec"), mod.__dict__)
finally:
sys.modules.pop(mod_name, None)
return mod


def _retired_by(text: str, n: int) -> str:
"""`queue_retire_text` notes its entries as retired by `lifecycle.py
close`; the `n` it just put at the head of the footer were retired here."""
old = "retired by `lifecycle.py close`"
m = re.search(r"^## Retired[ \t]*$", text, re.M) # the heading line, not prose
head = m.start() if m else -1
if head < 0:
return text
body = text[head:].replace(old, QUEUE_RETIRED_BY, n)
return text[:head] + body


def _new_sections(old: str, text: str, path: str, lm,
ctx: dict) -> tuple[str, str | None]:
"""`text` without the `## slug` sections `old` already has, and a note
Expand Down
88 changes: 77 additions & 11 deletions agents/conductors/batch/_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import json
import os
import re
import shutil
import subprocess
import sys
from pathlib import Path
Expand Down Expand Up @@ -346,6 +347,49 @@ def session_command(task: str, prompt_path: str, brief_path: Path, lease_dir: Pa
#: `claude --bg` prints `backgrounded · <8-hex id> · <name>` on its first line.
_BG_ID_RE = re.compile(r"backgrounded\W+([0-9a-f]{8})\b")

#: systemd-run's own failures: the scope was never made, so `claude` never
#: ran and a plain launch cannot double-spawn.
_SCOPE_FAILED_RE = re.compile(r"Failed to (start transient scope unit|connect to bus"
r"|create bus connection)", re.I)


def scope_command(argv: list[str], task: str, env: dict | None = None,
which=shutil.which) -> list[str]:
"""`argv` wrapped in its own transient systemd user scope, when the watcher
runs inside a systemd unit and `systemd-run` is on PATH (PyAutoBrain#634).

The first `claude --bg` starts the per-user background-session daemon
(`claude daemon run`, `origin=transient`) and its `bg-pty-host` spares.
They inherit the cgroup of whoever launched them. Launched from the
watcher's oneshot `pyauto-orchestrator.service`, they lived in that
unit's cgroup, outlived each tick, and systemd logged "Found left-over
process" on every tick of the first live shift (211 lines). In a scope
of their own (`app.slice/run-*.scope`) they never share the unit's
cgroup, and the scope goes away when its last process exits: the daemon
already quits on its own 5 s after its last client. A daemon some other
session already runs is only connected to; the scope then holds the
short-lived client and closes at once. Nothing here stops anything.

`--scope` runs the command as systemd-run's own child, so the worker's
environment and working folder pass through unchanged. Outside a unit
(no `INVOCATION_ID`: a hand-run tick, CI, macOS) or without
`systemd-run`, the argv comes back unchanged — spawned as before."""
env = os.environ if env is None else env
if not env.get("INVOCATION_ID") or not which("systemd-run"):
return list(argv)
return ["systemd-run", "--user", "--scope", "--quiet", "--collect",
f"--description=PyAuto shift session {task}", "--", *argv]


def run_scoped(run, argv: list[str], task: str, **kw):
"""Run `argv` through `scope_command`; if systemd-run itself could not
make the scope (no user bus), run it plain, exactly as before #634."""
wrapped = scope_command(argv, task, kw.get("env"))
res = run(wrapped, **kw)
if wrapped != argv and res.returncode != 0 and _SCOPE_FAILED_RE.search(res.stderr or ""):
return run(list(argv), **kw)
return res


class RealSpawner:
"""`claude --bg` workers from the session template (phase 3b)."""
Expand All @@ -366,8 +410,8 @@ def spawn(self, task: str, prompt_path: str, lease_dir: Path,
redispatch: bool = False) -> dict:
argv = session_command(task, prompt_path, self.brief_path, lease_dir, self.mode,
redispatch)
res = self.run(argv, cwd=self.cwd, capture_output=True, text=True, timeout=120,
env=worker_env(lease_dir))
res = run_scoped(self.run, argv, task, cwd=self.cwd, capture_output=True, text=True,
timeout=120, env=worker_env(lease_dir))
# An untrusted folder is refused here, fast ("Workspace not trusted") —
# never a silent stall. Workers start from a folder the human trusted.
if res.returncode != 0:
Expand All @@ -382,8 +426,10 @@ def spawn(self, task: str, prompt_path: str, lease_dir: Path,
def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Path) -> dict:
argv = closeout_command(task, pr_url, prompt_path, self.brief_path, lease_dir,
self.mode)
res = self.run(argv, cwd=self.cwd, capture_output=True, text=True, timeout=120,
env=worker_env(lease_dir))
# The same scoped route as a worker (#634): a close-out may be the
# session that starts the daemon.
res = run_scoped(self.run, argv, task, cwd=self.cwd, capture_output=True, text=True,
timeout=120, env=worker_env(lease_dir))
if res.returncode != 0:
raise OrchestratorError(f"claude --bg close-out failed for {task}: "
+ (res.stderr or res.stdout).strip()[:300])
Expand Down Expand Up @@ -1815,16 +1861,18 @@ def _live_status(slot: Path, mind: Path, shift: dict, now: _dt.datetime, agents,
health, github=None, *, stopped: bool = False) -> dict | None:
"""The end of every open tick: the status comment (create once, then edit)
and the dashboard's `- live:` line. Built from the same snapshot as
`batch watch`, from what this tick already read — no read of its own.
`batch watch`, from what this tick already read — no network read of its
own (the work-issue links are a local git read of Mind, #634).
On the `/stop` tick only the status write runs, as the acknowledgement:
nothing is queued or committed to Mind, exactly as under `STOP`."""
brief_path = shift.get("brief_path")
if brief_path is None:
return None
import _watch # noqa: E402 — deferred: _watch imports this module
snap = _watch.snapshot(brief_path, slot, now, agents=agents, health=health)
out = {}
issue = shift.get("issue", "")
snap = _watch.snapshot(brief_path, slot, now, agents=agents, health=health,
mind=mind, issue=issue)
out = {}
if issue.startswith("http"):
snap["commands_on"] = bool(mention_login())
out = _post_status(slot, issue, _watch.render_status(snap),
Expand Down Expand Up @@ -2048,7 +2096,7 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *,
# reports from here on reaches the human through the late sweep (#632).
counters["ledger_reported"] = len(_mind_writer.report(slot))
_write_counters(slot, counters)
digest = _digest.build(brief, slot, counters, health=health, issue=issue)
digest = _digest.build(brief, slot, counters, health=health, issue=issue, mind=mind)
(slot / DIGEST_FILE).write_text(digest, encoding="utf-8")
result = {"action": "digest", "ledger": None, "post": None, "packet": None}

Expand Down Expand Up @@ -2080,22 +2128,22 @@ def finish_shift(brief_path: Path, mind: Path, slot: Path, now: _dt.datetime, *,
result["post"] = {"posted": False, "error": "already posted this shift"}
return result
result["post"] = {k: posted[k] for k in ("posted", "url", "error") if k in posted}
closing = _close_status(brief_path, slot, issue, now, agents, github)
closing = _close_status(brief_path, slot, issue, now, agents, github, mind=mind)
if closing:
result["status"] = closing
return result


def _close_status(brief_path: Path, slot: Path, issue: str, now: _dt.datetime,
agents, github=None) -> dict | None:
agents, github=None, *, mind=None) -> dict | None:
"""One last edit of the status comment at `review-at:`, saying the shift
is closed (#622); never retried — the digest is the record from here."""
rec = _read_json(slot / STATUS_MARKER)
if not rec or rec.get("state") != "posted":
return None
import _watch # noqa: E402
snap = _watch.snapshot(brief_path, slot, now, agents=agents,
health=lambda u: "see the digest")
health=lambda u: "see the digest", mind=mind, issue=issue)
snap["commands_on"] = False
rec["due"] = True
(slot / STATUS_MARKER).write_text(json.dumps(rec, sort_keys=True))
Expand Down Expand Up @@ -2179,6 +2227,18 @@ def _closeouts(slot: Path, brief: dict, counters: dict, spawner, now: _dt.dateti
review_at)


def queue_retire_op(counters: dict, task: str, pr: str, now: _dt.datetime) -> dict | None:
"""The ledger op that retires a merged task's live `queue.md` entry —
what `lifecycle.py close` does and an unattended close-out skipped once
(PyAutoBrain#634). None when the pick recorded no prompt."""
prompt = (counters.get("picks", {}).get(task) or {}).get("prompt") or ""
if not prompt:
return None
return {"op": "queue-retire", "path": "queue.md", "prompt": Path(prompt).name,
"shipped_as": f"{pr} (merged by the unattended close-out, "
f"{now.strftime('%Y-%m-%d')})"}


def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_state,
tokens=transcript_usage, *, late: bool = False) -> dict:
"""Reap every finished close-out session (the first half of `_closeouts`):
Expand Down Expand Up @@ -2271,6 +2331,12 @@ def reap_closeouts(slot: Path, counters: dict, now: _dt.datetime, agents, pr_sta
"unique": f"| {co['task']} ({pr}) | {slot.name} |",
"row": stage2_row(now, co["task"], pr, slot.name, co["gate"], co["model"],
merged_by=(gh or {}).get("mergedBy") or "")})
retire = queue_retire_op(counters, co["task"], pr, now)
if retire:
# The close-out queues this with its complete record; this is
# the safety net when it did not (#634). A second retire of
# the same entry finds none live and is silent.
_mind_writer.queue_op(slot / _mind_writer.LEDGER_DIR, retire)
events["merged"].append(pr)
else:
# Never retried: a close-out that ended without a verdict is the
Expand Down
Loading
Loading