From a0bdafc5837bef6a7a7155f8af7f1aebcae16d90 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 16 Nov 2026 12:52:26 +0000 Subject: [PATCH 1/3] M3.4 build C (Mind half): shift-cockpit carve-out and Monitor/Bash hook PyAutoBrain#646. Human rulings H1 (a), H2 (b) 45 min, H3 (a), H3b (a). - policy/shift_cockpit_watch.md: the DESIGN 3.1 carve-out, worded as approved. It is its own page because end_at_deliverable.md is stamped into every repo's AGENTS.md and capped at 10 lines; that file now bans a Monitor or background loop on GitHub and points at the carve-out. - shift_watcher.md: the one sentence on the cockpit watch. - end_at_deliverable_hook.sh: Monitor runs only the canonical `pyauto-brain batch watch --stream --record .../batches/.md` from dispatched - 30 min to review-at + 45 min (fail closed on an unreadable record); any other form naming the watcher is refused; a Monitor naming GitHub (gh, fetching git, github.com, claude agents, ci_verdict) or a WebSocket is refused; local tails pass. A background Bash loop on GitHub is refused; foreground Bash always passes. Refusals say: read CI once in the foreground, report and hand back. - repos_sync.py: Monitor and Bash join DELIVERABLE_HOOK_MATCHER; --check now flags a settings.json registering the hook under a stale matcher and --write refreshes it in place (before, only the command was compared, so the widened matcher would never have propagated). - Mind's own generated copies regenerated; other repos follow via the propagate workflow after merge. Co-Authored-By: Claude Opus 5.5 --- .claude/hooks/end-at-deliverable.sh | 132 ++++++++++++- .claude/settings.json | 2 +- .codex/hooks.json | 2 +- AGENTS.md | 11 +- policy/end_at_deliverable.md | 11 +- policy/end_at_deliverable_hook.sh | 132 ++++++++++++- policy/shift_cockpit_watch.md | 36 ++++ policy/shift_watcher.md | 4 + scripts/repos_sync.py | 66 ++++++- tests/test_end_at_deliverable_hook.py | 267 +++++++++++++++++++++++++- tests/test_session_hook_sync.py | 50 +++++ 11 files changed, 692 insertions(+), 21 deletions(-) create mode 100644 policy/shift_cockpit_watch.md diff --git a/.claude/hooks/end-at-deliverable.sh b/.claude/hooks/end-at-deliverable.sh index 1e52f7596..801d4a5ea 100755 --- a/.claude/hooks/end-at-deliverable.sh +++ b/.claude/hooks/end-at-deliverable.sh @@ -16,14 +16,33 @@ # this one is enforced by the harness. # # Registered under `hooks.PreToolUse` with the matcher -# ^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$ +# ^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|Monitor|Bash|mcp__.*(send_later|subscribe_pr_activity).*)$ # # Allowed through: # * `RemoteTrigger` with action list / get / list_runs / get_run_log — reading # what already exists never outlives the turn; +# * `Monitor` running exactly the shift cockpit's stream +# (`/PyAutoBrain/bin/pyauto-brain batch watch --stream --record +# /PyAutoMind/batches/.md [--from N] [--for M] [--home DIR]`), +# only from 30 min before that record's `dispatched:` to 45 min after its +# `review-at:` (the carve-out in shift_cockpit_watch.md, human ruling +# 2026-11-16, PyAutoBrain#646); +# * any other `Monitor` that names neither GitHub nor the watcher — a local +# tail of a pilot run's log stays allowed; +# * every foreground `Bash` call, and every background one that is not a loop +# on GitHub — a one-shot `gh pr checks 12` is how a session reads CI; # * anything at all when PYAUTO_ALLOW_TIMERS=1 — the human-authorised escape # for a routine the human actually asked for. # +# Refused, beyond the timer tools: a `Monitor` that names GitHub (`gh`, a +# fetching `git`, github.com, `claude agents`, `ci_verdict`) or opens a +# WebSocket; a `Monitor` that names `batch watch` or `orchestrator_watch` in any +# but the canonical form (a piped or wrapped stream is never let through); the +# stream outside its window or on a record it cannot read; and a background +# `Bash` loop (`while`/`until`/`watch`/`sleep`) that names GitHub. Known gap: +# the check is textual, so `gh` called from inside a local script passes it, as +# with scheduler_action_guard.py; the prose rule covers that case. +# # Everything else exits 2 (the harness treats stderr as the reason and blocks # the call). An unreadable payload also exits 2: this fails closed, because the # failure it guards against is silent and costs a night of usage. @@ -41,7 +60,9 @@ payload="$(cat)" PYAUTO_HOOK_PAYLOAD="$payload" python3 <<'PY' import json import os +import re import sys +from datetime import datetime, timedelta, timezone # Read-only RemoteTrigger actions: they inspect what exists and schedule nothing. READ_ONLY_REMOTE_TRIGGER = {"list", "get", "list_runs", "get_run_log"} @@ -53,12 +74,115 @@ REASON = ( "for a routine the human asked for.\n" ) +# A watch on GitHub (CI, a review, a merge, a PR, an issue) or a remote feed. +WATCH_REASON = ( + "policy end_at_deliverable: sessions end at their deliverable " + "— {what} would watch GitHub past the turn.\n" + "Do not wait for CI in the session: read it once in the foreground " + "(`gh pr checks ` or `ci_verdict.py`), report the verdict and hand " + "back; the human re-runs /prm when it is green.\n" + "The only watch a session may hold is the shift cockpit's stream, inside " + "its window. PYAUTO_ALLOW_TIMERS=1 only for a routine the human asked " + "for.\n" +) + +# The cockpit stream asked for in the wrong form, or outside its shift. +STREAM_REASON = ( + "policy end_at_deliverable: sessions end at their deliverable " + "— {what}.\n" + "The only watch a session may hold is the shift cockpit's stream, inside " + "its window: exactly `/PyAutoBrain/bin/pyauto-brain batch watch " + "--stream --record /PyAutoMind/batches/.md [--from N] " + "[--for M] [--home DIR]`, from 30 min before the record's dispatched: to " + "45 min after its review-at:.\n" + "If the shift is over, report the digest and stop; do not re-arm.\n" +) + +STREAM_RE = re.compile( + r"^(?P/\S+/PyAutoBrain/bin/pyauto-brain) batch watch --stream" + r" --record (?P/\S+/PyAutoMind/batches/[A-Za-z0-9-]+\.md)" + r"(?: --from \d+)?(?: --for \d+)?(?: --home /\S+)?$" +) +# Anything that reads the watcher's state: only the canonical stream may. +WATCHER_RE = re.compile(r"batch\s+watch|orchestrator_watch") +GITHUB_WATCH_RE = re.compile( + r"(^|[\s;|&(`$\"'/])(gh\s|git(\s+-C\s+\S+)?\s+(fetch|pull|ls-remote|remote\s+update)\b)" + r"|github\.com|claude\s+agents\b|ci[_-]verdict" +) +LOOP_RE = re.compile(r"\b(while|until|watch|sleep)\b") +KEY_RE = re.compile( + r"^- (dispatched|review-at):\s*(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?Z)", + re.M, +) +BEFORE = timedelta(minutes=30) # before dispatched: +AFTER = timedelta(minutes=45) # after review-at: (the late-sweep window, H2) + def block(tool): sys.stderr.write(REASON.format(tool=tool)) raise SystemExit(2) +def refuse(template, what): + sys.stderr.write(template.format(what=what)) + raise SystemExit(2) + + +def parse_utc(stamp): + fmt = "%Y-%m-%dT%H:%M:%SZ" if stamp.count(":") == 2 else "%Y-%m-%dT%H:%MZ" + return datetime.strptime(stamp, fmt).replace(tzinfo=timezone.utc) + + +def shift_window(record): + """The (dispatched, review-at) pair of a shift record: the first of each key.""" + with open(record, encoding="utf-8") as handle: + text = handle.read() + keys = {} + for key, stamp in KEY_RE.findall(text): + keys.setdefault(key, stamp) + start, end = parse_utc(keys["dispatched"]), parse_utc(keys["review-at"]) + if end < start: + raise ValueError("review-at before dispatched") + return start, end + + +def check_monitor(tool_input): + if tool_input.get("ws") is not None: + refuse(WATCH_REASON, "a WebSocket Monitor") + cmd = str(tool_input.get("command") or "").strip() + stream = STREAM_RE.match(cmd) + if stream: + try: + start, end = shift_window(stream["rec"]) + except Exception: + # Fail closed: a window the hook cannot read is one it cannot clear. + refuse(STREAM_REASON, "a shift stream on an unreadable shift record") + now = datetime.now(timezone.utc) + if not os.path.isfile(stream["cli"]): + refuse(STREAM_REASON, "a shift stream from a CLI that does not exist") + if start - BEFORE <= now <= end + AFTER: + raise SystemExit(0) + refuse(STREAM_REASON, + "a shift stream outside its window (the shift has ended or not begun)") + if WATCHER_RE.search(cmd): + refuse(STREAM_REASON, "a Monitor on the shift watcher in a non-canonical form") + if GITHUB_WATCH_RE.search(cmd): + refuse(WATCH_REASON, "a Monitor on GitHub") + raise SystemExit(0) # H3a: a local watch (a pilot run's log) stays allowed + + +def check_bash(tool_input): + background = tool_input.get("run_in_background") + if isinstance(background, str): + background = background.strip().lower() == "true" + if background is not True: + raise SystemExit(0) # a foreground call ends inside the turn + cmd = str(tool_input.get("command") or "") + if GITHUB_WATCH_RE.search(cmd) and LOOP_RE.search(cmd): + refuse(WATCH_REASON, "a background Bash loop on GitHub") + raise SystemExit(0) + + try: event = json.loads(os.environ.get("PYAUTO_HOOK_PAYLOAD", "")) if not isinstance(event, dict): @@ -78,5 +202,11 @@ if "RemoteTrigger" in tool: if isinstance(action, str) and action in READ_ONLY_REMOTE_TRIGGER: raise SystemExit(0) +if tool == "Monitor": + check_monitor(tool_input) + +if tool == "Bash": + check_bash(tool_input) + block(tool) PY diff --git a/.claude/settings.json b/.claude/settings.json index 5578c7d29..cfd46ffd3 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -12,7 +12,7 @@ ], "PreToolUse": [ { - "matcher": "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$", + "matcher": "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|Monitor|Bash|mcp__.*(send_later|subscribe_pr_activity).*)$", "hooks": [ { "type": "command", diff --git a/.codex/hooks.json b/.codex/hooks.json index 6f8e6e76f..221f6d570 100644 --- a/.codex/hooks.json +++ b/.codex/hooks.json @@ -3,7 +3,7 @@ "hooks": { "PreToolUse": [ { - "matcher": "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$", + "matcher": "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|Monitor|Bash|mcp__.*(send_later|subscribe_pr_activity).*)$", "hooks": [ { "type": "command", diff --git a/AGENTS.md b/AGENTS.md index c8f45dc91..35ec684c9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,11 +89,12 @@ clean tree: `git fetch origin && git reset --hard origin/main && git clean -fd`. A session ends when it reports its deliverable — never arm anything that outlives the turn to wait for CI, a review or a merge: no `send_later`, no -`subscribe_pr_activity`, no `CronCreate`, no `ScheduleWakeup`, no `/loop`, no -`RemoteTrigger` create/update/run. Judge once, report, stop; the human re-runs -`/prm` (or the batch review) when it is green. Measured: five batch members -armed hourly check-ins on 2026-08-31, and a mobile `/prm` re-armed a 60-minute -`send_later` hourly all night on 2026-09-03 with no task active, draining usage. +`subscribe_pr_activity`, `CronCreate`, `ScheduleWakeup`, `/loop`, `RemoteTrigger` +create/update/run, or `Monitor` or background loop on GitHub. Judge once, report, +stop; the human re-runs `/prm` (or the batch review) when it is green. The one +exception, the shift cockpit's stream: PyAutoMind `policy/shift_cockpit_watch.md`. +Measured: five batch members armed hourly check-ins on 2026-08-31, and a mobile +`/prm` re-armed a 60-minute `send_later` hourly all night on 2026-09-03. diff --git a/policy/end_at_deliverable.md b/policy/end_at_deliverable.md index bc695517c..08c40457a 100644 --- a/policy/end_at_deliverable.md +++ b/policy/end_at_deliverable.md @@ -2,8 +2,9 @@ A session ends when it reports its deliverable — never arm anything that outlives the turn to wait for CI, a review or a merge: no `send_later`, no -`subscribe_pr_activity`, no `CronCreate`, no `ScheduleWakeup`, no `/loop`, no -`RemoteTrigger` create/update/run. Judge once, report, stop; the human re-runs -`/prm` (or the batch review) when it is green. Measured: five batch members -armed hourly check-ins on 2026-08-31, and a mobile `/prm` re-armed a 60-minute -`send_later` hourly all night on 2026-09-03 with no task active, draining usage. +`subscribe_pr_activity`, `CronCreate`, `ScheduleWakeup`, `/loop`, `RemoteTrigger` +create/update/run, or `Monitor` or background loop on GitHub. Judge once, report, +stop; the human re-runs `/prm` (or the batch review) when it is green. The one +exception, the shift cockpit's stream: PyAutoMind `policy/shift_cockpit_watch.md`. +Measured: five batch members armed hourly check-ins on 2026-08-31, and a mobile +`/prm` re-armed a 60-minute `send_later` hourly all night on 2026-09-03. diff --git a/policy/end_at_deliverable_hook.sh b/policy/end_at_deliverable_hook.sh index 1e52f7596..801d4a5ea 100755 --- a/policy/end_at_deliverable_hook.sh +++ b/policy/end_at_deliverable_hook.sh @@ -16,14 +16,33 @@ # this one is enforced by the harness. # # Registered under `hooks.PreToolUse` with the matcher -# ^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$ +# ^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|RemoteTrigger|Monitor|Bash|mcp__.*(send_later|subscribe_pr_activity).*)$ # # Allowed through: # * `RemoteTrigger` with action list / get / list_runs / get_run_log — reading # what already exists never outlives the turn; +# * `Monitor` running exactly the shift cockpit's stream +# (`/PyAutoBrain/bin/pyauto-brain batch watch --stream --record +# /PyAutoMind/batches/.md [--from N] [--for M] [--home DIR]`), +# only from 30 min before that record's `dispatched:` to 45 min after its +# `review-at:` (the carve-out in shift_cockpit_watch.md, human ruling +# 2026-11-16, PyAutoBrain#646); +# * any other `Monitor` that names neither GitHub nor the watcher — a local +# tail of a pilot run's log stays allowed; +# * every foreground `Bash` call, and every background one that is not a loop +# on GitHub — a one-shot `gh pr checks 12` is how a session reads CI; # * anything at all when PYAUTO_ALLOW_TIMERS=1 — the human-authorised escape # for a routine the human actually asked for. # +# Refused, beyond the timer tools: a `Monitor` that names GitHub (`gh`, a +# fetching `git`, github.com, `claude agents`, `ci_verdict`) or opens a +# WebSocket; a `Monitor` that names `batch watch` or `orchestrator_watch` in any +# but the canonical form (a piped or wrapped stream is never let through); the +# stream outside its window or on a record it cannot read; and a background +# `Bash` loop (`while`/`until`/`watch`/`sleep`) that names GitHub. Known gap: +# the check is textual, so `gh` called from inside a local script passes it, as +# with scheduler_action_guard.py; the prose rule covers that case. +# # Everything else exits 2 (the harness treats stderr as the reason and blocks # the call). An unreadable payload also exits 2: this fails closed, because the # failure it guards against is silent and costs a night of usage. @@ -41,7 +60,9 @@ payload="$(cat)" PYAUTO_HOOK_PAYLOAD="$payload" python3 <<'PY' import json import os +import re import sys +from datetime import datetime, timedelta, timezone # Read-only RemoteTrigger actions: they inspect what exists and schedule nothing. READ_ONLY_REMOTE_TRIGGER = {"list", "get", "list_runs", "get_run_log"} @@ -53,12 +74,115 @@ REASON = ( "for a routine the human asked for.\n" ) +# A watch on GitHub (CI, a review, a merge, a PR, an issue) or a remote feed. +WATCH_REASON = ( + "policy end_at_deliverable: sessions end at their deliverable " + "— {what} would watch GitHub past the turn.\n" + "Do not wait for CI in the session: read it once in the foreground " + "(`gh pr checks ` or `ci_verdict.py`), report the verdict and hand " + "back; the human re-runs /prm when it is green.\n" + "The only watch a session may hold is the shift cockpit's stream, inside " + "its window. PYAUTO_ALLOW_TIMERS=1 only for a routine the human asked " + "for.\n" +) + +# The cockpit stream asked for in the wrong form, or outside its shift. +STREAM_REASON = ( + "policy end_at_deliverable: sessions end at their deliverable " + "— {what}.\n" + "The only watch a session may hold is the shift cockpit's stream, inside " + "its window: exactly `/PyAutoBrain/bin/pyauto-brain batch watch " + "--stream --record /PyAutoMind/batches/.md [--from N] " + "[--for M] [--home DIR]`, from 30 min before the record's dispatched: to " + "45 min after its review-at:.\n" + "If the shift is over, report the digest and stop; do not re-arm.\n" +) + +STREAM_RE = re.compile( + r"^(?P/\S+/PyAutoBrain/bin/pyauto-brain) batch watch --stream" + r" --record (?P/\S+/PyAutoMind/batches/[A-Za-z0-9-]+\.md)" + r"(?: --from \d+)?(?: --for \d+)?(?: --home /\S+)?$" +) +# Anything that reads the watcher's state: only the canonical stream may. +WATCHER_RE = re.compile(r"batch\s+watch|orchestrator_watch") +GITHUB_WATCH_RE = re.compile( + r"(^|[\s;|&(`$\"'/])(gh\s|git(\s+-C\s+\S+)?\s+(fetch|pull|ls-remote|remote\s+update)\b)" + r"|github\.com|claude\s+agents\b|ci[_-]verdict" +) +LOOP_RE = re.compile(r"\b(while|until|watch|sleep)\b") +KEY_RE = re.compile( + r"^- (dispatched|review-at):\s*(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?Z)", + re.M, +) +BEFORE = timedelta(minutes=30) # before dispatched: +AFTER = timedelta(minutes=45) # after review-at: (the late-sweep window, H2) + def block(tool): sys.stderr.write(REASON.format(tool=tool)) raise SystemExit(2) +def refuse(template, what): + sys.stderr.write(template.format(what=what)) + raise SystemExit(2) + + +def parse_utc(stamp): + fmt = "%Y-%m-%dT%H:%M:%SZ" if stamp.count(":") == 2 else "%Y-%m-%dT%H:%MZ" + return datetime.strptime(stamp, fmt).replace(tzinfo=timezone.utc) + + +def shift_window(record): + """The (dispatched, review-at) pair of a shift record: the first of each key.""" + with open(record, encoding="utf-8") as handle: + text = handle.read() + keys = {} + for key, stamp in KEY_RE.findall(text): + keys.setdefault(key, stamp) + start, end = parse_utc(keys["dispatched"]), parse_utc(keys["review-at"]) + if end < start: + raise ValueError("review-at before dispatched") + return start, end + + +def check_monitor(tool_input): + if tool_input.get("ws") is not None: + refuse(WATCH_REASON, "a WebSocket Monitor") + cmd = str(tool_input.get("command") or "").strip() + stream = STREAM_RE.match(cmd) + if stream: + try: + start, end = shift_window(stream["rec"]) + except Exception: + # Fail closed: a window the hook cannot read is one it cannot clear. + refuse(STREAM_REASON, "a shift stream on an unreadable shift record") + now = datetime.now(timezone.utc) + if not os.path.isfile(stream["cli"]): + refuse(STREAM_REASON, "a shift stream from a CLI that does not exist") + if start - BEFORE <= now <= end + AFTER: + raise SystemExit(0) + refuse(STREAM_REASON, + "a shift stream outside its window (the shift has ended or not begun)") + if WATCHER_RE.search(cmd): + refuse(STREAM_REASON, "a Monitor on the shift watcher in a non-canonical form") + if GITHUB_WATCH_RE.search(cmd): + refuse(WATCH_REASON, "a Monitor on GitHub") + raise SystemExit(0) # H3a: a local watch (a pilot run's log) stays allowed + + +def check_bash(tool_input): + background = tool_input.get("run_in_background") + if isinstance(background, str): + background = background.strip().lower() == "true" + if background is not True: + raise SystemExit(0) # a foreground call ends inside the turn + cmd = str(tool_input.get("command") or "") + if GITHUB_WATCH_RE.search(cmd) and LOOP_RE.search(cmd): + refuse(WATCH_REASON, "a background Bash loop on GitHub") + raise SystemExit(0) + + try: event = json.loads(os.environ.get("PYAUTO_HOOK_PAYLOAD", "")) if not isinstance(event, dict): @@ -78,5 +202,11 @@ if "RemoteTrigger" in tool: if isinstance(action, str) and action in READ_ONLY_REMOTE_TRIGGER: raise SystemExit(0) +if tool == "Monitor": + check_monitor(tool_input) + +if tool == "Bash": + check_bash(tool_input) + block(tool) PY diff --git a/policy/shift_cockpit_watch.md b/policy/shift_cockpit_watch.md new file mode 100644 index 000000000..ddfd05f52 --- /dev/null +++ b/policy/shift_cockpit_watch.md @@ -0,0 +1,36 @@ + + +## The one watch a session may hold: the shift cockpit (2026-11-16, human ruling) + +A Claude session may keep one watch running past its turn only when all of these hold: + +1. **The human asked for it in this session** ("watch the shift"), and the session is running + the `cockpit` skill. No other skill, agent, shift worker or close-out session arms it. +2. **It is exactly the shift's event stream.** The watch is the `Monitor` tool running + `/bin/pyauto-brain batch watch --stream --record /batches/.md` + (plus `--from`, `--for`, `--home`), with nothing before, after or around it. That command + reads one local file the shift watcher writes. It makes no network call and spends no + tokens until an event lands. +3. **The shift is open.** It may start only from 30 minutes before the brief's `dispatched:` + to 45 minutes after its `review-at:` (the late-sweep window). The hook refuses it outside + that window. +4. **It ends with the shift, and is not re-armed.** The stream exits at the shift's end, at + `STOP`, or when the window closes. The session arms it again only after a `segment-end` + line, which the stream prints just before Monitor's 30-minute limit while the shift is + still open. After any other exit it never arms it again. +5. **Steering stays on the shift issue.** Every steering act is a comment from the human's + login on the shift's issue, which the watcher reads. The chat may post that comment for + the human, and it steers the shift in no other way. + +Everything else `end_at_deliverable.md` bans stays banned, inside a shift as well as +outside it: +- `send_later`, `subscribe_pr_activity`, `CronCreate`, `ScheduleWakeup` and `/loop`; +- `RemoteTrigger` create, update and run; +- any `Monitor` or background command that watches GitHub (CI, a review, a merge, a PR, an + issue), including one on a PR the shift itself opened. + +A session that wants to know whether a PR is green reads it once and reports. diff --git a/policy/shift_watcher.md b/policy/shift_watcher.md index 85c523b20..7f185747d 100644 --- a/policy/shift_watcher.md +++ b/policy/shift_watcher.md @@ -28,6 +28,10 @@ What keeps the exemption narrow: (PyAutoBrain#622; `PyAutoBrain/AUTONOMY.md` watcher network surface, amendment 2026-11-13). +The watcher's per-shift event file may be watched by one cockpit session the human starts +(`shift_cockpit_watch.md`, "The one watch a session may hold"). That watch reads a local file, +ends with the shift, and is not in the control loop: closing the chat changes nothing. + Why it is this narrow: the timer rule was written after five batch members armed hourly check-ins on 2026-08-31, and a mobile `/prm` re-armed a 60-minute `send_later` hourly all night on 2026-09-03 with no task active, draining usage. diff --git a/scripts/repos_sync.py b/scripts/repos_sync.py index 5f71d6868..25fbc287e 100644 --- a/scripts/repos_sync.py +++ b/scripts/repos_sync.py @@ -54,10 +54,12 @@ (SessionStart) — what makes a Claude Code web/mobile session run Python 3.12 instead of the container's 3.11 default; * `policy/end_at_deliverable_hook.sh` -> `.claude/hooks/end-at-deliverable.sh` - (PreToolUse, matching the timer-shaped tools) — the guard that enforces - `policy/end_at_deliverable.md`: a session ends at its deliverable and never - arms `send_later` / `subscribe_pr_activity` / `CronCreate` / `ScheduleWakeup` - / `RemoteTrigger` create-update-run to wait for CI, a review or a merge. + (PreToolUse, matching the timer-shaped tools plus Monitor and Bash) — the + guard that enforces `policy/end_at_deliverable.md`: a session ends at its + deliverable and never arms `send_later` / `subscribe_pr_activity` / + `CronCreate` / `ScheduleWakeup` / `RemoteTrigger` create-update-run, a + Monitor on GitHub or a background Bash loop on GitHub to wait for CI, a + review or a merge; the one watch allowed is the shift cockpit's stream. The copies must be byte-identical to the canonical files, so `--check` fails on any edit made to a copy. @@ -336,9 +338,15 @@ def all_checkouts(root): DELIVERABLE_HOOK_FILE = "policy/end_at_deliverable_hook.sh" DELIVERABLE_HOOK_REL = ".claude/hooks/end-at-deliverable.sh" DELIVERABLE_HOOK_COMMAND = "$CLAUDE_PROJECT_DIR/.claude/hooks/end-at-deliverable.sh" +# +# `Monitor` and `Bash` joined the matcher with the shift-cockpit carve-out +# (2026-11-16, PyAutoBrain#646): a Monitor may run only the cockpit's stream +# inside its shift window or a local watch, never one on GitHub, and a +# background Bash loop on GitHub is refused. Foreground Bash passes straight +# through the hook. DELIVERABLE_HOOK_MATCHER = ( "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|" - "RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$" + "RemoteTrigger|Monitor|Bash|mcp__.*(send_later|subscribe_pr_activity).*)$" ) # Codex reads project hooks from `.codex/hooks.json`, after the user has @@ -2603,6 +2611,44 @@ def settings_registers_deliverable_hook(text): return DELIVERABLE_HOOK_COMMAND in pre_tool_use_entries(settings) +def _deliverable_groups(settings): + """The PreToolUse groups that run the end-at-deliverable hook.""" + return [ + group + for group in settings.get("hooks", {}).get("PreToolUse", []) or [] + if isinstance(group, dict) + and any( + isinstance(hook, dict) and hook.get("command") == DELIVERABLE_HOOK_COMMAND + for hook in group.get("hooks", []) or [] + ) + ] + + +def settings_deliverable_matcher_current(text): + """True when every group running the hook carries today's matcher. + + The command alone is not enough: when the matcher widened to Monitor and + Bash (2026-11-16) a repo still registering the old one would let a Monitor + on CI through without ever calling the hook.""" + try: + settings = json.loads(text) + except (ValueError, TypeError): + return False + if not isinstance(settings, dict): + return False + groups = _deliverable_groups(settings) + return bool(groups) and all( + group.get("matcher") == DELIVERABLE_HOOK_MATCHER for group in groups + ) + + +def refresh_deliverable_matcher(settings): + """Set today's matcher on every group that runs the hook, in place.""" + for group in _deliverable_groups(settings): + group["matcher"] = DELIVERABLE_HOOK_MATCHER + return settings + + def register_deliverable_hook(settings): """Add the PreToolUse registration, preserving every other hook the repo already runs on PreToolUse (the workspace root, for one, guards Bash).""" @@ -2709,6 +2755,11 @@ def check_session_hooks(root, repos, hook_text, deliverable_text): f"'{name}': {SESSION_SETTINGS_REL} does not register the " "PreToolUse end-at-deliverable hook" ) + elif not settings_deliverable_matcher_current(settings_text): + problems.append( + f"'{name}': {SESSION_SETTINGS_REL} registers the " + "end-at-deliverable hook under a stale matcher" + ) return problems @@ -2760,6 +2811,11 @@ def write_session_hooks(root, repos, hook_text, deliverable_text): ) if not registered ] + if ( + settings_registers_deliverable_hook(text) + and not settings_deliverable_matcher_current(text) + ): + missing.append(refresh_deliverable_matcher) if not missing: print(f"unchanged: {settings}") continue diff --git a/tests/test_end_at_deliverable_hook.py b/tests/test_end_at_deliverable_hook.py index a6e651278..b1015e654 100644 --- a/tests/test_end_at_deliverable_hook.py +++ b/tests/test_end_at_deliverable_hook.py @@ -16,6 +16,7 @@ import os import subprocess import sys +from datetime import datetime, timedelta, timezone from pathlib import Path import pytest @@ -150,14 +151,14 @@ def test_a_missing_tool_input_is_not_a_crash(): @pytest.mark.parametrize("tool", [ "send_later", "subscribe_pr_activity", "ScheduleWakeup", "CronCreate", - "RemoteTrigger", "mcp__anything__send_later__x", + "RemoteTrigger", "mcp__anything__send_later__x", "Monitor", "Bash", ]) def test_the_registered_matcher_selects_every_timer_tool(tool): import re assert re.match(repos_sync.DELIVERABLE_HOOK_MATCHER, tool), tool -@pytest.mark.parametrize("tool", ["Bash", "Read", "Edit", "Task", "mcp__github__x"]) +@pytest.mark.parametrize("tool", ["Read", "Edit", "Task", "BashOutput", "mcp__github__x"]) def test_the_matcher_leaves_ordinary_tools_alone(tool): """An over-broad matcher would run this hook on every call in the session.""" import re @@ -196,3 +197,265 @@ def test_codex_malformed_payload_is_still_fail_closed(): result = run('{"turn_id":"turn-1","tool_input":{}}') assert result.returncode == 2 assert REASON in result.stderr + + + +# -------------------------------------------------------------------------- +# The shift-cockpit carve-out (2026-11-16, PyAutoBrain#646): Monitor and +# background Bash. The one watch allowed is the cockpit's stream inside its +# window; any watch on GitHub is refused; local tails and one-shot reads pass. +# -------------------------------------------------------------------------- + +WATCH = "would watch GitHub past the turn" +STREAM = "The only watch a session may hold is the shift cockpit's stream" +# Fictional shift times, set relative to the real clock so the hook runs +# unpatched: the record's window is [dispatched - 30 min, review-at + 45 min]. +SHIFT_LENGTH = timedelta(hours=2) + + +def stamp(moment): + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def fixture_shift(tmp_path, *, dispatched=None, review_at=None, body=None): + """A fictional workspace: the Brain CLI and one Mind shift record. + + Returns the canonical stream command for that record. Times default to a + shift that is open now (dispatched an hour ago, review-at in an hour). + """ + now = datetime.now(timezone.utc) + dispatched = dispatched or now - timedelta(hours=1) + review_at = review_at or dispatched + SHIFT_LENGTH + cli = tmp_path / "ws" / "PyAutoBrain" / "bin" / "pyauto-brain" + cli.parent.mkdir(parents=True) + cli.write_text("#!/bin/sh\n") + record = tmp_path / "ws" / "PyAutoMind" / "batches" / "2026-11-16-pm.md" + record.parent.mkdir(parents=True) + if body is None: + body = ( + "# Batch 2026-11-16-pm\n" + f"- dispatched: {stamp(dispatched)} # fictional\n" + f"- review-at: {stamp(review_at)}\n" + "- brief:\n" + ) + record.write_text(body) + return f"{cli} batch watch --stream --record {record}" + + +def monitor(command=None, **extra): + tool_input = {"description": "shift events", "timeout_ms": 1800000, **extra} + if command is not None: + tool_input["command"] = command + return run({"tool_name": "Monitor", "tool_input": tool_input}) + + +def bash(command, background): + tool_input = {"command": command, "description": "x"} + if background is not None: + tool_input["run_in_background"] = background + return run({"tool_name": "Bash", "tool_input": tool_input}) + + +def allowed(result): + return result.returncode == 0 and result.stderr == "" + + +# -- the stream: allowed only inside its window ------------------------------ + +def test_the_stream_is_allowed_mid_shift(tmp_path): + assert allowed(monitor(fixture_shift(tmp_path))) + + +@pytest.mark.parametrize("flags", [ + " --from 42", " --for 28", " --from 0 --for 28", + " --from 42 --for 28 --home /home/someone/.orchestrator", +]) +def test_the_stream_with_its_canonical_flags_is_allowed(tmp_path, flags): + assert allowed(monitor(fixture_shift(tmp_path) + flags)) + + +def test_the_stream_is_allowed_29_minutes_before_dispatched(tmp_path): + now = datetime.now(timezone.utc) + assert allowed(monitor(fixture_shift(tmp_path, dispatched=now + timedelta(minutes=29)))) + + +def test_the_stream_is_allowed_44_minutes_after_review_at(tmp_path): + now = datetime.now(timezone.utc) + review_at = now - timedelta(minutes=44) + cmd = fixture_shift(tmp_path, dispatched=review_at - SHIFT_LENGTH, review_at=review_at) + assert allowed(monitor(cmd)) + + +def test_the_stream_is_refused_46_minutes_after_review_at(tmp_path): + """The witness: the same record, the same command, the shift over.""" + now = datetime.now(timezone.utc) + review_at = now - timedelta(minutes=46) + cmd = fixture_shift(tmp_path, dispatched=review_at - SHIFT_LENGTH, review_at=review_at) + result = monitor(cmd) + assert result.returncode == 2 + assert "outside its window" in result.stderr + assert STREAM in result.stderr + assert "do not re-arm" in result.stderr + + +def test_the_stream_is_refused_31_minutes_before_dispatched(tmp_path): + now = datetime.now(timezone.utc) + result = monitor(fixture_shift(tmp_path, dispatched=now + timedelta(minutes=31))) + assert result.returncode == 2 + assert "outside its window" in result.stderr + + +def test_minute_precision_record_keys_are_read(tmp_path): + """Real briefs write `2026-11-14T19:50Z`, without seconds.""" + now = datetime.now(timezone.utc) + body = (f"- dispatched: {now - timedelta(hours=1):%Y-%m-%dT%H:%MZ}\n" + f"- review-at: {now + timedelta(hours=1):%Y-%m-%dT%H:%MZ}\n") + assert allowed(monitor(fixture_shift(tmp_path, body=body))) + + +@pytest.mark.parametrize("body", [ + "# a record with no brief keys\n", + "- dispatched: 2026-11-16T10:00Z\n", # no review-at + "- dispatched: soon\n- review-at: later\n", + "- dispatched: 2026-11-16T12:00Z\n- review-at: 2026-11-16T10:00Z\n", # inverted +]) +def test_the_stream_on_an_unreadable_record_fails_closed(tmp_path, body): + result = monitor(fixture_shift(tmp_path, body=body)) + assert result.returncode == 2 + assert "unreadable shift record" in result.stderr + + +def test_the_stream_on_a_missing_record_fails_closed(tmp_path): + cmd = fixture_shift(tmp_path).replace("2026-11-16-pm.md", "2026-11-17-am.md") + assert monitor(cmd).returncode == 2 + + +def test_the_stream_from_a_cli_that_does_not_exist_is_refused(tmp_path): + cmd = fixture_shift(tmp_path).replace("/ws/PyAutoBrain/", "/elsewhere/PyAutoBrain/") + assert monitor(cmd).returncode == 2 + + +@pytest.mark.parametrize("wrap", [ + "{cmd} | grep --line-buffered NEEDS", # piped + "{cmd}; gh pr checks 12", # chained to GitHub + "{cmd} && sleep 60", + "cd /tmp && {cmd}", # something before it + "{cmd} --watch-ci", # an unknown flag + "bash -c '{cmd}'", # wrapped +]) +def test_a_wrapped_or_piped_stream_is_refused(tmp_path, wrap): + result = monitor(wrap.format(cmd=fixture_shift(tmp_path))) + assert result.returncode == 2, result + + +def test_a_stream_from_a_relative_path_is_refused(tmp_path): + fixture_shift(tmp_path) + cmd = ("PyAutoBrain/bin/pyauto-brain batch watch --stream " + "--record PyAutoMind/batches/2026-11-16-pm.md") + result = monitor(cmd) + assert result.returncode == 2 + assert "non-canonical form" in result.stderr + + +def test_the_raw_watcher_script_under_monitor_is_refused(): + assert monitor("python3 /x/PyAutoBrain/bin/orchestrator_watch.py --once").returncode == 2 + + +# -- any other Monitor on GitHub is refused (H3a) ---------------------------- + +@pytest.mark.parametrize("cmd", [ + "gh pr checks 12 --watch", + "gh run watch 123456", + "while true; do gh api repos/o/r/issues/1/comments; sleep 30; done", + "until python3 /x/PyAutoBrain/bin/ci_verdict.py --repo o/r --pr 12; do sleep 60; done", + "while :; do python3 bin/ci-verdict o/r 12; sleep 60; done", + "while true; do s=$(gh pr view 12 --json state); echo $s; sleep 30; done", + "while true; do git fetch origin && git log -1 origin/main; sleep 60; done", + "while true; do git -C /x/repo fetch -q; sleep 60; done", + "while true; do curl -s https://api.github.com/repos/o/r/pulls/12; sleep 30; done", + "bash -c \"gh pr checks 12 --watch\"", + "claude agents --watch", +]) +def test_a_monitor_on_github_is_refused_with_the_check_once_instruction(cmd): + result = monitor(cmd) + assert result.returncode == 2, result + assert WATCH in result.stderr + # The refusal says what to do instead: read CI once and hand back. + assert "read it once in the foreground" in result.stderr + assert "hand back" in result.stderr + assert "/prm" in result.stderr + + +def test_a_websocket_monitor_is_refused(): + result = monitor(ws={"url": "wss://events.example.com/stream"}) + assert result.returncode == 2 + assert "WebSocket" in result.stderr + + +# -- local watches stay allowed (H3a) ---------------------------------------- + +@pytest.mark.parametrize("cmd", [ + "tail -f run.log | grep --line-buffered ERROR", + "tail -F /home/someone/Science/active/pilot/output/run.log " + "| grep -E --line-buffered 'elapsed|Traceback|Killed'", + "inotifywait -m --format '%e %f' /tmp/out", + "while true; do ls output | wc -l; sleep 5; done", + "tail -f /x/autolens_workspace/scripts/log.txt", # the word 'git' nowhere, 'log' is fine + "tail -f pilot.log | grep --line-buffered 'git status'", +]) +def test_a_local_monitor_is_allowed(cmd): + assert allowed(monitor(cmd)) + + +# -- Bash: one-shot reads pass; background GitHub loops do not (H3b) --------- + +@pytest.mark.parametrize("cmd,background", [ + ("gh pr checks 12", None), + ("gh pr checks 12", False), + ("gh pr checks 12 --watch", False), # foreground: it ends inside the turn + ("python3 /x/PyAutoBrain/bin/ci_verdict.py --repo o/r --pr 12", False), + ("until gh pr checks 12; do sleep 30; done", False), + ("pytest tests -q", True), + ("python3 pilot.py > run.log 2>&1", True), + ("until grep -q Ready dev.log; do sleep 0.5; done", True), + ("gh pr view 12 --json state", True), # background but one-shot +]) +def test_bash_that_does_not_loop_on_github_in_the_background_passes(cmd, background): + assert allowed(bash(cmd, background)) + + +@pytest.mark.parametrize("cmd", [ + "until gh pr checks 12; do sleep 30; done", + "while true; do gh api repos/o/r/actions/runs; sleep 60; done", + "gh pr checks 12 --watch", + "gh run watch 123", + "until python3 bin/ci_verdict.py --pr 12; do sleep 60; done", + "while ! git fetch origin; do sleep 30; done", +]) +def test_a_background_bash_loop_on_github_is_refused(cmd): + result = bash(cmd, True) + assert result.returncode == 2, result + assert "background Bash loop on GitHub" in result.stderr + assert "read it once in the foreground" in result.stderr + + +def test_a_string_run_in_background_is_read_as_the_flag(): + assert bash("until gh pr checks 12; do sleep 30; done", "true").returncode == 2 + + +# -- the escape and the fail-closed paths still hold for the new tools ------- + +@pytest.mark.parametrize("payload", [ + {"tool_name": "Monitor", "tool_input": {"command": "gh pr checks 12 --watch"}}, + {"tool_name": "Monitor", "tool_input": {"ws": {"url": "wss://x"}}}, + {"tool_name": "Bash", "tool_input": {"command": "until gh pr checks 1; do sleep 9; done", + "run_in_background": True}}, +]) +def test_the_escape_hatch_covers_the_new_branches(payload): + assert allowed(run(payload, env={"PYAUTO_ALLOW_TIMERS": "1"})) + + +def test_a_malformed_monitor_payload_fails_closed(): + result = run('{"tool_name": "Monitor", "tool_input": ') + assert result.returncode == 2 + assert REASON in result.stderr diff --git a/tests/test_session_hook_sync.py b/tests/test_session_hook_sync.py index 0acd3946b..69c9b4ced 100644 --- a/tests/test_session_hook_sync.py +++ b/tests/test_session_hook_sync.py @@ -912,3 +912,53 @@ def test_the_skipping_step_composes_both_decisions(tmp_path, hook_pr, assert proc.stdout.count("SKIPPED LEG") == len(skipped), proc.stdout for label in skipped: assert f"SKIPPED LEG: '{label}'" in proc.stdout + + +# -------------------------------------------------------------------------- +# A stale matcher is drift too (the 2026-11-16 widening to Monitor and Bash) +# -------------------------------------------------------------------------- + +OLD_MATCHER = ( + "^(send_later|subscribe_pr_activity|ScheduleWakeup|CronCreate|" + "RemoteTrigger|mcp__.*(send_later|subscribe_pr_activity).*)$" +) + + +def _stale_settings(): + settings = repos_sync.register_deliverable_hook( + repos_sync.register_session_hook({}) + ) + settings["hooks"]["PreToolUse"][0]["matcher"] = OLD_MATCHER + settings["hooks"]["PreToolUse"].insert( + 0, {"matcher": "Bash", "hooks": [{"type": "command", "command": "guard.sh"}]} + ) + return json.dumps(settings, indent=2) + "\n" + + +def test_a_registration_under_a_stale_matcher_is_reported(tmp_path): + """Registered but under the old matcher, the hook is never called for a + Monitor on CI, so a command-only check would read it as installed.""" + make_repo(tmp_path, "OrganOne", settings=_stale_settings()) + make_repo(tmp_path, "LibTwo") + problems = repos_sync.check_session_hooks( + tmp_path, REPOS, HOOK_TEXT, DELIVERABLE_TEXT + ) + assert len(problems) == 1, problems + assert "OrganOne" in problems[0] and "stale matcher" in problems[0] + + +def test_write_refreshes_a_stale_matcher_and_keeps_other_hooks(tmp_path): + make_repo(tmp_path, "OrganOne", settings=_stale_settings()) + make_repo(tmp_path, "LibTwo") + repos_sync.write_session_hooks(tmp_path, REPOS, HOOK_TEXT, DELIVERABLE_TEXT) + assert repos_sync.check_session_hooks( + tmp_path, REPOS, HOOK_TEXT, DELIVERABLE_TEXT + ) == [] + settings = json.loads( + (tmp_path / "OrganOne" / repos_sync.SESSION_SETTINGS_REL).read_text() + ) + groups = settings["hooks"]["PreToolUse"] + assert [g["matcher"] for g in groups] == [ + "Bash", repos_sync.DELIVERABLE_HOOK_MATCHER + ] + assert len(groups) == 2 # refreshed in place, not registered twice From e7db219e2e49c42a0aac76a0639a26ae9645d228 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Mon, 16 Nov 2026 13:06:02 +0000 Subject: [PATCH 2/3] M3.4 build C review fixes: strict pinned stream, stdin payload, fast path Findings on 767be8c03 (PyAutoBrain#646): - The stream command is matched whole and unstripped, every character in [A-Za-z0-9._/ -], so `;`, `$IFS`, backticks, `$( )`, quotes, globs, redirections and newlines can no longer ride on an allowed stream. - The CLI and the record are pinned to the Brain and Mind checkouts the workspace's own resolver names (PYAUTO_ROOT, else the `.pyauto-root` above the hook, then PyAutoBrain/agents/_repo_paths.py); a CLI that merely exists elsewhere is refused, and no resolvable workspace fails closed. - The payload reaches Python on stdin, not an env var: a call over 128 KB no longer fails to start Python (exit 126, which failed open). - A bash fast path allows a foreground Bash call before Python starts (90 ms -> 9 ms per call); anything ambiguous still goes to Python. - end_at_deliverable.md says "draining usage" again, still 10 lines. - shift_cockpit_watch.md lists the v1 limits (textual false refusals and false passes). Propagation: session_hook_propagate.yml writes the hook copy and the settings.json matcher through write_session_hooks and commits them in one commit per repo, so the new matcher never lands beside the old hook. Codex users must re-trust the changed hook hash in `/hooks`. Co-Authored-By: Claude Opus 5.5 --- .claude/hooks/end-at-deliverable.sh | 139 +++++++++++++++++-- AGENTS.md | 2 +- policy/end_at_deliverable.md | 2 +- policy/end_at_deliverable_hook.sh | 139 +++++++++++++++++-- policy/shift_cockpit_watch.md | 6 + tests/test_end_at_deliverable_hook.py | 193 +++++++++++++++++++++++++- 6 files changed, 443 insertions(+), 38 deletions(-) diff --git a/.claude/hooks/end-at-deliverable.sh b/.claude/hooks/end-at-deliverable.sh index 801d4a5ea..dd7ce8f16 100755 --- a/.claude/hooks/end-at-deliverable.sh +++ b/.claude/hooks/end-at-deliverable.sh @@ -23,7 +23,11 @@ # what already exists never outlives the turn; # * `Monitor` running exactly the shift cockpit's stream # (`/PyAutoBrain/bin/pyauto-brain batch watch --stream --record -# /PyAutoMind/batches/.md [--from N] [--for M] [--home DIR]`), +# /PyAutoMind/batches/.md [--from N] [--for M] [--home DIR]`, +# paths in [A-Za-z0-9._/-] only, so no shell metacharacter rides along), +# with the CLI and the record inside the Brain and Mind checkouts this +# workspace's own resolver names (PYAUTO_ROOT, else the `.pyauto-root` +# above this hook, then PyAutoBrain/agents/_repo_paths.py), # only from 30 min before that record's `dispatched:` to 45 min after its # `review-at:` (the carve-out in shift_cockpit_watch.md, human ruling # 2026-11-16, PyAutoBrain#646); @@ -39,9 +43,11 @@ # WebSocket; a `Monitor` that names `batch watch` or `orchestrator_watch` in any # but the canonical form (a piped or wrapped stream is never let through); the # stream outside its window or on a record it cannot read; and a background -# `Bash` loop (`while`/`until`/`watch`/`sleep`) that names GitHub. Known gap: -# the check is textual, so `gh` called from inside a local script passes it, as -# with scheduler_action_guard.py; the prose rule covers that case. +# `Bash` loop (`while`/`until`/`watch`/`sleep`) that names GitHub. Known gaps, +# listed in policy/shift_cockpit_watch.md "Limits": the check is textual, so +# `gh` inside a script file, `python -c` or `git -c ... fetch` passes it (as +# with scheduler_action_guard.py; the prose rule covers those), and a local +# watch that merely mentions github.com is refused. # # Everything else exits 2 (the harness treats stderr as the reason and blocks # the call). An unreadable payload also exits 2: this fails closed, because the @@ -54,10 +60,36 @@ set -uo pipefail payload="$(cat)" +# Fast path, before Python starts: a foreground Bash call is always allowed +# (the Python below would exit 0 for it too), and it is most of the calls this +# hook sees now that the matcher includes Bash. Taken only when the payload is +# unambiguous: one JSON object, exactly one "tool_name" key, that key ahead of +# "tool_input" (so it is the top-level one, not a key nested in an input) with +# the value "Bash", and no "run_in_background" key anywhere. Anything else, +# including every timer tool and every Monitor, goes to Python. Inside a JSON +# string a quote is escaped, so `"tool_name"` cannot match string content. +_name_key='"tool_name"[[:space:]]*:' +_bash_head='"tool_name"[[:space:]]*:[[:space:]]*"Bash"[[:space:]]*[,}]' +case "$payload" in + *'"run_in_background"'*) ;; + '{'*'}') + _head="${payload%%\"tool_input\"*}" + _rest="${payload#*\"tool_name\"}" + if [[ $_head =~ $_bash_head ]] && ! [[ $_rest =~ $_name_key ]]; then + exit 0 + fi + ;; +esac + # python3 rather than jq: python3 is present everywhere this hook is installed -# (it is what the SessionStart hook guarantees), jq is not. The payload rides in -# the environment rather than on stdin so the heredoc keeps its own stdin. -PYAUTO_HOOK_PAYLOAD="$payload" python3 <<'PY' +# (it is what the SessionStart hook guarantees), jq is not. The payload goes to +# Python on stdin and the program as `-c`: an environment variable or an +# argument is capped at 128 KB per string, and a Bash call carrying a longer +# command would then fail to start Python at all (exit 126, a non-blocking hook +# error, so the call would go through unchecked). +PYAUTO_HOOK_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" +export PYAUTO_HOOK_DIR +IFS= read -r -d '' _program <<'PY' import json import os import re @@ -98,10 +130,14 @@ STREAM_REASON = ( "If the shift is over, report the digest and stop; do not re-arm.\n" ) +# Every character of an allowed stream command: no shell metacharacter, quote, +# glob, `$`, backtick, bracket, redirection or newline can reach a shell. +STREAM_CHARS_RE = re.compile(r"[A-Za-z0-9._/ -]+") +_PATH = r"/[A-Za-z0-9._/-]+" STREAM_RE = re.compile( - r"^(?P/\S+/PyAutoBrain/bin/pyauto-brain) batch watch --stream" - r" --record (?P/\S+/PyAutoMind/batches/[A-Za-z0-9-]+\.md)" - r"(?: --from \d+)?(?: --for \d+)?(?: --home /\S+)?$" + rf"(?P{_PATH}/PyAutoBrain/bin/pyauto-brain) batch watch --stream" + rf" --record (?P{_PATH}/PyAutoMind/batches/[A-Za-z0-9-]+\.md)" + rf"(?: --from [0-9]+)?(?: --for [0-9]+)?(?: --home {_PATH})?" ) # Anything that reads the watcher's state: only the canonical stream may. WATCHER_RE = re.compile(r"batch\s+watch|orchestrator_watch") @@ -146,20 +182,91 @@ def shift_window(record): return start, end +def workspace_root(): + """PYAUTO_ROOT, else the nearest ancestor of this hook holding a + `.pyauto-root` marker, else the nearest one holding a Brain checkout: + the order of PyAutoBrain/bin/_pyauto_root.sh.""" + explicit = os.environ.get("PYAUTO_ROOT") + if explicit: + return explicit + start = os.environ.get("PYAUTO_HOOK_DIR") or os.getcwd() + ancestors = [] + path = os.path.realpath(start) + while True: + ancestors.append(path) + parent = os.path.dirname(path) + if parent == path: + break + path = parent + for path in ancestors: + if os.path.isfile(os.path.join(path, ".pyauto-root")): + return path + for path in ancestors: + if brain_resolver_file(path): + return path + raise LookupError("no workspace root") + + +def brain_resolver_file(root): + found = { + os.path.realpath(candidate) + for candidate in ( + os.path.join(root, "PyAutoBrain", "agents", "_repo_paths.py"), + os.path.join(root, "organs", "PyAutoBrain", "agents", "_repo_paths.py"), + ) + if os.path.isfile(candidate) + } + if len(found) > 1: + raise LookupError("ambiguous PyAutoBrain checkouts") + return next(iter(found), None) + + +def resolved_checkouts(): + """(Brain, Mind) as the workspace's own resolver places them.""" + import importlib.util + + root = workspace_root() + resolver = brain_resolver_file(root) + if resolver is None: + raise LookupError("no PyAutoBrain/agents/_repo_paths.py under the root") + spec = importlib.util.spec_from_file_location("_pyauto_repo_paths", resolver) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return ( + os.path.realpath(module.repo_path(root, "PyAutoBrain", required=True)), + os.path.realpath(module.repo_path(root, "PyAutoMind", required=True)), + ) + + def check_monitor(tool_input): if tool_input.get("ws") is not None: refuse(WATCH_REASON, "a WebSocket Monitor") - cmd = str(tool_input.get("command") or "").strip() - stream = STREAM_RE.match(cmd) + raw = str(tool_input.get("command") or "") + cmd = raw.strip() + # The stream is matched unstripped: no newline anywhere, not even a last one. + stream = STREAM_RE.fullmatch(raw) if STREAM_CHARS_RE.fullmatch(raw) else None if stream: + try: + brain, mind = resolved_checkouts() + except Exception: + refuse(STREAM_REASON, + "a shift stream with no resolvable Brain and Mind checkouts") + # Pinned to this workspace's own checkouts, not any file that exists. + if (os.path.realpath(stream["cli"]) + != os.path.join(brain, "bin", "pyauto-brain") + or not os.path.isfile(stream["cli"])): + refuse(STREAM_REASON, + "a shift stream from a CLI outside this workspace's PyAutoBrain") + if (os.path.dirname(os.path.realpath(stream["rec"])) + != os.path.join(mind, "batches")): + refuse(STREAM_REASON, + "a shift stream on a record outside this workspace's PyAutoMind") try: start, end = shift_window(stream["rec"]) except Exception: # Fail closed: a window the hook cannot read is one it cannot clear. refuse(STREAM_REASON, "a shift stream on an unreadable shift record") now = datetime.now(timezone.utc) - if not os.path.isfile(stream["cli"]): - refuse(STREAM_REASON, "a shift stream from a CLI that does not exist") if start - BEFORE <= now <= end + AFTER: raise SystemExit(0) refuse(STREAM_REASON, @@ -184,7 +291,7 @@ def check_bash(tool_input): try: - event = json.loads(os.environ.get("PYAUTO_HOOK_PAYLOAD", "")) + event = json.loads(sys.stdin.read()) if not isinstance(event, dict): raise ValueError("PreToolUse payload is not a JSON object") tool = event.get("tool_name") @@ -210,3 +317,5 @@ if tool == "Bash": block(tool) PY + +printf '%s' "$payload" | python3 -c "$_program" diff --git a/AGENTS.md b/AGENTS.md index 35ec684c9..d72645cd6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,7 +94,7 @@ create/update/run, or `Monitor` or background loop on GitHub. Judge once, report stop; the human re-runs `/prm` (or the batch review) when it is green. The one exception, the shift cockpit's stream: PyAutoMind `policy/shift_cockpit_watch.md`. Measured: five batch members armed hourly check-ins on 2026-08-31, and a mobile -`/prm` re-armed a 60-minute `send_later` hourly all night on 2026-09-03. +`/prm` re-armed a 60-minute `send_later` all night on 2026-09-03, draining usage. diff --git a/policy/end_at_deliverable.md b/policy/end_at_deliverable.md index 08c40457a..0a6c7f77f 100644 --- a/policy/end_at_deliverable.md +++ b/policy/end_at_deliverable.md @@ -7,4 +7,4 @@ create/update/run, or `Monitor` or background loop on GitHub. Judge once, report stop; the human re-runs `/prm` (or the batch review) when it is green. The one exception, the shift cockpit's stream: PyAutoMind `policy/shift_cockpit_watch.md`. Measured: five batch members armed hourly check-ins on 2026-08-31, and a mobile -`/prm` re-armed a 60-minute `send_later` hourly all night on 2026-09-03. +`/prm` re-armed a 60-minute `send_later` all night on 2026-09-03, draining usage. diff --git a/policy/end_at_deliverable_hook.sh b/policy/end_at_deliverable_hook.sh index 801d4a5ea..dd7ce8f16 100755 --- a/policy/end_at_deliverable_hook.sh +++ b/policy/end_at_deliverable_hook.sh @@ -23,7 +23,11 @@ # what already exists never outlives the turn; # * `Monitor` running exactly the shift cockpit's stream # (`/PyAutoBrain/bin/pyauto-brain batch watch --stream --record -# /PyAutoMind/batches/.md [--from N] [--for M] [--home DIR]`), +# /PyAutoMind/batches/.md [--from N] [--for M] [--home DIR]`, +# paths in [A-Za-z0-9._/-] only, so no shell metacharacter rides along), +# with the CLI and the record inside the Brain and Mind checkouts this +# workspace's own resolver names (PYAUTO_ROOT, else the `.pyauto-root` +# above this hook, then PyAutoBrain/agents/_repo_paths.py), # only from 30 min before that record's `dispatched:` to 45 min after its # `review-at:` (the carve-out in shift_cockpit_watch.md, human ruling # 2026-11-16, PyAutoBrain#646); @@ -39,9 +43,11 @@ # WebSocket; a `Monitor` that names `batch watch` or `orchestrator_watch` in any # but the canonical form (a piped or wrapped stream is never let through); the # stream outside its window or on a record it cannot read; and a background -# `Bash` loop (`while`/`until`/`watch`/`sleep`) that names GitHub. Known gap: -# the check is textual, so `gh` called from inside a local script passes it, as -# with scheduler_action_guard.py; the prose rule covers that case. +# `Bash` loop (`while`/`until`/`watch`/`sleep`) that names GitHub. Known gaps, +# listed in policy/shift_cockpit_watch.md "Limits": the check is textual, so +# `gh` inside a script file, `python -c` or `git -c ... fetch` passes it (as +# with scheduler_action_guard.py; the prose rule covers those), and a local +# watch that merely mentions github.com is refused. # # Everything else exits 2 (the harness treats stderr as the reason and blocks # the call). An unreadable payload also exits 2: this fails closed, because the @@ -54,10 +60,36 @@ set -uo pipefail payload="$(cat)" +# Fast path, before Python starts: a foreground Bash call is always allowed +# (the Python below would exit 0 for it too), and it is most of the calls this +# hook sees now that the matcher includes Bash. Taken only when the payload is +# unambiguous: one JSON object, exactly one "tool_name" key, that key ahead of +# "tool_input" (so it is the top-level one, not a key nested in an input) with +# the value "Bash", and no "run_in_background" key anywhere. Anything else, +# including every timer tool and every Monitor, goes to Python. Inside a JSON +# string a quote is escaped, so `"tool_name"` cannot match string content. +_name_key='"tool_name"[[:space:]]*:' +_bash_head='"tool_name"[[:space:]]*:[[:space:]]*"Bash"[[:space:]]*[,}]' +case "$payload" in + *'"run_in_background"'*) ;; + '{'*'}') + _head="${payload%%\"tool_input\"*}" + _rest="${payload#*\"tool_name\"}" + if [[ $_head =~ $_bash_head ]] && ! [[ $_rest =~ $_name_key ]]; then + exit 0 + fi + ;; +esac + # python3 rather than jq: python3 is present everywhere this hook is installed -# (it is what the SessionStart hook guarantees), jq is not. The payload rides in -# the environment rather than on stdin so the heredoc keeps its own stdin. -PYAUTO_HOOK_PAYLOAD="$payload" python3 <<'PY' +# (it is what the SessionStart hook guarantees), jq is not. The payload goes to +# Python on stdin and the program as `-c`: an environment variable or an +# argument is capped at 128 KB per string, and a Bash call carrying a longer +# command would then fail to start Python at all (exit 126, a non-blocking hook +# error, so the call would go through unchecked). +PYAUTO_HOOK_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" +export PYAUTO_HOOK_DIR +IFS= read -r -d '' _program <<'PY' import json import os import re @@ -98,10 +130,14 @@ STREAM_REASON = ( "If the shift is over, report the digest and stop; do not re-arm.\n" ) +# Every character of an allowed stream command: no shell metacharacter, quote, +# glob, `$`, backtick, bracket, redirection or newline can reach a shell. +STREAM_CHARS_RE = re.compile(r"[A-Za-z0-9._/ -]+") +_PATH = r"/[A-Za-z0-9._/-]+" STREAM_RE = re.compile( - r"^(?P/\S+/PyAutoBrain/bin/pyauto-brain) batch watch --stream" - r" --record (?P/\S+/PyAutoMind/batches/[A-Za-z0-9-]+\.md)" - r"(?: --from \d+)?(?: --for \d+)?(?: --home /\S+)?$" + rf"(?P{_PATH}/PyAutoBrain/bin/pyauto-brain) batch watch --stream" + rf" --record (?P{_PATH}/PyAutoMind/batches/[A-Za-z0-9-]+\.md)" + rf"(?: --from [0-9]+)?(?: --for [0-9]+)?(?: --home {_PATH})?" ) # Anything that reads the watcher's state: only the canonical stream may. WATCHER_RE = re.compile(r"batch\s+watch|orchestrator_watch") @@ -146,20 +182,91 @@ def shift_window(record): return start, end +def workspace_root(): + """PYAUTO_ROOT, else the nearest ancestor of this hook holding a + `.pyauto-root` marker, else the nearest one holding a Brain checkout: + the order of PyAutoBrain/bin/_pyauto_root.sh.""" + explicit = os.environ.get("PYAUTO_ROOT") + if explicit: + return explicit + start = os.environ.get("PYAUTO_HOOK_DIR") or os.getcwd() + ancestors = [] + path = os.path.realpath(start) + while True: + ancestors.append(path) + parent = os.path.dirname(path) + if parent == path: + break + path = parent + for path in ancestors: + if os.path.isfile(os.path.join(path, ".pyauto-root")): + return path + for path in ancestors: + if brain_resolver_file(path): + return path + raise LookupError("no workspace root") + + +def brain_resolver_file(root): + found = { + os.path.realpath(candidate) + for candidate in ( + os.path.join(root, "PyAutoBrain", "agents", "_repo_paths.py"), + os.path.join(root, "organs", "PyAutoBrain", "agents", "_repo_paths.py"), + ) + if os.path.isfile(candidate) + } + if len(found) > 1: + raise LookupError("ambiguous PyAutoBrain checkouts") + return next(iter(found), None) + + +def resolved_checkouts(): + """(Brain, Mind) as the workspace's own resolver places them.""" + import importlib.util + + root = workspace_root() + resolver = brain_resolver_file(root) + if resolver is None: + raise LookupError("no PyAutoBrain/agents/_repo_paths.py under the root") + spec = importlib.util.spec_from_file_location("_pyauto_repo_paths", resolver) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return ( + os.path.realpath(module.repo_path(root, "PyAutoBrain", required=True)), + os.path.realpath(module.repo_path(root, "PyAutoMind", required=True)), + ) + + def check_monitor(tool_input): if tool_input.get("ws") is not None: refuse(WATCH_REASON, "a WebSocket Monitor") - cmd = str(tool_input.get("command") or "").strip() - stream = STREAM_RE.match(cmd) + raw = str(tool_input.get("command") or "") + cmd = raw.strip() + # The stream is matched unstripped: no newline anywhere, not even a last one. + stream = STREAM_RE.fullmatch(raw) if STREAM_CHARS_RE.fullmatch(raw) else None if stream: + try: + brain, mind = resolved_checkouts() + except Exception: + refuse(STREAM_REASON, + "a shift stream with no resolvable Brain and Mind checkouts") + # Pinned to this workspace's own checkouts, not any file that exists. + if (os.path.realpath(stream["cli"]) + != os.path.join(brain, "bin", "pyauto-brain") + or not os.path.isfile(stream["cli"])): + refuse(STREAM_REASON, + "a shift stream from a CLI outside this workspace's PyAutoBrain") + if (os.path.dirname(os.path.realpath(stream["rec"])) + != os.path.join(mind, "batches")): + refuse(STREAM_REASON, + "a shift stream on a record outside this workspace's PyAutoMind") try: start, end = shift_window(stream["rec"]) except Exception: # Fail closed: a window the hook cannot read is one it cannot clear. refuse(STREAM_REASON, "a shift stream on an unreadable shift record") now = datetime.now(timezone.utc) - if not os.path.isfile(stream["cli"]): - refuse(STREAM_REASON, "a shift stream from a CLI that does not exist") if start - BEFORE <= now <= end + AFTER: raise SystemExit(0) refuse(STREAM_REASON, @@ -184,7 +291,7 @@ def check_bash(tool_input): try: - event = json.loads(os.environ.get("PYAUTO_HOOK_PAYLOAD", "")) + event = json.loads(sys.stdin.read()) if not isinstance(event, dict): raise ValueError("PreToolUse payload is not a JSON object") tool = event.get("tool_name") @@ -210,3 +317,5 @@ if tool == "Bash": block(tool) PY + +printf '%s' "$payload" | python3 -c "$_program" diff --git a/policy/shift_cockpit_watch.md b/policy/shift_cockpit_watch.md index ddfd05f52..4fd4b91f2 100644 --- a/policy/shift_cockpit_watch.md +++ b/policy/shift_cockpit_watch.md @@ -34,3 +34,9 @@ outside it: issue), including one on a PR the shift itself opened. A session that wants to know whether a PR is green reads it once and reports. + +**Limits (v1).** The hook reads command text, so it errs both ways in known places: +- It refuses some local watches that only *mention* GitHub, such as a `while read` loop + echoing a `github.com` URL or a log tail grepping for `github.com`. Reword the filter. +- It passes GitHub polling it cannot see: `gh` inside a script file, `python -c`, or + `git -c fetch`. The rule above still bans them; the hook does not catch them. diff --git a/tests/test_end_at_deliverable_hook.py b/tests/test_end_at_deliverable_hook.py index b1015e654..cc0f6b1e5 100644 --- a/tests/test_end_at_deliverable_hook.py +++ b/tests/test_end_at_deliverable_hook.py @@ -217,6 +217,18 @@ def stamp(moment): return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") +FIXTURE_RESOLVER = """\ +from pathlib import Path + + +def repo_path(root, name, required=False): + path = Path(root) / name + if required and not (path / ".git").exists(): + raise FileNotFoundError(name) + return path +""" + + def fixture_shift(tmp_path, *, dispatched=None, review_at=None, body=None): """A fictional workspace: the Brain CLI and one Mind shift record. @@ -226,11 +238,19 @@ def fixture_shift(tmp_path, *, dispatched=None, review_at=None, body=None): now = datetime.now(timezone.utc) dispatched = dispatched or now - timedelta(hours=1) review_at = review_at or dispatched + SHIFT_LENGTH - cli = tmp_path / "ws" / "PyAutoBrain" / "bin" / "pyauto-brain" - cli.parent.mkdir(parents=True) + ws = tmp_path / "ws" + for repo in ("PyAutoBrain", "PyAutoMind"): + (ws / repo / ".git").mkdir(parents=True) + # The workspace's own resolver: the hook pins the stream to the checkouts + # it names. A fictional stand-in with the real one's signature. + resolver = ws / "PyAutoBrain" / "agents" / "_repo_paths.py" + resolver.parent.mkdir() + resolver.write_text(FIXTURE_RESOLVER) + cli = ws / "PyAutoBrain" / "bin" / "pyauto-brain" + cli.parent.mkdir() cli.write_text("#!/bin/sh\n") - record = tmp_path / "ws" / "PyAutoMind" / "batches" / "2026-11-16-pm.md" - record.parent.mkdir(parents=True) + record = ws / "PyAutoMind" / "batches" / "2026-11-16-pm.md" + record.parent.mkdir() if body is None: body = ( "# Batch 2026-11-16-pm\n" @@ -242,11 +262,16 @@ def fixture_shift(tmp_path, *, dispatched=None, review_at=None, body=None): return f"{cli} batch watch --stream --record {record}" -def monitor(command=None, **extra): +def monitor(command=None, root=None, **extra): + """A Monitor call. The workspace root is the fixture's `ws/` when the + command names one (as PYAUTO_ROOT, the resolver's first source).""" tool_input = {"description": "shift events", "timeout_ms": 1800000, **extra} if command is not None: tool_input["command"] = command - return run({"tool_name": "Monitor", "tool_input": tool_input}) + if root is None and command and "/ws/" in command: + root = command[command.index("/"):].split("/ws/")[0] + "/ws" + env = {"PYAUTO_ROOT": str(root)} if root else {} + return run({"tool_name": "Monitor", "tool_input": tool_input}, env=env) def bash(command, background): @@ -335,6 +360,105 @@ def test_the_stream_from_a_cli_that_does_not_exist_is_refused(tmp_path): assert monitor(cmd).returncode == 2 +def test_a_fake_cli_outside_the_resolved_brain_is_refused(tmp_path): + """A file that merely exists at `.../PyAutoBrain/bin/pyauto-brain` is not + the workspace's Brain: anyone can write one under /tmp.""" + cmd = fixture_shift(tmp_path) + fake = tmp_path / "x" / "PyAutoBrain" / "bin" / "pyauto-brain" + fake.parent.mkdir(parents=True) + fake.write_text("#!/bin/sh\nwhile true; do gh pr checks 1; sleep 30; done\n") + result = monitor(cmd.replace(str(tmp_path / "ws" / "PyAutoBrain"), + str(tmp_path / "x" / "PyAutoBrain")), + root=tmp_path / "ws") + assert result.returncode == 2 + assert "outside this workspace's PyAutoBrain" in result.stderr + + +def test_a_record_outside_the_resolved_mind_is_refused(tmp_path): + cmd = fixture_shift(tmp_path) + other = tmp_path / "x" / "PyAutoMind" / "batches" / "2026-11-16-pm.md" + other.parent.mkdir(parents=True) + other.write_text((tmp_path / "ws" / "PyAutoMind" / "batches" + / "2026-11-16-pm.md").read_text()) + result = monitor(cmd.replace(str(tmp_path / "ws" / "PyAutoMind"), + str(tmp_path / "x" / "PyAutoMind")), + root=tmp_path / "ws") + assert result.returncode == 2 + assert "outside this workspace's PyAutoMind" in result.stderr + + +def test_the_stream_with_no_resolvable_workspace_is_refused(tmp_path): + cmd = fixture_shift(tmp_path) + (tmp_path / "ws" / "PyAutoBrain" / "agents" / "_repo_paths.py").unlink() + result = monitor(cmd) + assert result.returncode == 2 + assert "no resolvable Brain and Mind" in result.stderr + + +def test_the_root_is_found_from_the_hook_copy_by_its_marker(tmp_path): + """No PYAUTO_ROOT: an installed copy walks up to the `.pyauto-root`.""" + cmd = fixture_shift(tmp_path) + ws = tmp_path / "ws" + (ws / ".pyauto-root").write_text("# fixture root\n") + copy = ws / "PyAutoMind" / ".claude" / "hooks" / "end-at-deliverable.sh" + copy.parent.mkdir(parents=True) + copy.write_bytes(HOOK.read_bytes()) + copy.chmod(0o755) + env = {k: v for k, v in os.environ.items() if k != "PYAUTO_ROOT"} + payload = json.dumps({"tool_name": "Monitor", + "tool_input": {"command": cmd, "description": "x"}}) + result = subprocess.run([str(copy)], input=payload, capture_output=True, + text=True, env=env) + assert result.returncode == 0, result.stderr + + +def test_the_real_brain_resolver_accepts_the_fixture_workspace(tmp_path): + """The stand-in has the real resolver's signature; prove it against the + real one when a Brain checkout sits beside this Mind.""" + real = next((p for p in (MIND.parent / "PyAutoBrain/agents/_repo_paths.py",) + if p.is_file()), None) + if real is None: + pytest.skip("no PyAutoBrain checkout beside this Mind") + cmd = fixture_shift(tmp_path) + (tmp_path / "ws" / "PyAutoBrain" / "agents" / "_repo_paths.py").write_bytes( + real.read_bytes()) + assert allowed(monitor(cmd)) + + +@pytest.mark.parametrize("tail", [ + " --home /tmp/h;while${IFS}true;do${IFS}gh${IFS}pr${IFS}checks${IFS}1;" + "sleep${IFS}30;done", + " --home /tmp/h$(gh pr checks 1 --watch)", + " --home /tmp/h`gh pr checks 1 --watch`", + " --home /tmp/h${IFS}x", + " --home /tmp/h&", + " --home /tmp/h|cat", + " --home /tmp/h>out", + " --home /tmp/h Date: Mon, 16 Nov 2026 13:55:38 +0000 Subject: [PATCH 3/3] firewall gate: skip the end-at-deliverable block leg on a policy PR A PR that edits policy/end_at_deliverable.md cannot make the other repos' AGENTS.md blocks match on their cloned mains: the per-repo regeneration wave writes them after merge. The gate now decides `deliverable_pr` from the PR's diff (independent of the hook, filing, map and Codex decisions), asserts PyAutoMind's own block first, then drops only `end-at-deliverable blocks (generated)` with the same loud banner. The policy joins the push and pull_request path filters, so the leg is still graded on every other PR and on push to main. repos_sync gains a DELIVERABLE_BLOCKS label constant; workflow tests cover the decision, the skip, its composition and the compensating control. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/firewall_gate.yml | 50 +++++++++++++++- scripts/repos_sync.py | 3 +- tests/test_session_hook_sync.py | 93 +++++++++++++++++++++-------- 3 files changed, 119 insertions(+), 27 deletions(-) diff --git a/.github/workflows/firewall_gate.yml b/.github/workflows/firewall_gate.yml index 88b032579..f89fa5cf4 100644 --- a/.github/workflows/firewall_gate.yml +++ b/.github/workflows/firewall_gate.yml @@ -58,6 +58,16 @@ name: Tenant Firewall Gate # asserts what the PR controls — the generator's hermetic tests — and drops the # `generated Codex hooks` leg with the same loud banner; graded on push to main. # +# The end-at-deliverable block (`policy/end_at_deliverable.md`) is the fifth, +# with the same unmeetable precondition: every repo carries the block, and a PR +# that edits the policy cannot make the copies on the cloned mains match it — +# they are regenerated by the reviewed per-repo wave after merge +# (session_hook_propagate.yml deliberately leaves this block alone). So a PR +# whose diff touches the policy sets `deliverable_pr`, which asserts +# PyAutoMind's own block (the test that pins it) and drops the +# `end-at-deliverable blocks (generated)` leg with the same loud banner. +# Independent of the other decisions; graded on push to main. +# # All three organs are checked out. PyAutoHands was omitted at first — its # firewall clear waited behind the version-stamp task that claimed the repo # (PyAutoHands#235) — and joined once that leg landed as PyAutoHands#237, @@ -72,6 +82,7 @@ on: - "policy/session_start_hook.sh" - "policy/end_at_deliverable_hook.sh" - "policy/where_to_file.md" + - "policy/end_at_deliverable.md" - "policy/shared_standards.md" - "tests/test_repos_sync_standards_block.py" - "AGENTS.md" @@ -84,6 +95,7 @@ on: - "policy/session_start_hook.sh" - "policy/end_at_deliverable_hook.sh" - "policy/where_to_file.md" + - "policy/end_at_deliverable.md" - "policy/shared_standards.md" - "tests/test_repos_sync_standards_block.py" - "AGENTS.md" @@ -179,6 +191,14 @@ jobs: else echo "map_pr=false" >> "$GITHUB_OUTPUT" fi + # Independent of the decisions above: the end-at-deliverable block is + # stamped from this policy into every repo's AGENTS.md. + if printf '%s\n' "$changed" | grep -qxF \ + -e 'policy/end_at_deliverable.md'; then + echo "deliverable_pr=true" >> "$GITHUB_OUTPUT" + else + echo "deliverable_pr=false" >> "$GITHUB_OUTPUT" + fi # Independent of the three decisions above (PyAutoMind#520): does this PR # change what any repo's .codex/hooks.json should say? Rendered from the @@ -222,6 +242,16 @@ jobs: python3 -m pytest PyAutoMind/tests/test_repos_sync_filing_block.py -q \ -k "pyautomind_carries_its_own_block" + # The same compensating control for the end-at-deliverable block: the + # regeneration wave never writes PyAutoMind's AGENTS.md from a rollout + # session, so its own copy is the PR's to keep. + - name: Assert PyAutoMind's own end-at-deliverable block (copies regenerate after merge) + if: steps.hookpr.outputs.deliverable_pr == 'true' + run: | + pip install pytest + python3 -m pytest PyAutoMind/tests/test_repos_sync_deliverable_block.py -q \ + -k "pyautomind_carries_its_own_block" + # The compensating control for the organism map: the eight organ copies # are regenerated after merge, so what this PR controls is that the # manifest it edits renders a well-formed map at all. @@ -256,12 +286,13 @@ jobs: --only "shared-standards blocks (generated)" --repo PyAutoMind - name: Drift check (canonical-hook, where-to-file or repos.yaml PR — unmeetable legs skipped) - if: steps.hookpr.outputs.hook_pr == 'true' || steps.hookpr.outputs.filing_pr == 'true' || steps.hookpr.outputs.map_pr == 'true' || steps.codexpr.outputs.codex_pr == 'true' + if: steps.hookpr.outputs.hook_pr == 'true' || steps.hookpr.outputs.filing_pr == 'true' || steps.hookpr.outputs.map_pr == 'true' || steps.codexpr.outputs.codex_pr == 'true' || steps.hookpr.outputs.deliverable_pr == 'true' env: HOOK_PR: ${{ steps.hookpr.outputs.hook_pr }} FILING_PR: ${{ steps.hookpr.outputs.filing_pr }} MAP_PR: ${{ steps.hookpr.outputs.map_pr }} CODEX_PR: ${{ steps.codexpr.outputs.codex_pr }} + DELIVERABLE_PR: ${{ steps.hookpr.outputs.deliverable_pr }} run: | skip=() if [ "$HOOK_PR" = "true" ]; then @@ -327,11 +358,26 @@ jobs: echo "==============================================================" skip+=(--skip "generated Codex hooks") fi + if [ "${DELIVERABLE_PR:-false}" = "true" ]; then + echo "==============================================================" + echo "SKIPPED LEG: 'end-at-deliverable blocks (generated)'" + echo "WHY: this PR changes policy/end_at_deliverable.md. Every repo's" + echo " AGENTS.md carries the block; the sibling repos are checked out" + echo " at their mains, so their copies are stale BY CONSTRUCTION until" + echo " the per-repo regeneration wave (repos_sync.py --write) lands" + echo " after this PR merges, and it cannot have run yet." + echo "STILL ENFORCED: PyAutoMind's own end-at-deliverable block must be" + echo " the canonical text (asserted in the step above). The copies are" + echo " the wave's job." + echo "ON push TO main this leg is never skipped." + echo "==============================================================" + skip+=(--skip "end-at-deliverable blocks (generated)") + fi python3 PyAutoMind/scripts/repos_sync.py --check \ --root "$GITHUB_WORKSPACE" "${skip[@]}" # Every leg, the shared-standards leg included, graded on the cloned mains. - name: Drift check (all legs — absent repos are skipped) - if: steps.hookpr.outputs.hook_pr != 'true' && steps.hookpr.outputs.filing_pr != 'true' && steps.hookpr.outputs.map_pr != 'true' && steps.codexpr.outputs.codex_pr != 'true' + if: steps.hookpr.outputs.hook_pr != 'true' && steps.hookpr.outputs.filing_pr != 'true' && steps.hookpr.outputs.map_pr != 'true' && steps.codexpr.outputs.codex_pr != 'true' && steps.hookpr.outputs.deliverable_pr != 'true' run: | python3 PyAutoMind/scripts/repos_sync.py --check --root "$GITHUB_WORKSPACE" diff --git a/scripts/repos_sync.py b/scripts/repos_sync.py index 25fbc287e..38611e62f 100644 --- a/scripts/repos_sync.py +++ b/scripts/repos_sync.py @@ -279,6 +279,7 @@ def all_checkouts(root): CODEX_HOOKS_REL = ".codex/hooks.json" CODEX_HOOKS = "generated Codex hooks" FILING_BLOCKS = "where-to-file blocks (generated)" +DELIVERABLE_BLOCKS = "end-at-deliverable blocks (generated)" MAP_BLOCKS = "organism-map blocks (generated)" STANDARDS_BLOCKS = "shared-standards blocks (generated)" STANDARDS_BEGIN = "" @@ -3024,7 +3025,7 @@ def main(): "remote-session blocks (generated)": lambda: check_remote_blocks( root, repos, remote ), - "end-at-deliverable blocks (generated)": lambda: check_deliverable_blocks( + DELIVERABLE_BLOCKS: lambda: check_deliverable_blocks( root, repos, deliverable ), STANDARDS_BLOCKS: lambda: check_standards_blocks( diff --git a/tests/test_session_hook_sync.py b/tests/test_session_hook_sync.py index 69c9b4ced..9492ed9b9 100644 --- a/tests/test_session_hook_sync.py +++ b/tests/test_session_hook_sync.py @@ -631,11 +631,13 @@ def gate_steps(): SKIP_IF = ("steps.hookpr.outputs.hook_pr == 'true' || " "steps.hookpr.outputs.filing_pr == 'true' || " "steps.hookpr.outputs.map_pr == 'true' || " - "steps.codexpr.outputs.codex_pr == 'true'") + "steps.codexpr.outputs.codex_pr == 'true' || " + "steps.hookpr.outputs.deliverable_pr == 'true'") FULL_IF = ("steps.hookpr.outputs.hook_pr != 'true' && " "steps.hookpr.outputs.filing_pr != 'true' && " "steps.hookpr.outputs.map_pr != 'true' && " - "steps.codexpr.outputs.codex_pr != 'true'") + "steps.codexpr.outputs.codex_pr != 'true' && " + "steps.hookpr.outputs.deliverable_pr != 'true'") def test_the_skip_is_reachable_only_from_a_pull_request(): @@ -703,27 +705,31 @@ def test_mind_checkout_is_deep_enough_to_diff_against_the_base(): @pytest.mark.parametrize( - "changed, expected, filing, mapped", + "changed, expected, filing, mapped, deliverable", [ - ([repos_sync.SESSION_HOOK_FILE], "true", "false", "false"), - ([repos_sync.DELIVERABLE_HOOK_FILE], "true", "false", "false"), + ([repos_sync.SESSION_HOOK_FILE], "true", "false", "false", "false"), + ([repos_sync.DELIVERABLE_HOOK_FILE], "true", "false", "false", "false"), # The organism-map decision (PyAutoMind#486) reads repos.yaml alone. - (["repos.yaml"], "false", "false", "true"), + (["repos.yaml"], "false", "false", "true", "false"), (["scripts/repos_sync.py", ".github/workflows/firewall_gate.yml"], - "false", "false", "false"), - ([repos_sync.SESSION_HOOK_FILE, "repos.yaml"], "true", "false", "true"), + "false", "false", "false", "false"), + ([repos_sync.SESSION_HOOK_FILE, "repos.yaml"], "true", "false", "true", "false"), # A path the hook's name is only a SUBSTRING of is a different file. - (["docs/policy/session_start_hook.sh.md"], "false", "false", "false"), + (["docs/policy/session_start_hook.sh.md"], "false", "false", "false", "false"), # The where-to-file decision is independent of the hook one. - ([repos_sync.FILING_POLICY_FILE], "false", "true", "false"), + ([repos_sync.FILING_POLICY_FILE], "false", "true", "false", "false"), ([repos_sync.FILING_POLICY_FILE, repos_sync.SESSION_HOOK_FILE], - "true", "true", "false"), - (["docs/policy/where_to_file.md.bak"], "false", "false", "false"), - (["docs/repos.yaml.md"], "false", "false", "false"), + "true", "true", "false", "false"), + (["docs/policy/where_to_file.md.bak"], "false", "false", "false", "false"), + (["docs/repos.yaml.md"], "false", "false", "false", "false"), + # The end-at-deliverable block decision reads the policy alone. + ([repos_sync.DELIVERABLE_POLICY_FILE], "false", "false", "false", "true"), + ([repos_sync.DELIVERABLE_POLICY_FILE, repos_sync.DELIVERABLE_HOOK_FILE], + "true", "false", "false", "true"), ], ) def test_the_gate_decides_from_the_changed_files(tmp_path, changed, expected, - filing, mapped): + filing, mapped, deliverable): """Execute the CI decision against a real two-branch repo. The `paths:` filter cannot answer this — it has already matched, and it @@ -740,7 +746,8 @@ def test_the_gate_decides_from_the_changed_files(tmp_path, changed, expected, ".github/workflows/firewall_gate.yml", "docs/policy/session_start_hook.sh.md", repos_sync.FILING_POLICY_FILE, - "docs/policy/where_to_file.md.bak", "docs/repos.yaml.md"): + "docs/policy/where_to_file.md.bak", "docs/repos.yaml.md", + repos_sync.DELIVERABLE_POLICY_FILE): path = base / rel path.parent.mkdir(parents=True, exist_ok=True) path.write_text("base\n") @@ -764,7 +771,8 @@ def test_the_gate_decides_from_the_changed_files(tmp_path, changed, expected, ) assert output.read_text().splitlines() == [ - f"hook_pr={expected}", f"filing_pr={filing}", f"map_pr={mapped}"], proc.stdout + f"hook_pr={expected}", f"filing_pr={filing}", f"map_pr={mapped}", + f"deliverable_pr={deliverable}"], proc.stdout # -------------------------------------------------------------------------- @@ -807,7 +815,7 @@ def test_the_gate_skips_the_map_leg_by_its_printed_label(): run = _skip_step()["run"] assert f'--skip "{repos_sync.MAP_BLOCKS}"' in run, run assert "repos.yaml" in run - assert run.count("ON push TO main this leg is never skipped") == 4 + assert run.count("ON push TO main this leg is never skipped") == 5 # -------------------------------------------------------------------------- @@ -859,6 +867,38 @@ def test_the_gate_still_asserts_the_manifest_renders_the_map(): "the compensating control must run before the skipping drift check" +def test_the_gate_skips_the_deliverable_leg_by_its_printed_label(): + """A renamed leg must break here rather than silently stop being skipped.""" + run = _skip_step()["run"] + assert f'--skip "{repos_sync.DELIVERABLE_BLOCKS}"' in run, run + assert f"SKIPPED LEG: '{repos_sync.DELIVERABLE_BLOCKS}'" in run + assert repos_sync.DELIVERABLE_POLICY_FILE in run + + +def test_the_gate_still_asserts_this_repos_own_deliverable_block(): + """The compensating control: the `-k` must select a test that exists, and + it must run before the skipping drift check.""" + import test_repos_sync_deliverable_block as deliverable + step = next(step for step in gate_steps() + if step.get("if") == "steps.hookpr.outputs.deliverable_pr == 'true'" + and "pytest" in (step.get("run") or "")) + assert "tests/test_repos_sync_deliverable_block.py" in step["run"] + selector = step["run"].split('-k "')[1].split('"')[0] + assert selector in deliverable.test_pyautomind_carries_its_own_block.__name__ + steps = gate_steps() + assert steps.index(step) < steps.index(_skip_step()) + + +def test_the_gate_triggers_on_the_deliverable_policy(): + gate = ( + Path(__file__).resolve().parents[1] + / ".github/workflows/firewall_gate.yml" + ) + triggers = yaml.safe_load(gate.read_text())[True] + for event in ("push", "pull_request"): + assert repos_sync.DELIVERABLE_POLICY_FILE in triggers[event]["paths"], event + + def test_the_filing_decision_ignores_the_pr_body(): """A PR with no `Brain-ref:` line must get the skip exactly as one with it: the decision reads the diff, never the body the Brain-ref resolver reads.""" @@ -878,18 +918,22 @@ def test_the_gate_triggers_on_the_filing_policy(): @pytest.mark.parametrize( - "hook_pr, filing_pr, map_pr, skipped", + "hook_pr, filing_pr, map_pr, skipped, deliverable_pr", [ - ("true", "false", "false", [repos_sync.SESSION_HOOKS]), - ("false", "true", "false", [repos_sync.FILING_BLOCKS]), - ("false", "false", "true", [repos_sync.MAP_BLOCKS]), - ("true", "true", "false", [repos_sync.SESSION_HOOKS, repos_sync.FILING_BLOCKS]), + ("true", "false", "false", [repos_sync.SESSION_HOOKS], "false"), + ("false", "true", "false", [repos_sync.FILING_BLOCKS], "false"), + ("false", "false", "true", [repos_sync.MAP_BLOCKS], "false"), + ("true", "true", "false", [repos_sync.SESSION_HOOKS, repos_sync.FILING_BLOCKS], "false"), ("true", "true", "true", [repos_sync.SESSION_HOOKS, repos_sync.FILING_BLOCKS, - repos_sync.MAP_BLOCKS]), + repos_sync.MAP_BLOCKS], "false"), + ("false", "false", "false", [repos_sync.DELIVERABLE_BLOCKS], "true"), + ("true", "false", "false", [repos_sync.SESSION_HOOKS, + repos_sync.DELIVERABLE_BLOCKS], "true"), ], ) def test_the_skipping_step_composes_both_decisions(tmp_path, hook_pr, - filing_pr, map_pr, skipped): + filing_pr, map_pr, skipped, + deliverable_pr): """Execute the step with a stand-in python3 that records its argv: each decision adds exactly its own --skip (and banner), and both compose.""" bindir = tmp_path / "bin" @@ -903,6 +947,7 @@ def test_the_skipping_step_composes_both_decisions(tmp_path, hook_pr, cwd=tmp_path, env={**os.environ, "PATH": f"{bindir}:{os.environ['PATH']}", "HOOK_PR": hook_pr, "FILING_PR": filing_pr, "MAP_PR": map_pr, + "DELIVERABLE_PR": deliverable_pr, "GITHUB_WORKSPACE": str(tmp_path)}, check=True, capture_output=True, text=True, )