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
112 changes: 74 additions & 38 deletions agents/_repo_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,36 +33,89 @@ 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.

This bootstrap must work before PyYAML is installed. Accept the manifest's
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)
Expand Down Expand Up @@ -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]


Expand Down
9 changes: 5 additions & 4 deletions agents/conductors/docs/_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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


Expand Down
6 changes: 2 additions & 4 deletions agents/conductors/hygiene/_hygiene_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
27 changes: 6 additions & 21 deletions agents/conductors/hygiene/_hygiene_repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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]:
Expand All @@ -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


Expand Down
12 changes: 5 additions & 7 deletions agents/conductors/intake/_intake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
24 changes: 3 additions & 21 deletions bin/project_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = '<!-- Generated by PyAutoBrain/bin/project_discovery.py; do not edit. -->'
SURFACES = ('.claude/commands', '.claude/skills', '.codex/skills')
Expand Down Expand Up @@ -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:
Expand Down
20 changes: 4 additions & 16 deletions bin/public_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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


Expand Down
12 changes: 5 additions & 7 deletions board/_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"],
Expand Down
Loading
Loading