From 3b9a575d866c57da3428cdcf4d091d9fa6f5ec53 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 12 Nov 2026 19:22:47 +0000 Subject: [PATCH 1/2] feat: pre-dispatch premise check + Lane backfill, slices 1-2 (M1.3, #608) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Slice 1 — `batch premise ` (agents/conductors/batch/_premise.py): on a fresh main of each named repo it checks the backticked paths and functions a draft names, reads its issue/PR states, and compares a title's smoke-duration claim with the Heart's timing record. Returns ok | obsolete | unknown with evidence (exit 1 on obsolete); for a bug it says what to reproduce. Renames and newly-gitignored paths count as moved, not gone; a path with no history is work to create, never evidence. No LLM call. - `--write-verified` stamps `Verified: ()` on an ok draft, inside a shift as a new `set-header` ledger op (one Mind writer), else in place, uncommitted. `shift_ledger.py set-header` queues the same op. - First step of the shift worker template: stop and report on obsolete. - `batch brief --check` warns on each named task whose premise is obsolete (`--no-premise` skips it). - `--at ` replays main as it stood. Witness (a): both obsolete tasks of the 2026-11-06-pm shift (delaunay_smoke_300s_cap, gallery_runner_missing_tiers) return obsolete at shift dispatch time; fixtures under tests/fixtures/premise/. Slice 2 — `bin/lane_backfill.py`: proposes a Lane: for every lane-less draft in the planner pool (now `_batch.planner_pool`, the plan gates factored out as `pool_gate`), with the matching words as evidence; `--apply [--from table]` writes the headers, honouring a human's edits. Intake's LANE_SIGNALS learn A100, HPC, /mnt/ral (ral), bare GPU (gpu), any /mnt/ (wsl-data) and "private data" (local-dev); the backfill reads the same table. Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 33 ++ agents/conductors/batch/_batch.py | 203 +++++-- agents/conductors/batch/_mind_writer.py | 75 ++- agents/conductors/batch/_orchestrator.py | 4 +- agents/conductors/batch/_premise.py | 548 ++++++++++++++++++ agents/conductors/batch/batch.sh | 4 + agents/conductors/batch/worker_template.md | 15 + agents/conductors/intake/_intake.py | 36 +- bin/README.md | 3 + bin/lane_backfill.py | 201 +++++++ bin/shift_ledger.py | 6 +- skills/batch/reference.md | 4 +- .../premise/delaunay_smoke_300s_cap.md | 65 +++ .../premise/gallery_runner_missing_tiers.md | 34 ++ tests/test_lane_backfill.py | 150 +++++ tests/test_premise_check.py | 362 ++++++++++++ 16 files changed, 1699 insertions(+), 44 deletions(-) create mode 100644 agents/conductors/batch/_premise.py create mode 100644 bin/lane_backfill.py create mode 100644 tests/fixtures/premise/delaunay_smoke_300s_cap.md create mode 100644 tests/fixtures/premise/gallery_runner_missing_tiers.md create mode 100644 tests/test_lane_backfill.py create mode 100644 tests/test_premise_check.py diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index 8218906a..f2baa69a 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -134,6 +134,39 @@ hiding it, by resource: *"4 laptop-lane task(s) are ready (3 ral, 1 local-dev) of the resource lanes `ral` / `gpu` / `wsl-data`, each of which implies `local-dev` (`lane_is_local` in the sizing faculty is the one test). +## The premise check (`premise`) — before a run is spent + +In the first live shift that worked (2026-11-06-pm), 2 of 3 dispatched tasks +were obsolete on `main`: one named a harness deleted five weeks earlier, the +other a smoke-cap overrun the timing record had not shown for days. The +close-out guard (`looks-shipped`) looks for work that *arrived*; it cannot see +a premise that has *gone away*. `batch premise ` can (PyAutoBrain#608, +programme M1.3, `_premise.py`): + +- On a fresh `main` of every repo the draft names (`git fetch`; `--no-fetch` + reads the cached ref; `--at ` replays main as it stood), it checks the + backticked paths and `name()` functions the draft names, reads the state of + its `Repo#N` issues and PRs (`--offline` skips `gh`), and compares a title + that claims a smoke duration with the Heart's timing record + (`timings/scripts/.jsonl`, decisive only when fresh). +- It returns **`ok | obsolete | unknown`** with evidence: `obsolete` when the + timing record contradicts the title, a file or function the title or + `Witness:` names is gone (the deleting commit is the evidence), or every + named path is gone; renames and newly-gitignored paths are *moved*, not + gone, and a path with no history is work to create, never evidence. For a + bug it also prints what a worker must reproduce. Exit 1 on `obsolete`. +- `--write-verified` stamps `Verified: ()` on an `ok` + draft — inside a shift as a `set-header` ledger op the orchestrator + commits (one Mind writer), outside one in place, uncommitted. +- It is the **first step of every dispatched worker** (`worker_template.md`): + on `obsolete` the worker writes its proof packet and stops. And it runs at + **brief time**: `batch brief --check` adds a warning for each named task + whose premise is obsolete (`--no-premise` skips the leg). + +Mechanical by design — git reads and at most a few `gh api` calls, no LLM. +Replayed on the two obsolete tasks above it returns `obsolete` for both +(`tests/test_premise_check.py`). + ## It proposes; the human launches `AUTONOMY.md` ("What a batch launch is") defines a batch dispatch as **one diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index 95679693..c9d2ff93 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -45,7 +45,7 @@ sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) from _sizing import ( # noqa: E402 BODY_MAP_PATH, LIBRARY_REPOS, effective_autonomy, effective_consequence, - effective_difficulty, effective_review_minutes, effective_unattended, + effective_difficulty, pyauto_root, effective_review_minutes, effective_unattended, lane_is_local, normalise_repo, parse_prompt, priority_rank, ) # `_status` (same directory) is the one definition of this vocabulary — the @@ -265,6 +265,51 @@ def queue_rank(r: dict, queue: list[str]) -> int: return len(queue) +def next_phases(records: list[dict]) -> dict[str, float]: + """Each epic's lowest un-shipped phase — the only one that is startable.""" + next_phase: dict[str, float] = {} + for r in records: + if r.get("epic") and not r.get("done"): + e = r["epic"] + next_phase[e] = min(next_phase.get(e, float("inf")), + r.get("phase", float("inf"))) + return next_phase + + +def pool_gate(r: dict, next_phase: dict[str, float]) -> str: + """Why a surveyed record is NOT in the planner pool, or "" if it is. + + Every gate but the lane, which depends on the session. Readiness says the + work FITS one run; autonomy says the run may FINISH it. Under `--auto` a + `supervised` run's ship checkpoint resolves to decide-and-flag + (AUTONOMY.md, "Decide-and-flag", extended 2026-09-07): it ships to an open + PR rather than parking, so it FINISHES and belongs in the pool. Only + `human-required` would still stop at the ship checkpoint and come back as + a question — which is the failure the whole epic exists to remove.""" + if r.get("done"): + return "Status: says the work is already done" + if r.get("looks_shipped"): + return ("looks shipped — confirm (close) or " + f"dismiss it ({_shipped.DISMISS_FILE}) first") + if r.get("epic") and r.get("phase", float("inf")) > next_phase.get( + r["epic"], float("inf")): + return f"epic {r['epic']} phase {r.get('phase')} is not next" + if r["autonomy"] == "human-required": + return f"autonomy {r['autonomy']} — would park at ship" + if r["unattended"] != "ready": + return f"unattended: {r['unattended']}" + if r["blocked"]: + return "declares Blocked-by:" + return "" + + +def planner_pool(records: list[dict]) -> list[dict]: + """The records every session's planner would consider, before its lane + filters them — what a Lane backfill must cover.""" + next_phase = next_phases(records) + return [r for r in records if not pool_gate(r, next_phase)] + + def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, session_lane: str = "web-github", awaiting_review: int = 0, cap: int = DEFAULT_BACKPRESSURE_CAP, queue: list[str] | None = None, @@ -312,38 +357,13 @@ def plan(records: list[dict], *, budget: int = DEFAULT_REVIEW_BUDGET, # phase is startable. Without this the planner can propose phase 6 while # phase 3 is still open — the one-slice-per-epic rule below caps how many # run, not which. - next_phase: dict[str, float] = {} - for r in records: - if r.get("epic") and not r.get("done"): - e = r["epic"] - next_phase[e] = min(next_phase.get(e, float("inf")), - r.get("phase", float("inf"))) + next_phase = next_phases(records) pool = [] for r in records: - # Readiness says the work FITS one run; autonomy says the run may - # FINISH it. Under `--auto` a `supervised` run's ship checkpoint - # resolves to decide-and-flag (AUTONOMY.md, "Decide-and-flag", - # extended 2026-09-07): it ships to an open PR rather than parking, so - # it FINISHES and belongs in the pool. Only `human-required` would - # still stop at the ship checkpoint and come back as a question — - # which is the failure the whole epic exists to remove. - if r.get("done"): - rejected.append((r["path"], "Status: says the work is already done")) - elif r.get("looks_shipped"): - rejected.append((r["path"], "looks shipped — confirm (close) or " - f"dismiss it ({_shipped.DISMISS_FILE}) first")) - elif r.get("epic") and r.get("phase", float("inf")) > next_phase.get( - r["epic"], float("inf")): - rejected.append((r["path"], - f"epic {r['epic']} phase {r.get('phase')} is not next")) - elif r["autonomy"] == "human-required": - rejected.append((r["path"], - f"autonomy {r['autonomy']} — would park at ship")) - elif r["unattended"] != "ready": - rejected.append((r["path"], f"unattended: {r['unattended']}")) - elif r["blocked"]: - rejected.append((r["path"], "declares Blocked-by:")) + why = pool_gate(r, next_phase) + if why: + rejected.append((r["path"], why)) elif not _lane_ok(r["lane"], session_lane): rejected.append((r["path"], f"lane {r['lane']}, session {session_lane}")) else: @@ -2804,9 +2824,10 @@ def organ_for(kind: str, root: Path, slot: str) -> dict: def main(argv=None) -> int: ap = argparse.ArgumentParser(prog="batch") ap.add_argument("verb", choices=["plan", "collect", "brief", "digest", "watch", - "slice"], nargs="?", default="plan") + "slice", "premise"], nargs="?", default="plan") ap.add_argument("prompt", nargs="?", default="", - help="slice: the needs-slicing prompt to decompose") + help="slice: the needs-slicing prompt to decompose; " + "premise: the draft whose premise to check") ap.add_argument("--mind", type=Path, default=BODY_MAP_PATH.parent) ap.add_argument("--budget", type=int, default=DEFAULT_REVIEW_BUDGET, help="review-minutes available in the slot") @@ -2840,6 +2861,21 @@ def main(argv=None) -> int: help="watch: print one snapshot and exit") ap.add_argument("--interval", type=float, default=30.0, help="watch: seconds between refreshes (at least 30)") + # premise (and the premise leg of `brief --check`) + ap.add_argument("--root", type=Path, default=None, + help="premise: the workspace root holding the repo checkouts " + "(default: $PYAUTO_ROOT, else derived)") + ap.add_argument("--no-fetch", action="store_true", + help="premise: read the cached origin/main, do not fetch") + ap.add_argument("--at", default="", + help="premise: judge main as it stood at this ISO time (a replay)") + ap.add_argument("--offline", action="store_true", + help="premise: do not read issue/PR state with gh") + ap.add_argument("--write-verified", action="store_true", + help="premise: on `ok`, stamp `Verified: ` into the " + "draft — as a ledger op inside a shift, else in place") + ap.add_argument("--no-premise", action="store_true", + help="brief: skip the premise check of the named tasks") # collect only ap.add_argument("--slot", default="", help="the batch record to collect (default: the newest)") @@ -2868,7 +2904,7 @@ def main(argv=None) -> int: lane = a.lane or detect_lane() mind = a.mind.resolve() - if a.prompt and a.verb != "slice": + if a.prompt and a.verb not in ("slice", "premise"): print(f"batch {a.verb}: unexpected argument {a.prompt!r}", file=sys.stderr) return RC_USAGE if a.slices and a.verb != "slice": @@ -2877,6 +2913,8 @@ def main(argv=None) -> int: try: if a.verb == "slice": return _main_slice(mind, a) + if a.verb == "premise": + return _main_premise(mind, a) if a.verb == "collect": return _main_collect(mind, a) if a.verb == "brief": @@ -2922,6 +2960,93 @@ def _main_slice(mind: Path, a) -> int: return RC_OK if d["ok"] else RC_FINDINGS +def _premise_root(a) -> Path: + if a.root is not None: + return a.root.resolve() + return Path(os.environ.get("PYAUTO_ROOT") or pyauto_root()).resolve() + + +def _main_premise(mind: Path, a) -> int: + """`batch premise [--write-verified] [--at ISO] [--no-fetch] [--json]` — + does the draft's premise still hold on a fresh main? (`_premise`) + + Exit 0 on `ok` or `unknown`, 1 on `obsolete`: a dispatched worker stops on + 1 and reports the evidence instead of implementing.""" + import _premise + if not a.prompt: + print("batch premise: name the draft to check", file=sys.stderr) + return RC_USAGE + draft = Path(a.prompt) + if not draft.is_file(): + draft = find_prompt(mind, a.prompt) or draft + if not draft.is_file(): + print(f"batch premise: no such draft {a.prompt}", file=sys.stderr) + return RC_USAGE + res = _premise.check(draft.resolve(), _premise_root(a), fetch=not a.no_fetch, + at=a.at or None, offline=a.offline) + if a.write_verified: + res["recorded"] = record_verified(mind, draft.resolve(), res) + if a.as_json: + print(json.dumps(res, indent=2)) + else: + print(_premise.report(res)) + if a.write_verified: + print(f" Verified: {res['recorded']}") + return RC_FINDINGS if res["status"] == "obsolete" else RC_OK + + +def record_verified(mind: Path, draft: Path, res: dict) -> str: + """Stamp `Verified: ` on an `ok` draft. + + Inside a shift (`$PYAUTO_SHIFT_LEDGER_DIR` set) this is a `set-header` + ledger op the orchestrator commits — a worker never writes PyAutoMind + (AUTONOMY.md, "One Mind writer per shift"). Outside one it edits the file + in place and commits nothing. Only `ok` is stamped: a header saying + "verified" on an obsolete or unchecked premise would be a lie.""" + import _mind_writer + if res["status"] != "ok": + return f"not stamped ({res['status']})" + import _premise + value = _premise.verified_value(res) + try: + rel = draft.relative_to(mind.resolve()).as_posix() + except ValueError: + return "not stamped (the draft is not inside the Mind)" + ledger = os.environ.get("PYAUTO_SHIFT_LEDGER_DIR") + if ledger: + op = {"op": "set-header", "path": rel, "key": _premise.VERIFIED_KEY, + "value": value} + queued = _mind_writer.queue_op(Path(ledger), op) + return f"queued set-header {rel} → {queued.name}" + draft.write_text(_mind_writer.set_header(draft.read_text(encoding="utf-8"), + _premise.VERIFIED_KEY, value), + encoding="utf-8") + return f"wrote {_premise.VERIFIED_KEY}: {value} into {rel} (not committed)" + + +def brief_premises(brief_path: Path, mind: Path, root: Path, *, fetch: bool = True, + offline: bool = False) -> list[dict]: + """The premise verdict of every named task in a brief that resolves. + + Run by `batch brief --check` so a stale pick is flagged before the shift + starts rather than discovered by the worker it would have cost.""" + import _premise + try: + rec = _brief.parse(brief_path.read_text(encoding="utf-8", errors="replace")) + except (OSError, _brief.BriefError): + return [] + if rec["brief"] is None: + return [] + views: dict = {} + out = [] + for task in _brief.tasks_of(rec["brief"]): + f = _brief._resolve(mind, task) + if f is not None: + out.append({**_premise.check(f, root, fetch=fetch, offline=offline, + views=views), "task": task}) + return out + + def _main_digest(mind: Path, a) -> int: """`batch digest --record ` — print the shift's digest; writes nothing. @@ -2968,6 +3093,16 @@ def _main_brief(mind: Path, a) -> int: "(the digest is `batch digest --record `)", file=sys.stderr) return RC_USAGE res = _brief.check(Path(a.check), mind) + # The premise leg: a named task whose premise is gone on main is flagged + # here, before the shift pays a worker to discover it. A warning, not a + # refusal — the check is mechanical, and the human reads the evidence. + res["premise"] = [] if a.no_premise else brief_premises( + Path(a.check), mind, _premise_root(a), fetch=not a.no_fetch, + offline=a.offline) + for p in res["premise"]: + if p["status"] == "obsolete": + res["warnings"].append(f"brief.tasks: {p['task']} premise OBSOLETE on main — " + + "; ".join(p["reasons"] + p["evidence"][:2])) if a.as_json: print(json.dumps(res, indent=2)) else: @@ -2976,6 +3111,8 @@ def _main_brief(mind: Path, a) -> int: print(f" ✗ {e}") for w in res["warnings"]: print(f" ! {w}") + for p in res["premise"]: + print(f" premise {p['status']}: {p['task']}") return RC_OK if res["ok"] else RC_FINDINGS diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index bf9ffbd3..09915b69 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -17,6 +17,11 @@ {"op": "remove", "path": "active/x.md"} {"op": "drop-section", "path": "active.md", "section": "task-name"} {"op": "table-append", "path": "autonomy_log.md", "heading": "## Unattended …", "row": "| … |"} + {"op": "set-header", "path": "draft/a/b/x.md", "key": "Verified", "value": "2026-11-12 abc123 (Repo)"} + +`set-header` sets one `Key: value` line in a prompt's header block (replacing +the key's line if present) — how a shift worker records the premise check's +`Verified:` stamp (`batch premise --record`) without touching the file itself. Every path must be *ledger* by PyAutoMind's own rule (`scripts/ledger_merge.py` `is_ledger_path`, default deny), so a worker cannot route code through here. @@ -25,6 +30,7 @@ from __future__ import annotations import json +import re import shutil import subprocess import sys @@ -32,7 +38,8 @@ import types from pathlib import Path -OPS = ("append", "write", "move", "remove", "drop-section", "table-append") +OPS = ("append", "write", "move", "remove", "drop-section", "table-append", + "set-header") PUSH_TRIES = 3 LEDGER_DIR = "ledger" COMMITTED_DIR = "committed" @@ -87,6 +94,14 @@ def validate_op(op: dict, lm) -> list[str]: row = op.get("row") if not isinstance(row, str) or not row.startswith("|") or "\n" in row: errs.append("table-append: row must be one `| … |` 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): + errs.append("set-header: key must be one capitalised header word") + if not isinstance(value, str) or not value.strip() or "\n" in value: + errs.append("set-header: value must be one non-empty line") + if not str(op.get("path", "")).endswith(".md"): + errs.append("set-header: path must be a prompt (.md)") return errs @@ -122,6 +137,11 @@ def apply_op(tree: Path, op: dict, lm) -> None: if len(kept) == len(entries): raise MindWriteError(f"drop-section: no `## {op['section']}` in {op['path']}") target.write_text(lm.join_entries(preamble, kept), encoding="utf-8") + elif kind == "set-header": + if not target.exists(): + raise MindWriteError(f"set-header: {op['path']} does not exist") + target.write_text(set_header(target.read_text(encoding="utf-8"), + op["key"], op["value"]), encoding="utf-8") elif kind == "table-append": target.write_text(table_append(target.read_text(encoding="utf-8") if target.exists() else "", @@ -144,6 +164,59 @@ def table_append(text: str, heading: str, row: str) -> str: return "\n".join(lines) + "\n" +_HEADER_LINE_RE = re.compile(r"^[A-Z][A-Za-z-]*:(\s|$)") + + +def header_span(lines: list[str]) -> tuple[int, int] | None: + """`(start, end)` of a prompt's header block: the contiguous `Key: value` + lines (with their `- item` continuations) below the `# ` title, ending at + the first blank line. None when the prompt has no header block.""" + i = 0 + while i < len(lines) and not _HEADER_LINE_RE.match(lines[i]): + if i > 6 and lines[i].strip() and not lines[i].startswith("#"): + return None # prose before any header: there is no block + i += 1 + if i >= len(lines): + return None + end = i + while end < len(lines) and lines[end].strip() and ( + _HEADER_LINE_RE.match(lines[end]) or lines[end].startswith(("- ", " "))): + end += 1 + return i, end + + +def set_header(text: str, key: str, value: str, + after: tuple[str, ...] = ("Unattended", "Review-minutes")) -> str: + """`text` with `key: value` in its header block — the key's own line + replaced if present, else inserted after the first of `after` present, + else at the end of the block. A prompt with no block gets one under its + title. Every other line is left byte-for-byte as it was.""" + lines = text.split("\n") + new = f"{key}: {value}" + span = header_span(lines) + if span is None: + at = next((i + 1 for i, ln in enumerate(lines) if ln.startswith("# ")), 0) + return "\n".join(lines[:at] + ([""] if at else []) + [new] + + ([""] if at < len(lines) and lines[at].strip() else []) + + lines[at:]) + start, end = span + for i in range(start, end): + if lines[i].lower().startswith(key.lower() + ":"): + lines[i] = new + return "\n".join(lines) + at = end + for anchor in after: + hit = next((i for i in range(start, end) + if lines[i].lower().startswith(anchor.lower() + ":")), None) + if hit is not None: + at = hit + 1 + while at < end and lines[at].startswith(("- ", " ")): + at += 1 + break + lines.insert(at, new) + return "\n".join(lines) + + def _git(cwd: Path, *args, check=True) -> subprocess.CompletedProcess: res = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True) if check and res.returncode != 0: diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index cb3578b3..6985f28c 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -76,6 +76,8 @@ #: its pre-commit refuses a commit in PyAutoMind and chains to the repo's own. WORKER_HOOKS = Path(__file__).resolve().parents[3] / "bin" / "worker_git_hooks" SHIFT_LEDGER = Path(__file__).resolve().parents[3] / "bin" / "shift_ledger.py" +#: The Brain CLI a worker runs its first step with (`batch premise`). +BRAIN_CLI = Path(__file__).resolve().parents[3] / "bin" / "pyauto-brain" FAKE_ENV = "PYAUTO_ORCHESTRATOR_FAKE" HOME_ENV = "PYAUTO_ORCHESTRATOR_HOME" @@ -217,7 +219,7 @@ def worker_prompt(task: str, prompt_path: str, brief_path: Path, lease_dir: Path return WORKER_TEMPLATE.read_text(encoding="utf-8").format( task=task, task_path=prompt_path, brief_path=brief_path, lease_dir=lease_dir, ledger_dir=Path(lease_dir).parent / _mind_writer.LEDGER_DIR, - shift_ledger=SHIFT_LEDGER) + shift_ledger=SHIFT_LEDGER, brain_cli=BRAIN_CLI) def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, diff --git a/agents/conductors/batch/_premise.py b/agents/conductors/batch/_premise.py new file mode 100644 index 00000000..bb0108c3 --- /dev/null +++ b/agents/conductors/batch/_premise.py @@ -0,0 +1,548 @@ +"""The premise check — does a draft's premise still hold on a fresh `main`? + +Programme task M1.3, slice 1 (PyAutoBrain#608). In the one live shift that +worked (2026-11-06-pm), 2 of 3 dispatched tasks were obsolete on `main`: one +named a harness deleted five weeks earlier, the other a smoke-cap overrun the +timing record had not shown for days. Both workers noticed and stopped, but +each had been paid for as a full run. The planner's close-out guard looks for +work that ARRIVED; it cannot see a premise that has GONE AWAY. This can. + +It is mechanical and cheap — git reads plus, optionally, one `gh api` per +named issue; never an LLM call. For each repo the draft names it views `main` +(fetched first unless told not to, or as it stood at `--at ` for a +replay), then checks what the draft names: + +- **paths** (backticked tokens with a `/` or a file extension): found on main, + or GONE (deleted on main — the deleting commit is the evidence), or MOVED + (renamed, or untracked into `.gitignore` — not gone), or absent with no + history (a file the work may be meant to create: never evidence); +- **functions** (backticked `name()`): defined on main, or removed (the + pickaxe commit is the evidence), or never defined; +- **issues and PRs** (`Repo#N`, GitHub URLs): their state, reported only; +- **a timing premise**: a title that claims a smoke duration ("330–354 s") + against the Heart's permanent smoke-timing record for each named script — + decisive only when the record is fresh (FRESH_DAYS). + +The verdict is one of `ok | obsolete | unknown`: + +- `obsolete` — a timing premise the record contradicts, or a GONE artefact the + title or `Witness:` names (the work cannot be done as written), or every + named path is gone (two or more — one alone is `unknown`); +- `ok` — something was checked, nothing is gone or contradicted; +- `unknown` — nothing checkable, no repo resolved, or something is gone only + in the body (the worker reads the evidence and decides). + +For a bug, it also says what a worker must reproduce before fixing anything. +Stdlib-only; no instance fact is written here — owners come from each +checkout's own `origin` remote. +""" + +from __future__ import annotations + +import datetime as _dt +import json +import re +import shutil +import subprocess +from pathlib import Path + +STATUSES = ("ok", "obsolete", "unknown") +VERIFIED_KEY = "Verified" + +#: Extensions that make a backticked token a path even without a `/`. +PATH_EXTS = (".py", ".sh", ".md", ".txt", ".yml", ".yaml", ".json", ".jsonl", + ".toml", ".ipynb", ".cfg", ".ini", ".rst", ".html", ".js", ".css", + ".csv", ".fits", ".cjs") +#: Mind-relative record paths — the Mind's own ledger, not a repo's code. +MIND_PREFIXES = ("draft/", "active/", "complete/", "batches/", "planned/") +_TICK_RE = re.compile(r"`([^`\n]{2,200})`") +_PATH_RE = re.compile(r"^[A-Za-z0-9_.][A-Za-z0-9_./+-]*$") +_FUNC_RE = re.compile(r"^((?:[A-Za-z_]\w*\.)*)([A-Za-z_]\w{2,})\((?:[^()]*)\)$") +_REF_RE = re.compile(r"(? str | None: + try: + res = run(["git", "-C", str(path), *args], capture_output=True, text=True, + timeout=timeout) + except (OSError, subprocess.TimeoutExpired): + return None + return res.stdout if res.returncode == 0 else None + + +# --- the draft ------------------------------------------------------------------ + +def _header(text: str, key: str) -> str: + for line in text.splitlines()[:40]: + if line.lower().startswith(key.lower() + ":"): + return line.split(":", 1)[1].strip() + return "" + + +def _title(text: str) -> str: + for line in text.splitlines(): + if line.startswith("# "): + return line[2:].strip() + return "" + + +def declared_repos(text: str) -> list[str]: + """`Repos:` bullets, then `Target:` — as written, resolved later.""" + out: list[str] = [] + m = re.search(r"^Repos:\n((?:- .+\n?)+)", text, re.M) + if m: + out += [ln[1:].strip().split()[0] for ln in m.group(1).splitlines() if ln.strip()] + target = _header(text, "target") + if target: + out.append(target.split()[0]) + seen, uniq = set(), [] + for r in out: + if r.lower() not in seen: + seen.add(r.lower()) + uniq.append(r) + return uniq + + +def _clean_path(token: str) -> str: + token = token.strip().split("#", 1)[0] + token = _LINE_SUFFIX_RE.sub("", token) + while token.startswith("./"): + token = token[2:] + return token.rstrip("/") + + +def _is_path(token: str) -> bool: + if not _PATH_RE.match(token) or ".." in token or "//" in token: + return False + if token.startswith(MIND_PREFIXES) or token.startswith(("http", "-")): + return False + name = token.rsplit("/", 1)[-1] + if "/" in token: + return bool(name) and not token.startswith("/") + return name.endswith(PATH_EXTS) and name.rsplit(".", 1)[0] != "" + + +def extract(text: str) -> dict: + """What the draft names: paths, functions, issue/PR references.""" + paths, funcs = [], [] + for raw in _TICK_RE.findall(text): + token = raw.strip() + fm = _FUNC_RE.match(token) + if fm and fm.group(2) not in funcs: + funcs.append(fm.group(2)) + continue + token = token.split()[0] if token.split() else "" + cleaned = _clean_path(token) + if cleaned and _is_path(cleaned) and cleaned not in paths: + paths.append(cleaned) + refs = [] + for owner, repo, num in _URL_RE.findall(text): + key = (f"{owner}/{repo}", int(num)) + if key not in refs: + refs.append(key) + for repo, num in _REF_RE.findall(text): + key = (repo, int(num)) + if key not in refs and not any(r[0].endswith("/" + repo) and r[1] == key[1] + for r in refs): + refs.append(key) + return {"paths": paths[:MAX_PATHS], "functions": funcs[:MAX_FUNCS], + "refs": refs[:MAX_REFS]} + + +# --- a repo at main ------------------------------------------------------------- + +class RepoView: + """One checkout's `main` (or `main` as of `at`): its sha and file tree.""" + + def __init__(self, name: str, path: Path, *, fetch: bool, at: str | None, run): + self.name, self.path, self.run = name, path, run + self.notes: list[str] = [] + if fetch: + if _git(path, "fetch", "-q", "origin", "main", run=run, timeout=90) is None: + self.notes.append(f"{name}: fetch failed — using the cached origin/main") + base = next((b for b in ("origin/main", "main") + if _git(path, "rev-parse", "--verify", "-q", b, run=run)), None) + self.base = base + sha = None + if base and at: + sha = (_git(path, "rev-list", "-1", f"--before={at}", base, run=run) or "").strip() + elif base: + sha = (_git(path, "rev-parse", base, run=run) or "").strip() + self.sha = sha or None + listing = _git(path, "ls-tree", "-r", "--name-only", self.sha, run=run) \ + if self.sha else None + self.files = set((listing or "").splitlines()) + self.dirs = {f.rsplit("/", i)[0] for f in self.files + for i in range(1, f.count("/") + 1)} + self.by_name: dict[str, list[str]] = {} + for f in self.files: + self.by_name.setdefault(f.rsplit("/", 1)[-1], []).append(f) + + @property + def ok(self) -> bool: + return self.sha is not None + + def short(self) -> str: + return (self.sha or "?")[:8] + + def locate(self, token: str) -> str | None: + """The path on main this token names, or None.""" + if token in self.files or token in self.dirs: + return token + if "scripts/" + token in self.files: + return "scripts/" + token + name = token.rsplit("/", 1)[-1] + for f in sorted(self.by_name.get(name, [])): + if "/" not in token or f.endswith("/" + token): + return f + if "/" in token: + hits = sorted(d for d in self.dirs if d.endswith("/" + token)) + if hits: + return hits[0] + return None + + def deleted(self, token: str) -> dict | None: + """The newest commit on main that deleted — or renamed away — the file + this token names.""" + name = token.rsplit("/", 1)[-1] + out = _git(self.path, "log", self.sha, "--diff-filter=DR", "-M", "--name-status", + "--date=short", "--format=%x00%h %ad %s", "--", + f":(glob)**/{name}", run=self.run) + for block in (out or "").split("\x00")[1:]: + lines = [ln for ln in block.splitlines() if ln.strip()] + if not lines: + continue + for entry in lines[1:]: + parts = entry.split("\t") + if len(parts) < 2: + continue + p = parts[1] + if p == token or p.endswith("/" + token) or token.endswith("/" + p) \ + or ("/" not in token and p.rsplit("/", 1)[-1] == token): + commit = lines[0] + renamed = parts[2] if parts[0].startswith("R") and len(parts) > 2 else None + return {"commit": commit, "path": p, + "moved_to": renamed or self._moved_to(commit.split()[0], p), + "ignored": False if renamed else self._ignored(p)} + return None + + def _moved_to(self, commit: str, path: str) -> str | None: + """Where a "deletion" actually went. A pathspec-limited log cannot pair + a rename (its other side is outside the pathspec), so the deleting + commit is re-read whole, with rename detection.""" + out = _git(self.path, "show", "-M", "--name-status", "--format=", commit, + run=self.run) + for line in (out or "").splitlines(): + parts = line.split("\t") + if len(parts) == 3 and parts[0].startswith("R") and parts[1] == path: + return parts[2] + return None + + def _ignored(self, path: str) -> bool: + """A path main stopped TRACKING because it is generated (now in + `.gitignore`) is not gone — read from the checkout's ignore rules.""" + try: + res = self.run(["git", "-C", str(self.path), "check-ignore", "-q", + "--no-index", path], capture_output=True, text=True, + timeout=30) + except (OSError, subprocess.TimeoutExpired): + return False + return res.returncode == 0 + + def defines(self, func: str) -> str | None: + out = _git(self.path, "grep", "-n", "-E", rf"(def|class) {func}\b", + self.sha, "--", "*.py", run=self.run) + first = (out or "").splitlines()[:1] + return first[0].split(":", 1)[1] if first else None + + def removed(self, func: str) -> str | None: + out = _git(self.path, "log", self.sha, "-1", "--date=short", + "--format=%h %ad %s", f"-Sdef {func}(", "--", "*.py", + run=self.run, timeout=120) + return (out or "").strip() or None + + def show(self, rel: str) -> str | None: + return _git(self.path, "show", f"{self.sha}:{rel}", run=self.run) + + def slug(self) -> str | None: + url = (_git(self.path, "remote", "get-url", "origin", run=self.run) or "").strip() + m = re.search(r"[:/]([\w.-]+)/([\w.-]+?)(?:\.git)?$", url) + return f"{m.group(1)}/{m.group(2)}" if m else None + + +def checkouts(root: Path) -> dict[str, Path]: + """Every checkout under the workspace root, by lower-cased name.""" + import sys + agents = Path(__file__).resolve().parents[2] + if str(agents) not in sys.path: + sys.path.insert(0, str(agents)) + from _repo_paths import iter_checkouts + try: + return {p.name.lower(): p for p in iter_checkouts(root)} + except (OSError, ValueError): + return {} + + +# --- the probes ----------------------------------------------------------------- + +def _claimed_seconds(title: str) -> int | None: + nums = [] + for a, b in _SECONDS_RE.findall(title): + nums += [int(a)] + ([int(b)] if b else []) + nums = [n for n in nums if n >= 60] + return min(nums) if nums else None + + +def _parse_day(value: str): + try: + return _dt.date.fromisoformat(value[:10]) + except ValueError: + return None + + +def timing_probe(title: str, scripts: list[tuple[str, str]], heart, + now: _dt.date | None = None) -> dict | None: + """A title that claims a duration, against the Heart's timing record. + + `scripts` is `(repo, path on main)` for every named `.py` that resolved. + Returns None when the draft makes no timing claim or nothing is recorded. + Only rows newer than FRESH_DAYS before `now` decide anything: a script + dropped from the smoke list leaves its last rows behind for ever. + """ + now = now or _dt.date.today() + claimed = _claimed_seconds(title) + # The Heart's record is the SMOKE profile; a release-profile claim (an + # 1800 s or 3600 s override) is not comparable with it. + if claimed is None or "smoke" not in title.lower() or not scripts \ + or heart is None or not heart.ok: + return None + for repo, script in scripts: + rel = f"timings/scripts/{repo}.jsonl" + raw = heart.show(rel) + if not raw: + continue + rows = [] + for line in raw.splitlines(): + try: + rec = json.loads(line) + except ValueError: + continue + entry = (rec.get("entries") or {}).get(script) + if entry: + rows.append((rec.get("at", ""), float(entry[0]), str(entry[1]))) + if not rows: + continue + rows = sorted(rows)[-TIMING_ROWS:] + secs = [s for _, s, _ in rows] + span = f"{min(secs):g}–{max(secs):g} s" if len(secs) > 1 else f"{secs[0]:g} s" + line = (f"PyAutoHeart@{heart.short()} {rel}: the newest {len(rows)} smoke " + f"runs of {script} took {span} ({rows[0][0][:10]} → {rows[-1][0][:10]}) " + f"against the title's claimed ≥{claimed} s") + newest = _parse_day(rows[-1][0]) + if newest is None or (now - newest).days > FRESH_DAYS: + return {"verdict": "stale-record", + "evidence": line + f" — older than {FRESH_DAYS} days, so not decisive"} + if max(secs) < claimed / 2: + return {"verdict": "contradicted", "evidence": line} + if max(secs) >= 0.8 * claimed: + return {"verdict": "reproduced", "evidence": line} + return {"verdict": "inconclusive", "evidence": line} + return None + + +def _gh_state(slug: str, num: int, run) -> str: + try: + res = run(["gh", "api", f"repos/{slug}/issues/{num}", "--jq", + '[.state, (if .pull_request then "pr" else "issue" end), ' + '(.pull_request.merged_at // "")] | @tsv'], + capture_output=True, text=True, timeout=30) + except (OSError, subprocess.TimeoutExpired): + return "unreadable" + if res.returncode != 0: + return "missing" if "Not Found" in (res.stderr or "") else "unreadable" + parts = res.stdout.strip().split("\t") + state, kind = parts[0], parts[1] if len(parts) > 1 else "issue" + merged = len(parts) > 2 and parts[2] + return f"{kind} {'merged' if merged else state}" + + +# --- the check ------------------------------------------------------------------ + +def check(draft: Path, root: Path, *, fetch: bool = True, at: str | None = None, + offline: bool = False, run=subprocess.run, text: str | None = None, + views: dict | None = None) -> dict: + """The premise verdict for one draft. Reads only; writes nothing. + + `views` is a cache shared across drafts (a brief names several that share + repos), so each repo is fetched and listed once. + """ + text = draft.read_text(encoding="utf-8", errors="replace") if text is None else text + title, witness = _title(text), _header(text, "witness") + work_type = _header(text, "type").lower() + named = extract(text) + found_co = checkouts(root) + views = {} if views is None else views + + def view(name: str): + key = name.lower() + if key not in found_co: + return None + if key not in views: + views[key] = RepoView(found_co[key].name, found_co[key], fetch=fetch, + at=at, run=run) + return views[key] + + evidence: list[str] = [] + declared = declared_repos(text) + repos = [v for v in (view(r) for r in declared) if v is not None and v.ok] + # `Target:` may be a category (`workspaces`), not a checkout: only a + # `Repos:` entry that resolves to nothing is worth saying. + listed = re.search(r"^Repos:\n((?:- .+\n?)+)", text, re.M) + listed = {ln[1:].strip().split()[0].lower() + for ln in (listed.group(1).splitlines() if listed else []) if ln.strip()} + unresolved = [r for r in declared if r.lower() in listed + and (view(r) is None or not view(r).ok)] + if unresolved: + evidence.append("unresolved repo(s): " + ", ".join(unresolved)) + + found, gone, absent, moved = [], [], [], [] + scripts: list[tuple[str, str]] = [] + for token in named["paths"]: + targets, tok = repos, token + head = token.split("/", 1) + if len(head) == 2 and view(head[0]) is not None and view(head[0]).ok: + targets, tok = [view(head[0])], head[1] + if not targets: + continue + hit = next(((v, v.locate(tok)) for v in targets if v.locate(tok)), None) + if hit: + v, where = hit + if f"{v.name}:{where}" in found: + continue + found.append(f"{v.name}:{where}") + if where.endswith(".py"): + scripts.append((v.name, where)) + continue + dele = next(((v, d) for v in targets if (d := v.deleted(tok))), None) + if dele and dele[1]["moved_to"]: + v, d = dele + moved.append(f"{token} → {v.name}:{d['moved_to']} ({d['commit'].split()[0]})") + elif dele and dele[1]["ignored"]: + v, d = dele + moved.append(f"{token} → untracked, now in {v.name}'s .gitignore " + f"({d['commit'].split()[0]})") + elif dele: + v, d = dele + gone.append({"token": token, "repo": v.name, "path": d["path"], + "commit": d["commit"]}) + else: + absent.append(token) + + funcs_found, funcs_gone = [], [] + for func in named["functions"]: + hit = next(((v, d) for v in repos if (d := v.defines(func))), None) + if hit: + funcs_found.append(f"{func} ({hit[0].name})") + continue + rm = next(((v, c) for v in repos if (c := v.removed(func))), None) + if rm: + funcs_gone.append({"token": f"{func}()", "repo": rm[0].name, + "commit": rm[1]}) + + refs = [] + if not offline and shutil.which("gh"): + for repo, num in named["refs"]: + slug = repo if "/" in repo else (view(repo).slug() if view(repo) else None) + if slug: + refs.append(f"{repo}#{num}: {_gh_state(slug, num, run)}") + elif named["refs"]: + evidence.append(f"{len(named['refs'])} issue/PR reference(s) not read " + "(offline or no gh)") + + timing = timing_probe(title, scripts, view("PyAutoHeart"), + now=_parse_day(at) if at else None) + + # The verdict. + pinned = f"{title}\n{witness}" + gone_all = gone + funcs_gone + gone_pinned = [g for g in gone_all if g["token"].rstrip("()") in pinned] + reasons = [] + if timing and timing["verdict"] == "contradicted": + reasons.append("the timing record contradicts the title's duration") + if gone_pinned: + reasons.append("a file or function the title or Witness: names is gone on main") + if len(gone) >= 2 and not found and not moved: + reasons.append("every named path is gone on main") + checked = len(found) + len(funcs_found) + len(gone_all) + len(moved) + if reasons: + status = "obsolete" + elif not repos or checked == 0: + status = "unknown" + reasons.append("nothing checkable resolved" if repos else "no named repo resolved") + elif gone_all: + status = "unknown" + reasons.append("something the body names is gone on main — read the evidence") + else: + status = "ok" + + for g in gone_all: + where = f"{g['repo']}:{g.get('path', g['token'])}" + evidence.append(f"GONE {g['token']} — {where} removed in {g['commit']}") + if timing: + evidence.append(f"timing {timing['verdict']}: {timing['evidence']}") + if found: + evidence.append(f"found on main ({len(found)}): " + ", ".join(found[:8]) + + (" …" if len(found) > 8 else "")) + if funcs_found: + evidence.append("defined on main: " + ", ".join(funcs_found[:8])) + if moved: + evidence.append("moved, not gone: " + "; ".join(moved[:6])) + if absent: + evidence.append("absent, no history (may be work to create): " + + ", ".join(absent[:8])) + evidence += refs + for v in repos: + evidence += v.notes + + reproduce = "" + if work_type == "bug" or "/bug/" in str(draft): + reproduce = (f"reproduce before fixing: {title}" + + (f" — the defect is fixed when: {witness}" if witness else "")) + + return { + "path": str(draft), "status": status, "reasons": reasons, + "evidence": evidence, "reproduce": reproduce, + "repos": {v.name: v.short() for v in repos}, + "at": at or "", "date": (at or _dt.date.today().isoformat())[:10], + } + + +def verified_value(result: dict) -> str: + """` ` per repo — the `Verified:` header's value.""" + shas = ", ".join(f"{sha} ({repo})" for repo, sha in sorted(result["repos"].items())) + return f"{result['date']} {shas}".strip() + + +def report(result: dict) -> str: + lines = [f"premise: {result['status']} — {result['path']}"] + if result["repos"]: + lines.append(" main: " + ", ".join(f"{r}@{s}" for r, s in result["repos"].items()) + + (f" (as of {result['at']})" if result["at"] else "")) + for r in result["reasons"]: + lines.append(f" why: {r}") + for e in result["evidence"]: + lines.append(f" - {e}") + if result["reproduce"]: + lines.append(f" {result['reproduce']}") + if result["status"] == "obsolete": + lines.append(" → a dispatched worker stops here and reports this evidence") + return "\n".join(lines) diff --git a/agents/conductors/batch/batch.sh b/agents/conductors/batch/batch.sh index 55b6b77b..6a02c5e4 100755 --- a/agents/conductors/batch/batch.sh +++ b/agents/conductors/batch/batch.sh @@ -30,6 +30,10 @@ # batch.sh slice --slices plan.md # slices from a plan file instead # batch.sh slice --apply # write children + epics.md entry # +# batch.sh premise # does its premise still hold on a fresh +# # main? ok | obsolete | unknown (exit 1 = +# # obsolete); --write-verified stamps it +# # collect reads and prints; only --apply writes (the packet page and the # record's stamps). Exit: 0 all delivered, 1 a member needs the human, # 2 usage, 4 no Mind. diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 579f7dda..65df4170 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -1,6 +1,21 @@ You are a worker in a shift the human launched by writing a shift brief: {brief_path} +First, before anything else, check the task's premise on a fresh main +(PyAutoBrain#608 — 2 of 3 tasks in the first live shift were obsolete): + + {brain_cli} batch premise {task_path} --write-verified + +- `obsolete` (exit 1): stop. Open no issue, branch or worktree and implement + nothing. Write {lease_dir}/{task}.proof.md headed + `#### {task} — obsolete (premise check)` with the check's evidence lines, + then {lease_dir}/{task}.done containing the word `obsolete`. That is your + deliverable; the human retires the draft. +- `ok` or `unknown`: go on (`ok` queued its `Verified:` stamp through the + ledger). For a bug, reproduce what its `reproduce before fixing:` line names + before changing code; if it does not reproduce, park on the issue with + that evidence instead of fixing. + Use the start-dev skill. {task_path} --auto The terms of this shift (AUTONOMY.md "Shift briefs and unattended `glance`"): diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 28871575..3e7caec9 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -675,19 +675,41 @@ def _declared_passthrough(header_lines) -> list[tuple[str, str]]: # prompt that needs RAL and the GPU is a RAL task, because RAL is the scarcer # gateway. Deliberately narrow — a loose pattern routes cloud-runnable work off # the cloud, which is the failure the lane exists to prevent. +# +# 2026-11-12 (PyAutoBrain#608, M1.3 slice 2): the words the ecosystem review +# found missing. `A100` and `HPC` are RAL resources (the A100s live there), as +# is a `/mnt/ral` path; a bare upper-case `GPU` is the laptop GPU (no cloud +# session has one); any other `/mnt/` is WSL data; and "private data" +# needs the laptop's local trees, so it is `local-dev`. The Lane backfill +# (`bin/lane_backfill.py`) reads this same table, so filing and backfill +# cannot drift apart. LANE_SIGNALS = ( - ("ral", re.compile(r"\bRAL\b|\bSLURM\b|\bsbatch\b|\bsqueue\b|euclid_jump")), + ("ral", re.compile(r"\bRAL\b|\bSLURM\b|\bsbatch\b|\bsqueue\b|euclid_jump" + r"|\bA100s?\b|\bHPC\b|/mnt/ral\b")), ("gpu", re.compile(r"\bCUDA\b|laptop GPU|\bGPU\b on the laptop", re.I)), - ("wsl-data", re.compile(r"/mnt/c\b|Workspace/Science\b")), + ("gpu", re.compile(r"\bGPUs?\b")), + ("wsl-data", re.compile(r"/mnt/[a-z]\b|Workspace/Science\b")), + ("local-dev", re.compile(r"\bprivate (?:data|datasets?|catalogues?)\b", re.I)), ) -def infer_lane(text: str) -> str: - """`ral` | `gpu` | `wsl-data` when the text names that resource, else `any`.""" +def infer_lane_evidence(text: str) -> tuple[str, str]: + """`(lane, snippet)`: the first signal that matches, with the words around + it — what a human skims to accept or reject a proposed lane. `("any", "")` + when the text names no resource.""" for lane, pattern in LANE_SIGNALS: - if pattern.search(text): - return lane - return "any" + m = pattern.search(text) + if m: + lo, hi = max(0, m.start() - 50), min(len(text), m.end() + 50) + snippet = " ".join(text[lo:hi].split()) + return lane, snippet + return "any", "" + + +def infer_lane(text: str) -> str: + """`ral` | `gpu` | `wsl-data` | `local-dev` when the text names that + resource, else `any`.""" + return infer_lane_evidence(text)[0] def _render_header(title, work_type, target_display, repos, level, autonomy, diff --git a/bin/README.md b/bin/README.md index 798a6b86..cc7bfc84 100644 --- a/bin/README.md +++ b/bin/README.md @@ -10,6 +10,9 @@ Executable tooling for the PyAuto organism. `state.json` (fallback: local `pyauto-heart readiness --json`), read-only, never ticks; exit 0 green · 1 yellow/stale · 2 red · 3 grey. Run first by `start_dev` step 0a and `route`. +- **`lane_backfill.py`** — proposes a `Lane:` for every lane-less draft in + the planner pool, from intake's own lane signals, as a table for a human to + skim; `--apply [--from ]` writes the headers (commits nothing). - **`gh_app_token.py`** — mints a fresh pyautolabs-bot App installation token (stdlib + `openssl`) so the nightly release driver can outlive the 60-minute token the workflow starts with. Prints only the token. diff --git a/bin/lane_backfill.py b/bin/lane_backfill.py new file mode 100644 index 00000000..fe66f182 --- /dev/null +++ b/bin/lane_backfill.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +"""Propose — and, only when told, write — a `Lane:` for every lane-less draft. + +Programme task M1.3, slice 2 (PyAutoBrain#608). `Lane:` was on 12 of ~270 +drafts and an absent Lane reads as `any`, so a draft whose Witness needs RAL or +an A100 is planned into a cloud session that cannot run it. Intake has +inferred a lane at filing since 2026-11-03; the older backlog was never +backfilled. This is the one scripted pass. + + lane_backfill.py [--mind DIR] [--all] [--out proposals.md] [--json] + lane_backfill.py --apply [--from proposals.md] [--mind DIR] + +Without `--apply` it only READS the Mind and writes the proposal table (to +`--out`, else stdout) for a human to skim at the block gate: one row per draft +with the proposed lane and the words that proposed it. Everything that names +no resource gets an explicit `any`. + +`--apply` writes `Lane: ` into each draft's header block (after +`Unattended:`, where intake writes it) and commits nothing. With `--from` it +applies the table as the human left it — edit a row's lane to overrule it, +delete the row to skip it — rather than re-proposing. + +Why here, in the Brain, and not in the Mind's `scripts/`: the proposal must +use the SAME signal table intake files with (`_intake.LANE_SIGNALS`) and the +SAME pool the planner draws from (`_batch.planner_pool`); a Mind copy of either +would drift from the one the planner actually runs. + +Scope: the planner pool (every gate but the session's lane) by default; +`--all` covers every draft. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from pathlib import Path + +BRAIN = Path(__file__).resolve().parents[1] +for sub in ("agents/faculties/sizing", "agents/conductors/intake", + "agents/conductors/batch"): + sys.path.insert(0, str(BRAIN / sub)) +import _batch # noqa: E402 +import _intake # noqa: E402 +import _mind_writer # noqa: E402 +from _sizing import LANE_VALUES, declared_header # noqa: E402 + +_ROW_RE = re.compile(r"^\|\s*`?([^|`]+?\.md)`?\s*\|\s*`?([a-z-]+)`?\s*\|") + + +def lane_less(mind: Path, *, every: bool = False) -> list[dict]: + """Drafts (the planner pool, or all with `every`) with no valid `Lane:`.""" + records = _batch.survey(mind) + scope = records if every else _batch.planner_pool(records) + out = [] + for r in scope: + text = (mind / r["path"]).read_text(encoding="utf-8", errors="replace") + h = declared_header(text) + if h.get("lane"): + continue + out.append({"path": r["path"], "text": text, + "invalid": h.get("lane_invalid") or ""}) + return out + + +def propose(mind: Path, *, every: bool = False) -> list[dict]: + rows = [] + for d in lane_less(mind, every=every): + lane, snippet = _intake.infer_lane_evidence(d["text"]) + rows.append({"path": d["path"], "lane": lane, "evidence": snippet, + "invalid": d["invalid"]}) + return sorted(rows, key=lambda r: (r["lane"] == "any", r["lane"], r["path"])) + + +def counts(rows: list[dict]) -> dict[str, int]: + out: dict[str, int] = {} + for r in rows: + out[r["lane"]] = out.get(r["lane"], 0) + 1 + return dict(sorted(out.items(), key=lambda kv: -kv[1])) + + +def table(rows: list[dict], *, scope: str, stamp: str = "") -> str: + c = counts(rows) + lines = [ + "# Lane backfill — proposals", + "", + f"Scope: {scope}. {len(rows)} draft(s) without a valid `Lane:`." + + (f" Read from {stamp}." if stamp else ""), + "", + "Counts: " + ", ".join(f"`{k}` {v}" for k, v in c.items()) + ".", + "", + "Skim the non-`any` rows: a keyword hit is an upper bound, and a draft", + "that only *mentions* RAL or a GPU as context should be `any`. Edit the", + "lane column to overrule a row, delete the row to skip it, then run", + "`lane_backfill.py --apply --from `.", + "", + "| draft | lane | evidence |", + "|---|---|---|", + ] + for r in rows: + ev = r["evidence"].replace("|", "\\|").replace("`", "'") + if r["invalid"]: + ev = (f"replaces invalid `Lane: {r['invalid']}`; " + ev).strip("; ") + lines.append(f"| `{r['path']}` | `{r['lane']}` | {ev or '—'} |") + return "\n".join(lines) + "\n" + + +def read_table(path: Path) -> list[dict]: + rows = [] + for line in path.read_text(encoding="utf-8").splitlines(): + m = _ROW_RE.match(line) + if m and m.group(1) != "draft": + rows.append({"path": m.group(1).strip(), "lane": m.group(2).strip()}) + return rows + + +def apply(mind: Path, rows: list[dict]) -> tuple[list[str], list[str]]: + """Write each row's `Lane:`. Returns (written, refused).""" + written, refused = [], [] + for r in rows: + if r["lane"] not in LANE_VALUES: + refused.append(f"{r['path']}: {r['lane']} is not a lane") + continue + f = mind / r["path"] + if not f.is_file(): + refused.append(f"{r['path']}: no such draft") + continue + text = f.read_text(encoding="utf-8") + if declared_header(text).get("lane"): + refused.append(f"{r['path']}: already declares a lane") + continue + f.write_text(_mind_writer.set_header(text, "Lane", r["lane"]), encoding="utf-8") + written.append(r["path"]) + return written, refused + + +def _mind_stamp(mind: Path) -> str: + """`PyAutoMind@ ` when the Mind is a git checkout — so the human + knows which backlog the table was read from.""" + import datetime as _dt + import subprocess + try: + res = subprocess.run(["git", "-C", str(mind), "log", "-1", "--format=%h"], + capture_output=True, text=True, timeout=30) + sha = res.stdout.strip() if res.returncode == 0 else "" + except OSError: + sha = "" + today = _dt.date.today().isoformat() + return f"PyAutoMind@{sha} on {today}" if sha else f"on {today}" + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(prog="lane_backfill", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--mind", type=Path, + default=Path(os.environ.get("PYAUTO_MIND") + or _batch.BODY_MAP_PATH.parent)) + ap.add_argument("--all", action="store_true", dest="every", + help="every draft, not only the planner pool") + ap.add_argument("--out", type=Path, help="write the proposal table here") + ap.add_argument("--json", action="store_true", dest="as_json") + ap.add_argument("--apply", action="store_true", + help="write the Lane: headers (commits nothing)") + ap.add_argument("--from", type=Path, dest="table", + help="--apply: the (human-edited) proposal table to apply") + a = ap.parse_args(argv) + mind = a.mind.resolve() + if not (mind / "draft").is_dir(): + print(f"lane_backfill: no PyAutoMind backlog at {mind}", file=sys.stderr) + return 4 + if a.table and not a.apply: + print("lane_backfill: --from belongs to --apply", file=sys.stderr) + return 2 + if a.apply: + rows = read_table(a.table) if a.table else propose(mind, every=a.every) + written, refused = apply(mind, rows) + print(f"lane_backfill: wrote Lane: into {len(written)} draft(s) " + f"(not committed); refused {len(refused)}") + for r in refused: + print(f" ✗ {r}") + return 1 if refused else 0 + rows = propose(mind, every=a.every) + scope = "every draft" if a.every else "the planner pool (every gate but the lane)" + if a.as_json: + print(json.dumps({"scope": scope, "counts": counts(rows), "rows": rows}, + indent=2)) + return 0 + out = table(rows, scope=scope, stamp=_mind_stamp(mind)) + if a.out: + a.out.parent.mkdir(parents=True, exist_ok=True) + a.out.write_text(out, encoding="utf-8") + print(f"lane_backfill: {len(rows)} proposal(s) → {a.out} — " + + ", ".join(f"{k} {v}" for k, v in counts(rows).items())) + else: + print(out, end="") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/shift_ledger.py b/bin/shift_ledger.py index 69024b03..93453126 100755 --- a/bin/shift_ledger.py +++ b/bin/shift_ledger.py @@ -11,6 +11,7 @@ shift_ledger.py move draft/feature/x/y.md active/y.md 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)" The ledger directory is `$PYAUTO_SHIFT_LEDGER_DIR` (set for every worker). """ @@ -29,7 +30,8 @@ def main(argv=None) -> int: formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("op", choices=mw.OPS) ap.add_argument("path") - ap.add_argument("arg", nargs="?", help="move: destination; drop-section: section") + ap.add_argument("arg", nargs="?", help="move: destination; drop-section: section; " + "set-header: the header key") ap.add_argument("--text-file", type=Path) ap.add_argument("--text") ap.add_argument("--mind", type=Path, default=os.environ.get("PYAUTO_MIND"), @@ -45,6 +47,8 @@ def main(argv=None) -> int: op["to"] = a.arg if a.op == "drop-section": op["section"] = a.arg + if a.op == "set-header": + op["key"], op["value"] = 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/skills/batch/reference.md b/skills/batch/reference.md index 6f40c094..7094446b 100644 --- a/skills/batch/reference.md +++ b/skills/batch/reference.md @@ -82,7 +82,9 @@ brief against the `batches/AGENTS.md` schema (every error names its key; exit 1 refuses it), and `batch plan --brief ` composes inside it: named tasks first, then only the backlog its policy covers, against its `review-minutes:`. Run the check before writing a brief's `review-at:` into -`batches/`. Dispatch is the watcher's (`batch.md`, "The watcher"), not a verb. `batch digest +`batches/`. The check also runs `batch premise` on each named task and warns +when one is **obsolete on main** (`--no-premise` skips it) — drop that task +before the shift pays a worker to find out. Dispatch is the watcher's (`batch.md`, "The watcher"), not a verb. `batch digest --record ` prints a shift's digest and writes nothing; the record append and the one issue comment are the watcher's, at `review-at:`. diff --git a/tests/fixtures/premise/delaunay_smoke_300s_cap.md b/tests/fixtures/premise/delaunay_smoke_300s_cap.md new file mode 100644 index 00000000..379786a9 --- /dev/null +++ b/tests/fixtures/premise/delaunay_smoke_300s_cap.md @@ -0,0 +1,65 @@ +# `imaging/features/pixelization/delaunay.py` sits on the 300 s smoke cap (330–354 s under the release profile) + +Type: bug +Target: autolens_workspace +Repos: +- autolens_workspace +Difficulty: small +Autonomy: safe +Priority: medium +Status: draft +Issued: 2026-09-04 +Consequence: glance +Witness: `scripts/imaging/features/pixelization/delaunay.py` completes in under ~200 s under the smoke profile (`PYAUTO_TEST_MODE`) on a clean `main` checkout, measured twice, with no change to the global 300 s smoke cap; or the script is removed from `smoke_tests.txt` and named in the release-profile list instead. +Review-minutes: 3 +Unattended: ready + +## Symptom + +`scripts/imaging/features/pixelization/delaunay.py` is a knife edge on the smoke gate's 300 s +per-script cap. It does not fail reproducibly and it is not a regression — it simply takes about +as long as the cap allows, so whether it passes depends on machine load. + +Measured under the **release** profile (1800 s cap, all PASS): + +| Run | Date | Time | +|-----|------|------| +| [33602064424](https://github.com/PyAutoLabs/PyAutoHands/actions/runs/33602064424) | 2026-09-02 | 353.9 s | +| [33847995194](https://github.com/PyAutoLabs/PyAutoHands/actions/runs/33847995194) | 2026-09-04 | 338.8 s | +| [33899429414](https://github.com/PyAutoLabs/PyAutoHands/actions/runs/33899429414) | 2026-09-04 | 332.9 s | + +And on the **post-release smoke leg** of the live release run +[33908218375](https://github.com/PyAutoLabs/PyAutoHands/actions/runs/33908218375) (300 s cap): +attempt 1 **TIMEOUT at 305 s**, attempt 2 **PASS**. Same script, same commit, one retry apart — +the definition of a cap that the script is sitting on rather than a script that is broken. + +The script entered the smoke gate in autolens_workspace#307 (`9eba5071`, 2026-07-21), which added +it to `smoke_tests.txt` when the 2026-04-10 `FitException` was fixed. Its cost has grown with the +script since. + +## Cause (to confirm by profiling) + +The script is 1628 lines and runs **seven** separate `Nautilus` fits in one file +(`n_live=` 100, 75, 200, 150, 75, 150, 150), covering the `Overlay` image-mesh, the `Hilbert` +image-mesh, the adapt-image path and a multi-search source pipeline. Even at `PYAUTO_TEST_MODE` +live-point counts, seven searches plus the Delaunay/qhull mesh construction in each is the bulk +of the runtime. Profile the stages before assuming which one dominates. + +## Fix + +Pick whichever the profile supports; **do not raise the global smoke cap** — the cap is the only +thing keeping the gate's total runtime bounded, and one script's convenience is not worth it. + +1. **Cut it under ~200 s under the smoke ENV.** Reduce live points and/or the mesh grid size for + the smoke profile only (the script already reads `PYAUTO_TEST_MODE`), so the release profile + keeps the scientifically meaningful settings. +2. **Split it.** Seven searches in one file is a lot for one gate entry; a `delaunay.py` + + `delaunay_hilbert.py` (or similar) split halves the per-script time without dropping coverage, + and each half stays well under the cap. +3. **Move it to the release-profile list only.** Remove it from `smoke_tests.txt` and rely on the + Release Integrate leg (1800 s cap) that already exercises it three times a week. This is the + cheapest option and the honest one if the script genuinely needs 330 s of real work — but it + costs pre-release coverage, so prefer 1 or 2 if the profile shows easy savings. + +Whichever route, re-measure twice under the smoke profile and regenerate the notebook if the +script changes. diff --git a/tests/fixtures/premise/gallery_runner_missing_tiers.md b/tests/fixtures/premise/gallery_runner_missing_tiers.md new file mode 100644 index 00000000..3bc30c42 --- /dev/null +++ b/tests/fixtures/premise/gallery_runner_missing_tiers.md @@ -0,0 +1,34 @@ +# Gallery runner: add visualization_upper + decide the modeling_visualization_jit tier + +Type: feature +Target: workspaces +Repos: +- autolens_workspace_test +Themes: +- visualization +- ci-smoke +Difficulty: small +Autonomy: safe +Priority: low +Status: formalised +Consequence: glance +Witness: `scripts/gallery/gallery_run.sh` DEFAULT_SCRIPTS contains both `imaging/visualization_upper.py` and `interferometer/visualization_upper.py`, a run of the tier they were slotted into renders their 12 and 17 figures, and `eyes survey autolens_workspace_test` reports no never-rendered `visualization_upper` producer. +Review-minutes: 3 +Unattended: ready +Filed: 2026-07-16 (backfilled from git) + +First real findings from the Eyes conductor's live survey (PyAutoBrain#117 +Phase 2, `eyes survey autolens_workspace_test`): + +1. `scripts/imaging/visualization_upper.py` and + `scripts/interferometer/visualization_upper.py` produce full figure sets + (12+17 png) but are missing from `scripts/gallery/gallery_run.sh`'s + DEFAULT_SCRIPTS — add them (time them first; slot into fast or slow tier). +2. The `modeling_visualization_jit*` scripts (imaging ×3, interferometer, + point_source) are never-rendered in the survey. Decide: include them in a + runner tier (probably `--all`) or exclude them from the producer-token + match story — they are JIT smoke tests whose figures may still be worth + eyeballing once. +3. While there: consider `eyes survey` output as the runner's source of + truth for gaps going forward (the survey already diffs producers vs + rendered trees). diff --git a/tests/test_lane_backfill.py b/tests/test_lane_backfill.py new file mode 100644 index 00000000..6c98768b --- /dev/null +++ b/tests/test_lane_backfill.py @@ -0,0 +1,150 @@ +"""The Lane backfill (PyAutoBrain#608, M1.3 slice 2): `bin/lane_backfill.py` +and the intake inference words it shares. + +Witness (b): the proposal covers every planner-pool draft that lacks a valid +`Lane:`, and applying it to a copy leaves none without one. +""" + +from __future__ import annotations + +import importlib.util +import shutil +import sys +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "intake")) +import _intake # noqa: E402 +from _sizing import declared_header # noqa: E402 + +_spec = importlib.util.spec_from_file_location("lane_backfill", BRAIN / "bin" / "lane_backfill.py") +lb = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(lb) + + +# --- intake learns the missing words --------------------------------------------- + +@pytest.mark.parametrize("text,lane", [ + ("Re-run the timing leg on the A100 for @PyAutoBrain.", "ral"), + ("Profile it on two A100s.", "ral"), + ("Submit the sweep to the HPC queue.", "ral"), + ("Submit it with SLURM.", "ral"), + ("Outputs live under /mnt/ral/jnightin/out.", "ral"), + ("Compare the GPU and CPU timings.", "gpu"), + ("Read the cutouts from /mnt/d/archive.", "wsl-data"), + ("Fit the Euclid private data release.", "local-dev"), + ("Needs the private datasets on the laptop.", "local-dev"), +]) +def test_intake_infers_the_new_lane_words(text, lane): + assert _intake.infer_lane(text) == lane + assert f"\nLane: {lane}" in _intake.analyse(text + " @PyAutoBrain", "test")["header"] + + +@pytest.mark.parametrize("text", [ + "Tidy a docstring.", + "The PyAutoGPU venv path is documented.", # no word boundary: not the GPU + "A general refactor of the parser.", # `RAL` must be its own word + "Point the gpu flag at the right default.", # lower-case code identifier +]) +def test_intake_stays_narrow(text): + assert _intake.infer_lane(text) == "any" + + +def test_ral_outranks_gpu_and_evidence_is_the_matching_words(): + lane, snippet = _intake.infer_lane_evidence( + "Benchmark on the GPU. The full sweep runs on the RAL A100 nodes.") + assert lane == "ral" and "RAL" in snippet + + +# --- the backfill ------------------------------------------------------------------ + +def _prompt(lane_line: str, body: str, unattended="ready") -> str: + return (f"# T\n\nType: feature\nTarget: PyAutoBrain\nRepos:\n- PyAutoBrain\n" + f"Autonomy: safe\nConsequence: glance\nWitness: w\nReview-minutes: 3\n" + f"Unattended: {unattended}\n{lane_line}\n\n{body}\n") + + +def _mind(tmp_path) -> Path: + mind = tmp_path / "mind" + d = mind / "draft" / "feature" / "pyautobrain" + d.mkdir(parents=True) + files = { + "ral.md": _prompt("", "Time it on the A100 via sbatch."), + "gpu.md": _prompt("", "Compare GPU throughput."), + "wsl.md": _prompt("", "Data under /mnt/c/Users/x/data."), + "private.md": _prompt("", "Needs the private data on disk."), + "plain.md": _prompt("", "Tidy a docstring."), + "invalid.md": _prompt("Lane: any | local-dev", "Tidy."), + "declared.md": _prompt("Lane: local-dev", "Mentions RAL but declares."), + "not_ready.md": _prompt("", "On RAL.", unattended="needs-slicing"), + } + for name, text in files.items(): + (d / name).write_text(text) + return mind + + +def _lane_less_pool(mind: Path) -> set[str]: + return {d["path"] for d in lb.lane_less(mind)} + + +def test_witness_b_proposal_covers_the_pool_and_apply_leaves_none(tmp_path): + mind = _mind(tmp_path) + before = _lane_less_pool(mind) + rows = lb.propose(mind) + assert {r["path"] for r in rows} == before # covers every one + by = {Path(r["path"]).stem: r for r in rows} + assert {k: by[k]["lane"] for k in by} == { + "ral": "ral", "gpu": "gpu", "wsl": "wsl-data", "private": "local-dev", + "plain": "any", "invalid": "any"} + assert "A100" in by["ral"]["evidence"] and by["plain"]["evidence"] == "" + assert "not_ready" not in by and "declared" not in by # outside the pool / declared + + # Applied to a COPY, through the human-skimmable table, edits honoured. + copy = tmp_path / "copy" + shutil.copytree(mind, copy) + table = tmp_path / "proposals.md" + text = lb.table(rows, scope="test") + table.write_text(text.replace("| `draft/feature/pyautobrain/gpu.md` | `gpu` |", + "| `draft/feature/pyautobrain/gpu.md` | `any` |")) + assert lb.main(["--mind", str(copy), "--apply", "--from", str(table)]) == 0 + assert _lane_less_pool(copy) == set() # none left without one + gpu = (copy / "draft/feature/pyautobrain/gpu.md").read_text() + assert declared_header(gpu)["lane"] == "any" # the human's overrule won + # Lane: lands after Unattended:, the invalid line is replaced, the rest kept. + ral = (copy / "draft/feature/pyautobrain/ral.md").read_text() + assert "Unattended: ready\nLane: ral\n" in ral + inv = (copy / "draft/feature/pyautobrain/invalid.md").read_text() + assert inv.count("Lane:") == 1 and "Lane: any\n" in inv + # The original Mind is untouched: proposing never writes. + assert _lane_less_pool(mind) == before + + +def test_apply_without_a_table_reproposes_and_all_widens_the_scope(tmp_path): + mind = _mind(tmp_path) + assert lb.main(["--mind", str(mind), "--apply"]) == 0 + assert _lane_less_pool(mind) == set() + assert {Path(d["path"]).stem for d in lb.lane_less(mind, every=True)} == {"not_ready"} + + +def test_apply_refuses_a_bad_lane_and_a_declared_one(tmp_path): + mind = _mind(tmp_path) + written, refused = lb.apply(mind, [ + {"path": "draft/feature/pyautobrain/plain.md", "lane": "cloud"}, + {"path": "draft/feature/pyautobrain/declared.md", "lane": "any"}, + {"path": "draft/feature/pyautobrain/missing.md", "lane": "any"}]) + assert written == [] and len(refused) == 3 + + +def test_proposal_mode_writes_only_the_table(tmp_path, capsys): + mind = _mind(tmp_path) + before = {f: f.read_text() for f in mind.rglob("*.md")} + out = tmp_path / "scratch" / "proposals.md" + assert lb.main(["--mind", str(mind), "--out", str(out)]) == 0 + assert {f: f.read_text() for f in mind.rglob("*.md")} == before + text = out.read_text() + assert "Counts: `any` 2" in text and text.count("| `draft/") == 6 + assert "--from belongs" not in capsys.readouterr().err + assert lb.main(["--mind", str(mind), "--from", str(out)]) == 2 diff --git a/tests/test_premise_check.py b/tests/test_premise_check.py new file mode 100644 index 00000000..d55dd84a --- /dev/null +++ b/tests/test_premise_check.py @@ -0,0 +1,362 @@ +"""The premise check (PyAutoBrain#608, M1.3 slice 1): `batch premise`, its +`Verified:` stamp through the one-Mind-writer ledger, the brief-time leg and +the worker template's first step. + +Witness (a) is replayed here on the two drafts that were obsolete in the +2026-11-06-pm shift, exactly as they stood in the Mind before it +(`tests/fixtures/premise/`, from the Mind commit before the shift's brief). +The repos they name are rebuilt as small git fixtures carrying the facts the +real ones carried at dispatch: the harness deleted on 2026-09-30, and a Heart +timing record showing the "300 s" script at ~8-16 s for the days before. +Repo names are read from the fixtures, never written here (tenant firewall). +""" + +from __future__ import annotations + +import datetime as _dt +import importlib.util +import json +import os +import re +import subprocess +import sys +import types +from pathlib import Path + +import pytest + +BRAIN = Path(__file__).resolve().parents[1] +FIX = Path(__file__).resolve().parent / "fixtures" / "premise" +sys.path.insert(0, str(BRAIN / "agents" / "faculties" / "sizing")) +sys.path.insert(0, str(BRAIN / "agents" / "conductors" / "batch")) +_spec = importlib.util.spec_from_file_location( + "_batch_premise", BRAIN / "agents" / "conductors" / "batch" / "_batch.py") +_batch = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_batch) +import _mind_writer # noqa: E402 +import _orchestrator as orch # noqa: E402 +import _premise # noqa: E402 + +SHIFT = "2026-11-06T11:20Z" +DELAUNAY = FIX / "delaunay_smoke_300s_cap.md" +GALLERY = FIX / "gallery_runner_missing_tiers.md" + + +def _repo_of(draft: Path) -> str: + return _premise.declared_repos(draft.read_text())[0] + + +def _git(repo: Path, *args, date: str = "2026-09-01T12:00:00Z"): + env = {**os.environ, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} + subprocess.run(["git", "-C", str(repo), "-c", "user.name=t", "-c", + "user.email=t@example.invalid", *args], check=True, + capture_output=True, env=env) + + +def _repo(root: Path, name: str, files: dict[str, str], date="2026-09-01T12:00:00Z") -> Path: + repo = root / name + repo.mkdir(parents=True) + subprocess.run(["git", "init", "-q", "-b", "main", str(repo)], check=True) + for rel, body in files.items(): + (repo / rel).parent.mkdir(parents=True, exist_ok=True) + (repo / rel).write_text(body) + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "initial", date=date) + return repo + + +def _heart(root: Path, repo: str, script: str, secs, start: str): + day = _dt.date.fromisoformat(start) + rows = [] + for i, s in enumerate(secs): + at = (day + _dt.timedelta(days=i // 2)).isoformat() + rows.append(json.dumps({"at": f"{at}T10:00:00Z", "date": at, + "entries": {script: [s, "passed", 300.0]}})) + _repo(root, "PyAutoHeart", + {f"timings/scripts/{repo}.jsonl": "\n".join(rows) + "\n"}, + date="2026-11-05T12:00:00Z") + + +SCRIPT = "scripts/imaging/features/pixelization/delaunay.py" + + +def _delaunay_root(tmp_path, secs, start="2026-11-02"): + root = tmp_path / "root" + name = _repo_of(DELAUNAY) + _repo(root, name, {SCRIPT: "# seven Nautilus fits\n", + "smoke_tests.txt": "imaging/features/pixelization/delaunay.py\n"}) + _heart(root, name, SCRIPT, secs, start) + return root + + +def _gallery_root(tmp_path): + root = tmp_path / "root" + repo = _repo(root, _repo_of(GALLERY), {"gallery/gallery_run.sh": "DEFAULT_SCRIPTS=()\n", + "scripts/imaging/visualization/x.py": "\n"}) + (repo / "gallery" / "gallery_run.sh").unlink() + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "chore: retire the pre-organ gallery harness", + date="2026-09-30T12:00:00Z") + return root + + +# --- Witness (a): the two obsolete prompts of the 2026-11-06-pm shift ---------- + +def test_witness_a_delaunay_smoke_cap_is_obsolete_by_the_timing_record(tmp_path): + root = _delaunay_root(tmp_path, [8.3, 9.8, 15.9, 14.4, 9.3, 11.0, 8.6, 14.5]) + res = _premise.check(DELAUNAY, root, fetch=False, at=SHIFT, offline=True) + assert res["status"] == "obsolete", res + timing = next(e for e in res["evidence"] if e.startswith("timing contradicted")) + assert SCRIPT in timing and "≥300 s" in timing + # A bug says what a worker must reproduce before fixing anything. + assert res["reproduce"].startswith("reproduce before fixing:") + + +def test_witness_a_gallery_runner_is_obsolete_by_the_deleted_harness(tmp_path): + res = _premise.check(GALLERY, _gallery_root(tmp_path), fetch=False, at=SHIFT, + offline=True) + assert res["status"] == "obsolete", res + gone = next(e for e in res["evidence"] if e.startswith("GONE")) + assert "scripts/gallery/gallery_run.sh" in gone + assert "retire the pre-organ gallery harness" in gone + assert any("title or Witness" in r for r in res["reasons"]) + + +def test_witness_a_is_cheap(tmp_path): + """A few git reads, never an LLM: the whole replay stays well under the + witness's 'few thousand tokens' when printed.""" + root = _delaunay_root(tmp_path, [9.0, 10.0]) + out = _premise.report(_premise.check(DELAUNAY, root, fetch=False, at=SHIFT, + offline=True)) + assert len(out) < 4000 + + +# --- the timing probe's guards --------------------------------------------------- + +def test_a_timing_record_that_still_shows_the_overrun_is_not_obsolete(tmp_path): + root = _delaunay_root(tmp_path, [330.0, 338.8, 353.9, 305.0]) + res = _premise.check(DELAUNAY, root, fetch=False, at=SHIFT, offline=True) + assert res["status"] == "ok", res + assert any(e.startswith("timing reproduced") for e in res["evidence"]) + + +def test_a_stale_timing_record_decides_nothing(tmp_path): + root = _delaunay_root(tmp_path, [9.0, 10.0], start="2026-09-16") + res = _premise.check(DELAUNAY, root, fetch=False, at=SHIFT, offline=True) + assert res["status"] == "ok", res + assert any(e.startswith("timing stale-record") for e in res["evidence"]) + + +def test_a_release_profile_claim_is_not_compared_with_smoke_timings(tmp_path): + root = _delaunay_root(tmp_path, [9.0, 10.0]) + text = DELAUNAY.read_text().replace( + "sits on the 300 s smoke cap (330–354 s under the release profile)", + "needs its 3600 s release override") + res = _premise.check(DELAUNAY, root, fetch=False, at=SHIFT, offline=True, text=text) + assert not any(e.startswith("timing") for e in res["evidence"]) + + +# --- gone, moved, ignored, absent ----------------------------------------------- + +def _draft(tmp_path, repo: str, body: str, witness: str = "") -> Path: + f = tmp_path / "d.md" + f.write_text(f"# A task\n\nType: feature\nTarget: {repo}\nRepos:\n- {repo}\n" + + (f"Witness: {witness}\n" if witness else "") + f"\n{body}\n") + return f + + +def _demo(tmp_path) -> Path: + root = tmp_path / "root" + repo = _repo(root, "demo_repo", {"pkg/a.py": "def keep_me():\n pass\n", + "pkg/old.py": "def dropped():\n pass\n", + "pkg/other.py": "x = 1\n", + "pkg/moved.py": "def m():\n return 'a long enough body'\n"}) + (repo / "pkg" / "old.py").unlink() + (repo / "pkg" / "other.py").unlink() + (repo / "pkg" / "new").mkdir() + (repo / "pkg" / "moved.py").rename(repo / "pkg" / "new" / "moved.py") + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "refactor: drop old, move moved", + date="2026-10-01T12:00:00Z") + return root + + +def test_everything_found_is_ok(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Edit `pkg/a.py` and `keep_me()`.") + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "ok", res + assert res["repos"]["demo_repo"] + assert _premise.verified_value(res).startswith(res["date"]) + + +def test_a_rename_is_moved_not_gone(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Body.", witness="`pkg/moved.py` still runs") + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "ok", res + assert any("pkg/new/moved.py" in e for e in res["evidence"]) + + +def test_one_path_gone_in_the_body_only_is_unknown(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Read `pkg/old.py` for context; edit `pkg/a.py`.") + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "unknown", res + assert any(e.startswith("GONE pkg/old.py") for e in res["evidence"]) + + +def test_every_named_path_gone_is_obsolete(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Merge `pkg/old.py` into `pkg/other.py`.") + assert _premise.check(d, root, fetch=False, offline=True)["status"] == "obsolete" + + +def test_a_removed_function_named_by_the_witness_is_obsolete(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Edit `pkg/a.py`.", witness="`dropped()` is fast") + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "obsolete", res + assert any(e.startswith("GONE dropped()") for e in res["evidence"]) + + +def test_a_file_to_create_is_not_evidence(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Add `pkg/brand_new.py` beside `pkg/a.py`.", + witness="`pkg/brand_new.py` exists") + assert _premise.check(d, root, fetch=False, offline=True)["status"] == "ok" + + +def test_at_replays_main_as_it_stood(tmp_path): + root = _demo(tmp_path) + d = _draft(tmp_path, "demo_repo", "Merge `pkg/old.py` into `pkg/other.py`.") + res = _premise.check(d, root, fetch=False, offline=True, at="2026-09-15T00:00Z") + assert res["status"] == "ok", res + + +def test_no_resolvable_repo_is_unknown(tmp_path): + d = _draft(tmp_path, "no_such_repo", "Edit `pkg/a.py`.") + res = _premise.check(d, tmp_path, fetch=False, offline=True) + assert res["status"] == "unknown" + + +def test_extract_reads_paths_functions_and_refs(): + got = _premise.extract("Edit `scripts/x.py:29` and `a/b/`; call `mod.fetch(x)`; " + "see Repo#12 and https://github.com/o/r/pull/7; " + "not `draft/a.md`, `n_live=100` or `*.py`.") + assert got["paths"] == ["scripts/x.py", "a/b"] + assert got["functions"] == ["fetch"] + assert ("o/r", 7) in got["refs"] and ("Repo", 12) in got["refs"] + + +# --- the Verified: stamp, through the ledger ------------------------------------- + +def _mind_with(tmp_path, draft_text: str) -> tuple[Path, Path]: + mind = tmp_path / "mind" + f = mind / "draft" / "feature" / "demo" / "d.md" + f.parent.mkdir(parents=True) + f.write_text(draft_text) + return mind, f + + +DEMO_DRAFT = ("# A task\n\nType: feature\nTarget: demo_repo\nRepos:\n- demo_repo\n" + "Unattended: ready\nLane: any\n\nEdit `pkg/a.py`.\n") + + +def test_cli_stamps_verified_through_the_ledger_inside_a_shift(tmp_path, monkeypatch): + root = _demo(tmp_path) + mind, f = _mind_with(tmp_path, DEMO_DRAFT) + ledger = tmp_path / "ledger" + monkeypatch.setenv("PYAUTO_SHIFT_LEDGER_DIR", str(ledger)) + rc = _batch.main(["premise", "draft/feature/demo/d.md", "--mind", str(mind), + "--root", str(root), "--no-fetch", "--offline", "--write-verified"]) + assert rc == 0 + assert f.read_text() == DEMO_DRAFT # a worker never writes the Mind + op = json.loads(next(ledger.glob("*.json")).read_text()) + assert op["op"] == "set-header" and op["key"] == "Verified" + assert op["path"] == "draft/feature/demo/d.md" + assert re.match(r"\d{4}-\d\d-\d\d [0-9a-f]{8} \(demo_repo\)$", op["value"]) + + +def test_cli_stamps_in_place_outside_a_shift_and_never_on_obsolete(tmp_path, monkeypatch): + root = _demo(tmp_path) + monkeypatch.delenv("PYAUTO_SHIFT_LEDGER_DIR", raising=False) + mind, f = _mind_with(tmp_path, DEMO_DRAFT) + assert _batch.main(["premise", str(f), "--mind", str(mind), "--root", str(root), + "--no-fetch", "--offline", "--write-verified"]) == 0 + head = f.read_text().split("\n\n")[1].splitlines() + assert head.index("Unattended: ready") + 1 == head.index( + next(l for l in head if l.startswith("Verified: "))) + obsolete = DEMO_DRAFT.replace("Edit `pkg/a.py`.", "Merge `pkg/old.py` into `pkg/other.py`.") + f.write_text(obsolete) + assert _batch.main(["premise", str(f), "--mind", str(mind), "--root", str(root), + "--no-fetch", "--offline", "--write-verified"]) == 1 + assert f.read_text() == obsolete + + +def test_set_header_replaces_or_inserts_and_touches_nothing_else(): + text = "# T\n\nType: bug\nRepos:\n- a\nUnattended: ready\nLane: any\n\nBody: prose.\n" + once = _mind_writer.set_header(text, "Verified", "2026-11-12 abc (a)") + assert once == text.replace("Unattended: ready\n", + "Unattended: ready\nVerified: 2026-11-12 abc (a)\n") + twice = _mind_writer.set_header(once, "Verified", "2026-11-13 def (a)") + assert twice.count("Verified:") == 1 and "2026-11-13 def (a)" in twice + bare = _mind_writer.set_header("# T\n\nJust prose.\n", "Lane", "any") + assert bare == "# T\n\nLane: any\n\nJust prose.\n" + + +def test_set_header_op_validates_and_applies(tmp_path): + lm = types.SimpleNamespace(is_ledger_path=lambda p: p.startswith("draft/")) + good = {"op": "set-header", "path": "draft/x/d.md", "key": "Verified", "value": "v"} + assert _mind_writer.validate_op(good, lm) == [] + assert _mind_writer.validate_op({**good, "value": "a\nb"}, lm) + assert _mind_writer.validate_op({**good, "key": "verified: x"}, lm) + assert _mind_writer.validate_op({**good, "path": "scripts/x.py"}, lm) + (tmp_path / "draft" / "x").mkdir(parents=True) + (tmp_path / "draft" / "x" / "d.md").write_text(DEMO_DRAFT) + _mind_writer.apply_op(tmp_path, good, lm) + assert "Verified: v\n" in (tmp_path / "draft" / "x" / "d.md").read_text() + + +# --- brief time, and the worker's first step ------------------------------------ + +BRIEF = """\ +# Batch 2026-11-06 pm +- dispatched: 2026-11-06T11:20Z +- review-at: 2026-11-06T12:20Z +- brief: + - goals: + - 1. replay + - tasks: + - {task} + - backlog: none + - review-minutes: 30 + - lanes: any local-dev + - merge-cap: 1 + - token-budget: 2000000 +""" + + +def test_brief_check_flags_a_stale_pick_before_the_shift(tmp_path, capsys): + root = _gallery_root(tmp_path) + mind, f = _mind_with(tmp_path, GALLERY.read_text()) + brief = tmp_path / "brief.md" + brief.write_text(BRIEF.format(task="draft/feature/demo/d.md")) + rc = _batch.main(["brief", "--check", str(brief), "--mind", str(mind), "--root", + str(root), "--no-fetch", "--offline", "--json"]) + res = json.loads(capsys.readouterr().out) + assert rc == 0 # flagged, not refused + assert res["premise"][0]["status"] == "obsolete" + assert any("premise OBSOLETE" in w and "gallery_run.sh" in w for w in res["warnings"]) + rc = _batch.main(["brief", "--check", str(brief), "--mind", str(mind), "--root", + str(root), "--no-premise", "--json"]) + assert json.loads(capsys.readouterr().out)["premise"] == [] + + +def test_the_premise_check_is_the_workers_first_step(tmp_path): + prompt = orch.session_command("t1", "draft/x/t1.md", tmp_path / "shift.md", + tmp_path / "leases", "auto")[-1] + step = f"{orch.BRAIN_CLI} batch premise draft/x/t1.md --write-verified" + assert step in prompt + assert prompt.index(step) < prompt.index("Use the start-dev skill.") + assert "`obsolete` (exit 1): stop." in prompt From 02bb592bfa92bba3f74754d8c19f09a259894863 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 12 Nov 2026 19:40:53 +0000 Subject: [PATCH 2/2] fix: premise and Lane-backfill review findings (#608) Must-fix: - premise: a deleted root-level file no longer matches a nested path the draft means to create (`token.endswith("/" + p)` only when p has a dir). - premise: a function missing from the declared repos is looked up in every library/organ checkout before it can be gone, and only a removal after the draft's Filed: (else Issued:, else 180 days) counts as evidence. - intake lane signals: RAL, A100, HPC and GPU count only in the title, the Witness: line or a requirement phrase ("on the A100", "submit ... to RAL", "needs a GPU"); mechanisms (SLURM, sbatch, --gres, /mnt paths, CUDA, private data) count anywhere; negated mentions never count. The proposal table gains a `why` column (infer_lane_reason). Also: - `batch premise` degrades any crash to `unknown (check failed: ...)`, exit 0; the worker template says to proceed on unknown and report it. - set-header on a draft no longer on main is skipped with a note, not raised. - the digest shows an `obsolete ` .done as "obsolete (premise check)". - lane_backfill --apply with nothing left exits 0, "nothing to apply". Co-Authored-By: Claude Opus 5.5 --- agents/conductors/batch/AGENTS.md | 14 ++- agents/conductors/batch/_batch.py | 13 ++- agents/conductors/batch/_digest.py | 19 +++- agents/conductors/batch/_mind_writer.py | 19 ++-- agents/conductors/batch/_premise.py | 99 +++++++++++++++++-- agents/conductors/batch/worker_template.md | 14 +-- agents/conductors/intake/_intake.py | 105 +++++++++++++++++---- bin/lane_backfill.py | 28 ++++-- tests/test_lane_backfill.py | 38 ++++++-- tests/test_premise_check.py | 90 +++++++++++++++++- 10 files changed, 373 insertions(+), 66 deletions(-) diff --git a/agents/conductors/batch/AGENTS.md b/agents/conductors/batch/AGENTS.md index f2baa69a..36624b11 100644 --- a/agents/conductors/batch/AGENTS.md +++ b/agents/conductors/batch/AGENTS.md @@ -153,13 +153,19 @@ programme M1.3, `_premise.py`): timing record contradicts the title, a file or function the title or `Witness:` names is gone (the deleting commit is the evidence), or every named path is gone; renames and newly-gitignored paths are *moved*, not - gone, and a path with no history is work to create, never evidence. For a - bug it also prints what a worker must reproduce. Exit 1 on `obsolete`. + gone, and a path with no history is work to create, never evidence. A + function counts as gone only if no library or organ checkout still defines + it and it was removed after the draft's `Filed:` date. For a bug it also + prints what a worker must reproduce. Exit 1 on `obsolete` only: a check + that crashes prints `unknown (check failed: …)` and exits 0. - `--write-verified` stamps `Verified: ()` on an `ok` draft — inside a shift as a `set-header` ledger op the orchestrator - commits (one Mind writer), outside one in place, uncommitted. + commits (one Mind writer), outside one in place, uncommitted. A stamp for + a draft that has left `main` since is skipped with a note, never raised. - It is the **first step of every dispatched worker** (`worker_template.md`): - on `obsolete` the worker writes its proof packet and stops. And it runs at + on `obsolete` the worker writes its proof packet and an `obsolete ` + `.done`, and stops; the digest shows it as `obsolete (premise check): `. + On `unknown` it goes on and says so in its proof packet. And it runs at **brief time**: `batch brief --check` adds a warning for each named task whose premise is obsolete (`--no-premise` skips the leg). diff --git a/agents/conductors/batch/_batch.py b/agents/conductors/batch/_batch.py index c9d2ff93..3edd626d 100644 --- a/agents/conductors/batch/_batch.py +++ b/agents/conductors/batch/_batch.py @@ -2982,8 +2982,13 @@ def _main_premise(mind: Path, a) -> int: if not draft.is_file(): print(f"batch premise: no such draft {a.prompt}", file=sys.stderr) return RC_USAGE - res = _premise.check(draft.resolve(), _premise_root(a), fetch=not a.no_fetch, - at=a.at or None, offline=a.offline) + try: + root = _premise_root(a) + except Exception as e: # noqa: BLE001 — degrade to unknown, never exit 1 + root = Path(".") + print(f"batch premise: no workspace root ({e})", file=sys.stderr) + res = _premise.safe_check(draft.resolve(), root, fetch=not a.no_fetch, + at=a.at or None, offline=a.offline) if a.write_verified: res["recorded"] = record_verified(mind, draft.resolve(), res) if a.as_json: @@ -3042,8 +3047,8 @@ def brief_premises(brief_path: Path, mind: Path, root: Path, *, fetch: bool = Tr for task in _brief.tasks_of(rec["brief"]): f = _brief._resolve(mind, task) if f is not None: - out.append({**_premise.check(f, root, fetch=fetch, offline=offline, - views=views), "task": task}) + out.append({**_premise.safe_check(f, root, fetch=fetch, offline=offline, + views=views), "task": task}) return out diff --git a/agents/conductors/batch/_digest.py b/agents/conductors/batch/_digest.py index 537a0b36..6b7c63f5 100644 --- a/agents/conductors/batch/_digest.py +++ b/agents/conductors/batch/_digest.py @@ -64,18 +64,26 @@ def parse_done(text: str) -> dict: """A worker's `.done` file: one PR or issue URL per line, `merged ` for - a PR it merged in-turn under its tier.""" - prs, merged = [], [] + a PR it merged in-turn under its tier, `obsolete ` when its premise + check stopped it.""" + prs, merged, obsolete = [], [], None for line in text.splitlines(): words = line.split() if not words: continue - if words[0] == "merged" and len(words) > 1: + if words[0] == "obsolete": + # The worker's premise check found the task obsolete on main and + # it stopped (worker_template.md); the rest is its evidence. + obsolete = line.strip()[len("obsolete"):].strip(" :—-") + elif words[0] == "merged" and len(words) > 1: merged.append(words[1]) prs.append(words[1]) elif words[0].startswith("http"): prs.append(words[0]) - return {"prs": prs, "merged": merged} + out = {"prs": prs, "merged": merged} + if obsolete is not None: + out["obsolete"] = obsolete + return out def pr_health(url: str, run=None) -> str: @@ -119,6 +127,9 @@ def task_state(task: str, counters: dict, health, *, live: bool = False, if live and task in counters.get("pending_redispatch", []): return "crashed — awaiting re-dispatch", True return "not started", False + if not out["prs"] and "obsolete" in out: + return ("obsolete (premise check): " + + (out["obsolete"] or "see its proof packet")), False if not out["prs"]: return "finished, no PR or issue named in its .done", False parts = [] diff --git a/agents/conductors/batch/_mind_writer.py b/agents/conductors/batch/_mind_writer.py index 09915b69..0a0074c1 100644 --- a/agents/conductors/batch/_mind_writer.py +++ b/agents/conductors/batch/_mind_writer.py @@ -105,8 +105,12 @@ def validate_op(op: dict, lm) -> list[str]: return errs -def apply_op(tree: Path, op: dict, lm) -> None: - """Apply one validated op inside `tree`; raises MindWriteError if it cannot.""" +def apply_op(tree: Path, op: dict, lm) -> str | None: + """Apply one validated op inside `tree`; raises MindWriteError if it cannot. + + Returns a note when the op was deliberately skipped. Only `set-header` + skips: it is a stamp, and a draft moved or retired on main since the + check ran must not hold every other op of the shift pending for ever.""" target = tree / op["path"] kind = op["op"] if kind == "append": @@ -139,7 +143,8 @@ def apply_op(tree: Path, op: dict, lm) -> None: target.write_text(lm.join_entries(preamble, kept), encoding="utf-8") elif kind == "set-header": if not target.exists(): - raise MindWriteError(f"set-header: {op['path']} does not exist") + return (f"set-header: {op['path']} is not on main (moved or retired " + f"since the check) — {op['key']}: skipped") target.write_text(set_header(target.read_text(encoding="utf-8"), op["key"], op["value"]), encoding="utf-8") elif kind == "table-append": @@ -273,8 +278,9 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, try: _git(mind_repo, "worktree", "add", "-q", "--detach", str(tree), f"{remote}/{branch}") - for op in ops: - apply_op(tree, op, lm) + notes = [n for op in ops if (n := apply_op(tree, op, lm))] + for n in notes: + print(f"mind-writer: {n}", file=sys.stderr) _git(tree, "add", "-A") if not _git(tree, "status", "--porcelain").stdout.strip(): sha = None # every op was already true on main @@ -288,7 +294,8 @@ def commit_ledger(slot: Path, mind_repo: Path, message: str, done.mkdir(parents=True, exist_ok=True) for f in files: f.replace(done / f.name) - return {"committed": sha, "ops": len(ops), "tries": attempt} + return {"committed": sha, "ops": len(ops), "tries": attempt, + "skipped": notes} finally: # Our own throwaway tree. A failed apply can leave it dirty, so # delete the directory and prune the registration, no force flag. diff --git a/agents/conductors/batch/_premise.py b/agents/conductors/batch/_premise.py index bb0108c3..ab469fca 100644 --- a/agents/conductors/batch/_premise.py +++ b/agents/conductors/batch/_premise.py @@ -226,7 +226,11 @@ def deleted(self, token: str) -> dict | None: if len(parts) < 2: continue p = parts[1] - if p == token or p.endswith("/" + token) or token.endswith("/" + p) \ + # `token.endswith("/" + p)` only for a p WITH a directory: a + # deleted root-level `__init__.py` says nothing about the + # `pkg/new_module/__init__.py` a draft means to create. + if p == token or p.endswith("/" + token) \ + or ("/" in p and token.endswith("/" + p)) \ or ("/" not in token and p.rsplit("/", 1)[-1] == token): commit = lines[0] renamed = parts[2] if parts[0].startswith("R") and len(parts) > 2 else None @@ -264,10 +268,15 @@ def defines(self, func: str) -> str | None: first = (out or "").splitlines()[:1] return first[0].split(":", 1)[1] if first else None - def removed(self, func: str) -> str | None: - out = _git(self.path, "log", self.sha, "-1", "--date=short", - "--format=%h %ad %s", f"-Sdef {func}(", "--", "*.py", - run=self.run, timeout=120) + def removed(self, func: str, since: str | None = None) -> str | None: + """The newest commit since `since` whose diff adds or drops `def func(`. + A removal older than the draft is history the author wrote against, + not evidence that its premise went away.""" + args = ["log", self.sha, "-1", "--date=short", "--format=%h %ad %s", + f"-Sdef {func}("] + if since: + args.append(f"--since={since}") + out = _git(self.path, *args, "--", "*.py", run=self.run, timeout=120) return (out or "").strip() or None def show(self, rel: str) -> str | None: @@ -292,6 +301,54 @@ def checkouts(root: Path) -> dict[str, Path]: return {} +def code_repos(found_co: dict[str, Path]) -> list[Path]: + """The local library and organ checkouts — where a function a draft names + may live even when its `Repos:` header points elsewhere. Read from the + body map's `category:`; every checkout when there is no body map.""" + mind = found_co.get("pyautomind") + manifest = mind / "repos.yaml" if mind else None + if manifest is None or not manifest.is_file(): + return list(found_co.values()) + keep, current = set(), None + for line in manifest.read_text(encoding="utf-8", errors="replace").splitlines(): + m = re.match(r"^ ([A-Za-z0-9_.-]+):\s*$", line) + if m: + current = m.group(1).lower() + continue + m = re.match(r"^ category:\s*(\w+)", line) + if m and current and m.group(1) in ("library", "organ"): + keep.add(current) + return [p for name, p in found_co.items() if name in keep] + + +def live_definition(path: Path, func: str, at: str | None, run) -> str | None: + """`def func` / `class func` on this checkout's main (as of `at`), cheaply: + one ref lookup and one `git grep`, no fetch and no tree listing.""" + base = next((b for b in ("origin/main", "main") + if _git(path, "rev-parse", "--verify", "-q", b, run=run)), None) + if base is None: + return None + ref = ((_git(path, "rev-list", "-1", f"--before={at}", base, run=run) or "").strip() + if at else base) + if not ref: + return None + out = _git(path, "grep", "-l", "-E", rf"(def|class) {func}\b", ref, "--", "*.py", + run=run) + first = (out or "").splitlines()[:1] + return first[0].split(":", 1)[1] if first else None + + +def _since(text: str, at: str | None) -> str: + """The evidence bound for a removal: the draft's `Filed:` (else + `Issued:`) date, else 180 days before the check.""" + for key in ("filed", "issued"): + day = _parse_day(_header(text, key)) + if day is not None: + return day.isoformat() + ref = _parse_day(at or "") or _dt.date.today() + return (ref - _dt.timedelta(days=180)).isoformat() + + # --- the probes ----------------------------------------------------------------- def _claimed_seconds(title: str) -> int | None: @@ -448,12 +505,25 @@ def view(name: str): absent.append(token) funcs_found, funcs_gone = [], [] + since = _since(text, at) + elsewhere = None for func in named["functions"]: hit = next(((v, d) for v in repos if (d := v.defines(func))), None) if hit: funcs_found.append(f"{func} ({hit[0].name})") continue - rm = next(((v, c) for v in repos if (c := v.removed(func))), None) + # Not in the declared repos: a live definition in ANY library or organ + # checkout means the draft just named the wrong repo, not that the + # function is gone. + if elsewhere is None: + declared_paths = {v.path for v in repos} + elsewhere = [p for p in code_repos(found_co) if p not in declared_paths] + live = next(((p, f) for p in elsewhere + if (f := live_definition(p, func, at, run))), None) + if live: + funcs_found.append(f"{func} ({live[0].name}:{live[1]})") + continue + rm = next(((v, c) for v in repos if (c := v.removed(func, since))), None) if rm: funcs_gone.append({"token": f"{func}()", "repo": rm[0].name, "commit": rm[1]}) @@ -526,6 +596,19 @@ def view(name: str): } +def safe_check(draft: Path, root: Path, **kw) -> dict: + """`check`, but a crash is `unknown (check failed: …)`, never an exit 1: + only a real `obsolete` may stop a worker.""" + try: + return check(draft, root, **kw) + except Exception as e: # noqa: BLE001 — any failure degrades to unknown + at = kw.get("at") or "" + return {"path": str(draft), "status": "unknown", + "reasons": [f"check failed: {type(e).__name__}: {e}"], + "evidence": [], "reproduce": "", "repos": {}, "at": at, + "date": (at or _dt.date.today().isoformat())[:10]} + + def verified_value(result: dict) -> str: """` ` per repo — the `Verified:` header's value.""" shas = ", ".join(f"{sha} ({repo})" for repo, sha in sorted(result["repos"].items())) @@ -533,7 +616,9 @@ def verified_value(result: dict) -> str: def report(result: dict) -> str: - lines = [f"premise: {result['status']} — {result['path']}"] + failed = next((r for r in result["reasons"] if r.startswith("check failed")), "") + lines = [f"premise: {result['status']}" + (f" ({failed})" if failed else "") + + f" — {result['path']}"] if result["repos"]: lines.append(" main: " + ", ".join(f"{r}@{s}" for r, s in result["repos"].items()) + (f" (as of {result['at']})" if result["at"] else "")) diff --git a/agents/conductors/batch/worker_template.md b/agents/conductors/batch/worker_template.md index 65df4170..7085337a 100644 --- a/agents/conductors/batch/worker_template.md +++ b/agents/conductors/batch/worker_template.md @@ -9,12 +9,14 @@ First, before anything else, check the task's premise on a fresh main - `obsolete` (exit 1): stop. Open no issue, branch or worktree and implement nothing. Write {lease_dir}/{task}.proof.md headed `#### {task} — obsolete (premise check)` with the check's evidence lines, - then {lease_dir}/{task}.done containing the word `obsolete`. That is your - deliverable; the human retires the draft. -- `ok` or `unknown`: go on (`ok` queued its `Verified:` stamp through the - ledger). For a bug, reproduce what its `reproduce before fixing:` line names - before changing code; if it does not reproduce, park on the issue with - that evidence instead of fixing. + then {lease_dir}/{task}.done containing one line: `obsolete `. That is your deliverable; the human retires the draft. +- `ok`: go on (it queued its `Verified:` stamp through the ledger). +- `unknown` (exit 0, including `check failed: …`): go on, and say in your + proof packet that the premise check was unknown and why. +- For a bug, reproduce what its `reproduce before fixing:` line names before + changing code; if it does not reproduce, park on the issue with that + evidence instead of fixing. Use the start-dev skill. {task_path} --auto diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 3e7caec9..5d99da61 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -677,33 +677,100 @@ def _declared_passthrough(header_lines) -> list[tuple[str, str]]: # the cloud, which is the failure the lane exists to prevent. # # 2026-11-12 (PyAutoBrain#608, M1.3 slice 2): the words the ecosystem review -# found missing. `A100` and `HPC` are RAL resources (the A100s live there), as -# is a `/mnt/ral` path; a bare upper-case `GPU` is the laptop GPU (no cloud -# session has one); any other `/mnt/` is WSL data; and "private data" -# needs the laptop's local trees, so it is `local-dev`. The Lane backfill -# (`bin/lane_backfill.py`) reads this same table, so filing and backfill -# cannot drift apart. +# found missing, and a stricter reading of the loose ones. An unambiguous +# mechanism (`sbatch`, `SLURM`, `--gres`, a `/mnt/ral` or `/mnt/` path, +# CUDA, the laptop GPU, "private data") is a requirement wherever it appears. +# A bare resource NAME — RAL, A100, HPC, GPU — is not: drafts mention them as +# context ("not a CPU-vs-GPU limitation", "GPU runs are unaffected", "A100 +# likelihoods ... was removed"). Those count only in a requirement context: +# the title or the `Witness:` line, or a phrase that puts the work there +# ("re-run ... on the A100", "submit ... to RAL", "needs a GPU"). A negated +# mention ("not", "no longer", "unaffected", "without") never counts. A100 and +# HPC are RAL resources (the A100s live there); a GPU is the laptop's. The +# Lane backfill (`bin/lane_backfill.py`) reads this same table, so filing and +# backfill cannot drift apart. +LANE_ORDER = ("ral", "gpu", "wsl-data", "local-dev") LANE_SIGNALS = ( - ("ral", re.compile(r"\bRAL\b|\bSLURM\b|\bsbatch\b|\bsqueue\b|euclid_jump" - r"|\bA100s?\b|\bHPC\b|/mnt/ral\b")), + ("ral", re.compile(r"\bSLURM\b|\bsbatch\b|\bsqueue\b|--gres\b|euclid_jump" + r"|/mnt/ral\b")), ("gpu", re.compile(r"\bCUDA\b|laptop GPU|\bGPU\b on the laptop", re.I)), - ("gpu", re.compile(r"\bGPUs?\b")), ("wsl-data", re.compile(r"/mnt/[a-z]\b|Workspace/Science\b")), ("local-dev", re.compile(r"\bprivate (?:data|datasets?|catalogues?)\b", re.I)), ) +#: Resource names that need a requirement context, by lane. +LANE_RESOURCES = ( + ("ral", r"RAL|A100s?|HPC"), + ("gpu", r"GPUs?"), +) +_RUN_VERBS = (r"(?i:run|runs|ran|running|re-?run|reruns?|time|timed|profile[sd]?|" + r"measure[sd]?|benchmark(?:ed|s)?|reproduce[sd]?|fit|fits|test(?:ed)?|" + r"execute[sd]?)") + + +def _requirement_patterns(names: str) -> tuple: + # "rerun on the HPC" is how drafts weigh an OPTION; HPC needs the title, + # the Witness:, a submit or a need — never a bare "on the HPC". + placed = "|".join(n for n in names.split("|") if n != "HPC") + return ( + re.compile(rf"\b{_RUN_VERBS}\b[^.\n]{{0,40}}?\b(?:on|with)\s+" + rf"(?:the\s+|an?\s+|\d+\s+|two\s+|four\s+|eight\s+)?(?:RAL\s+)?" + rf"(?:{placed})\b"), + re.compile(rf"\b(?i:submit)\w*\b[^.\n]{{0,30}}?\b(?:to|on)\s+(?:the\s+)?(?:{names})\b"), + re.compile(rf"\b(?i:needs?|requires?|requiring)\b[^.\n]{{0,30}}?\b(?:{names})\b"), + ) + + +_NEGATION = re.compile(r"\bnot\b|n't\b|\bno longer\b|\bunaffected\b|\bwithout\b" + r"|\bnever\b|\bnor\b", re.I) + + +def _negated(text: str, start: int, end: int) -> bool: + """A negation word in the same clause as the match.""" + lo = max(text.rfind(c, 0, start) for c in ".\n;") + 1 + his = [i for i in (text.find(c, end) for c in ".\n;") if i != -1] + return bool(_NEGATION.search(text[lo:min(his) if his else len(text)])) + + +def _snippet(text: str, start: int, end: int) -> str: + lo, hi = max(0, start - 50), min(len(text), end + 50) + return " ".join(text[lo:hi].split()) + + +def _first(pattern, text: str, offset: int = 0): + for m in pattern.finditer(text): + if not _negated(text, m.start(), m.end()): + return m.start() + offset, m.end() + offset, m.group(0) + return None + + +def infer_lane_reason(text: str) -> tuple[str, str, str]: + """`(lane, snippet, why)`: the first requirement signal, in lane + precedence, with the words around it and the rule that fired — what a + human skims to accept or reject a proposed lane. `("any", "", "no + resource required")` when the text names none.""" + title = next((ln for ln in text.splitlines() if ln.startswith("# ")), "") + witness = next((ln for ln in text.splitlines()[:40] if ln.startswith("Witness:")), "") + for lane in LANE_ORDER: + for sig_lane, pattern in LANE_SIGNALS: + if sig_lane == lane and (hit := _first(pattern, text)): + return lane, _snippet(text, hit[0], hit[1]), f"names {hit[2]!r}" + names = dict(LANE_RESOURCES).get(lane) + if not names: + continue + word = re.compile(rf"\b(?:{names})\b") + for where, line in (("title", title), ("Witness:", witness)): + if line and (hit := _first(word, line)): + return lane, " ".join(line.split())[:160], f"the {where} names {hit[2]!r}" + for pattern in _requirement_patterns(names): + if hit := _first(pattern, text): + return lane, _snippet(text, hit[0], hit[1]), \ + f"requirement: {' '.join(hit[2].split())!r}" + return "any", "", "no resource required" def infer_lane_evidence(text: str) -> tuple[str, str]: - """`(lane, snippet)`: the first signal that matches, with the words around - it — what a human skims to accept or reject a proposed lane. `("any", "")` - when the text names no resource.""" - for lane, pattern in LANE_SIGNALS: - m = pattern.search(text) - if m: - lo, hi = max(0, m.start() - 50), min(len(text), m.end() + 50) - snippet = " ".join(text[lo:hi].split()) - return lane, snippet - return "any", "" + """`(lane, snippet)` — `infer_lane_reason` without the rule.""" + return infer_lane_reason(text)[:2] def infer_lane(text: str) -> str: diff --git a/bin/lane_backfill.py b/bin/lane_backfill.py index fe66f182..2fd9f6f0 100644 --- a/bin/lane_backfill.py +++ b/bin/lane_backfill.py @@ -67,9 +67,9 @@ def lane_less(mind: Path, *, every: bool = False) -> list[dict]: def propose(mind: Path, *, every: bool = False) -> list[dict]: rows = [] for d in lane_less(mind, every=every): - lane, snippet = _intake.infer_lane_evidence(d["text"]) - rows.append({"path": d["path"], "lane": lane, "evidence": snippet, - "invalid": d["invalid"]}) + lane, snippet, why = _intake.infer_lane_reason(d["text"]) + rows.append({"path": d["path"], "lane": lane, "why": why, + "evidence": snippet, "invalid": d["invalid"]}) return sorted(rows, key=lambda r: (r["lane"] == "any", r["lane"], r["path"])) @@ -90,19 +90,20 @@ def table(rows: list[dict], *, scope: str, stamp: str = "") -> str: "", "Counts: " + ", ".join(f"`{k}` {v}" for k, v in c.items()) + ".", "", - "Skim the non-`any` rows: a keyword hit is an upper bound, and a draft", - "that only *mentions* RAL or a GPU as context should be `any`. Edit the", + "Skim the non-`any` rows. A resource name counts only in the title, the", + "`Witness:` line or a requirement phrase; `why` says which rule fired. Edit the", "lane column to overrule a row, delete the row to skip it, then run", "`lane_backfill.py --apply --from `.", "", - "| draft | lane | evidence |", - "|---|---|---|", + "| draft | lane | why | evidence |", + "|---|---|---|---|", ] for r in rows: ev = r["evidence"].replace("|", "\\|").replace("`", "'") + why = r.get("why", "").replace("|", "\\|").replace("`", "'") if r["invalid"]: - ev = (f"replaces invalid `Lane: {r['invalid']}`; " + ev).strip("; ") - lines.append(f"| `{r['path']}` | `{r['lane']}` | {ev or '—'} |") + why = f"replaces invalid Lane: {r['invalid']}; " + why + lines.append(f"| `{r['path']}` | `{r['lane']}` | {why or '—'} | {ev or '—'} |") return "\n".join(lines) + "\n" @@ -174,6 +175,15 @@ def main(argv=None) -> int: return 2 if a.apply: rows = read_table(a.table) if a.table else propose(mind, every=a.every) + # A rerun: every row already declares its lane — nothing to do, not a + # refusal. + rows = [r for r in rows if not ((mind / r["path"]).is_file() + and declared_header((mind / r["path"]).read_text( + encoding="utf-8", errors="replace")).get("lane"))] + if not rows: + print("lane_backfill: nothing to apply — every proposed draft " + "already declares a lane") + return 0 written, refused = apply(mind, rows) print(f"lane_backfill: wrote Lane: into {len(written)} draft(s) " f"(not committed); refused {len(refused)}") diff --git a/tests/test_lane_backfill.py b/tests/test_lane_backfill.py index 6c98768b..034ee7c7 100644 --- a/tests/test_lane_backfill.py +++ b/tests/test_lane_backfill.py @@ -33,7 +33,11 @@ ("Submit the sweep to the HPC queue.", "ral"), ("Submit it with SLURM.", "ral"), ("Outputs live under /mnt/ral/jnightin/out.", "ral"), - ("Compare the GPU and CPU timings.", "gpu"), + ("Run the benchmark on the GPU.", "gpu"), + ("This needs a GPU.", "gpu"), + ("# Wrong likelihoods on an A100\n\nBody.", "ral"), + ("Body.\nWitness: the cell completes on the RAL A100\n", "ral"), + ("Request one with --gres=gpu:1.", "ral"), ("Read the cutouts from /mnt/d/archive.", "wsl-data"), ("Fit the Euclid private data release.", "local-dev"), ("Needs the private datasets on the laptop.", "local-dev"), @@ -48,15 +52,22 @@ def test_intake_infers_the_new_lane_words(text, lane): "The PyAutoGPU venv path is documented.", # no word boundary: not the GPU "A general refactor of the parser.", # `RAL` must be its own word "Point the gpu flag at the right default.", # lower-case code identifier + # Mentions, not requirements (the review's false positives, 2026-11-12): + "It is not a CPU-vs-GPU limitation — the wheels were dropped.", + "Today's production GPU runs, which fit the plain dataset, are unaffected.", + "Compare the GPU and CPU timings.", + "The chunked vmap for inversion-heavy A100 likelihoods was removed with NSS.", + "Either scrape output, or doing large reruns on the HPC, if elegant.", + "We do not run this on RAL.", ]) def test_intake_stays_narrow(text): assert _intake.infer_lane(text) == "any" def test_ral_outranks_gpu_and_evidence_is_the_matching_words(): - lane, snippet = _intake.infer_lane_evidence( + lane, snippet, why = _intake.infer_lane_reason( "Benchmark on the GPU. The full sweep runs on the RAL A100 nodes.") - assert lane == "ral" and "RAL" in snippet + assert lane == "ral" and "RAL" in snippet and why.startswith("requirement:") # --- the backfill ------------------------------------------------------------------ @@ -73,7 +84,8 @@ def _mind(tmp_path) -> Path: d.mkdir(parents=True) files = { "ral.md": _prompt("", "Time it on the A100 via sbatch."), - "gpu.md": _prompt("", "Compare GPU throughput."), + "gpu.md": _prompt("", "Run the throughput leg on the GPU."), + "mention.md": _prompt("", "GPU runs are unaffected."), "wsl.md": _prompt("", "Data under /mnt/c/Users/x/data."), "private.md": _prompt("", "Needs the private data on disk."), "plain.md": _prompt("", "Tidy a docstring."), @@ -98,8 +110,10 @@ def test_witness_b_proposal_covers_the_pool_and_apply_leaves_none(tmp_path): by = {Path(r["path"]).stem: r for r in rows} assert {k: by[k]["lane"] for k in by} == { "ral": "ral", "gpu": "gpu", "wsl": "wsl-data", "private": "local-dev", - "plain": "any", "invalid": "any"} + "plain": "any", "invalid": "any", "mention": "any"} assert "A100" in by["ral"]["evidence"] and by["plain"]["evidence"] == "" + assert by["ral"]["why"] == "names 'sbatch'" + assert by["plain"]["why"] == "no resource required" assert "not_ready" not in by and "declared" not in by # outside the pool / declared # Applied to a COPY, through the human-skimmable table, edits honoured. @@ -145,6 +159,18 @@ def test_proposal_mode_writes_only_the_table(tmp_path, capsys): assert lb.main(["--mind", str(mind), "--out", str(out)]) == 0 assert {f: f.read_text() for f in mind.rglob("*.md")} == before text = out.read_text() - assert "Counts: `any` 2" in text and text.count("| `draft/") == 6 + assert "Counts: `any` 3" in text and text.count("| `draft/") == 7 + assert "| draft | lane | why | evidence |" in text assert "--from belongs" not in capsys.readouterr().err assert lb.main(["--mind", str(mind), "--from", str(out)]) == 2 + + +def test_apply_rerun_with_nothing_left_is_a_clean_no_op(tmp_path, capsys): + mind = _mind(tmp_path) + table = tmp_path / "proposals.md" + table.write_text(lb.table(lb.propose(mind), scope="test")) + assert lb.main(["--mind", str(mind), "--apply", "--from", str(table)]) == 0 + capsys.readouterr() + assert lb.main(["--mind", str(mind), "--apply", "--from", str(table)]) == 0 + assert "nothing to apply" in capsys.readouterr().out + assert lb.main(["--mind", str(mind), "--apply"]) == 0 diff --git a/tests/test_premise_check.py b/tests/test_premise_check.py index d55dd84a..778e89e6 100644 --- a/tests/test_premise_check.py +++ b/tests/test_premise_check.py @@ -234,6 +234,74 @@ def test_at_replays_main_as_it_stood(tmp_path): assert res["status"] == "ok", res +def test_a_root_level_namesake_deletion_is_not_evidence(tmp_path): + """Review finding 1: a deleted root-level `__init__.py` must not make the + `pkg/solver_v2/__init__.py` a Witness means to CREATE read as gone.""" + root = tmp_path / "root" + repo = _repo(root, "demo_repo", {"__init__.py": "\n", "pkg/a.py": "\n"}) + (repo / "__init__.py").unlink() + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "drop the root __init__", date="2022-01-01T00:00:00Z") + d = _draft(tmp_path, "demo_repo", "Add a solver beside `pkg/a.py`.", + witness="`pkg/point/solver_v2/__init__.py` exports Solver") + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "ok", res + assert not any(e.startswith("GONE") for e in res["evidence"]) + assert any("pkg/point/solver_v2/__init__.py" in e for e in res["evidence"] + if e.startswith("absent")) + + +def _two_repos(tmp_path) -> Path: + """A function removed from the declared repo long ago, alive in another + library checkout — review finding 2 (`LensCalc.from_tracer()`).""" + root = tmp_path / "root" + lens = _repo(root, "lens_lib", {"lens/calc.py": "def from_tracer():\n pass\n"}, + date="2020-01-01T00:00:00Z") + (lens / "lens" / "calc.py").write_text("x = 1\n") + _git(lens, "add", "-A") + _git(lens, "commit", "-q", "-m", "removed from_tracer", date="2020-03-28T00:00:00Z") + _repo(root, "galaxy_lib", {"galaxy/calc.py": "class LensCalc:\n" + " def from_tracer(cls):\n pass\n"}) + return root + + +def test_a_function_alive_in_another_checkout_is_found_not_gone(tmp_path): + root = _two_repos(tmp_path) + d = _draft(tmp_path, "lens_lib", "Edit `lens/calc.py`.", + witness="`LensCalc.from_tracer()` returns the plane") + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "ok", res + assert any("from_tracer (galaxy_lib" in e for e in res["evidence"]) + + +def test_a_removal_older_than_the_draft_is_not_evidence(tmp_path): + root = _two_repos(tmp_path) + shutil_rm = __import__("shutil").rmtree + shutil_rm(root / "galaxy_lib") # alive nowhere now + text = _draft(tmp_path, "lens_lib", "Edit `lens/calc.py`.", + witness="`from_tracer()` returns the plane").read_text() + d = tmp_path / "filed.md" + d.write_text(text.replace("Type: feature\n", "Type: feature\nFiled: 2026-09-01\n")) + res = _premise.check(d, root, fetch=False, offline=True) + assert res["status"] == "ok", res + assert not any(e.startswith("GONE") for e in res["evidence"]) + # The same removal AFTER the draft was filed is evidence. + d.write_text(text.replace("Type: feature\n", "Type: feature\nFiled: 2020-02-01\n")) + assert _premise.check(d, root, fetch=False, offline=True)["status"] == "obsolete" + + +def test_a_crashing_check_is_unknown_and_exit_0(tmp_path, monkeypatch, capsys): + root = _demo(tmp_path) + mind, f = _mind_with(tmp_path, DEMO_DRAFT) + monkeypatch.setattr(_premise, "extract", lambda text: 1 / 0) + rc = _batch.main(["premise", str(f), "--mind", str(mind), "--root", str(root), + "--no-fetch", "--offline", "--write-verified"]) + out = capsys.readouterr().out + assert rc == 0 + assert out.startswith("premise: unknown (check failed: ZeroDivisionError") + assert f.read_text() == DEMO_DRAFT + + def test_no_resolvable_repo_is_unknown(tmp_path): d = _draft(tmp_path, "no_such_repo", "Edit `pkg/a.py`.") res = _premise.check(d, tmp_path, fetch=False, offline=True) @@ -305,6 +373,13 @@ def test_set_header_replaces_or_inserts_and_touches_nothing_else(): assert bare == "# T\n\nLane: any\n\nJust prose.\n" +def test_set_header_on_a_draft_gone_from_main_skips_not_raises(tmp_path): + lm = types.SimpleNamespace(is_ledger_path=lambda p: p.startswith("draft/")) + op = {"op": "set-header", "path": "draft/x/moved.md", "key": "Verified", "value": "v"} + note = _mind_writer.apply_op(tmp_path, op, lm) + assert note and "skipped" in note and not (tmp_path / "draft").exists() + + def test_set_header_op_validates_and_applies(tmp_path): lm = types.SimpleNamespace(is_ledger_path=lambda p: p.startswith("draft/")) good = {"op": "set-header", "path": "draft/x/d.md", "key": "Verified", "value": "v"} @@ -314,7 +389,7 @@ def test_set_header_op_validates_and_applies(tmp_path): assert _mind_writer.validate_op({**good, "path": "scripts/x.py"}, lm) (tmp_path / "draft" / "x").mkdir(parents=True) (tmp_path / "draft" / "x" / "d.md").write_text(DEMO_DRAFT) - _mind_writer.apply_op(tmp_path, good, lm) + assert _mind_writer.apply_op(tmp_path, good, lm) is None assert "Verified: v\n" in (tmp_path / "draft" / "x" / "d.md").read_text() @@ -360,3 +435,16 @@ def test_the_premise_check_is_the_workers_first_step(tmp_path): assert step in prompt assert prompt.index(step) < prompt.index("Use the start-dev skill.") assert "`obsolete` (exit 1): stop." in prompt + assert "`unknown` (exit 0, including `check failed: …`): go on" in prompt + + +def test_the_digest_names_an_obsolete_worker(): + import _digest + out = _digest.parse_done("obsolete a file the Witness: names is gone on main\n") + assert out == {"prs": [], "merged": [], + "obsolete": "a file the Witness: names is gone on main"} + state, tiered = _digest.task_state("t1", {"outcomes": {"t1": out}}, None) + assert state == ("obsolete (premise check): a file the Witness: names is gone " + "on main") and not tiered + bare = _digest.task_state("t1", {"outcomes": {"t1": _digest.parse_done("obsolete")}}, None) + assert bare[0] == "obsolete (premise check): see its proof packet"