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
11 changes: 9 additions & 2 deletions agents/_common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# remote session ($HOME=/root, checkouts under /home/user) and report empty
# rather than fail.
. "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../bin/_pyauto_root.sh"
. "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../bin/_repo_paths.sh"

# _resolve_bin <command-name> <fallback-path> — echo a runnable invocation or
# print an install hint to stderr and return 127.
Expand All @@ -34,11 +35,15 @@ _resolve_bin() {
# organism). The former name was `pyauto-pulse` (the back-compat shim has since
# been removed); the canonical command is `pyauto-heart`.
resolve_heart() {
_resolve_bin pyauto-heart "$PYAUTO_ROOT/PyAutoHeart/bin/pyauto-heart"
local checkout
checkout="$(pyauto_repo_path PyAutoHeart "$PYAUTO_ROOT")" || return $?
_resolve_bin pyauto-heart "$checkout/bin/pyauto-heart"
}

resolve_autohands() {
_resolve_bin autohands "$PYAUTO_ROOT/PyAutoHands/bin/autohands"
local checkout
checkout="$(pyauto_repo_path PyAutoHands "$PYAUTO_ROOT")" || return $?
_resolve_bin autohands "$checkout/bin/autohands"
}

# _resolve_dir <env-var-name> <repo-name> — echo the path to a sibling PyAuto
Expand All @@ -54,6 +59,8 @@ _resolve_dir() {
# (organs are typically cloned side by side), so check it first.
local brain_parent
brain_parent="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../.." && pwd)"
c="$(pyauto_repo_path "$repo" "$PYAUTO_ROOT")" || return 1
if [[ -d "$c" ]]; then printf '%s' "$c"; return 0; fi
# $PYAUTO_ROOT already resolves to the checkout parent on a developer box,
# so the old instance-named entry here was redundant as well as wrong
# anywhere else.
Expand Down
197 changes: 197 additions & 0 deletions agents/_repo_paths.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""Repository placement, independent of a workspace's physical layout.

Mind's repos.yaml declares preferred canonical paths. Actual context wins: CI
and task bundles can still place those same repositories side by side. Discovery
stops at checkout boundaries and rejects ambiguity rather than selecting another
checkout silently. Missing optional paths are returned for callers which inspect
partial clones; callers requiring a repository use required=True.
"""
from __future__ import annotations

import argparse
import os
from pathlib import Path, PurePosixPath
import re
import sys


def _name(name: str) -> str:
if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9_.-]+', name) or name in ('.', '..'):
raise ValueError(f'unsafe repository identity: {name!r}')
return name


def _placement(name: str, value: str) -> Path:
if not isinstance(value, str) or '\\' in value:
raise ValueError(f'{name}: invalid repository path: {value!r}')
path = PurePosixPath(value)
if path.is_absolute() or '..' in path.parts or not path.parts or path.name != name:
raise ValueError(f'{name}: unsafe repository path: {value!r}')
if len(path.parts) > 2 or any(p.startswith('.') for p in path.parts[:-1]):
raise ValueError(f'{name}: expected a repository at root or in one family directory: {value!r}')
return Path(*path.parts)


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 = 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])
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()
if raw.startswith(('"', "'")):
quote = raw[0]
end = raw.find(quote, 1)
if end < 0 or (raw[end + 1:].strip() and not raw[end + 1:].strip().startswith('#')):
raise ValueError(f'{current}: invalid path scalar: {raw!r}')
value = raw[1:end]
else:
value = raw.split(' #', 1)[0].strip()
paths[current] = _placement(current, value)
by_path: dict[Path, str] = {}
for name, path in paths.items():
if path in by_path:
raise ValueError(f'duplicate repository placement: {by_path[path]} and {name}')
by_path[path] = name
return paths


def is_checkout(path: Path) -> bool:
return path.is_dir() and (path / '.git').exists()


def _families(root: Path):
if root.is_dir():
for path in sorted(root.iterdir()):
if (path.is_dir() and not path.is_symlink()
and not path.name.startswith('.') and not is_checkout(path)):
yield path


def iter_checkouts(root: Path) -> list[Path]:
"""Actual flat or family checkouts, including symlinked bundle dependencies.

Never recursively search inside a repository (datasets can contain clones).
Each logical identity must have exactly one physical target in this context.
"""
root = Path(root)
if not root.is_dir():
return []
found = [p for p in sorted(root.iterdir()) if is_checkout(p)]
for family in _families(root):
found.extend(p for p in sorted(family.iterdir()) if is_checkout(p))
unique: dict[str, Path] = {}
for path in found:
previous = unique.get(path.name)
if previous is not None and previous.resolve() != path.resolve():
raise ValueError(f'{path.name}: ambiguous checkouts: {previous}, {path}')
unique.setdefault(path.name, path)
return sorted(unique.values(), key=lambda p: p.name)


def repo_path(root: Path, name: str, required: bool = False) -> Path:
"""Locate a repo within the specified context, never a different workspace.

Existing directories remain usable for partial fixtures and bootstrap writes;
only required=True establishes checkout presence, through the .git marker.
Missing paths retain their declared placement for precise error messages.
"""
root = Path(root)
name = _name(name)
declared = manifest_paths(root).get(name, Path(name))
if len(declared.parts) > 1 and (root / declared.parts[0]).is_symlink():
raise ValueError(f'{name}: repository family must not be a symlink: {root / declared.parts[0]}')
candidates = [root / name, root / declared]
candidates.extend(family / name for family in _families(root))
existing: dict[Path, Path] = {}
for path in candidates:
if path.is_dir():
existing.setdefault(path.resolve(), path)
if len(existing) > 1:
raise ValueError(f'{name}: ambiguous checkouts: ' + ', '.join(map(str, existing.values())))
result = next(iter(existing.values()), root / declared)
if required and not is_checkout(result):
raise FileNotFoundError(f'{name}: repository checkout missing at {result}')
return result


def repo_paths(root: Path) -> dict[str, Path]:
"""All manifest identities, retaining missing paths so coverage cannot shrink."""
return {name: repo_path(root, name) for name in manifest_paths(Path(root))}


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 = 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)
return [repo_path(root, name) for name in names]


def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest='command', required=True)
one = commands.add_parser('path')
one.add_argument('name')
one.add_argument('--required', action='store_true')
for cmd in (one, commands.add_parser('list'), commands.add_parser('pythonpath')):
cmd.add_argument('--root', type=Path, default=Path(os.environ.get('PYAUTO_ROOT', '.')))
args = parser.parse_args(argv)
try:
if args.command == 'path':
print(repo_path(args.root, args.name, args.required))
elif args.command == 'pythonpath':
print(os.pathsep.join(str(p) for p in package_paths(args.root) if p.is_dir()))
else:
for path in iter_checkouts(args.root):
print(f'{path.name}\t{path}')
except (ValueError, OSError) as error:
print(f'repository lookup: {error}', file=sys.stderr)
return 2
return 0


if __name__ == '__main__':
raise SystemExit(main())
6 changes: 5 additions & 1 deletion agents/conductors/batch/_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,10 @@
import subprocess
from pathlib import Path

import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from _repo_paths import repo_path # noqa: E402

BRAIN = Path(__file__).resolve().parents[3]
WORKTREE_SH = BRAIN / "bin" / "worktree.sh"

Expand Down Expand Up @@ -217,7 +221,7 @@ def ensure_root(slot: str, repo_dirs: list, notes: list):
return None
return root
for name in repo_dirs:
if (root / name / ".git").exists():
if (repo_path(root, name) / ".git").exists():
continue
proc = _worktree_sh("worktree_add_repo", slot, name)
if proc.returncode != 0:
Expand Down
11 changes: 6 additions & 5 deletions agents/conductors/clone/_clone.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
# failing.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import _pyauto_root # noqa: E402
from _repo_paths import repo_path, iter_checkouts # noqa: E402

PYAUTO_ROOT = _pyauto_root.pyauto_root()

Expand Down Expand Up @@ -203,7 +204,7 @@ def fail(code, msg):


def repo_root(name):
path = PYAUTO_ROOT / name
path = repo_path(PYAUTO_ROOT, name)
if not (path / ".git").exists():
fail(4, f"repo '{name}' not checked out at {path}")
return path
Expand Down Expand Up @@ -343,7 +344,7 @@ def build_decision(args):
ws = workspace_shape(workspace_root_)
if not ws["start_here"] and "start_here" not in " ".join(ws["script_dirs"]):
risks.append("workspace has no scripts/start_here.py — weak front-door signal")
if (PYAUTO_ROOT / target).exists():
if (repo_path(PYAUTO_ROOT, target)).exists():
risks.append(f"target '{target}' already exists locally — name collision")

return {
Expand Down Expand Up @@ -415,7 +416,7 @@ def reference_library(reference_name):
derived from its name (e.g. autolens_assistant -> autolens, PyAutoLens)."""
package = reference_name.replace("_assistant", "")
want = f"pyauto{package[4:]}" if package.startswith("auto") else None
for child in sorted(PYAUTO_ROOT.iterdir()):
for child in sorted(set(iter_checkouts(PYAUTO_ROOT)) | set(PYAUTO_ROOT.iterdir())):
if child.is_dir() and child.name.lower() == want:
return package, child.name
fail(4, f"cannot resolve the reference's library repo for '{reference_name}'")
Expand Down Expand Up @@ -556,7 +557,7 @@ def apply_seed(args, decision):
plan_path = Path(tempfile.mkstemp(prefix="clone_plan_", suffix=".json")[1])
plan_path.write_text(json.dumps(plan, indent=2))

seed_script = PYAUTO_ROOT / "PyAutoHands" / "autohands" / "clone_seed.py"
seed_script = repo_path(PYAUTO_ROOT, "PyAutoHands") / "autohands" / "clone_seed.py"
if not seed_script.exists():
fail(4, f"Build primitive not found: {seed_script}")
cmd = [sys.executable, str(seed_script), str(plan_path)]
Expand Down Expand Up @@ -634,7 +635,7 @@ def discover_targets(reference_name):
"""Sibling assistants checked out beside the reference."""
return sorted(
child.name
for child in PYAUTO_ROOT.iterdir()
for child in (set(iter_checkouts(PYAUTO_ROOT)) | set(PYAUTO_ROOT.iterdir()))
if child.is_dir()
and child.name.endswith("_assistant")
and child.name != reference_name
Expand Down
7 changes: 6 additions & 1 deletion agents/conductors/hygiene/_hygiene_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@
from dataclasses import asdict, dataclass
from pathlib import Path

import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from _repo_paths import iter_checkouts # noqa: E402


TRIPLE_QUOTE = re.compile(r"(?i)^[ruf]*(?:\"\"\"|''')")

Expand All @@ -36,7 +40,8 @@ class ParseError:

def repository_paths(root: Path) -> list[Path]:
"""Return user-facing ``*_workspace`` and ``HowTo*`` repositories."""
candidates = [*root.glob("*_workspace"), *root.glob("HowTo*")]
candidates = [*iter_checkouts(root), *root.glob("*_workspace"), *root.glob("HowTo*")]
candidates = [p for p in candidates if p.name.endswith("_workspace") or p.name.startswith("HowTo")]
return sorted(
{path.resolve() for path in candidates if (path / "scripts").is_dir()},
key=lambda path: path.name.lower(),
Expand Down
7 changes: 6 additions & 1 deletion agents/conductors/hygiene/_hygiene_escapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
from dataclasses import asdict, dataclass
from pathlib import Path

import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from _repo_paths import iter_checkouts # noqa: E402

SKIP_PARTS = {".git", "__pycache__", "build", "dist", ".ipynb_checkpoints"}
# A newline in a string value is ordinary text, not evidence of a mangled macro.
CONTROL_EXCEPT_NEWLINE = "\n"
Expand All @@ -59,7 +63,8 @@ class ParseError:

def repository_paths(root: Path) -> list[Path]:
"""Return user-facing ``*_workspace`` and ``HowTo*`` repositories."""
candidates = [*root.glob("*_workspace"), *root.glob("HowTo*")]
candidates = [*iter_checkouts(root), *root.glob("*_workspace"), *root.glob("HowTo*")]
candidates = [p for p in candidates if p.name.endswith("_workspace") or p.name.startswith("HowTo")]
return sorted(
{path.resolve() for path in candidates if (path / "scripts").is_dir()},
key=lambda path: path.name.lower(),
Expand Down
6 changes: 5 additions & 1 deletion agents/conductors/hygiene/_hygiene_extras.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@
import tomllib
from pathlib import Path

import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from _repo_paths import iter_checkouts # noqa: E402

# The extra mode=release installs for every library, and therefore the coverage
# mode=smoke is expected to match.
RELEASE_EXTRA = "optional"
Expand Down Expand Up @@ -97,7 +101,7 @@ def libraries(root: Path) -> dict[str, tuple[str, dict]]:
return {}

found: dict[str, tuple[str, dict]] = {}
for checkout in sorted(p for p in root.iterdir() if p.is_dir()):
for checkout in sorted(p for p in (set(iter_checkouts(root)) | set(root.iterdir())) if p.is_dir()):
pyproject = checkout / "pyproject.toml"
try:
data = tomllib.loads(pyproject.read_text())
Expand Down
6 changes: 5 additions & 1 deletion agents/conductors/hygiene/_hygiene_optdeps.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@
import warnings
from pathlib import Path

import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from _repo_paths import repo_path # noqa: E402

# Workspace prose blocks contain LaTeX (\sigma, \epsilon, ...), so parsing them
# emits a SyntaxWarning per occurrence. That is the scanned repo's business, not
# a signal from this scan, and it would bury the report.
Expand Down Expand Up @@ -87,7 +91,7 @@ def unguarded(root: Path) -> list[dict]:
findings: list[dict] = []

for name in WORKSPACES:
workspace = root / name
workspace = repo_path(root, name)
if not (workspace / ".git").exists():
continue

Expand Down
Loading
Loading