From 8386d5ca24534d8006ce78c37fc02c88f537fbb5 Mon Sep 17 00:00:00 2001 From: Jammy2211 Date: Sun, 22 Nov 2026 18:03:33 +0000 Subject: [PATCH] refactor: one stdlib reader for repos.yaml instead of about ten Add manifest_entries / manifest_repos / manifest_field (raw value per repo from the repos: block; comment and blank lines skipped, ended by the next top-level key), manifest_text, manifest_homes and majority_owner to agents/_repo_paths.py, stdlib only. Move manifest_paths, package_paths, project_discovery.manifest_categories, _hygiene_repos.parse_minimal, public_names.body_map_packages, _docs.known_repos, _intake._mind_home, _board.repo_homes and both derive_org owner votes onto it. Each caller keeps its own value handling (quotes, comments), so on the real body map and on quoted / commented / block-ended fixtures every reader returns what it did before. Closes #708 Co-Authored-By: Claude Opus 5.5 --- agents/_repo_paths.py | 112 +++++++++++++------- agents/conductors/docs/_docs.py | 9 +- agents/conductors/hygiene/_hygiene_ci.py | 6 +- agents/conductors/hygiene/_hygiene_repos.py | 27 ++--- agents/conductors/intake/_intake.py | 12 +-- bin/project_discovery.py | 24 +---- bin/public_names.py | 20 +--- board/_board.py | 12 +-- tests/test_repo_paths.py | 46 ++++++++ 9 files changed, 150 insertions(+), 118 deletions(-) diff --git a/agents/_repo_paths.py b/agents/_repo_paths.py index 93e4f47f..38c931e8 100644 --- a/agents/_repo_paths.py +++ b/agents/_repo_paths.py @@ -33,6 +33,74 @@ def _placement(name: str, value: str) -> Path: return Path(*path.parts) +_REPOS_KEY = re.compile(r'repos:\s*(?:#.*)?') +_REPO_KEY = re.compile(r' ([A-Za-z0-9_.-]+):\s*(?:#.*)?') +_FIELD = re.compile(r' ([A-Za-z0-9_]+)\s*:(.*)') + + +def manifest_entries(text: str): + """Walk the body map's `repos:` block: yield `(repo, None, None)` for each + two-space repo key and `(repo, field, raw)` for each four-space field. + + The one stdlib reader of `repos.yaml`, so it works before PyYAML is + installed. Blank and comment lines are skipped; the next top-level key + ends the block. `raw` is the text after the field's colon, stripped and + otherwise verbatim (quotes and any trailing comment included): each + caller decides what a value means. + """ + active = False + current = None + for line in text.splitlines(): + if not line.strip() or line.lstrip().startswith('#'): + continue + if not line.startswith(' '): + if active: + return + active = bool(_REPOS_KEY.fullmatch(line)) + continue + if not active: + continue + match = _REPO_KEY.fullmatch(line) + if match: + current = match[1] + yield current, None, None + continue + match = _FIELD.fullmatch(line) + if current and match: + yield current, match[1], match[2].strip() + + +def manifest_repos(text: str) -> list[str]: + """Every repo key of the `repos:` block, in file order (repeats kept).""" + return [repo for repo, field, _raw in manifest_entries(text) if field is None] + + +def manifest_field(text: str, key: str) -> dict[str, str]: + """`{repo: raw value}` of one four-space field, in file order; a repo + without the field is absent.""" + return {repo: raw for repo, field, raw in manifest_entries(text) if field == key} + + +def manifest_homes(text: str) -> list[str]: + """Every repo's `github:` home (`owner/name`), in file order; a value with + a space in it (a trailing comment) is not a home.""" + return [raw for raw in manifest_field(text, 'github').values() + if re.fullmatch(r'\S+', raw)] + + +def majority_owner(homes: list[str]) -> str | None: + """The GitHub owner most homes share — the organism's org — or None.""" + owners = [h.split('/')[0] for h in homes if '/' in h] + return max(set(owners), key=owners.count) if owners else None + + +def manifest_text(root: Path) -> str: + """The body map's text from the PyAutoMind checkout under `root`, `''` + when it is not on disk.""" + manifest = bootstrap_repo_path(Path(root), 'PyAutoMind') / 'repos.yaml' + return manifest.read_text() if manifest.is_file() else '' + + def manifest_paths(root: Path) -> dict[str, Path]: """Read only identity and placement from the body's simple YAML mapping. @@ -40,29 +108,14 @@ def manifest_paths(root: Path) -> dict[str, Path]: two/four-space mapping grammar, including quoted path scalars, and validate every explicit placement. Other metadata is deliberately not interpreted. """ - manifest = bootstrap_repo_path(Path(root), 'PyAutoMind') / 'repos.yaml' - if not manifest.is_file(): - return {} paths: dict[str, Path] = {} - active = False - current = None - for line in manifest.read_text().splitlines(): - if line.strip() == 'repos:': - active = True - continue - if not active or not line.strip() or line.lstrip().startswith('#'): - continue - if not line.startswith(' '): - break - match = re.fullmatch(r' ([A-Za-z0-9_.-]+):\s*(?:#.*)?', line) - if match: - current = _name(match[1]) + for current, field, raw in manifest_entries(manifest_text(root)): + if field is None: + current = _name(current) if current in paths: raise ValueError(f'duplicate repository identity: {current}') paths[current] = Path(current) - continue - if current and re.match(r' path\s*:', line): - raw = line.split(':', 1)[1].strip() + elif field == 'path': if raw.startswith(('"', "'")): quote = raw[0] end = raw.find(quote, 1) @@ -174,25 +227,8 @@ def package_paths(root: Path) -> list[Path]: """Import roots for packages declared by the body map, in manifest order.""" root = Path(root) declared = manifest_paths(root) - manifest = bootstrap_repo_path(root, 'PyAutoMind') / 'repos.yaml' - if not manifest.is_file(): - return [] - names = [] - current = None - active = False - for line in manifest.read_text().splitlines(): - if line.strip() == 'repos:': - active = True - continue - if not active or not line.strip() or line.lstrip().startswith('#'): - continue - if not line.startswith(' '): - break - match = re.fullmatch(r' ([A-Za-z0-9_.-]+):\s*(?:#.*)?', line) - if match: - current = match[1] - elif current in declared and re.match(r' package:\s*\S+', line): - names.append(current) + names = [name for name, raw in manifest_field(manifest_text(root), 'package').items() + if name in declared and raw] return [repo_path(root, name) for name in names] diff --git a/agents/conductors/docs/_docs.py b/agents/conductors/docs/_docs.py index ee96437a..68c9b72f 100644 --- a/agents/conductors/docs/_docs.py +++ b/agents/conductors/docs/_docs.py @@ -31,7 +31,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import _pyauto_root # noqa: E402 -from _repo_paths import repo_path # noqa: E402 +from _repo_paths import manifest_field, repo_path # noqa: E402 PYAUTO_ROOT = _pyauto_root.pyauto_root() BRAIN_HOME = Path(__file__).resolve().parents[3] @@ -168,9 +168,10 @@ def known_repos(): text = manifest.read_text(encoding="utf-8") except OSError: return repos - for m in re.finditer(r"^ ([A-Za-z][\w.-]*):\s*\n(?: .*\n)*? category:\s*(\w+)", - text, re.M): - repos[m.group(1)] = m.group(2) + for name, raw in manifest_field(text, "category").items(): + m = re.match(r"\w+", raw) + if m and re.fullmatch(r"[A-Za-z][\w.-]*", name): + repos[name] = m.group(0) return repos diff --git a/agents/conductors/hygiene/_hygiene_ci.py b/agents/conductors/hygiene/_hygiene_ci.py index a9bf2b27..3c71edc8 100755 --- a/agents/conductors/hygiene/_hygiene_ci.py +++ b/agents/conductors/hygiene/_hygiene_ci.py @@ -74,7 +74,7 @@ sys.path.insert(0, str(HERE)) from _hygiene_repos import resolve_map # noqa: E402 sys.path.insert(0, str(HERE.parents[2])) -from _repo_paths import repo_path # noqa: E402 +from _repo_paths import majority_owner, manifest_homes, repo_path # noqa: E402 import _pyauto_root # noqa: E402 DEFAULT_HEART = "PyAuto" + "Heart" # an organ: framework identity, not an instance fact @@ -89,9 +89,7 @@ def derive_org() -> str | None: path = resolve_map() if path is None: return None - homes = re.findall(r"^\s+github:\s*(\S+)\s*$", path.read_text(encoding="utf-8"), re.M) - owners = [h.split("/")[0] for h in homes if "/" in h] - return max(set(owners), key=owners.count) if owners else None + return majority_owner(manifest_homes(path.read_text(encoding="utf-8"))) def pyauto_root() -> Path: diff --git a/agents/conductors/hygiene/_hygiene_repos.py b/agents/conductors/hygiene/_hygiene_repos.py index 0578a1af..3f725c32 100755 --- a/agents/conductors/hygiene/_hygiene_repos.py +++ b/agents/conductors/hygiene/_hygiene_repos.py @@ -43,7 +43,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[2])) -from _repo_paths import bootstrap_repo_path # noqa: E402 +from _repo_paths import bootstrap_repo_path, manifest_field # noqa: E402 from _pyauto_root import pyauto_root # noqa: E402 MAP_FILENAME = "repos.yaml" @@ -96,9 +96,8 @@ def resolve_map() -> Path | None: # module exists to prevent, so "PyYAML absent" must not become a way to # re-introduce it. -_REPO_LINE = re.compile(r"^ ([A-Za-z0-9._-]+):\s*(#.*)?$") -_CATEGORY_LINE = re.compile(r"^ category:\s*['\"]?([A-Za-z0-9_-]+)['\"]?\s*(#.*)?$") -_TOP_LEVEL = re.compile(r"^\S") +#: A `category:` value: one bare or quoted word, optionally commented. +_CATEGORY_VALUE = re.compile(r"['\"]?([A-Za-z0-9_-]+)['\"]?\s*(#.*)?") def parse_minimal(text: str) -> dict[str, str]: @@ -110,24 +109,10 @@ def parse_minimal(text: str) -> dict[str, str]: fallback, not a YAML implementation. """ out: dict[str, str] = {} - in_repos = False - current: str | None = None - for line in text.splitlines(): - if not line.strip() or line.lstrip().startswith("#"): - continue - if _TOP_LEVEL.match(line): - in_repos = line.startswith("repos:") - current = None - continue - if not in_repos: - continue - m = _REPO_LINE.match(line) + for repo, raw in manifest_field(text, "category").items(): + m = _CATEGORY_VALUE.fullmatch(raw) if m: - current = m.group(1) - continue - m = _CATEGORY_LINE.match(line) - if m and current: - out[current] = m.group(1) + out[repo] = m.group(1) return out diff --git a/agents/conductors/intake/_intake.py b/agents/conductors/intake/_intake.py index 041bbe7c..9a4c9c06 100755 --- a/agents/conductors/intake/_intake.py +++ b/agents/conductors/intake/_intake.py @@ -53,7 +53,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "faculties" / "memory")) import _memory # noqa: E402 sys.path.insert(0, str(Path(__file__).resolve().parents[2])) -from _repo_paths import repo_path # noqa: E402 +from _repo_paths import manifest_field, repo_path # noqa: E402 # The shared board theme: the one place that answers "what does a one-tap board # look like". Presentation only — the stylesheet, the hero, the pills — so this @@ -1862,12 +1862,10 @@ def _mind_home(mind: Path) -> str: f = mind / "repos.yaml" if not f.is_file(): return "" - # `github:` may follow other keys of the entry (`path:`) — scan the whole - # indented block, not just line one. - m = re.search(r"^\s{2}PyAutoMind:[ \t]*\n(?:[ \t]{4,}.*\n)*?[ \t]{4,}github:" - r"[ \t]*([^\s#]+)", - f.read_text(encoding="utf-8", errors="replace"), re.M) - return f"https://github.com/{m.group(1)}" if m else "" + raw = manifest_field(f.read_text(encoding="utf-8", errors="replace"), + "github").get("PyAutoMind", "") + m = re.match(r"[^\s#]+", raw) + return f"https://github.com/{m.group(0)}" if m else "" # The dev batch record's member grammar — duplicated from diff --git a/bin/project_discovery.py b/bin/project_discovery.py index e567d7fa..2576d69e 100644 --- a/bin/project_discovery.py +++ b/bin/project_discovery.py @@ -10,7 +10,7 @@ import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'agents')) -from _repo_paths import bootstrap_repo_path, manifest_paths, repo_path +from _repo_paths import manifest_field, manifest_paths, manifest_text, repo_path MARKER = '' SURFACES = ('.claude/commands', '.claude/skills', '.codex/skills') @@ -164,26 +164,8 @@ def actual(path: Path) -> dict[str, tuple[str, str]]: def manifest_categories(root: Path) -> dict[str, str]: """Read category metadata from the same body map used for repo placement.""" - manifest = bootstrap_repo_path(root, 'PyAutoMind') / 'repos.yaml' - if not manifest.is_file(): - return {} - categories = {} - current = None - in_repos = False - for line in manifest.read_text().splitlines(): - if line.strip() == 'repos:': - in_repos = True - continue - if not in_repos: - continue - if line and not line.startswith(' '): - break - match = re.fullmatch(r' ([A-Za-z0-9_.-]+):\s*(?:#.*)?', line) - if match: - current = match[1] - elif current and re.match(r' category:\s*', line): - categories[current] = line.split(':', 1)[1].split('#', 1)[0].strip().strip('"\'') - return categories + return {repo: raw.split('#', 1)[0].strip().strip('"\'') + for repo, raw in manifest_field(manifest_text(root), 'category').items()} def run(root: Path, names: list[str], write: bool) -> int: diff --git a/bin/public_names.py b/bin/public_names.py index 7789552a..b7236c03 100644 --- a/bin/public_names.py +++ b/bin/public_names.py @@ -73,7 +73,7 @@ BRAIN_HOME = Path(__file__).resolve().parents[1] sys.path.insert(0, str(BRAIN_HOME / "agents")) import _pyauto_root # noqa: E402 -from _repo_paths import repo_path # noqa: E402 +from _repo_paths import manifest_field, repo_path # noqa: E402 CLEAN, HIT, CANNOT = "CLEAN", "HIT", "CANNOT-TELL" EXIT = {CLEAN: 0, HIT: 1, CANNOT: 2} @@ -107,22 +107,10 @@ def body_map_packages(text: str) -> dict[str, str]: """repo name → `package:` from the body map's two-level `repos:` block (two-space repo keys, four-space fields), without PyYAML.""" out: dict[str, str] = {} - in_repos, current = False, None - for line in text.splitlines(): - if not line.strip() or line.lstrip().startswith("#"): - continue - if not line.startswith(" "): - in_repos, current = line.startswith("repos:"), None - continue - if not in_repos: - continue - m = re.match(r"^ ([A-Za-z0-9._-]+):\s*(#.*)?$", line) + for repo, raw in manifest_field(text, "package").items(): + m = re.fullmatch(r"['\"]?([A-Za-z0-9_.]+)['\"]?\s*(#.*)?", raw) if m: - current = m.group(1) - continue - m = re.match(r"^ package:\s*['\"]?([A-Za-z0-9_.]+)['\"]?\s*(#.*)?$", line) - if m and current: - out[current] = m.group(1) + out[repo] = m.group(1) return out diff --git a/board/_board.py b/board/_board.py index ab3b544d..8ffb51bf 100755 --- a/board/_board.py +++ b/board/_board.py @@ -40,7 +40,7 @@ # looked in the wrong tree. sys.path.insert(0, str(BRAIN_HOME / "agents")) import _pyauto_root # noqa: E402 -from _repo_paths import repo_path # noqa: E402 +from _repo_paths import majority_owner, manifest_homes, repo_path # noqa: E402 PYAUTO_ROOT, ROOT_REASON = _pyauto_root.workspace_root_reason() GH = os.environ.get("BOARD_GH", "gh") @@ -77,17 +77,15 @@ def repo_homes(): body_map = repo_path(PYAUTO_ROOT, "PyAutoMind") / "repos.yaml" if not body_map.is_file(): return [] - return re.findall( - r"^\s+github:\s*(\S+)\s*$", body_map.read_text(encoding="utf-8"), re.M - ) + return manifest_homes(body_map.read_text(encoding="utf-8")) def derive_org(homes): """The organism's GitHub org = the most common owner in the body map; falls back to the Brain checkout's own remote when the Mind is absent.""" - owners = [h.split("/")[0] for h in homes if "/" in h] - if owners: - return max(set(owners), key=owners.count) + owner = majority_owner(homes) + if owner: + return owner try: r = subprocess.run( ["git", "-C", str(BRAIN_HOME), "remote", "get-url", "origin"], diff --git a/tests/test_repo_paths.py b/tests/test_repo_paths.py index b63cfd62..fefee88c 100644 --- a/tests/test_repo_paths.py +++ b/tests/test_repo_paths.py @@ -124,3 +124,49 @@ def test_grouped_mind_bootstraps_its_own_manifest(tmp_path): (tmp_path / 'PyAutoMind').mkdir() with pytest.raises(ValueError, match='ambiguous'): manifest_paths(tmp_path) + + +# ---------------------------------------------- the one body-map reader --- +BODY_MAP = '''# header comment +categories: + library: + category: not-a-repo +repos: + # --- organs --- + PyAutoMind: # the Mind + github: "Org/PyAutoMind" # quoted, commented + path: 'organs/PyAutoMind' + + autofit_tool: + # a comment inside an entry + category: library # trailing + package: autofit +smoke_bootstrap_rollout: true +later: + Ghost: + category: organ +''' + + +def test_manifest_field_reads_only_the_repos_block_raw(): + module = paths + assert module.manifest_repos(BODY_MAP) == ['PyAutoMind', 'autofit_tool'] + assert module.manifest_field(BODY_MAP, 'category') == {'autofit_tool': 'library # trailing'} + assert module.manifest_field(BODY_MAP, 'github') == { + 'PyAutoMind': '"Org/PyAutoMind" # quoted, commented'} + assert module.manifest_field(BODY_MAP, 'path') == {'PyAutoMind': "'organs/PyAutoMind'"} + assert module.manifest_field(BODY_MAP, 'package') == {'autofit_tool': 'autofit'} + + +def test_manifest_homes_and_majority_owner(): + module = paths + text = ('repos:\n A:\n github: Org/A\n B:\n github: Org/B # c\n' + ' C:\n github: Org/C\n D:\n github: Other/D\n') + assert module.manifest_homes(text) == ['Org/A', 'Org/C', 'Other/D'] + assert module.majority_owner(module.manifest_homes(text)) == 'Org' + assert module.majority_owner([]) is None + + +def test_the_reader_needs_no_pyyaml(): + source = MODULE.read_text() + assert 'import yaml' not in source and 'from yaml' not in source