Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions .github/workflows/navigator_check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,86 @@ 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
# released version, never the library's main. The workspace is checked out
# under its own repository name so the manifest's `<repo>:<path>` anchors
# resolve against it; for the autofit workspace the integration-test
# 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: ${{ steps.repo.outputs.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 / integration-test branches
shell: bash
run: |
BRANCH="${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}"
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
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
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 <PyAutoHands>/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 "${{ steps.repo.outputs.name }}"
--manifest search_manifest.json

staleness:
name: Catalogue staleness
runs-on: ubuntu-latest
Expand Down
63 changes: 53 additions & 10 deletions autohands/check_search_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,17 @@
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 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 <workspace_dir> [--scripts-dir scripts]
[--manifest manifest.json]

Exit codes:
0 no unbatched multi-start searches found
Expand All @@ -30,13 +39,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
Expand All @@ -60,9 +71,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 and name in names:
return True
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`) 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)
Expand All @@ -76,7 +103,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.
Expand All @@ -86,15 +113,19 @@ 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}")

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

Expand All @@ -107,15 +138,27 @@ 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)
if not root.is_dir():
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
Expand Down
124 changes: 124 additions & 0 deletions autohands/check_search_roster.py
Original file line number Diff line number Diff line change
@@ -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
(``<repo>:<path>[#<Section>]``) must resolve in ``DIR/<repo>``; 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.<Name>(...)`` 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 <checkout> [--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 <repo>/ 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())
40 changes: 38 additions & 2 deletions autohands/navigator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -368,3 +370,37 @@ 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.
"""
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"]
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 "<!-- search-roster:begin" in p.read_text(encoding="utf-8")
]
if not paths:
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, workspace_path)
print(
f"Search roster: {len(paths)} file(s), {len(changed)} rewritten "
f"({search_roster.stamp(manifest)})"
)
return changed
Loading
Loading