From 200064bcfa7d8449e88fb1e8fec550817278ecd4 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 15 Oct 2026 14:21:41 +0100 Subject: [PATCH 1/4] feat(hands): generate search rosters from the installed autofit search manifest One generator for every search roster (search-ext A5 consumers, #310): autohands/search_roster.py renders fenced search-roster blocks (style=list|table, indent, link) stamped from the manifest printed by the installed autofit; regenerate_search_roster / check_search_roster are the CLI verbs. --check fails on a changed roster body, notes a stamp-only difference (unless --strict-version), resolves manifest example / integration_test anchors under --workspace-root, checks that every search = af.(...) in --names-in scripts is a manifest search, and --against-source reports source-vs-installed drift without failing. regenerate_navigator --roster rewrites only the roster block in a curated llms.txt / scripts READMEs. check_search_memory --manifest guards exactly the manifest's MultiStart* searches (prefix rule stays the stdlib fallback). navigator_check.yml gains a search_roster job: pip install autofit, dump the manifest, run both checks against it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/navigator_check.yml | 65 ++++ autohands/check_search_memory.py | 62 +++- autohands/check_search_roster.py | 124 +++++++ autohands/navigator.py | 37 ++- autohands/regenerate_navigator.py | 30 +- autohands/regenerate_search_roster.py | 58 ++++ autohands/search_roster.py | 459 ++++++++++++++++++++++++++ bin/autohands | 60 +++- tests/test_check_search_memory.py | 34 ++ tests/test_search_roster.py | 241 ++++++++++++++ 10 files changed, 1151 insertions(+), 19 deletions(-) create mode 100644 autohands/check_search_roster.py create mode 100644 autohands/regenerate_search_roster.py create mode 100644 autohands/search_roster.py create mode 100644 tests/test_search_roster.py diff --git a/.github/workflows/navigator_check.yml b/.github/workflows/navigator_check.yml index 69f009a5..2f432918 100644 --- a/.github/workflows/navigator_check.yml +++ b/.github/workflows/navigator_check.yml @@ -70,6 +70,71 @@ jobs: - name: Check for unbatched multi-start searches run: python PyAutoHands/autohands/check_search_memory.py --root workspace + search_roster: + # Search rosters, manifest anchors and named searches against the search + # manifest of the INSTALLED autofit release (search-manifest@1) — the + # pinned version, never the library's main. The workspace is checked out + # under its own repository name so the manifest's `:` anchors + # resolve against it; for the autofit workspace the integration-test + # workspace is checked out beside it so both anchor kinds resolve. Other + # projects' anchors point into repos not checked out here and are skipped. + name: Search roster vs installed manifest + runs-on: ubuntu-latest + env: + NUMBA_CACHE_DIR: /tmp/numba_cache + MPLCONFIGDIR: /tmp/matplotlib + steps: + - name: Checkout workspace + uses: actions/checkout@v4 + with: + path: ${{ github.event.repository.name }} + - name: Checkout PyAutoHands + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/PyAutoHands + path: PyAutoHands + - name: Checkout the integration-test workspace (autofit only) + if: inputs.project == 'autofit' + uses: actions/checkout@v4 + with: + repository: PyAutoLabs/autofit_workspace_test + path: autofit_workspace_test + sparse-checkout: scripts/searches + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + - name: Match PyAutoHands branch + shell: bash + run: | + BRANCH="${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" + pushd PyAutoHands + if [[ -n "$(git ls-remote --heads origin "$BRANCH")" ]]; then + git fetch origin "$BRANCH" + git checkout "$BRANCH" + fi + popd + - name: Install the released autofit + run: pip install --quiet autofit + - name: Dump the installed search manifest + run: | + python -m autofit search-manifest --json > search_manifest.json + python -c "import json; d = json.load(open('search_manifest.json')); print(d['schema'], 'autofit', d['autofit_version'], len(d['searches']), 'searches')" + - name: Check roster blocks, anchors and named searches + run: > + python PyAutoHands/autohands/check_search_roster.py + --root "${{ github.event.repository.name }}" + --manifest search_manifest.json + --workspace-root . + --names-in "scripts/searches/*.py" + --names-in "scripts/cookbooks/search.py" + --names-in "scripts/guides/modeling/searches.py" + - name: Multi-start batch_size check, names from the manifest + run: > + python PyAutoHands/autohands/check_search_memory.py + --root "${{ github.event.repository.name }}" + --manifest search_manifest.json + staleness: name: Catalogue staleness runs-on: ubuntu-latest diff --git a/autohands/check_search_memory.py b/autohands/check_search_memory.py index 74eb72f7..9271416e 100644 --- a/autohands/check_search_memory.py +++ b/autohands/check_search_memory.py @@ -19,8 +19,16 @@ point is that the memory decision is typed out where a reviewer sees it, rather than arrived at by defaulting. +Which names are guarded: with ``--manifest`` (a saved +``python -m autofit search-manifest --json`` dump) the guarded set is exactly +the manifest's ``MultiStart*`` searches, read from the installed release rather +than hard-coded here. Without it -- the stdlib-only CI leg, which must not depend +on installing the science stack -- the ``MultiStart`` prefix rule below stands +in, which is a superset of every manifest to date. + Usage: python check_search_memory.py --root [--scripts-dir scripts] + [--manifest manifest.json] Exit codes: 0 no unbatched multi-start searches found @@ -30,13 +38,15 @@ import argparse import ast +import json import sys from pathlib import Path -from typing import List, NamedTuple +from typing import FrozenSet, List, NamedTuple, Optional -# Any search whose name starts with this is a gradient multi-start search and -# carries the batch_size knob. Matched by prefix rather than an enumerated list -# so a new MultiStart* sibling in PyAutoFit is covered the day it lands. +# Fallback when no manifest is given: any search whose name starts with this is +# a gradient multi-start search and carries the batch_size knob. Matched by +# prefix rather than an enumerated list so a new MultiStart* sibling in +# PyAutoFit is covered the day it lands. SEARCH_PREFIX = "MultiStart" # Not a search: the convergence-criteria object shares the prefix but takes no @@ -60,9 +70,25 @@ def _called_name(node: ast.Call): return None -def findings_in_source(source: str, path: Path) -> List[Finding]: +def guarded_names(manifest: dict) -> FrozenSet[str]: + """The manifest's multi-start searches -- the names carrying ``batch_size``.""" + return frozenset( + s["name"] for s in manifest["searches"] if s["name"].startswith(SEARCH_PREFIX) + ) + + +def _guarded(name: str, names: Optional[FrozenSet[str]]) -> bool: + if names is not None: + return name in names + return name.startswith(SEARCH_PREFIX) and name not in NOT_A_SEARCH + + +def findings_in_source( + source: str, path: Path, names: Optional[FrozenSet[str]] = None +) -> List[Finding]: """Every multi-start search construction in ``source`` with no explicit - ``batch_size``. A syntax error yields nothing — this check is not a linter + ``batch_size``. ``names`` (from :func:`guarded_names`) replaces the prefix + rule when given. A syntax error yields nothing — this check is not a linter and must not be the thing that reports a broken file.""" try: tree = ast.parse(source) @@ -76,7 +102,7 @@ def findings_in_source(source: str, path: Path) -> List[Finding]: name = _called_name(node) if name is None: continue - if not name.startswith(SEARCH_PREFIX) or name in NOT_A_SEARCH: + if not _guarded(name, names): continue # **kwargs may carry batch_size; a splat keyword has arg=None. Treat # that as explicit rather than guess at the dict's contents. @@ -86,7 +112,9 @@ def findings_in_source(source: str, path: Path) -> List[Finding]: return found -def check_root(root: Path, scripts_dir: str = "scripts") -> List[Finding]: +def check_root( + root: Path, scripts_dir: str = "scripts", names: Optional[FrozenSet[str]] = None +) -> List[Finding]: scripts = root / scripts_dir if not scripts.is_dir(): raise FileNotFoundError(f"scripts directory not found: {scripts}") @@ -94,7 +122,9 @@ def check_root(root: Path, scripts_dir: str = "scripts") -> List[Finding]: found = [] for file in sorted(scripts.rglob("*.py")): found.extend( - findings_in_source(file.read_text(encoding="utf-8", errors="replace"), file) + findings_in_source( + file.read_text(encoding="utf-8", errors="replace"), file, names + ) ) return found @@ -107,6 +137,10 @@ def main(argv=None) -> int: default="scripts", help="scripts directory relative to root (default: scripts)", ) + parser.add_argument( + "--manifest", + help="search-manifest --json dump; guards exactly its MultiStart* searches", + ) args = parser.parse_args(argv) root = Path(args.root) @@ -114,8 +148,16 @@ def main(argv=None) -> int: print(f"error: root not found: {root}", file=sys.stderr) return 2 + names = None + if args.manifest: + try: + names = guarded_names(json.loads(Path(args.manifest).read_text(encoding="utf-8"))) + except (OSError, ValueError, KeyError) as e: + print(f"error: unreadable manifest {args.manifest}: {e}", file=sys.stderr) + return 2 + try: - found = check_root(root, args.scripts_dir) + found = check_root(root, args.scripts_dir, names) except FileNotFoundError as e: print(f"error: {e}", file=sys.stderr) return 2 diff --git a/autohands/check_search_roster.py b/autohands/check_search_roster.py new file mode 100644 index 00000000..9f27eaa9 --- /dev/null +++ b/autohands/check_search_roster.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Fail when a search roster, anchor or named search drifts from the manifest. + +Three checks against the search manifest of the installed ``autofit`` (or a +saved ``--manifest`` dump), runnable locally or in CI: + + (a) Roster blocks (HARD FAIL on a changed body) + Every ``search-roster`` block under ``--root`` (or in ``--files``) is + re-rendered and compared. A different body is drift. An identical body + under an older/newer version stamp is reported only, unless + ``--strict-version``. + + (b) Anchors (HARD FAIL on a missing target), with ``--workspace-root DIR`` + Each search's ``example`` / ``integration_test`` anchor + (``:[#
]``) must resolve in ``DIR/``; a + ``#Section`` must appear as ``__Section__``. Repos not checked out under + DIR are listed as skipped. + + (c) Named searches (HARD FAIL), with ``--names-in GLOB`` (repeatable) + Every ``<...search...> = af.(...)`` in the matching scripts must + name a search the manifest lists. Globs are relative to ``--root``; a + glob matching nothing is fine (one invocation serves every workspace). + +``--against-source PATH`` additionally prints how the manifest of the source +checkout at PATH differs from the installed one. It is a report, never a +failure: the installed release is the source of truth. + +Usage: + python check_search_roster.py --root [--files F ...] + [--manifest manifest.json] [--strict-version] + [--workspace-root DIR] [--names-in GLOB ...] [--against-source PATH] + +Exit codes: 0 clean · 1 drift (details on stdout) · 2 usage / manifest error. +""" + +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import search_roster # noqa: E402 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", default=".", help="checkout to check (default: cwd)") + parser.add_argument("--files", nargs="+", help="explicit files (relative to --root)") + parser.add_argument("--manifest", help="saved search-manifest --json dump") + parser.add_argument("--strict-version", action="store_true", + help="a stale version stamp fails even when the roster is identical") + parser.add_argument("--workspace-root", help="directory holding / checkouts for anchors") + parser.add_argument("--names-in", action="append", default=[], metavar="GLOB", + help="scripts whose constructed searches must be in the manifest") + parser.add_argument("--against-source", metavar="PATH", + help="report (never fail on) source-checkout manifest differences") + args = parser.parse_args(argv) + + root = Path(args.root) + if not root.is_dir(): + print(f"error: root not found: {root}", file=sys.stderr) + return 2 + try: + manifest = search_roster.load_manifest(args.manifest) + paths = ( + [root / f for f in args.files] if args.files else search_roster.discover_files(root) + ) + drift = search_roster.check_files(paths, manifest, root) + except (search_roster.RosterError, OSError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + failed = False + print(f"Search roster check against {search_roster.stamp(manifest)}") + + print(f"\n(a) roster blocks: {len(paths)} file(s)") + for d in drift: + fatal = d.kind in ("body", "unstamped") or args.strict_version + failed |= fatal + print(f" {'FAIL' if fatal else 'note'} {d.path}:{d.line}: {d.detail}") + if not drift: + print(" all blocks regenerate byte-identically") + + if args.workspace_root: + results = search_roster.resolve_anchors(manifest, Path(args.workspace_root)) + ok = sum(r.status == "ok" for r in results) + print(f"\n(b) anchors: {ok} resolved") + for r in results: + if r.status == "missing": + failed = True + print(f" FAIL {r.search}.{r.field} {r.anchor}: {r.detail}") + skipped = sorted({r.detail for r in results if r.status == "skipped"}) + for detail in skipped: + print(f" skip {detail}") + + if args.names_in: + scripts = sorted({p for g in args.names_in for p in root.glob(g) if p.is_file()}) + unknown = search_roster.unknown_named_searches(scripts, manifest, root) + print(f"\n(c) named searches: {len(scripts)} script(s)") + for where, line, name in unknown: + failed = True + print(f" FAIL {where}:{line}: af.{name} is not in the search manifest") + + if args.against_source: + try: + source = search_roster.load_manifest(source=args.against_source) + except search_roster.RosterError as exc: + print(f"\n(report) source manifest unavailable: {exc}") + else: + diff = search_roster.manifest_difference(manifest, source) + print(f"\n(report) source {source['autofit_version']} vs installed " + f"{manifest['autofit_version']}: {len(diff)} difference(s)") + for line in diff: + print(f" {line}") + + if failed: + print("\nRegenerate with regenerate_search_roster.py (blocks) or fix the " + "named script / anchor, then commit.") + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/autohands/navigator.py b/autohands/navigator.py index 3ad059c0..d4fb3e1d 100644 --- a/autohands/navigator.py +++ b/autohands/navigator.py @@ -18,8 +18,10 @@ - ``llms-full.txt`` — an expanded, human-readable ``llms.txt`` form. - ``workspace_index.json`` — the same records as a machine-readable array. -The curated ``llms.txt`` is never read or written here; that file is hand -maintained routing and is intentionally left alone. +The curated ``llms.txt`` is hand-maintained routing and is left alone, with one +exception: :func:`write_roster` (``regenerate_navigator.py --roster``) rewrites +the fenced search-roster block inside it -- and only that block -- from the +installed ``autofit`` search manifest (see ``search_roster.py``). Output is **deterministic**: scripts are sorted lexicographically by their repo-relative path, groups follow a fixed order, JSON is serialised with sorted @@ -368,3 +370,34 @@ def write_catalogue(workspace_path: Path, project: Optional[str] = None) -> List f"({len(records)} scripts)" ) return [llms_full_path, index_path] + + +def write_roster(workspace_path: Path, manifest_file: Optional[str] = None) -> List[Path]: + """ + Re-render the search-roster blocks in the workspace's curated ``llms.txt`` + and ``scripts/**/README.md`` files from the search manifest; returns the + files rewritten. Text outside the ``search-roster`` markers is untouched, and + a workspace with no block is a no-op. + """ + import search_roster + + workspace_path = Path(workspace_path) + candidates = [workspace_path / "llms.txt"] + scripts = workspace_path / "scripts" + if scripts.is_dir(): + candidates.extend(sorted(scripts.rglob("README.md"))) + paths = [ + p + for p in candidates + if p.is_file() and "`` / ```` +block in the given files (default: every .md / .txt file under ``--root`` +holding one) and rewrites only the text between the markers, stamped with the +manifest schema and the ``autofit`` version that rendered it. See +``search_roster.py`` for the block format. + +Usage: + python regenerate_search_roster.py --root [--files F ...] + [--manifest manifest.json] + +``--manifest`` reads a saved ``python -m autofit search-manifest --json`` dump; +without it the manifest comes from the ``autofit`` importable by this +interpreter (the installed release in CI). + +Exit codes: 0 done (changed or not) · 2 usage / manifest / block error. +""" + +import argparse +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import search_roster # noqa: E402 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--root", default=".", help="checkout to scan (default: cwd)") + parser.add_argument("--files", nargs="+", help="explicit files (relative to --root)") + parser.add_argument("--manifest", help="saved search-manifest --json dump") + args = parser.parse_args(argv) + + root = Path(args.root) + try: + manifest = search_roster.load_manifest(args.manifest) + paths = ( + [root / f for f in args.files] if args.files else search_roster.discover_files(root) + ) + changed = search_roster.regenerate_files(paths, manifest) + except (search_roster.RosterError, OSError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + + print( + f"Search roster: {len(paths)} file(s) with blocks, {len(changed)} rewritten " + f"({search_roster.stamp(manifest)})" + ) + for path in changed: + print(f" rewrote {path}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/autohands/search_roster.py b/autohands/search_roster.py new file mode 100644 index 00000000..d6414045 --- /dev/null +++ b/autohands/search_roster.py @@ -0,0 +1,459 @@ +""" +Search rosters generated from the versioned ``autofit`` search manifest. + +Every consumer that lists the non-linear searches -- a workspace's curated +``llms.txt``, a scripts README, an assistant's skill or wiki page -- used to +carry a hand-written roster, and several had gone stale (searches removed from +the library still listed, new ones missing). This module renders those rosters +from the one source of truth instead: the ``search-manifest@1`` document the +*installed* ``autofit`` prints with:: + + python -m autofit search-manifest --json + +A consumer opts in by placing a fenced block in its file:: + + + + ...generated... + + +Only the text between the markers is ever written; prose outside them is left +untouched. The begin marker carries the rendering options, so no per-consumer +configuration lives here: + +``style=list`` one bullet per search family (the default) +``style=table`` one Markdown table row per search, with its capabilities +``indent=N`` prefix every rendered line with N spaces (nested lists) +``link=`` render example anchors that point into ```` as + relative Markdown links (a workspace linking its own scripts); + anchors into any other repo render as ``repo:path`` citations + +The second line inside the block is the stamp: the manifest schema and the +``autofit`` version that rendered it. ``--check`` re-renders against the +installed ``autofit``; a changed roster body is drift (failure), while a body +that is identical under a newer stamp is only reported, so an ``autofit`` +release that adds no search does not redden every consumer. ``strict_version`` +turns the stamp difference into a failure too. + +Two further checks ride on the same manifest: + +* :func:`resolve_anchors` -- each search's ``example`` and ``integration_test`` + anchor (``:[#
]``) must exist in the named checkout under + a workspace root, and a ``#Section`` must appear as a ``__Section__`` heading. + Repos not checked out are reported as skipped, never failed. +* :func:`named_searches` -- every search a script constructs as + ``search = af.(...)`` must be in the manifest (the hand-written search + guides keep their prose; only the names they use are checked). + +Stdlib only, and nothing here imports ``autofit``: the manifest is read from a +JSON file or from a subprocess, so the module is testable without the science +stack. +""" + +import ast +import json +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import Dict, Iterable, List, NamedTuple, Optional, Tuple + +SCHEMA = "search-manifest@1" + +BEGIN_RE = re.compile(r"^(?P[ \t]*)\s*$") +END_RE = re.compile(r"^[ \t]*\s*$") +STAMP_RE = re.compile( + r"^[ \t]*\s*$" +) + +STYLES = ("list", "table") + +# Files scanned for roster blocks when no explicit file list is given. Rosters +# live in prose and catalogue files, never in scripts. +SCAN_SUFFIXES = (".md", ".txt") +SKIP_DIRS = {".git", "notebooks", "output", "dataset", "node_modules", "__pycache__"} + + +class RosterError(Exception): + """A malformed block or an unreadable manifest.""" + + +# --------------------------------------------------------------------------- +# Manifest loading +# --------------------------------------------------------------------------- + + +def load_manifest(manifest_file: Optional[str] = None, source: Optional[str] = None) -> dict: + """The search manifest. + + ``manifest_file`` reads a saved ``--json`` dump. Otherwise the manifest is + printed by ``python -m autofit search-manifest --json`` in a subprocess of + the current interpreter -- the installed ``autofit``, or, with ``source``, + the checkout at that path put first on ``PYTHONPATH``. + """ + if manifest_file: + text = Path(manifest_file).read_text(encoding="utf-8") + else: + env = dict(os.environ) + if source: + env["PYTHONPATH"] = str(Path(source).resolve()) + ( + os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "" + ) + proc = subprocess.run( + [sys.executable, "-m", "autofit", "search-manifest", "--json"], + capture_output=True, + text=True, + env=env, + ) + if proc.returncode != 0: + tail = "\n".join(proc.stderr.strip().splitlines()[-5:]) + raise RosterError( + f"`python -m autofit search-manifest --json` failed " + f"(exit {proc.returncode}):\n{tail}" + ) + text = proc.stdout + try: + manifest = json.loads(text) + except json.JSONDecodeError as exc: + raise RosterError(f"search manifest is not JSON: {exc}") from exc + if manifest.get("schema") != SCHEMA: + raise RosterError( + f"unsupported manifest schema {manifest.get('schema')!r} (expected {SCHEMA})" + ) + return manifest + + +def stamp(manifest: dict) -> str: + return f"" + + +def search_names(manifest: dict) -> List[str]: + return [s["name"] for s in manifest["searches"]] + + +# --------------------------------------------------------------------------- +# Rendering +# --------------------------------------------------------------------------- + + +def parse_anchor(anchor: str) -> Tuple[str, str, Optional[str]]: + """``repo:path#Section`` -> (repo, path, section or None).""" + repo, _, rest = anchor.partition(":") + path, _, section = rest.partition("#") + return repo, path, (section or None) + + +def parse_options(opts: str) -> Dict[str, str]: + out = {} + for token in opts.split(): + key, sep, value = token.partition("=") + if not sep: + raise RosterError(f"roster option {token!r} is not key=value") + out[key] = value + style = out.setdefault("style", "list") + if style not in STYLES: + raise RosterError(f"unknown roster style {style!r} (choose from {', '.join(STYLES)})") + if "indent" in out and not out["indent"].isdigit(): + raise RosterError(f"roster indent {out['indent']!r} is not a number") + return out + + +def _example_ref(anchor: Optional[str], link: Optional[str]) -> Optional[str]: + if not anchor: + return None + repo, path, _ = parse_anchor(anchor) + if link and repo == link: + return f"[{path}]({path})" + return f"`{repo}:{path}`" + + +def _families(manifest: dict) -> List[Tuple[str, str, List[dict]]]: + """(key, label, searches) per family, in manifest order.""" + out = [] + for key, label in manifest["families"].items(): + members = [s for s in manifest["searches"] if s["family"] == key] + if members: + out.append((key, label, members)) + return out + + +def _render_list(manifest: dict, link: Optional[str]) -> List[str]: + lines = [] + for key, label, members in _families(manifest): + names = [] + for s in members: + name = f"`af.{s['name']}`" + if s["capabilities"].get("status") == "experimental": + name += " (experimental)" + names.append(name) + line = f"- **{label}** (`{key}`): " + ", ".join(names) + examples = [] + for s in members: + ref = _example_ref((s.get("example") or "").partition("#")[0] or None, link) + if ref and ref not in examples: + examples.append(ref) + if examples: + line += " — example: " + ", ".join(examples) + lines.append(line) + return lines + + +def _yes_no(value) -> str: + return "yes" if value else "no" + + +def _render_table(manifest: dict, link: Optional[str]) -> List[str]: + lines = [ + "| Search | Family | Status | JAX | Gradient | Evidence | Posterior | Example |", + "|---|---|---|---|---|---|---|---|", + ] + for key, _label, members in _families(manifest): + for s in members: + c = s["capabilities"] + ref = _example_ref((s.get("example") or "").partition("#")[0] or None, link) + lines.append( + f"| `af.{s['name']}` | {key} | {c.get('status', '')} | " + f"{c.get('jax_use', '')} | {c.get('gradient', '')} | " + f"{_yes_no(c.get('produces_evidence'))} | {c.get('posterior_kind', '')} | " + f"{ref or '—'} |" + ) + return lines + + +def render_body(manifest: dict, options: Dict[str, str]) -> List[str]: + """The generated lines between the stamp and the end marker.""" + link = options.get("link") + if options["style"] == "table": + lines = _render_table(manifest, link) + else: + lines = _render_list(manifest, link) + pad = " " * int(options.get("indent", "0")) + return [pad + line if line else line for line in lines] + + +# --------------------------------------------------------------------------- +# Blocks in a file +# --------------------------------------------------------------------------- + + +class Block(NamedTuple): + begin: int # index of the begin-marker line + end: int # index of the end-marker line + options: Dict[str, str] + lead: str # whitespace before the begin marker, reused for stamp / end + stamp_version: Optional[str] + body: List[str] # existing generated lines (after the stamp) + + +def find_blocks(lines: List[str], where: str = "") -> List[Block]: + blocks = [] + i = 0 + while i < len(lines): + m = BEGIN_RE.match(lines[i]) + if not m: + if END_RE.match(lines[i]): + raise RosterError(f"{where}:{i + 1}: search-roster:end without a begin") + i += 1 + continue + options = parse_options(m.group("opts")) + j = i + 1 + while j < len(lines) and not END_RE.match(lines[j]): + if BEGIN_RE.match(lines[j]): + raise RosterError(f"{where}:{j + 1}: nested search-roster:begin") + j += 1 + if j == len(lines): + raise RosterError(f"{where}:{i + 1}: search-roster:begin without an end") + inner = lines[i + 1 : j] + version = None + body = inner + if inner: + sm = STAMP_RE.match(inner[0]) + if sm: + version = sm.group("version") + body = inner[1:] + blocks.append(Block(i, j, options, m.group("lead"), version, list(body))) + i = j + 1 + return blocks + + +def regenerate_text(text: str, manifest: dict, where: str = "") -> Tuple[str, int]: + """``text`` with every roster block re-rendered; (new text, block count).""" + lines = text.split("\n") + blocks = find_blocks(lines, where) + for block in reversed(blocks): + new_inner = [block.lead + stamp(manifest)] + render_body(manifest, block.options) + lines[block.begin + 1 : block.end] = new_inner + return "\n".join(lines), len(blocks) + + +class Drift(NamedTuple): + path: str + line: int + kind: str # "body" | "stamp" | "unstamped" + detail: str + + +def check_text(text: str, manifest: dict, where: str = "") -> List[Drift]: + lines = text.split("\n") + out = [] + installed = manifest["autofit_version"] + for block in find_blocks(lines, where): + expected = render_body(manifest, block.options) + if block.body != expected: + out.append( + Drift(where, block.begin + 1, "body", + "roster differs from the installed manifest — regenerate") + ) + elif block.stamp_version is None: + out.append(Drift(where, block.begin + 1, "unstamped", "block has no manifest stamp")) + elif block.stamp_version != installed: + out.append( + Drift(where, block.begin + 1, "stamp", + f"stamped autofit {block.stamp_version}, installed {installed}; " + f"roster identical") + ) + return out + + +def discover_files(root: Path) -> List[Path]: + """Every .md / .txt file under ``root`` that contains a roster block.""" + found = [] + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")) + for name in sorted(filenames): + if not name.endswith(SCAN_SUFFIXES): + continue + path = Path(dirpath) / name + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + if " ... +) under --root from the search manifest printed by the +installed autofit (python -m autofit search-manifest --json), stamped +. Only text between the markers is +written. --manifest reads a saved dump instead of importing autofit. + +Arguments: + --root Checkout to scan for .md/.txt files holding a block (default: cwd) + --files Explicit files, relative to --root + --manifest Saved search-manifest --json dump +EOF +} +cmd_regenerate_search_roster() { + _python_in_autohands regenerate_search_roster.py "$@" +} + +help_check_search_roster() { + cat <<'EOF' +autohands check_search_roster [--root DIR] [--files F ...] [--manifest FILE] + [--strict-version] [--workspace-root DIR] + [--names-in GLOB ...] [--against-source PATH] + +Guard against drift from the installed autofit search manifest: + (a) every search-roster block regenerates byte-identically (a changed body + fails; an identical body under another version stamp is only noted, + unless --strict-version); + (b) with --workspace-root, each manifest example / integration_test anchor + resolves in DIR/ (repos not checked out are skipped); + (c) with --names-in, every `search = af.(...)` in those scripts names a + manifest search. +--against-source PATH reports how a source checkout's manifest differs from the +installed one; it never fails. + +Runs in CI from .github/workflows/navigator_check.yml (search_roster job) and +from the assistants' wiki-currency workflows. +EOF +} +cmd_check_search_roster() { + _python_in_autohands check_search_roster.py "$@" +} + help_check_search_memory() { cat <<'EOF' -autohands check_search_memory --root DIR [--scripts-dir DIR] +autohands check_search_memory --root DIR [--scripts-dir DIR] [--manifest FILE] Guard: every af.MultiStart* search in a workspace's scripts sets batch_size explicitly. The default (batch_size=None) vmaps all 48 starts at once, which @@ -395,6 +449,8 @@ defaulting. Arguments: --root Workspace root (required) --scripts-dir Scripts directory relative to root (default: scripts) + --manifest search-manifest --json dump: guard exactly its MultiStart* + searches instead of the MultiStart prefix rule Runs in CI from .github/workflows/navigator_check.yml. EOF diff --git a/tests/test_check_search_memory.py b/tests/test_check_search_memory.py index b2667fc1..0b9605a9 100644 --- a/tests/test_check_search_memory.py +++ b/tests/test_check_search_memory.py @@ -142,3 +142,37 @@ def test_main_exit_codes(tmp_path, capsys): assert main(["--root", str(clean)]) == 0 assert main(["--root", str(tmp_path / "does_not_exist")]) == 2 + + +# --- names read from the search manifest ------------------------------------- + + +def _manifest(*names): + return {"searches": [{"name": n} for n in names]} + + +def test_guarded_names_are_the_manifest_multi_starts(): + manifest = _manifest("Nautilus", "MultiStartAdam", "MultiStartProdigy", "LBFGS") + assert check_search_memory.guarded_names(manifest) == { + "MultiStartAdam", + "MultiStartProdigy", + } + + +def test_manifest_names_replace_the_prefix_rule(): + names = check_search_memory.guarded_names(_manifest("MultiStartProdigy")) + source = "a = af.MultiStartProdigy()\nb = af.MultiStartNotInTheManifest()\n" + found = findings_in_source(source, Path("x.py"), names) + assert [f.search for f in found] == ["MultiStartProdigy"] + + +def test_main_reads_the_manifest_file(tmp_path, capsys): + import json + + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps(_manifest("MultiStartAdam"))) + ws = _workspace(tmp_path, **{"x.py": "s = af.MultiStartProdigy()\n"}) + # Prodigy is not in this manifest, so only the prefix fallback flags it. + assert main(["--root", str(ws), "--manifest", str(manifest)]) == 0 + assert main(["--root", str(ws)]) == 1 + assert main(["--root", str(ws), "--manifest", str(tmp_path / "nope.json")]) == 2 diff --git a/tests/test_search_roster.py b/tests/test_search_roster.py new file mode 100644 index 00000000..cee4ea5a --- /dev/null +++ b/tests/test_search_roster.py @@ -0,0 +1,241 @@ +"""Tests for autohands/search_roster.py and its two CLI entrypoints. + +Hermetic: a small fabricated ``search-manifest@1`` document stands in for +``python -m autofit search-manifest --json``, so nothing here imports the +science stack. Repo names in anchors are fake on purpose. +""" + +import json +import sys +from pathlib import Path + +import pytest + +AUTOHANDS_DIR = Path(__file__).parent.parent / "autohands" +sys.path.insert(0, str(AUTOHANDS_DIR)) + +import check_search_roster # noqa: E402 +import regenerate_search_roster # noqa: E402 +import search_roster # noqa: E402 + + +def _search(name, family, status="stable", example=None, jax="none", evidence=False): + return { + "name": name, + "class_path": f"pkg.{name}", + "family": family, + "lazy": False, + "requires": [], + "example": example, + "integration_test": f"ws_test:scripts/searches/{name}.py", + "capabilities": { + "jax_use": jax, + "gradient": "none", + "produces_evidence": evidence, + "posterior_kind": "weighted" if evidence else "point", + "status": status, + }, + } + + +def _manifest(version="1.0.0", extra=()): + return { + "schema": "search-manifest@1", + "autofit_version": version, + "families": {"nest": "Nested sampling", "mle": "Maximum likelihood"}, + "capability_attributes": [], + "searches": [ + _search("Nautilus", "nest", example="ws:scripts/searches/nest.py#Search: Nautilus", + evidence=True), + _search("NSS", "nest", status="experimental", jax="required", evidence=True), + _search("LBFGS", "mle", example="ws:scripts/searches/mle.py#Search: LBFGS"), + *extra, + ], + } + + +BLOCK = "intro\n\n\noutro\n" + + +def test_list_block_renders_families_in_manifest_order(): + text, n = search_roster.regenerate_text(BLOCK, _manifest()) + assert n == 1 + lines = text.split("\n") + assert lines[0] == "intro" and lines[-2] == "outro" + assert lines[2] == "" + assert lines[3] == ( + "- **Nested sampling** (`nest`): `af.Nautilus`, `af.NSS` (experimental)" + " — example: `ws:scripts/searches/nest.py`" + ) + assert lines[4].startswith("- **Maximum likelihood** (`mle`): `af.LBFGS`") + + +def test_link_option_makes_own_repo_examples_relative_links(): + block = BLOCK.replace("style=list", "style=list link=ws indent=2") + text, _ = search_roster.regenerate_text(block, _manifest()) + assert " - **Nested sampling** (`nest`)" in text + assert "[scripts/searches/nest.py](scripts/searches/nest.py)" in text + + +def test_table_block_has_one_row_per_search(): + block = BLOCK.replace("style=list", "style=table") + text, _ = search_roster.regenerate_text(block, _manifest()) + rows = [l for l in text.split("\n") if l.startswith("| `af.")] + assert [r.split("|")[1].strip() for r in rows] == ["`af.Nautilus`", "`af.NSS`", "`af.LBFGS`"] + assert "| `af.NSS` | nest | experimental | required | none | yes | weighted | — |" in rows + + +def test_regeneration_is_idempotent_and_leaves_prose_alone(): + once, _ = search_roster.regenerate_text(BLOCK, _manifest()) + twice, _ = search_roster.regenerate_text(once, _manifest()) + assert once == twice + assert once.startswith("intro\n") and once.endswith("outro\n") + + +def test_check_is_clean_after_regeneration(): + text, _ = search_roster.regenerate_text(BLOCK, _manifest()) + assert search_roster.check_text(text, _manifest()) == [] + + +def test_check_flags_a_changed_roster_as_body_drift(): + text, _ = search_roster.regenerate_text(BLOCK, _manifest()) + grown = _manifest(extra=[_search("Drawer", "mle")]) + drift = search_roster.check_text(text, grown) + assert [d.kind for d in drift] == ["body"] + + +def test_check_only_notes_a_new_version_with_the_same_roster(): + text, _ = search_roster.regenerate_text(BLOCK, _manifest("1.0.0")) + drift = search_roster.check_text(text, _manifest("1.1.0")) + assert [d.kind for d in drift] == ["stamp"] + + +def test_unstamped_block_is_reported(): + text, _ = search_roster.regenerate_text(BLOCK, _manifest()) + lines = [l for l in text.split("\n") if "search-manifest@1" not in l] + drift = search_roster.check_text("\n".join(lines), _manifest()) + assert [d.kind for d in drift] == ["unstamped"] + + +@pytest.mark.parametrize( + "text", + [ + "\nno end\n", + "\n", + "\n\n", + "\n\n\n", + ], +) +def test_malformed_blocks_raise(text): + with pytest.raises(search_roster.RosterError): + search_roster.regenerate_text(text, _manifest()) + + +def test_load_manifest_rejects_another_schema(tmp_path): + f = tmp_path / "m.json" + f.write_text(json.dumps(dict(_manifest(), schema="search-manifest@9"))) + with pytest.raises(search_roster.RosterError): + search_roster.load_manifest(str(f)) + + +def test_anchors_resolve_skip_and_fail(tmp_path): + ws = tmp_path / "ws" / "scripts" / "searches" + ws.mkdir(parents=True) + (ws / "nest.py").write_text('"""\n__Search: Nautilus__\n"""\n') + (ws / "mle.py").write_text('"""\n__Search: Something Else__\n"""\n') + results = search_roster.resolve_anchors(_manifest(), tmp_path) + by = {(r.search, r.field): r.status for r in results} + assert by[("Nautilus", "example")] == "ok" + assert by[("LBFGS", "example")] == "missing" # section absent + assert by[("Nautilus", "integration_test")] == "skipped" # ws_test not checked out + + +def test_named_searches_only_reads_search_assignments(): + source = ( + "search = af.Nautilus(n_live=100)\n" + "search_mle = af.Gone()\n" + "model = af.Model(Thing)\n" + '"""prose naming af.UltraNest"""\n' + ) + assert search_roster.named_searches(source) == [(1, "Nautilus"), (2, "Gone")] + + +def test_manifest_difference_reports_added_and_changed(): + source = _manifest("2.0.0", extra=[_search("Drawer", "mle")]) + source["searches"][1]["capabilities"]["status"] = "stable" + diff = search_roster.manifest_difference(_manifest(), source) + assert any(l.startswith("+ Drawer") for l in diff) + assert any(l.startswith("~ NSS") for l in diff) + + +# --- the CLIs ---------------------------------------------------------------- + + +def _tree(tmp_path): + root = tmp_path / "ws" + (root / "scripts" / "searches").mkdir(parents=True) + (root / "llms.txt").write_text(BLOCK) + (root / "notes.md").write_text("no block here\n") + (root / "scripts" / "searches" / "nest.py").write_text( + '"""\n__Search: Nautilus__\n"""\nsearch = af.Nautilus()\n' + ) + manifest = tmp_path / "manifest.json" + manifest.write_text(json.dumps(_manifest())) + return root, manifest + + +def test_cli_regenerate_then_check(tmp_path, capsys): + root, manifest = _tree(tmp_path) + args = ["--root", str(root), "--manifest", str(manifest)] + assert check_search_roster.main(args) == 1 # unrendered block = body drift + assert regenerate_search_roster.main(args) == 0 + assert check_search_roster.main(args + ["--names-in", "scripts/**/*.py"]) == 0 + out = capsys.readouterr().out + assert "regenerate byte-identically" in out + + +def test_cli_stamp_is_a_note_unless_strict(tmp_path): + root, manifest = _tree(tmp_path) + regenerate_search_roster.main(["--root", str(root), "--manifest", str(manifest)]) + newer = tmp_path / "newer.json" + newer.write_text(json.dumps(_manifest("9.9.9"))) + args = ["--root", str(root), "--manifest", str(newer)] + assert check_search_roster.main(args) == 0 + assert check_search_roster.main(args + ["--strict-version"]) == 1 + + +def test_cli_unknown_named_search_fails(tmp_path, capsys): + root, manifest = _tree(tmp_path) + regenerate_search_roster.main(["--root", str(root), "--manifest", str(manifest)]) + (root / "scripts" / "searches" / "old.py").write_text("search = af.UltraNest()\n") + args = ["--root", str(root), "--manifest", str(manifest), "--names-in", "scripts/**/*.py"] + assert check_search_roster.main(args) == 1 + assert "af.UltraNest is not in the search manifest" in capsys.readouterr().out + + +def test_cli_missing_anchor_fails(tmp_path): + root, manifest = _tree(tmp_path) + regenerate_search_roster.main(["--root", str(root), "--manifest", str(manifest)]) + args = ["--root", str(root), "--manifest", str(manifest), "--workspace-root", str(tmp_path)] + assert check_search_roster.main(args) == 1 # LBFGS example file absent + + +def test_cli_usage_errors(tmp_path): + assert check_search_roster.main(["--root", str(tmp_path / "absent")]) == 2 + root, _ = _tree(tmp_path) + bad = tmp_path / "bad.json" + bad.write_text("not json") + assert check_search_roster.main(["--root", str(root), "--manifest", str(bad)]) == 2 + + +def test_navigator_roster_mode_rewrites_only_the_block(tmp_path): + root, manifest = _tree(tmp_path) + sys.argv = ["generate.py", "autofit"] + import navigator + + changed = navigator.write_roster(root, str(manifest)) + assert changed == [root / "llms.txt"] + text = (root / "llms.txt").read_text() + assert text.startswith("intro\n") and text.endswith("outro\n") + assert "" in text + assert navigator.write_roster(root, str(manifest)) == [] # idempotent From 4500743cafc18db02e281245c78c0f1ba53b6faa Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 15 Oct 2026 14:26:08 +0100 Subject: [PATCH 2/4] fix(hands): roster discovery skips nested git checkouts An assistant's wiki-currency job clones source repos under sources/; those are other repositories, so --root . must not check (or rewrite) their blocks. Co-Authored-By: Claude Opus 5.5 --- autohands/search_roster.py | 15 +++++++++++++-- tests/test_search_roster.py | 8 ++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/autohands/search_roster.py b/autohands/search_roster.py index d6414045..65c7f803 100644 --- a/autohands/search_roster.py +++ b/autohands/search_roster.py @@ -317,10 +317,21 @@ def check_text(text: str, manifest: dict, where: str = "") -> List[Drift]: def discover_files(root: Path) -> List[Path]: - """Every .md / .txt file under ``root`` that contains a roster block.""" + """Every .md / .txt file under ``root`` that contains a roster block. + + Nested git checkouts (a directory holding its own ``.git``, e.g. the source + clones an assistant's CI places under ``sources/``) are other repositories + and are not descended into. + """ found = [] for dirpath, dirnames, filenames in os.walk(root): - dirnames[:] = sorted(d for d in dirnames if d not in SKIP_DIRS and not d.startswith(".")) + dirnames[:] = sorted( + d + for d in dirnames + if d not in SKIP_DIRS + and not d.startswith(".") + and not (Path(dirpath) / d / ".git").exists() + ) for name in sorted(filenames): if not name.endswith(SCAN_SUFFIXES): continue diff --git a/tests/test_search_roster.py b/tests/test_search_roster.py index cee4ea5a..e262e2fe 100644 --- a/tests/test_search_roster.py +++ b/tests/test_search_roster.py @@ -239,3 +239,11 @@ def test_navigator_roster_mode_rewrites_only_the_block(tmp_path): assert text.startswith("intro\n") and text.endswith("outro\n") assert "" in text assert navigator.write_roster(root, str(manifest)) == [] # idempotent + + +def test_discovery_skips_nested_checkouts(tmp_path): + root, _ = _tree(tmp_path) + nested = root / "sources" / "other_repo" + (nested / ".git").mkdir(parents=True) + (nested / "llms.txt").write_text(BLOCK) + assert search_roster.discover_files(root) == [root / "llms.txt"] From e7202630156c7e00dc4b0dad0ae3f7105ed02eb9 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 15 Oct 2026 14:34:26 +0100 Subject: [PATCH 3/4] fix(hands): search roster review findings - installed mode drops PYTHONPATH from the manifest subprocess, so a dev shell with a source checkout on it cannot pass source main off as the installed release (hint printed on failure); --against-source keeps it - CRLF files keep CRLF; markers inside code fences are documentation; unknown block options are rejected - link= targets are made relative to the file holding the block - named searches: target must be search / search_ (settings_search and grid_search are not searches); annotated, attribute and search= keyword forms are read - check_search_memory --manifest unites manifest names with the prefix rule - navigator imports search_roster package-relative first - navigator_check: caller repo from GITHUB_REPOSITORY, integration-test workspace branch-matched, regenerate hint in the job summary on drift Co-Authored-By: Claude Opus 5.5 --- .github/workflows/navigator_check.yml | 55 +++++---- autohands/check_search_memory.py | 19 ++-- autohands/navigator.py | 7 +- autohands/regenerate_search_roster.py | 2 +- autohands/search_roster.py | 157 ++++++++++++++++++++------ tests/test_check_search_memory.py | 9 +- tests/test_search_roster.py | 56 ++++++++- 7 files changed, 232 insertions(+), 73 deletions(-) diff --git a/.github/workflows/navigator_check.yml b/.github/workflows/navigator_check.yml index 2f432918..ece319e0 100644 --- a/.github/workflows/navigator_check.yml +++ b/.github/workflows/navigator_check.yml @@ -73,21 +73,26 @@ jobs: search_roster: # Search rosters, manifest anchors and named searches against the search # manifest of the INSTALLED autofit release (search-manifest@1) — the - # pinned version, never the library's main. The workspace is checked out + # released version, never the library's main. The workspace is checked out # under its own repository name so the manifest's `:` anchors # resolve against it; for the autofit workspace the integration-test - # workspace is checked out beside it so both anchor kinds resolve. Other - # projects' anchors point into repos not checked out here and are skipped. + # workspace is checked out beside it (branch-matched, so a paired PR that + # adds an integration script resolves). Other projects' anchors point into + # repos not checked out here and are skipped. name: Search roster vs installed manifest runs-on: ubuntu-latest env: NUMBA_CACHE_DIR: /tmp/numba_cache MPLCONFIGDIR: /tmp/matplotlib steps: + - name: Resolve the caller repository name + id: repo + shell: bash + run: echo "name=${GITHUB_REPOSITORY#*/}" >> "$GITHUB_OUTPUT" - name: Checkout workspace uses: actions/checkout@v4 with: - path: ${{ github.event.repository.name }} + path: ${{ steps.repo.outputs.name }} - name: Checkout PyAutoHands uses: actions/checkout@v4 with: @@ -104,16 +109,18 @@ jobs: uses: actions/setup-python@v5 with: python-version: '3.12' - - name: Match PyAutoHands branch + - name: Match PyAutoHands / integration-test branches shell: bash run: | BRANCH="${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" - pushd PyAutoHands - if [[ -n "$(git ls-remote --heads origin "$BRANCH")" ]]; then - git fetch origin "$BRANCH" - git checkout "$BRANCH" - fi - popd + for d in PyAutoHands autofit_workspace_test; do + [ -d "$d" ] || continue + if [[ -n "$(git -C "$d" ls-remote --heads origin "$BRANCH")" ]]; then + echo "Branch $BRANCH exists in $d — checking it out" + git -C "$d" fetch origin "$BRANCH" + git -C "$d" checkout FETCH_HEAD + fi + done - name: Install the released autofit run: pip install --quiet autofit - name: Dump the installed search manifest @@ -121,18 +128,26 @@ jobs: python -m autofit search-manifest --json > search_manifest.json python -c "import json; d = json.load(open('search_manifest.json')); print(d['schema'], 'autofit', d['autofit_version'], len(d['searches']), 'searches')" - name: Check roster blocks, anchors and named searches - run: > - python PyAutoHands/autohands/check_search_roster.py - --root "${{ github.event.repository.name }}" - --manifest search_manifest.json - --workspace-root . - --names-in "scripts/searches/*.py" - --names-in "scripts/cookbooks/search.py" - --names-in "scripts/guides/modeling/searches.py" + shell: bash + run: | + if ! python PyAutoHands/autohands/check_search_roster.py \ + --root "${{ steps.repo.outputs.name }}" \ + --manifest search_manifest.json \ + --workspace-root . \ + --names-in "scripts/searches/*.py" \ + --names-in "scripts/cookbooks/search.py" \ + --names-in "scripts/guides/modeling/searches.py"; then + { + echo "### Search roster drift" + echo "Regenerate against the installed release and commit:" + echo '`pip install -U autofit && python /autohands/regenerate_search_roster.py --root .`' + } >> "$GITHUB_STEP_SUMMARY" + exit 1 + fi - name: Multi-start batch_size check, names from the manifest run: > python PyAutoHands/autohands/check_search_memory.py - --root "${{ github.event.repository.name }}" + --root "${{ steps.repo.outputs.name }}" --manifest search_manifest.json staleness: diff --git a/autohands/check_search_memory.py b/autohands/check_search_memory.py index 9271416e..1fa97f51 100644 --- a/autohands/check_search_memory.py +++ b/autohands/check_search_memory.py @@ -20,11 +20,12 @@ than arrived at by defaulting. Which names are guarded: with ``--manifest`` (a saved -``python -m autofit search-manifest --json`` dump) the guarded set is exactly -the manifest's ``MultiStart*`` searches, read from the installed release rather -than hard-coded here. Without it -- the stdlib-only CI leg, which must not depend -on installing the science stack -- the ``MultiStart`` prefix rule below stands -in, which is a superset of every manifest to date. +``python -m autofit search-manifest --json`` dump) the guarded set is the +manifest's ``MultiStart*`` searches, read from the installed release rather +than hard-coded here, united with the ``MultiStart`` prefix rule below (so a +source-only sibling newer than the installed release keeps its guard). Without +it -- the stdlib-only CI leg, which must not depend on installing the science +stack -- the prefix rule alone applies. Usage: python check_search_memory.py --root [--scripts-dir scripts] @@ -78,8 +79,8 @@ def guarded_names(manifest: dict) -> FrozenSet[str]: def _guarded(name: str, names: Optional[FrozenSet[str]]) -> bool: - if names is not None: - return name in names + if names is not None and name in names: + return True return name.startswith(SEARCH_PREFIX) and name not in NOT_A_SEARCH @@ -87,8 +88,8 @@ def findings_in_source( source: str, path: Path, names: Optional[FrozenSet[str]] = None ) -> List[Finding]: """Every multi-start search construction in ``source`` with no explicit - ``batch_size``. ``names`` (from :func:`guarded_names`) replaces the prefix - rule when given. A syntax error yields nothing — this check is not a linter + ``batch_size``. ``names`` (from :func:`guarded_names`) is guarded in + addition to the prefix rule. A syntax error yields nothing — this check is not a linter and must not be the thing that reports a broken file.""" try: tree = ast.parse(source) diff --git a/autohands/navigator.py b/autohands/navigator.py index d4fb3e1d..88fb1098 100644 --- a/autohands/navigator.py +++ b/autohands/navigator.py @@ -379,7 +379,10 @@ def write_roster(workspace_path: Path, manifest_file: Optional[str] = None) -> L files rewritten. Text outside the ``search-roster`` markers is untouched, and a workspace with no block is a no-op. """ - import search_roster + try: + from . import search_roster + except ImportError: # run as a script with autohands/ on sys.path + import search_roster workspace_path = Path(workspace_path) candidates = [workspace_path / "llms.txt"] @@ -395,7 +398,7 @@ def write_roster(workspace_path: Path, manifest_file: Optional[str] = None) -> L print("Search roster: no search-roster block in llms.txt or scripts READMEs") return [] manifest = search_roster.load_manifest(manifest_file) - changed = search_roster.regenerate_files(paths, manifest) + changed = search_roster.regenerate_files(paths, manifest, workspace_path) print( f"Search roster: {len(paths)} file(s), {len(changed)} rewritten " f"({search_roster.stamp(manifest)})" diff --git a/autohands/regenerate_search_roster.py b/autohands/regenerate_search_roster.py index 056ba0a5..a47328d4 100644 --- a/autohands/regenerate_search_roster.py +++ b/autohands/regenerate_search_roster.py @@ -40,7 +40,7 @@ def main(argv=None) -> int: paths = ( [root / f for f in args.files] if args.files else search_roster.discover_files(root) ) - changed = search_roster.regenerate_files(paths, manifest) + changed = search_roster.regenerate_files(paths, manifest, root) except (search_roster.RosterError, OSError) as exc: print(f"error: {exc}", file=sys.stderr) return 2 diff --git a/autohands/search_roster.py b/autohands/search_roster.py index 65c7f803..a3828e8c 100644 --- a/autohands/search_roster.py +++ b/autohands/search_roster.py @@ -53,6 +53,7 @@ import ast import json import os +import posixpath import re import subprocess import sys @@ -68,6 +69,11 @@ ) STYLES = ("list", "table") +OPTION_KEYS = {"style", "indent", "link"} +FENCE_RE = re.compile(r"^[ \t]*(```|~~~)") +# A `<...>search` variable holds a search; `settings_search` / `grid_search` hold +# a settings object or a grid-search wrapper, so the name must START with search. +SEARCH_TARGET_RE = re.compile(r"search(_\w+)?") # Files scanned for roster blocks when no explicit file list is given. Rosters # live in prose and catalogue files, never in scripts. @@ -91,6 +97,10 @@ def load_manifest(manifest_file: Optional[str] = None, source: Optional[str] = N printed by ``python -m autofit search-manifest --json`` in a subprocess of the current interpreter -- the installed ``autofit``, or, with ``source``, the checkout at that path put first on ``PYTHONPATH``. + + In the default (installed) mode ``PYTHONPATH`` is removed from the + subprocess environment: a development shell that puts a source checkout on + it would otherwise turn "installed" into "source main" silently. """ if manifest_file: text = Path(manifest_file).read_text(encoding="utf-8") @@ -100,6 +110,8 @@ def load_manifest(manifest_file: Optional[str] = None, source: Optional[str] = N env["PYTHONPATH"] = str(Path(source).resolve()) + ( os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "" ) + else: + env.pop("PYTHONPATH", None) proc = subprocess.run( [sys.executable, "-m", "autofit", "search-manifest", "--json"], capture_output=True, @@ -108,9 +120,15 @@ def load_manifest(manifest_file: Optional[str] = None, source: Optional[str] = N ) if proc.returncode != 0: tail = "\n".join(proc.stderr.strip().splitlines()[-5:]) + hint = ( + "" + if source + else "\n(PYTHONPATH is ignored here on purpose: install the autofit release " + "into this interpreter, or pass --manifest )" + ) raise RosterError( f"`python -m autofit search-manifest --json` failed " - f"(exit {proc.returncode}):\n{tail}" + f"(exit {proc.returncode}):\n{tail}{hint}" ) text = proc.stdout try: @@ -150,6 +168,10 @@ def parse_options(opts: str) -> Dict[str, str]: key, sep, value = token.partition("=") if not sep: raise RosterError(f"roster option {token!r} is not key=value") + if key not in OPTION_KEYS: + raise RosterError( + f"unknown roster option {key!r} (choose from {', '.join(sorted(OPTION_KEYS))})" + ) out[key] = value style = out.setdefault("style", "list") if style not in STYLES: @@ -159,12 +181,15 @@ def parse_options(opts: str) -> Dict[str, str]: return out -def _example_ref(anchor: Optional[str], link: Optional[str]) -> Optional[str]: +def _example_ref(anchor: Optional[str], link: Optional[str], rel_dir: str = "") -> Optional[str]: + """``rel_dir`` is the repo-relative folder of the file holding the block; + a ``link=`` target is made relative to it so the link resolves in place.""" if not anchor: return None repo, path, _ = parse_anchor(anchor) if link and repo == link: - return f"[{path}]({path})" + target = posixpath.relpath(path, rel_dir) if rel_dir not in ("", ".") else path + return f"[{path}]({target})" return f"`{repo}:{path}`" @@ -178,7 +203,7 @@ def _families(manifest: dict) -> List[Tuple[str, str, List[dict]]]: return out -def _render_list(manifest: dict, link: Optional[str]) -> List[str]: +def _render_list(manifest: dict, link: Optional[str], rel_dir: str = "") -> List[str]: lines = [] for key, label, members in _families(manifest): names = [] @@ -190,7 +215,7 @@ def _render_list(manifest: dict, link: Optional[str]) -> List[str]: line = f"- **{label}** (`{key}`): " + ", ".join(names) examples = [] for s in members: - ref = _example_ref((s.get("example") or "").partition("#")[0] or None, link) + ref = _example_ref((s.get("example") or "").partition("#")[0] or None, link, rel_dir) if ref and ref not in examples: examples.append(ref) if examples: @@ -203,7 +228,7 @@ def _yes_no(value) -> str: return "yes" if value else "no" -def _render_table(manifest: dict, link: Optional[str]) -> List[str]: +def _render_table(manifest: dict, link: Optional[str], rel_dir: str = "") -> List[str]: lines = [ "| Search | Family | Status | JAX | Gradient | Evidence | Posterior | Example |", "|---|---|---|---|---|---|---|---|", @@ -211,7 +236,7 @@ def _render_table(manifest: dict, link: Optional[str]) -> List[str]: for key, _label, members in _families(manifest): for s in members: c = s["capabilities"] - ref = _example_ref((s.get("example") or "").partition("#")[0] or None, link) + ref = _example_ref((s.get("example") or "").partition("#")[0] or None, link, rel_dir) lines.append( f"| `af.{s['name']}` | {key} | {c.get('status', '')} | " f"{c.get('jax_use', '')} | {c.get('gradient', '')} | " @@ -221,13 +246,13 @@ def _render_table(manifest: dict, link: Optional[str]) -> List[str]: return lines -def render_body(manifest: dict, options: Dict[str, str]) -> List[str]: +def render_body(manifest: dict, options: Dict[str, str], rel_dir: str = "") -> List[str]: """The generated lines between the stamp and the end marker.""" link = options.get("link") if options["style"] == "table": - lines = _render_table(manifest, link) + lines = _render_table(manifest, link, rel_dir) else: - lines = _render_list(manifest, link) + lines = _render_list(manifest, link, rel_dir) pad = " " * int(options.get("indent", "0")) return [pad + line if line else line for line in lines] @@ -247,9 +272,23 @@ class Block(NamedTuple): def find_blocks(lines: List[str], where: str = "") -> List[Block]: + """Roster blocks in ``lines``. Markers inside a fenced code block + (```` ``` ```` / ``~~~``) are documentation of the format, not blocks.""" blocks = [] + fence = None i = 0 while i < len(lines): + fm = FENCE_RE.match(lines[i]) + if fm: + if fence is None: + fence = fm.group(1) + elif fm.group(1) == fence: + fence = None + i += 1 + continue + if fence is not None: + i += 1 + continue m = BEGIN_RE.match(lines[i]) if not m: if END_RE.match(lines[i]): @@ -277,14 +316,22 @@ def find_blocks(lines: List[str], where: str = "") -> List[Block]: return blocks -def regenerate_text(text: str, manifest: dict, where: str = "") -> Tuple[str, int]: +def _split(text: str) -> Tuple[List[str], str]: + """Lines and the file's newline (CRLF files keep CRLF).""" + newline = "\r\n" if "\r\n" in text else "\n" + return text.replace("\r\n", "\n").split("\n"), newline + + +def regenerate_text( + text: str, manifest: dict, where: str = "", rel_dir: str = "" +) -> Tuple[str, int]: """``text`` with every roster block re-rendered; (new text, block count).""" - lines = text.split("\n") + lines, newline = _split(text) blocks = find_blocks(lines, where) for block in reversed(blocks): - new_inner = [block.lead + stamp(manifest)] + render_body(manifest, block.options) + new_inner = [block.lead + stamp(manifest)] + render_body(manifest, block.options, rel_dir) lines[block.begin + 1 : block.end] = new_inner - return "\n".join(lines), len(blocks) + return newline.join(lines), len(blocks) class Drift(NamedTuple): @@ -294,12 +341,14 @@ class Drift(NamedTuple): detail: str -def check_text(text: str, manifest: dict, where: str = "") -> List[Drift]: - lines = text.split("\n") +def check_text( + text: str, manifest: dict, where: str = "", rel_dir: str = "" +) -> List[Drift]: + lines, _ = _split(text) out = [] installed = manifest["autofit_version"] for block in find_blocks(lines, where): - expected = render_body(manifest, block.options) + expected = render_body(manifest, block.options, rel_dir) if block.body != expected: out.append( Drift(where, block.begin + 1, "body", @@ -345,14 +394,32 @@ def discover_files(root: Path) -> List[Path]: return found -def regenerate_files(paths: Iterable[Path], manifest: dict) -> List[Path]: - """Re-render every block in ``paths``; returns the files whose text changed.""" +def _rel_dir(path: Path, root: Optional[Path]) -> str: + if root is None: + return "" + try: + return path.resolve().parent.relative_to(Path(root).resolve()).as_posix() + except ValueError: + return "" + + +def _read(path: Path) -> str: + with open(path, encoding="utf-8", newline="") as f: + return f.read() + + +def regenerate_files( + paths: Iterable[Path], manifest: dict, root: Optional[Path] = None +) -> List[Path]: + """Re-render every block in ``paths``; returns the files whose text changed. + ``root`` (the repo root) makes ``link=`` targets relative to each file.""" changed = [] for path in paths: - old = path.read_text(encoding="utf-8") - new, _ = regenerate_text(old, manifest, str(path)) + old = _read(path) + new, _ = regenerate_text(old, manifest, str(path), _rel_dir(path, root)) if new != old: - path.write_text(new, encoding="utf-8") + with open(path, "w", encoding="utf-8", newline="") as f: + f.write(new) changed.append(path) return changed @@ -361,7 +428,7 @@ def check_files(paths: Iterable[Path], manifest: dict, root: Optional[Path] = No out = [] for path in paths: where = str(path.relative_to(root)) if root and path.is_relative_to(root) else str(path) - out.extend(check_text(path.read_text(encoding="utf-8"), manifest, where)) + out.extend(check_text(_read(path), manifest, where, _rel_dir(path, root))) return out @@ -408,28 +475,46 @@ def resolve_anchors(manifest: dict, workspace_root: Path) -> List[AnchorResult]: def _is_search_target(target: ast.expr) -> bool: - return isinstance(target, ast.Name) and "search" in target.id.lower() + if isinstance(target, ast.Name): + name = target.id + elif isinstance(target, ast.Attribute): # self.search = ... + name = target.attr + else: + return False + return SEARCH_TARGET_RE.fullmatch(name.lower()) is not None + + +def _af_call(value) -> Optional[str]: + if not isinstance(value, ast.Call): + return None + func = value.func + if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name) and func.value.id == "af": + return func.attr + return None def named_searches(source: str) -> List[Tuple[int, str]]: - """(line, Name) for every ``<…search…> = af.(...)`` in ``source``.""" + """(line, Name) for every search constructed as ``af.(...)`` and held + by a ``search`` / ``search_`` name: plain and annotated assignments, + ``self.search = ...`` and a ``search=af.(...)`` keyword argument.""" try: tree = ast.parse(source) except SyntaxError: return [] out = [] for node in ast.walk(tree): - if not isinstance(node, ast.Assign) or not isinstance(node.value, ast.Call): - continue - if not any(_is_search_target(t) for t in node.targets): - continue - func = node.value.func - if ( - isinstance(func, ast.Attribute) - and isinstance(func.value, ast.Name) - and func.value.id == "af" - ): - out.append((node.lineno, func.attr)) + if isinstance(node, ast.Assign): + name = _af_call(node.value) + if name and any(_is_search_target(t) for t in node.targets): + out.append((node.lineno, name)) + elif isinstance(node, ast.AnnAssign): + name = _af_call(node.value) + if name and _is_search_target(node.target): + out.append((node.lineno, name)) + elif isinstance(node, ast.keyword) and node.arg and SEARCH_TARGET_RE.fullmatch(node.arg): + name = _af_call(node.value) + if name: + out.append((node.value.lineno, name)) return sorted(out) diff --git a/tests/test_check_search_memory.py b/tests/test_check_search_memory.py index 0b9605a9..f1a11649 100644 --- a/tests/test_check_search_memory.py +++ b/tests/test_check_search_memory.py @@ -159,11 +159,12 @@ def test_guarded_names_are_the_manifest_multi_starts(): } -def test_manifest_names_replace_the_prefix_rule(): +def test_manifest_names_unite_with_the_prefix_rule(): + # A source-only sibling newer than the installed manifest keeps its guard. names = check_search_memory.guarded_names(_manifest("MultiStartProdigy")) source = "a = af.MultiStartProdigy()\nb = af.MultiStartNotInTheManifest()\n" found = findings_in_source(source, Path("x.py"), names) - assert [f.search for f in found] == ["MultiStartProdigy"] + assert [f.search for f in found] == ["MultiStartProdigy", "MultiStartNotInTheManifest"] def test_main_reads_the_manifest_file(tmp_path, capsys): @@ -172,7 +173,7 @@ def test_main_reads_the_manifest_file(tmp_path, capsys): manifest = tmp_path / "manifest.json" manifest.write_text(json.dumps(_manifest("MultiStartAdam"))) ws = _workspace(tmp_path, **{"x.py": "s = af.MultiStartProdigy()\n"}) - # Prodigy is not in this manifest, so only the prefix fallback flags it. - assert main(["--root", str(ws), "--manifest", str(manifest)]) == 0 + # Prodigy is not in this manifest; the prefix rule still guards it. + assert main(["--root", str(ws), "--manifest", str(manifest)]) == 1 assert main(["--root", str(ws)]) == 1 assert main(["--root", str(ws), "--manifest", str(tmp_path / "nope.json")]) == 2 diff --git a/tests/test_search_roster.py b/tests/test_search_roster.py index e262e2fe..a363e728 100644 --- a/tests/test_search_roster.py +++ b/tests/test_search_roster.py @@ -156,8 +156,14 @@ def test_named_searches_only_reads_search_assignments(): "search_mle = af.Gone()\n" "model = af.Model(Thing)\n" '"""prose naming af.UltraNest"""\n' + "settings_search = af.SettingsSearch()\n" + "grid_search = af.SearchGridSearch()\n" + "search: object = af.Annotated()\n" + "self.search = af.OnSelf()\n" + "chain(search=af.Keyword())\n" ) - assert search_roster.named_searches(source) == [(1, "Nautilus"), (2, "Gone")] + assert search_roster.named_searches(source) == [ + (1, "Nautilus"), (2, "Gone"), (7, "Annotated"), (8, "OnSelf"), (9, "Keyword")] def test_manifest_difference_reports_added_and_changed(): @@ -247,3 +253,51 @@ def test_discovery_skips_nested_checkouts(tmp_path): (nested / ".git").mkdir(parents=True) (nested / "llms.txt").write_text(BLOCK) assert search_roster.discover_files(root) == [root / "llms.txt"] + + +def test_crlf_files_keep_crlf_and_regenerate_cleanly(): + crlf = BLOCK.replace("\n", "\r\n") + text, _ = search_roster.regenerate_text(crlf, _manifest()) + assert "\r\n" in text and "\n" not in text.replace("\r\n", "") + assert search_roster.check_text(text, _manifest()) == [] + + +def test_markers_inside_code_fences_are_documentation(): + doc = "```\n\n\n```\n" + assert search_roster.regenerate_text(doc, _manifest()) == (doc, 0) + assert search_roster.regenerate_text("~~~\n\n~~~\n", _manifest())[1] == 0 + + +def test_unknown_option_is_rejected(): + with pytest.raises(search_roster.RosterError): + search_roster.regenerate_text(BLOCK.replace("style=list", "stlye=table"), _manifest()) + + +def test_link_is_relative_to_the_file_holding_the_block(tmp_path): + root = tmp_path / "ws" + (root / "scripts" / "searches").mkdir(parents=True) + readme = root / "scripts" / "searches" / "README.md" + readme.write_text(BLOCK.replace("style=list", "style=list link=ws")) + search_roster.regenerate_files([readme], _manifest(), root) + assert "[scripts/searches/nest.py](nest.py)" in readme.read_text() + assert search_roster.check_files([readme], _manifest(), root) == [] + + +def test_installed_mode_ignores_pythonpath(tmp_path, monkeypatch): + # A source checkout on PYTHONPATH must not stand in for the installed autofit. + fake = tmp_path / "src" / "autofit" + fake.mkdir(parents=True) + (fake / "__init__.py").write_text("") + (fake / "__main__.py").write_text( + "import json\nprint(json.dumps({'schema': 'search-manifest@1', " + "'autofit_version': 'FROM-PYTHONPATH', 'families': {}, 'searches': []}))\n" + ) + monkeypatch.setenv("PYTHONPATH", str(tmp_path / "src")) + try: + manifest = search_roster.load_manifest() + except search_roster.RosterError: + manifest = None # no installed autofit in this interpreter: also correct + assert manifest is None or manifest["autofit_version"] != "FROM-PYTHONPATH" + # ...while --against-source deliberately reads the checkout at the path. + source = search_roster.load_manifest(source=str(tmp_path / "src")) + assert source["autofit_version"] == "FROM-PYTHONPATH" From 5e4224efa100184c166918bf5c600f30f0b02e62 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Thu, 15 Oct 2026 14:37:05 +0100 Subject: [PATCH 4/4] fix(hands): installed-mode manifest runs from a neutral directory python -m puts the working directory first on sys.path, so running the tool from inside a source checkout made source main pose as the installed release (re-review finding). --against-source is unchanged. Co-Authored-By: Claude Opus 5.5 --- autohands/search_roster.py | 18 ++++++++++++------ tests/test_search_roster.py | 1 + 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/autohands/search_roster.py b/autohands/search_roster.py index a3828e8c..df00b42d 100644 --- a/autohands/search_roster.py +++ b/autohands/search_roster.py @@ -57,6 +57,7 @@ import re import subprocess import sys +import tempfile from pathlib import Path from typing import Dict, Iterable, List, NamedTuple, Optional, Tuple @@ -112,12 +113,17 @@ def load_manifest(manifest_file: Optional[str] = None, source: Optional[str] = N ) else: env.pop("PYTHONPATH", None) - proc = subprocess.run( - [sys.executable, "-m", "autofit", "search-manifest", "--json"], - capture_output=True, - text=True, - env=env, - ) + # `-m` puts the working directory first on sys.path: run the installed + # mode from a neutral directory so a shell sitting inside a source + # checkout cannot pass it off as the installed release either. + with tempfile.TemporaryDirectory() as neutral: + proc = subprocess.run( + [sys.executable, "-m", "autofit", "search-manifest", "--json"], + capture_output=True, + text=True, + env=env, + cwd=None if source else neutral, + ) if proc.returncode != 0: tail = "\n".join(proc.stderr.strip().splitlines()[-5:]) hint = ( diff --git a/tests/test_search_roster.py b/tests/test_search_roster.py index a363e728..a4e013b6 100644 --- a/tests/test_search_roster.py +++ b/tests/test_search_roster.py @@ -293,6 +293,7 @@ def test_installed_mode_ignores_pythonpath(tmp_path, monkeypatch): "'autofit_version': 'FROM-PYTHONPATH', 'families': {}, 'searches': []}))\n" ) monkeypatch.setenv("PYTHONPATH", str(tmp_path / "src")) + monkeypatch.chdir(tmp_path / "src") # nor the working directory try: manifest = search_roster.load_manifest() except search_roster.RosterError: