diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 84ca1e5a..60870eb7 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -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 /STOP` (or comment `/stop` on diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 941f8ce8..e6766807 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -41,6 +41,9 @@ NO_PICKS = "- none" #: What a shadow shift's line and packet section say instead of work (phase 4a). PROPOSED = "proposed (shadow)" +#: A worker whose lease is still held when the digest is built (#634, N1): it +#: was dispatched and is not done; the late sweep reports how it ends. +STILL_OUT = "still running at review time — the late sweep will report it" NO_PACKETS_SHADOW = "- none — shadow shift: nothing was dispatched" #: A shadow digest's counters, in one line: every one is 0 by construction. SHADOW_COUNTERS = "- all counters 0 — shadow shift, nothing dispatched" @@ -187,8 +190,9 @@ def task_state(task: str, counters: dict, health, *, live: bool = False, """(what a task is doing, whether its tier follows) — the one wording the digest and `batch watch` share, so the live view and the digest never disagree. Only the live view passes `live=True` (with the task's `lease` - and the `agents` view): at `review-at:` the watcher has already reaped - every lease, and the digest's wording stays exactly as it was. A task the + and the `agents` view). The digest passes a lease only for a worker still + out at `review-at:`, which reads `STILL_OUT`, never "not started" + (PyAutoBrain#634, N1); the late sweep reports how it ends. A task the human dropped by `/drop` (PyAutoBrain#622) says so first.""" state, tiered = _task_state(task, counters, health, live=live, lease=lease, agents=agents) @@ -213,6 +217,8 @@ def _task_state(task: str, counters: dict, health, *, live: bool = False, if out is None: if live and lease is not None: return _lease_state(lease, agents), True + if lease is not None: + return STILL_OUT, True if live and task in counters.get("pending_redispatch", []): return "crashed — awaiting re-dispatch", True return "not started", False @@ -270,31 +276,214 @@ def _lease_state(lease: dict, agents) -> str: return f"running (agent {agent}, {state}, since {since})" -def mind_blob_base(issue_url: str) -> str: - """`https://github.com///blob/main/` from the brief's `issue:` - (a Mind issue), so a pick links its prompt; "" when it cannot tell.""" - m = _ISSUE_RE.match(issue_url or "") - return f"{m.group(1)}/blob/main/" if m else "" +# --- links and the two-line task entry (PyAutoBrain#634) --------------------------- + +#: A prompt moves at most draft/ → active/ → complete/YYYY/MM/ in a shift; +#: a few more hops are tolerated, never an unbounded walk. +MAX_MOVES = 6 +_GH_URL_RE = re.compile(r"^https://github\.com/[^/\s]+/[^/\s]+/(?:issues|pull)/\d+$") + + +class MindLinks: + """Where a task's Mind prompt and its work issue are, read at render time + from the watcher's own Mind checkout: local git on its `origin/main` ref, + which the watcher's one fetch and the Mind writer's pushes keep current. + It makes no network call of its own (PyAutoBrain#634). + + A prompt moves draft/ → active/ → complete/YYYY/MM/ during a shift, often + renamed, so the `blob/main/draft/...` link the first live shift wrote was + dead by the time the digest was read. The prompt link here follows the + moves and is pinned to a commit sha, so it does not go dead later. When it + cannot read something it returns "", and the caller drops the link.""" + + def __init__(self, mind=None, issue: str = "", ref: str = "origin/main", run=None): + m = _ISSUE_RE.match(issue or "") + self.repo = m.group(1) if m else "" + self.mind, self.ref = (Path(mind) if mind else None), ref + self.run = run or subprocess.run + self._cache: dict = {} + + def _git(self, *args) -> str | None: + """git's stdout, or None when it fails or there is no Mind checkout.""" + if self.mind is None: + return None + if args not in self._cache: + try: + res = self.run(["git", "-C", str(self.mind), *args], capture_output=True, + text=True, timeout=30) + self._cache[args] = res.stdout if res.returncode == 0 else None + except (OSError, subprocess.SubprocessError): + self._cache[args] = None + return self._cache[args] + + def head(self) -> str: + """The `origin/main` sha, "" when `mind` is not a checkout of its own.""" + top = self._git("rev-parse", "--show-toplevel") + if top is None or Path(top.strip()).resolve() != self.mind.resolve(): + return "" + return (self._git("rev-parse", "--verify", "-q", self.ref + "^{commit}") or "").strip() + + def _renamed(self, commit: str, path: str) -> str | None: + diff = self._git("diff", "-M", "--name-status", f"{commit}^", commit) or "" + for line in diff.splitlines(): + parts = line.split("\t") + if len(parts) == 3 and parts[0].startswith("R") and parts[1] == path: + return parts[2] + return None + + def prompt_url(self, prompt: str) -> str: + """The prompt where it is now on `origin/main`, pinned to that sha. + A prompt deleted without a detectable rename links to its last + version (the deleting commit's parent). "" when it was never there.""" + head = self.head() if self.repo and prompt else "" + if not head: + return "" + path = prompt + for _ in range(MAX_MOVES): + if self._git("cat-file", "-e", f"{head}:{path}") is not None: + return f"{self.repo}/blob/{head}/{path}" + gone = (self._git("rev-list", "-1", head, "--", path) or "").strip() + if not gone: + return "" + moved = self._renamed(gone, path) + if moved is None: + parent = (self._git("rev-parse", "--verify", "-q", gone + "^") or "").strip() + return f"{self.repo}/blob/{parent}/{path}" if parent else "" + path = moved + return "" + + def work_issue(self, task: str, prompt: str) -> str: + """The work repo's issue for a task that has claimed itself: the + `- issue:` of its `active.md` section on `origin/main`, matched by the + task name or by its `- prompt:` file name (the section's slug is the + worker's choice and often differs). "" when there is none.""" + head = self.head() + if not head: + return "" + stem = Path(prompt or "").name + for section in re.split(r"(?m)^## ", self._git("show", f"{head}:active.md") or "")[1:]: + name, _, body = section.partition("\n") + keys = dict(re.findall(r"(?m)^- (issue|prompt):[ \t]*(\S+)", body)) + if name.strip() == task or (stem and Path(keys.get("prompt", "")).name == stem): + url = keys.get("issue", "") + return url if _GH_URL_RE.match(url) else "" + return "" + + +def work_link(task: str, counters: dict, links: MindLinks | None = None) -> str: + """What a task's title links to: its PR, else the work repo's issue + (the one its `.done` named, else the one its claim in `active.md` names), + else "" — the title is then plain text. Never a Mind path (#634).""" + out = counters.get("outcomes", {}).get(task) or {} + urls = urls_of(out) + if urls: + return urls[0] + pick = counters.get("picks", {}).get(task) or {} + return links.work_issue(task, pick.get("prompt") or "") if links is not None else "" -def label(task: str, pick: dict | None, base: str = "") -> str: - """How a pick is named to a human: its title, linked to its prompt, the - task slug in backticks, then size and repos. A pick recorded before titles - were (or with none) falls back to the bare slug.""" +def label(task: str, pick: dict | None, url: str = "") -> str: + """How a pick is named in a technical list: its title (linked to `url`, + the work itself, when there is one), the task slug in backticks, then + size and repos. A pick recorded before titles were (or with none) falls + back to the bare slug.""" pick = pick or {} title = pick.get("title") if not title: return task - prompt = pick.get("prompt") or "" - head = f"[{title}]({base}{prompt})" if base and prompt else f"**{title}**" + head = f"[{title}]({url})" if url else f"**{title}**" details = " · ".join(x for x in (pick.get("size"), ", ".join(pick.get("repos") or [])) if x) return f"{head} (`{task}`" + (f"; {details}" if details else "") + ")" -def _line(task: str, counters: dict, tier: str, health, base: str = "") -> str: - state, tiered = task_state(task, counters, health) - name = label(task, counters.get("picks", {}).get(task), base) - return f"- {name} — {state}" + (f" — {tier}" if tiered else "") +#: A task's outcome in plain words (PyAutoBrain#634), read from one part of +#: its `task_state`; the first match wins. The exact state stays on the +#: entry's second line, so nothing is lost by the short form. +_PLAIN = ( + ("merged", "Merged"), + ("awaiting /prm — close-out refused: CI FAILED", "CI failed — needs you"), + ("awaiting /prm — close-out refused: CI RED", "CI failed — needs you"), + ("awaiting /prm", "Needs you — not merged unattended"), + ("close-out running", "Still running — close-out checking it"), + (STILL_OUT, "Still running at review time"), + ("verdict posted", "Verdict posted"), + ("PARKED-ON-ISSUE", "Needs you — question on the issue"), + ("FAILED", "CI failed — needs you"), + ("RUNNING", "CI running"), + ("HEALTHY", "CI green — awaiting merge"), + ("NO-CHECKS", "No CI checks — needs your merge"), + ("UNKNOWN", "CI unknown — needs you"), + ("parked", "Needs you — blocked on a person"), + ("blocked on a person", "Needs you — blocked on a person"), + ("abandoned", "Abandoned — crashed twice"), + ("crashed", "Crashed — waiting to be re-dispatched"), + ("ended", "Crashed"), + ("obsolete", "Obsolete — nothing to do"), + ("finished", "Finished — no PR or issue named"), + ("running", "Still running"), + ("not started", "Not started"), + (PROPOSED, "Proposed (shadow)"), +) + + +def plain_outcome(state: str) -> str: + """The first line's words for a `task_state`: merged, needs you, CI + failed, still running. One word set per URL part, de-duplicated.""" + for prefix, word in (("dropped, still running — ", "Dropped, still running"), + ("dropped by /drop — ", "Dropped")): + if state.startswith(prefix): + rest = plain_outcome(state[len(prefix):]) + return word if rest in ("Not started", "Still running") or \ + word.endswith("running") else f"{word} — {rest}" + words = [] + for part in state.split("; "): + what = part.split(" — ", 1)[1] if part.startswith("http") and " — " in part else part + word = next((w for p, w in _PLAIN if what.startswith(p)), "") + word = word or (what[:1].upper() + what[1:]) + if word not in words: + words.append(word) + return " · ".join(words) + + +def entry_lines(task: str, pick: dict | None, state: str, tiered: bool, tier: str, + link: str = "", *, why: str = "", extra=(), mind_url: str = "") -> list[str]: + """One task as the human reads it (PyAutoBrain#634): the outcome in plain + words and the title, linked to the work itself; then a second, smaller + line with the slug, tier, size, repos, the exact state, any `extra`, the + Mind prompt and, last, the `why:` (`validate` reads it from the end).""" + pick = pick or {} + title = pick.get("title") or task + head = f"- **{plain_outcome(state)}** — " + (f"[{title}]({link})" if link else title) + detail = state.replace(f"{link} — ", "", 1) if link else state + bits = [f"`{task}`"] + ([tier] if tiered else []) \ + + [x for x in (pick.get("size"), ", ".join(pick.get("repos") or [])) if x] \ + + [detail] + list(extra) + ([f"[Mind prompt]({mind_url})"] if mind_url else []) \ + + ([f"why: {why}"] if why else []) + return [head, " " + " · ".join(bits) + ""] + + +def held_leases(slot: Path) -> dict[str, dict]: + """The leases still held in a slot — `_orchestrator.leases`, read here + because this module must not import the orchestrator.""" + out = {} + for f in sorted((Path(slot) / "leases").glob("*.json")): + try: + out[f.stem] = json.loads(f.read_text()) + except (OSError, ValueError): + continue + return out + + +def _line(task: str, counters: dict, tier: str, health, links: MindLinks | None = None, + why: str = "", lease: dict | None = None) -> str: + state, tiered = task_state(task, counters, health, lease=lease) + pick = counters.get("picks", {}).get(task) + mind_url = links.prompt_url((pick or {}).get("prompt") or "") if links else "" + again = counters.get("redispatched", {}).get(task, 0) + return "\n".join(entry_lines(task, pick, state, tiered, tier, + work_link(task, counters, links), why=why, + extra=[f"re-dispatched {again}×"] if again else [], + mind_url=mind_url)) def _packet(task: str, slot: Path, counters: dict) -> str: @@ -309,8 +498,9 @@ def _packet(task: str, slot: Path, counters: dict) -> str: def build(brief: dict, slot: Path, counters: dict, *, tiers: dict | None = None, - health=None, issue: str = "") -> str: - """The `## Digest` block for one shift, as Markdown.""" + health=None, issue: str = "", mind=None) -> str: + """The `## Digest` block for one shift, as Markdown. `mind` is the + watcher's Mind checkout, read locally for the prompt links (#634).""" tiers = tiers or {} health = health or pr_health picks = counters.get("picks", {}) @@ -318,12 +508,15 @@ 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, "", "### Brief work"] - base = mind_blob_base(issue) - lines += [_line(t, counters, tiers.get(t, picks.get(t, {}).get("tier", "?")), health, base) - for t in named] or [NO_PICKS] + links = MindLinks(mind, issue) + # A worker still out at review-at keeps its lease (#634, N1). + held = {t: l for t, l in held_leases(slot).items() if l.get("state") != "parked"} + lines += [_line(t, counters, tiers.get(t, picks.get(t, {}).get("tier", "?")), health, links, + lease=held.get(t)) for t in named] or [NO_PICKS] lines += ["", "### Backlog picks"] - lines += [_line(t, counters, tiers.get(t, picks[t].get("tier", "?")), health, base) - + f" — why: {picks[t].get('why') or 'NOT RECORDED'}" for t in backlog] or [NO_PICKS] + lines += [_line(t, counters, tiers.get(t, picks[t].get("tier", "?")), health, links, + why=picks[t].get("why") or "NOT RECORDED", lease=held.get(t)) + for t in backlog] or [NO_PICKS] lines += backlog_gate_lines(counters) started = [t for t in named + backlog @@ -339,7 +532,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 += ["", WORKERS_HEADING] + (worker_lines(counters, base) or [NO_PICKS]) + lines += ["", WORKERS_HEADING] + (worker_lines(counters, links) or [NO_PICKS]) lines += ["", REFUSALS_HEADING] + (refusal_lines(counters) or [NO_PICKS]) lines += report_lines(slot) lines += identity_lines(counters) @@ -430,12 +623,13 @@ def names(paths): CRASH_WORDS = ("crashed", "launch-failed") -def worker_lines(counters: dict, base: str = "") -> list[str]: +def worker_lines(counters: dict, links: MindLinks | None = None) -> list[str]: """One line per worker the shift started (or failed to start).""" picks = counters.get("picks", {}) out = [] for w in counters.get("workers", []): - line = f"- {label(w['task'], picks.get(w['task']), base)} ({w.get('key') or '?'}): " \ + url = work_link(w["task"], counters, links) + line = f"- {label(w['task'], picks.get(w['task']), url)} ({w.get('key') or '?'}): " \ + "/".join(w.get("exits") or ["spawned"]) if w.get("stalled_s"): line += f" — blocked {round(w['stalled_s'] / 60)} min" @@ -678,18 +872,40 @@ def _sections(text: str) -> dict[str, list[str]]: return out -def _slug(line: str) -> str: - """The task a digest bullet is about: the backticked slug a titled pick - carries, else the bullet's first word (a pick recorded without a title).""" - m = _BULLET_RE.match(line) +def _items(lines: list[str]) -> list[str]: + """A section's bullets, each joined with its indented continuation lines + (the second line of a #634 entry).""" + items: list[str] = [] + for line in lines: + if line.startswith("- "): + items.append(line) + elif items and line.startswith(" ") and line.strip(): + items[-1] += "\n" + line + return items + + +#: A #634 entry names its task first on its second line. +_SUB_SLUG_RE = re.compile(r"(?m)^\s+`([^`]+)`") +_WHY_RE = re.compile(r"(?m)(?: — | · )why: (.*?)\s*(?:)?\s*$") + + +def _slug(item: str) -> str: + """The task a digest bullet is about: the slug on a #634 entry's second + line, else the backticked slug a titled pick carries on its one line, + else the bullet's first word (a pick recorded without a title).""" + m = _BULLET_RE.match(item) if not m: return "" - s = _SLUG_RE.search(line.split(" — ", 1)[0]) + sub = _SUB_SLUG_RE.search(item) + if sub: + return sub.group(1) + s = _SLUG_RE.search(item.split("\n", 1)[0].split(" — ", 1)[0]) return s.group(1) if s else m.group(1) def validate(text: str) -> list[str]: - """Errors in a record's `## Digest`; empty when there is none, or it is whole.""" + """Errors in a record's `## Digest`; empty when there is none, or it is whole. + Reads both the one-line entries of shifts before #634 and the two-line ones.""" if DIGEST_HEADING not in text: return [] errs = [] @@ -697,11 +913,11 @@ def validate(text: str) -> list[str]: for s in SECTIONS: if s not in secs: errs.append(f"digest: {s[4:]} section missing") - for line in secs.get("### Backlog picks", []): - slug = _slug(line) - if slug and line.strip() != NO_PICKS: - why = line.split(" — why: ", 1) - if len(why) < 2 or not why[1].strip() or why[1].strip() == "NOT RECORDED": + for item in _items(secs.get("### Backlog picks", [])): + slug = _slug(item) + if slug and item.strip() != NO_PICKS: + why = _WHY_RE.search(item) + if not why or not why.group(1).strip() or why.group(1).strip() == "NOT RECORDED": errs.append(f"digest: backlog pick {slug} has no `why:` — " "every pick names the brief rule it was picked under") seen = {} @@ -715,10 +931,10 @@ def validate(text: str) -> list[str]: errs.append(f"digest: counter {key} missing") packets = "\n".join(secs.get("### Proof packets", [])) for sec in ("### Brief work", "### Backlog picks"): - for line in secs.get(sec, []): - slug = _slug(line) - if slug and line.strip() != NO_PICKS and "not started" not in line \ - and PROPOSED not in line \ + for item in _items(secs.get(sec, [])): + slug = _slug(item) + if slug and item.strip() != NO_PICKS and "not started" not in item \ + and PROPOSED not in item and STILL_OUT not in item \ and f"#### {slug}" not in packets: errs.append(f"digest: {slug} has no proof packet") return errs diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index e9ed4613..4047ab0d 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -21,6 +21,17 @@ {"op": "jsonl-upsert", "path": "batches/pilot/pilot.jsonl", "key": "slot", "row": {...}} {"op": "table-upsert", "path": "batches/pilot/pilot.md", "key": "", "row": "| … |", "header": "…"} {"op": "record-key", "path": "batches/.md", "key": "live", "value": "…"} + {"op": "queue-retire", "path": "queue.md", "prompt": "x.md", "shipped_as": " → 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` @@ -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" @@ -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): @@ -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") @@ -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/.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 diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 207c514d..18192015 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -36,6 +36,7 @@ import json import os import re +import shutil import subprocess import sys from pathlib import Path @@ -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> · ` 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).""" @@ -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: @@ -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]) @@ -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), @@ -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} @@ -2080,14 +2128,14 @@ 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) @@ -2095,7 +2143,7 @@ def _close_status(brief_path: Path, slot: Path, issue: str, now: _dt.datetime, 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)) @@ -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`): @@ -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 diff --git a/agents/conductors/batch/_watch.py b/agents/conductors/batch/_watch.py index 6dddad9f..e6a463b1 100644 --- a/agents/conductors/batch/_watch.py +++ b/agents/conductors/batch/_watch.py @@ -90,8 +90,11 @@ def _opens_in(now: _dt.datetime, start: _dt.datetime) -> str: def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, - health=None, tick_lines: int = TICK_LINES) -> dict: - """Everything one refresh draws, as a dict. Reads only.""" + health=None, tick_lines: int = TICK_LINES, mind=None, issue: str = "") -> dict: + """Everything one refresh draws, as a dict. Reads only. With the + watcher's Mind checkout (`mind`) and the shift issue, a task with no PR + yet links to the work issue its claim names — a local git read + (`_digest.MindLinks`), no network (PyAutoBrain#634).""" rec = _brief.parse(Path(brief_path).read_text(encoding="utf-8")) top, brief = rec["top"], rec["brief"] or {} shadow = _brief.is_shadow(brief) @@ -115,16 +118,27 @@ def snapshot(brief_path: Path, slot: Path, now: _dt.datetime, *, agents=None, agents = _orchestrator.AgentsView() # one `claude agents --json` per refresh health = health or _digest.pr_health + links = _digest.MindLinks(mind, issue) if mind else None rows = [] for task in tasks: - state, _ = _digest.task_state(task, counters, health, live=True, - lease=held.get(task), agents=agents) + state, tiered = _digest.task_state(task, counters, health, live=True, + lease=held.get(task), agents=agents) + tier = picks.get(task, {}).get("tier", "?") + why = ("named in the brief" if task in named + else picks.get(task, {}).get("why") or "NOT RECORDED") + again = counters.get("redispatched", {}).get(task, 0) + # The status comment's two-line entry (#634): no Mind prompt link — + # a sha-pinned link would change on every Mind commit and force an + # edit each time; the digest carries it. + entry = _digest.entry_lines( + task, picks.get(task), state, tiered, tier, + _digest.work_link(task, counters, links), + why="" if task in named else why, + extra=[f"re-dispatched {again}×"] if again else []) rows.append({"task": task, "state": state, "label": _digest.label(task, picks.get(task)), - "tier": picks.get(task, {}).get("tier", "?"), - "why": "named in the brief" if task in named - else picks.get(task, {}).get("why") or "NOT RECORDED", - "redispatched": counters.get("redispatched", {}).get(task, 0)}) + "tier": tier, "why": why, "redispatched": again, + "entry": entry}) values = _digest.counter_values(brief, counters) merges = values["merges"] @@ -229,9 +243,7 @@ def render_status(snap: dict) -> str: lines = [f"**Shift `{snap['slot']}` — " + " · ".join(_flags(snap)) + "**", f"{snap['dispatched']} → {snap['review_at']} (as of {snap['now']}; " "this comment is edited in place, never re-posted)", "", "**Tasks**"] - lines += [f"- {r['label']} — {r['state']} — {r['tier']} — why: {r['why']}" - + (f" — re-dispatched {r['redispatched']}×" if r["redispatched"] else "") - for r in snap["tasks"]] or ["- none yet"] + lines += [line for r in snap["tasks"] for line in r["entry"]] or ["- none yet"] b = snap["budgets"] lines += ["", "**Budgets**", f"- workers: {b['workers']}", f"- sessions: {b['sessions']}", f"- tokens: {b['tokens']}", f"- merges: {b['merges']}", diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index 00318da8..194f8be3 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -45,8 +45,14 @@ outcome — the human merges by `/prm` at check-in. judged exactly as a human-typed `/prm`. Never commit to PyAutoMind yourself — a hook refuses it; queue each Mind change with `{shift_ledger} append|write|move|remove|drop-section ...` (ops land in - {ledger_dir}/) and the orchestrator commits them. Do **not** append the - Shadow-window row: the watcher writes the stage-2 row from your verdict. + {ledger_dir}/) and the orchestrator commits them. With the complete + record, also retire the task's `queue.md` entry, as `lifecycle.py close` + does (it is silent when there is none): + + {shift_ledger} queue-retire queue.md --text "{pr_url} → ()" + + Do **not** append the Shadow-window row: the watcher writes the stage-2 + row from your verdict. 7. End at your deliverable. Never arm anything that outlives your turn. Last, write {lease_dir}/{task}.closeout as one JSON object: diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 1958731a..3477e0c3 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -35,6 +35,16 @@ The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): - End at your deliverable: a PR, a posted verdict, or a park with a question on the issue. Never arm anything that outlives your turn (no send_later, ScheduleWakeup, CronCreate, RemoteTrigger or /loop) — the watcher keeps time. +- Before every push to an organ repo (PyAutoBrain, PyAutoHeart or PyAutoHands, + the organs the tenant firewall reads), run the firewall from your task root + (the folder that holds `.pyauto-root` and your organ worktree), and fix + each finding in your diff before you push: + + cd && python3 PyAutoMind/scripts/repos_sync.py --check --only "tenant firewall (organ code)" --root "$PWD" + + It is the check the organ's PR CI runs. PyAutoHeart#347 failed CI on a + hard-coded repo name it would have caught. A finding outside your diff is + not yours: name it in your proof packet. Other repos skip this step. - If the task is `Consequence: glance`, end at PR-open: do not wait for CI and do not merge. Once CI lands, the watcher starts an independent close-out session that runs the witness and merges, or refuses (AUTONOMY.md diff --git a/bin/shift_ledger.py b/bin/shift_ledger.py index 93453126..e11e8e0f 100755 --- a/bin/shift_ledger.py +++ b/bin/shift_ledger.py @@ -12,6 +12,7 @@ shift_ledger.py remove active/y.md shift_ledger.py drop-section active.md my-task shift_ledger.py set-header draft/x/y.md Verified --text "2026-11-12 abc1234 (Repo)" + shift_ledger.py queue-retire queue.md y.md --text " → complete/2026/11/y.md (2026-11-14)" The ledger directory is `$PYAUTO_SHIFT_LEDGER_DIR` (set for every worker). """ @@ -31,7 +32,7 @@ def main(argv=None) -> int: ap.add_argument("op", choices=mw.OPS) ap.add_argument("path") ap.add_argument("arg", nargs="?", help="move: destination; drop-section: section; " - "set-header: the header key") + "set-header: the header key; queue-retire: the prompt file name") ap.add_argument("--text-file", type=Path) ap.add_argument("--text") ap.add_argument("--mind", type=Path, default=os.environ.get("PYAUTO_MIND"), @@ -49,6 +50,8 @@ def main(argv=None) -> int: op["section"] = a.arg if a.op == "set-header": op["key"], op["value"] = a.arg, (a.text or "") + if a.op == "queue-retire": + op["prompt"], op["shipped_as"] = a.arg, (a.text or "") if a.op in ("append", "write"): op["text"] = a.text_file.read_text(encoding="utf-8") if a.text_file else (a.text or "") if a.mind: diff --git a/bin/systemd/pyauto-orchestrator.service b/bin/systemd/pyauto-orchestrator.service index 0d1d0875..f6832365 100644 --- a/bin/systemd/pyauto-orchestrator.service +++ b/bin/systemd/pyauto-orchestrator.service @@ -11,6 +11,11 @@ Type=oneshot # background-session daemon inside this unit, so the workers died with the tick # (pilot live shift 1, 2026-11-06, PyAutoBrain#592). After changing this, copy # the unit again and run `systemctl --user daemon-reload`. +# Since PyAutoBrain#634 each session is launched in its own transient scope +# (`systemd-run --user --scope`), so the daemon no longer lives in this unit's +# cgroup and systemd stops logging "Found left-over process" each tick. Keep +# KillMode=process anyway: a daemon started before that change, or by a tick +# 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} diff --git a/tests/test_batch_warmup_findings.py b/tests/test_batch_warmup_findings.py new file mode 100644 index 00000000..bd47ae84 --- /dev/null +++ b/tests/test_batch_warmup_findings.py @@ -0,0 +1,344 @@ +"""PyAutoBrain#634: fixes from the first live shift with real workers (2026-11-14-pm). + +1. Task titles link to the work (PR, else the work repo's issue, else plain); + the Mind prompt link follows the prompt's moves and is pinned to a sha. +2. Every `claude --bg` launch from inside a systemd unit runs in its own + transient scope, so the daemon it may start leaves the unit's cgroup. +3. Each task reads outcome-first, in plain words, with the detail below. +4. Organ-repo workers run the tenant firewall before they push. +5. An unattended close-out retires the task's live `queue.md` entry. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import os +import shutil +import signal +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "tests")) +import test_orchestrator_closeout as co # noqa: E402 +import test_orchestrator_digest as t # noqa: E402 +from test_orchestrator_digest import _digest, orch # noqa: E402 +import _mind_writer as mw # noqa: E402 + +PR = "https://github.com/o/r/pull/7" +WORK_ISSUE = "https://github.com/o/r/issues/6" +MIND_ISSUE = "https://github.com/example-org/example-mind/issues/1" + + +def git(cwd, *args): + res = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) + assert res.returncode == 0, (args, res.stderr) + return res.stdout.strip() + + +def _commit(repo, msg): + git(repo, "add", "-A") + git(repo, "-c", "user.name=T", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", msg) + + +@pytest.fixture +def moved_mind(tmp_path): + """A Mind clone whose `origin/main` holds a prompt moved draft/ → active/ + → complete/ (renamed), and an `active.md` claim for a second task.""" + if shutil.which("git") is None: + pytest.skip("needs git") + bare, mind = tmp_path / "mind.git", tmp_path / "mind" + git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare)) + git(tmp_path, "clone", "-q", str(bare), str(mind)) + body = "# Task t1\n\n" + "".join(f"line {i}\n" for i in range(30)) + (mind / "draft" / "bug" / "x").mkdir(parents=True) + (mind / "draft" / "bug" / "x" / "t1.md").write_text(body) + (mind / "draft" / "bug" / "x" / "t2.md").write_text("# t2\n") + (mind / "active.md").write_text("# Active\n") + _commit(mind, "seed") + (mind / "active").mkdir() + git(mind, "mv", "draft/bug/x/t1.md", "active/t1.md") + git(mind, "mv", "draft/bug/x/t2.md", "active/t2.md") + (mind / "active.md").write_text( + "# Active\n\n## t2-claim\n- issue: " + WORK_ISSUE + "\n- prompt: active/t2.md\n") + _commit(mind, "claim") + (mind / "complete" / "2026" / "11").mkdir(parents=True) + git(mind, "mv", "active/t1.md", "complete/2026/11/t-one.md") + (mind / "complete" / "2026" / "11" / "t-one.md").write_text("## What shipped\n\n- x\n\n" + body) + _commit(mind, "close") + git(mind, "push", "-q", "origin", "HEAD:main") + git(mind, "fetch", "-q", "origin") + return mind + + +# --- 1. links ---------------------------------------------------------------------- + +def test_titles_link_to_the_pr_else_the_work_issue_else_plain_and_mind_links_never_die( + moved_mind): + head = git(moved_mind, "rev-parse", "origin/main") + links = _digest.MindLinks(moved_mind, MIND_ISSUE) + # The prompt is found where it is now (renamed under complete/), pinned to a sha. + assert links.prompt_url("draft/bug/x/t1.md") == ( + f"https://github.com/example-org/example-mind/blob/{head}/complete/2026/11/t-one.md") + assert links.prompt_url("draft/bug/x/never.md") == "" # never on main: no link + counters = {"picks": {"t1": {"title": "One", "prompt": "draft/bug/x/t1.md"}, + "t2": {"title": "Two", "prompt": "draft/bug/x/t2.md"}, + "t3": {"title": "Three", "prompt": "draft/bug/x/t3.md"}}, + "outcomes": {"t1": {"prs": [PR], "merged": [PR], "issues": []}}} + assert _digest.work_link("t1", counters, links) == PR + assert _digest.work_link("t2", counters, links) == WORK_ISSUE # its claim's issue + assert _digest.work_link("t3", counters, links) == "" # neither: plain + line = _digest._line("t1", counters, "glance", lambda u: "HEALTHY", links) + assert line.startswith(f"- **Merged** — [One]({PR})\n") + assert f"[Mind prompt](https://github.com/example-org/example-mind/blob/{head}/" in line + assert "blob/main" not in line + assert _digest._line("t3", counters, "glance", lambda u: "x", links).startswith( + "- **Not started** — Three\n") + # No Mind checkout (a scratch slot, CI): links come only from the .done. + assert _digest.MindLinks(None, MIND_ISSUE).prompt_url("draft/bug/x/t1.md") == "" + + +# --- 2. the daemon leaves the unit's cgroup ------------------------------------------- + +FAKE_CLAUDE = """#!/bin/sh +# A fake `claude --bg`: start a detached "daemon" that outlives this client. +setsid sleep 30 /dev/null 2>&1 & +echo $! > "$FAKE_DAEMON_PID" +echo "backgrounded · deadbeef · shift:$1" +""" + + +class Run: + """`subprocess.run`, recorded; the first call can be made to fail.""" + + def __init__(self, fail_first: str = ""): + self.calls, self.fail_first = [], fail_first + + def __call__(self, argv, **kw): + self.calls.append(list(argv)) + if self.fail_first and len(self.calls) == 1: + return subprocess.CompletedProcess(argv, 1, "", self.fail_first) + return subprocess.CompletedProcess(argv, 0, "backgrounded · 0123abcd · x\n", "") + + +def test_sessions_launch_in_their_own_scope_inside_a_unit_and_plain_elsewhere( + tmp_path, monkeypatch): + found = lambda name: "/usr/bin/" + name # noqa: E731 + argv = ["claude", "--bg", "x"] + wrapped = orch.scope_command(argv, "t1", {"INVOCATION_ID": "abc"}, which=found) + assert wrapped[:4] == ["systemd-run", "--user", "--scope", "--quiet"] and wrapped[-3:] == argv + assert orch.scope_command(argv, "t1", {}, which=found) == argv # not in a unit + assert orch.scope_command(argv, "t1", {"INVOCATION_ID": "a"}, which=lambda n: None) == argv + + # Workers and close-outs take the same route (the spawn env carries the unit's id). + monkeypatch.setenv("INVOCATION_ID", "abc") + monkeypatch.setattr(orch.shutil, "which", found) + run = Run() + sp = orch.RealSpawner(tmp_path / "b.md", "auto", run=run) + sp.spawn("t1", "draft/x/t1.md", tmp_path) + sp.spawn_closeout("t1", PR, "draft/x/t1.md", tmp_path) + assert [c[:3] for c in run.calls] == [["systemd-run", "--user", "--scope"]] * 2 + i = run.calls[0].index("claude") + assert run.calls[0][i - 1] == "--" and run.calls[0][i:i + 4] == ["claude", "--bg", "--name", + "shift:t1"] + # systemd-run could not make the scope (no user bus): launched plain, once. + run = Run(fail_first="Failed to connect to bus: No such file or directory") + orch.RealSpawner(tmp_path / "b.md", "auto", run=run).spawn("t1", "draft/x/t1.md", tmp_path) + assert run.calls[0][0] == "systemd-run" and run.calls[1][0] == "claude" and len(run.calls) == 2 + + +def _user_scopes_work() -> bool: + if not sys.platform.startswith("linux") or shutil.which("systemd-run") is None: + return False + res = subprocess.run(["systemd-run", "--user", "--scope", "--quiet", "--collect", "true"], + capture_output=True, text=True, timeout=30) + return res.returncode == 0 + + +def test_a_daemon_started_through_the_route_lives_in_its_own_scope(tmp_path): + """Live, on a machine with a systemd user manager: a fake `claude` starts + a detached stand-in daemon through `run_scoped`; it lands in a + `run-*.scope`, not in the caller's cgroup. The stand-in is this test's own + `sleep`, stopped at the end — no real daemon is touched.""" + if not _user_scopes_work(): + pytest.skip("no systemd user manager here (CI, macOS)") + fake = tmp_path / "claude" + fake.write_text(FAKE_CLAUDE) + fake.chmod(0o755) + pidfile = tmp_path / "daemon.pid" + env = {**os.environ, "INVOCATION_ID": "test", "FAKE_DAEMON_PID": str(pidfile)} + res = orch.run_scoped(subprocess.run, [str(fake), "t1"], "t1", capture_output=True, + text=True, timeout=60, env=env) + assert res.returncode == 0 and "backgrounded · deadbeef" in res.stdout + for _ in range(50): + if pidfile.exists() and pidfile.read_text().strip(): + break + time.sleep(0.1) + pid = int(pidfile.read_text()) + try: + cgroup = Path(f"/proc/{pid}/cgroup").read_text().strip() + mine = Path("/proc/self/cgroup").read_text().strip() + assert cgroup.endswith(".scope") and "/run-" in cgroup and cgroup != mine + finally: + os.kill(pid, signal.SIGTERM) + + +# --- 3. plain wording ----------------------------------------------------------------- + +def test_golden_wording_for_a_merged_a_refused_and_a_running_task(): + pick = {"title": "Fix the thing", "size": "small", "repos": ["example_workspace"]} + merged = _digest.entry_lines( + "fix", pick, f"{PR} — merged unattended (close-out, claude-opus-5-5)", True, "glance", PR) + assert merged == [ + f"- **Merged** — [Fix the thing]({PR})", + " `fix` · glance · small · example_workspace · " + "merged unattended (close-out, claude-opus-5-5)"] + refused = _digest.entry_lines( + "fix", pick, f"{PR} — awaiting /prm — close-out refused: CI FAILED — never merged " + "unattended", True, "glance", PR, why="scoped tier glance") + assert refused == [ + f"- **CI failed — needs you** — [Fix the thing]({PR})", + " `fix` · glance · small · example_workspace · awaiting /prm — close-out " + "refused: CI FAILED — never merged unattended · why: scoped tier glance"] + running = _digest.entry_lines( + "fix", pick, "running (agent 0123abcd, working, since 2026-11-14T12:26Z)", True, + "glance", WORK_ISSUE, extra=["re-dispatched 1×"]) + assert running == [ + f"- **Still running** — [Fix the thing]({WORK_ISSUE})", + " `fix` · glance · small · example_workspace · running (agent 0123abcd, " + "working, since 2026-11-14T12:26Z) · re-dispatched 1×"] + assert _digest.plain_outcome("dropped by /drop — not started") == "Dropped" + assert _digest.plain_outcome(f"{PR} — RUNNING") == "CI running" + # validate reads the two-line entries and the one-line records before #634. + two = ("## Digest\n\n### Brief work\n- none\n\n### Backlog picks\n" + + "\n".join(refused) + "\n\n### Proof packets\n#### fix — x\n\n### Counters\n" + + "".join(f"- {k}: 0\n" for k in _digest.COUNTERS)) + assert _digest.validate(two) == [] + assert any("backlog pick fix has no `why:`" in e + for e in _digest.validate(two.replace(" · why: scoped tier glance", ""))) + + +# --- 4. the organ firewall ------------------------------------------------------------- + +def test_the_worker_template_runs_the_tenant_firewall_before_an_organ_push(tmp_path): + prompt = orch.worker_prompt("t1", "draft/x/t1.md", tmp_path / "b.md", tmp_path) + assert ('python3 PyAutoMind/scripts/repos_sync.py --check --only ' + '"tenant firewall (organ code)" --root "$PWD"') in prompt + assert "Before every push to an organ repo (PyAutoBrain, PyAutoHeart or PyAutoHands" in prompt + + +# --- 5. the close-out retires the queue entry ------------------------------------------ + +def test_a_merged_closeout_queues_the_queue_md_retirement(tmp_path): + mind, brief, home, sp = co._shift(tmp_path) + co._tick(brief, mind, home, sp, 1) + co._verdict(home, brief, "named", result="merged", pr=co.PR1, gate="g", model="m") + co._tick(brief, mind, home, sp, 2) + ops = [json.loads(f.read_text()) for f in mw.pending_ops(orch.slot_dir(brief, home))] + retire = [o for o in ops if o["op"] == "queue-retire"] + assert retire == [{"op": "queue-retire", "path": "queue.md", "prompt": "named.md", + "shipped_as": f"{co.PR1} (merged by the unattended close-out, " + "2026-11-04)"}] + assert "queue-retire queue.md " in orch.closeout_prompt( + "named", co.PR1, "draft/x/named.md", brief, tmp_path) + + +LIFECYCLE = t.LEDGER_MERGE.with_name("lifecycle.py") +QUEUE = """# Queue + +## 1. Fix it +- kind: prompt +- ref: draft/feature/x/t1.md + +## 2. Other +- kind: prompt +- ref: draft/feature/x/t9.md +""" + + +@pytest.mark.skipif(not LIFECYCLE.is_file() or shutil.which("git") is None, + reason="needs git and PyAutoMind's scripts/lifecycle.py beside this Brain") +def test_queue_retire_lands_in_the_ledger_commit_with_minds_own_rule(tmp_path): + bare, seed = tmp_path / "mind.git", tmp_path / "seed" + git(tmp_path, "init", "-q", "--bare", "-b", "main", str(bare)) + git(tmp_path, "clone", "-q", str(bare), str(seed)) + (seed / "scripts").mkdir() + shutil.copy(t.LEDGER_MERGE, seed / "scripts" / "ledger_merge.py") + shutil.copy(LIFECYCLE, seed / "scripts" / "lifecycle.py") + (seed / "queue.md").write_text(QUEUE) + (seed / "active").mkdir() + (seed / "active" / "t1.md").write_text("# t1\n") + _commit(seed, "seed") + git(seed, "push", "-q", "origin", "HEAD:main") + canon = tmp_path / "canon" + git(tmp_path, "clone", "-q", str(bare), str(canon)) + git(canon, "config", "user.name", "T") + git(canon, "config", "user.email", "t@example.invalid") + slot = tmp_path / "slot" + ledger = slot / mw.LEDGER_DIR + mw.queue_op(ledger, {"op": "move", "path": "active/t1.md", + "to": "complete/2026/11/t1.md"}) + mw.queue_op(ledger, {"op": "queue-retire", "path": "queue.md", "prompt": "t1.md", + "shipped_as": f"{PR} → complete/2026/11/t1.md (2026-11-14)"}) + # The watcher's safety net, the same retirement again: silent, no note. + mw.queue_op(ledger, {"op": "queue-retire", "path": "queue.md", "prompt": "t1.md", + "shipped_as": f"{PR} (merged by the unattended close-out, 2026-11-14)"}) + res = mw.commit_ledger(slot, canon, "shift: ledger") + assert res["committed"] and not res.get("set_aside") and not res.get("skipped") + queue = git(canon, "show", "origin/main:queue.md") + live, retired = queue.split("## Retired") + assert "Fix it" not in live and "## 2. Other" in live + assert f"- shipped-as: {PR} → complete/2026/11/t1.md (2026-11-14)" in retired + assert mw.QUEUE_RETIRED_BY in retired and "lifecycle.py close" not in retired + files = git(canon, "show", "--name-status", "--format=", "origin/main") + assert "queue.md" in files and "complete/2026/11/t1.md" in files # one commit + + +# --- N1: a worker still out at review-at -------------------------------------------- + +def test_a_worker_still_running_at_review_at_is_not_digested_as_not_started(tmp_path): + slot = tmp_path / "slot" + (slot / "leases").mkdir(parents=True) + (slot / "leases" / "t1.json").write_text(json.dumps({"agent_id": "0123abcd", + "started": "2026-11-14T20:01Z"})) + counters = {"picks": {"t1": {"title": "One", "tier": "glance", "size": "small", + "prompt": "draft/x/t1.md"}, + "t2": {"title": "Two", "tier": "glance"}}, + "outcomes": {}} + brief = {"tasks": {"value": "", "children": [{"text": "draft/x/t1.md"}, + {"text": "draft/x/t2.md"}]}, + "token-budget": {"value": "100"}, "review-minutes": {"value": "15"}} + d = _digest.build(brief, slot, counters, health=lambda u: "HEALTHY") + work = d.split("### Brief work")[1].split("### Backlog picks")[0] + assert ("- **Still running at review time** — One\n `t1` · glance · small · " + "still running at review time — the late sweep will report it") in work + assert "- **Not started** — Two" in work # no lease: truly not started + assert not any("t1 has no proof packet" in e for e in _digest.validate(d)) + + +def test_queue_retire_contains_a_broken_lifecycle_as_one_op_failure(tmp_path): + """Mind main's lifecycle.py is not the watcher's code: a syntax error or a + renamed `queue_retire_text` must surface as this op's MindWriteError (set + aside like any failing op), never as an exception that crashes the tick.""" + (tmp_path / "scripts").mkdir() + (tmp_path / "queue.md").write_text("# Queue\n\n## Retired\n", encoding="utf-8") + op = {"op": "queue-retire", "path": "queue.md", "prompt": "t1.md", + "shipped_as": "https://example.invalid/pr/1"} + for body in ("def broken(:\n", "def other():\n pass\n"): + (tmp_path / "scripts" / "lifecycle.py").write_text(body, encoding="utf-8") + with pytest.raises(mw.MindWriteError, match="queue-retire"): + mw.apply_op(tmp_path, op, None) + + +def test_retired_by_anchors_on_the_heading_not_header_prose(): + text = ("# Queue\nsee the `## Retired` footer\n\n## 1. A\n- note: retired by " + "`lifecycle.py close` once\n\n## Retired\n\n### B\n- note: retired by " + "`lifecycle.py close`\n") + out = mw._retired_by(text, 1) + assert "- note: retired by `lifecycle.py close` once" in out + assert out.endswith("- note: " + mw.QUEUE_RETIRED_BY + "\n") diff --git a/tests/test_batch_watch.py b/tests/test_batch_watch.py index 0153d443..e98bbdf2 100644 --- a/tests/test_batch_watch.py +++ b/tests/test_batch_watch.py @@ -213,7 +213,7 @@ def test_cli_once_through_pyauto_brain(tmp_path): def test_digest_and_watch_word_every_task_the_same(tmp_path): """With no lease held (as at review-at), each watch line carries the digest - line's state verbatim.""" + line's state verbatim, and the status comment's entry is the digest's.""" brief, slot = _record(tmp_path), _live_slot(tmp_path) for f in (slot / "leases").glob("*.json"): f.unlink() @@ -224,7 +224,7 @@ def test_digest_and_watch_word_every_task_the_same(tmp_path): digest = _digest.build(block, slot, orch.read_counters(slot), health=_health) snap = _watch.snapshot(brief, slot, NOW, health=_health) for row in snap["tasks"]: - assert f"- {row['task']} — {row['state']}" in digest, row + assert "\n".join(row["entry"]) in digest, row def test_refresh_interval_floor_and_cached_health(): diff --git a/tests/test_digest_counters.py b/tests/test_digest_counters.py index 5a7fada9..acf26ed7 100644 --- a/tests/test_digest_counters.py +++ b/tests/test_digest_counters.py @@ -118,7 +118,8 @@ def test_a_done_written_after_the_last_tick_appears_in_the_digest(tmp_path): r = _finish(brief, mind, home, AFTER, agents=d._agents({"t1": "done"}, slot)) assert r["action"] == "digest" text = (slot / orch.DIGEST_FILE).read_text() - assert f"{PR} — HEALTHY" in text and "the worker wrote no proof packet" in text + assert f"- **CI green — awaiting merge** — [t1]({PR})" in text \ + and "the worker wrote no proof packet" in text assert "(00000001): spawned/finished" in text assert orch.leases(slot) == {} diff --git a/tests/test_orchestrator_closeout.py b/tests/test_orchestrator_closeout.py index fa12c0a7..7ea3bc83 100644 --- a/tests/test_orchestrator_closeout.py +++ b/tests/test_orchestrator_closeout.py @@ -198,7 +198,9 @@ def test_a_refused_closeout_is_digested_and_never_retried(tmp_path): c = orch.read_counters(slot) assert c["glance_auto_merges"] == 0 and c["outcomes"]["named"]["merged"] == [] d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, c, health=t._health) - assert f"{PR1} — awaiting /prm — close-out refused: decision-taken label" in d + assert (f"- **Needs you — not merged unattended** — [named]({PR1})\n" + " `named` · glance · small · pyautobrain · awaiting /prm — close-out refused:" + " decision-taken label") in d def test_a_failed_closeout_is_refused_not_read_as_running(tmp_path): diff --git a/tests/test_orchestrator_digest.py b/tests/test_orchestrator_digest.py index 96f3d45f..2497bd37 100644 --- a/tests/test_orchestrator_digest.py +++ b/tests/test_orchestrator_digest.py @@ -172,14 +172,16 @@ def test_digest_separates_brief_work_from_backlog_picks_with_reasons(tmp_path): health=_health, issue=ISSUE) work = d.split("### Brief work")[1].split("### Backlog picks")[0] picks = d.split("### Backlog picks")[1].split("### Proof packets")[0] - # Picks read by title, linked to the prompt on the Mind the issue lives in. - blob = "https://github.com/example-org/example-mind/blob/main/" - assert (f"- [named]({blob}draft/feature/pyautobrain/named.md) (`named`; small · pyautobrain)" - " — https://github.com/o/r/pull/1 — merged — glance") in work - assert "- never — not started" in work + # Each task: the outcome in plain words and the title, linked to its PR + # (never to a Mind path, which moves and 404s, #634); the detail below. + assert ("- **Merged** — [named](https://github.com/o/r/pull/1)\n" + " `named` · glance · small · pyautobrain · merged") in work + assert "- **Not started** — never\n `never` · not started" in work + assert "blob/main" not in d # Green and glance: since phase 4b its close-out is running at review time. - assert ("(`picked`; small · pyautobrain) — https://github.com/o/r/pull/2 — close-out running" - " — glance — why: scoped epic e1 · not in queue.md") in picks + assert ("- **Still running — close-out checking it** — [picked](https://github.com/o/r/pull/2)\n" + " `picked` · glance · small · pyautobrain · close-out running" + " · why: scoped epic e1 · not in queue.md") in picks assert "`named`" not in picks @@ -237,7 +239,7 @@ def test_brief_check_refuses_a_missing_counter(tmp_path): def test_brief_check_refuses_a_pick_without_a_reason(tmp_path): mind, brief, home = _shift(tmp_path) rec = _with_digest(tmp_path, brief, home, - lambda d: d.replace(" — why: scoped epic e1", "")) + lambda d: d.replace(" · why: scoped epic e1", "")) res = _brief.check(rec, mind) assert not res["ok"] assert any("backlog pick picked has no `why:`" in e for e in res["errors"]) diff --git a/tests/test_orchestrator_shadow.py b/tests/test_orchestrator_shadow.py index 30708596..a3fa8c83 100644 --- a/tests/test_orchestrator_shadow.py +++ b/tests/test_orchestrator_shadow.py @@ -71,9 +71,11 @@ def test_the_shadow_digest_lists_proposals_and_validates(tmp_path): slot = orch.slot_dir(brief, home) d = _digest.build(_brief.parse(brief.read_text())["brief"], slot, orch.read_counters(slot), health=t._health) - assert "- **named** (`named`; small · pyautobrain) — proposed (shadow) — glance" in d - assert "- **picked** (`picked`; small · pyautobrain) — proposed (shadow) — glance — why: scoped epic e1 · not in queue.md" in d - assert "- never — not started" in d + assert ("- **Proposed (shadow)** — named\n" + " `named` · glance · small · pyautobrain · proposed (shadow)") in d + assert ("- **Proposed (shadow)** — picked\n `picked` · glance · small · pyautobrain" + " · proposed (shadow) · why: scoped epic e1 · not in queue.md") in d + assert "- **Not started** — never" in d assert _digest.NO_PACKETS_SHADOW in d # Every counter is 0 in a shadow shift: one line, not nine. assert _digest.SHADOW_COUNTERS + " · review-minutes-planned: 45" in d @@ -157,7 +159,7 @@ def test_titled_picks_validate_and_a_missing_why_names_the_slug(tmp_path): orch.read_counters(slot), health=t._health, issue=t.ISSUE) assert _digest.validate(d) == [] import re - bad = re.sub(r" — why: scoped epic e1[^\n]*", " — why: NOT RECORDED", d) + bad = re.sub(r" · why: scoped epic e1[^\n]*", " · why: NOT RECORDED", d) assert any("backlog pick picked has no `why:`" in e for e in _digest.validate(bad)) # The one-line shadow counters are accepted only as that line: a live # digest without its counters is still refused. diff --git a/tests/test_orchestrator_steering.py b/tests/test_orchestrator_steering.py index bbe342c5..d5dc97f7 100644 --- a/tests/test_orchestrator_steering.py +++ b/tests/test_orchestrator_steering.py @@ -133,7 +133,8 @@ def test_the_status_comment_is_created_once_and_then_only_edited(tmp_path, monke body = gh.status()[0]["body"] assert body == (slot / orch.STATUS_FILE).read_text() assert "**Shift `shift` — LIVE · 2h 30m left**" in body and "- tokens: 0 of 100000" in body - assert "(`t1`; small · pyautobrain) — running? (agent 00000001" in body and "@" not in body + assert "- **Still running** — t1\n `t1` · glance · small · pyautobrain · running? (agent 00000001" \ + in body and "@" not in body r = _tick(brief, mind, home, 1, claude, gh, {"t1": "working"}) # now listed: a change assert r["status"]["status"] == "edited" and "running (agent 00000001, working" in \ @@ -143,7 +144,7 @@ def test_the_status_comment_is_created_once_and_then_only_edited(tmp_path, monke (slot / "leases" / "t1.done").write_text("https://github.com/o/r/pull/9\n") r = _tick(brief, mind, home, 4, claude, gh, {"t1": "done"}) # a state change assert r["status"]["status"] == "edited" - assert "https://github.com/o/r/pull/9 — RUNNING" in gh.status()[0]["body"] + assert "- **CI running** — [t1](https://github.com/o/r/pull/9)" in gh.status()[0]["body"] r = _tick(brief, mind, home, 20, claude, gh) # the 10-minute refresh assert r["status"]["status"] == "edited" and "2h 10m left" in gh.status()[0]["body"]