Files
repoctl/src/stewardship/cli.py
T
Alexander Baranov 86dd79c8ae test: add spec-driven universal CLI suite; fix context strict + path confinement bugs
- tests-universal/ drives repoctl only as a subprocess CLI, asserting
  directly against docs/specification.md (envelope, exit codes 0-5,
  validation rules MVP, security invariants) so the same suite can judge
  any conforming implementation, including the sibling codex/repoctl-l1
  branch built independently from the same baseline.
- Running it surfaced two real bugs, both fixed:
  - `context --strict` only checked budget truncation, never stale or
    missing referenced documents, despite specification.md 19.2 defining
    exit 4 as "stale or incomplete context" (not just truncation).
  - `paths.confined_path` crashed with an unhandled WinError2 when a
    referenced path's parent directory also didn't exist, because it
    resolved a single non-existent parent with strict=True instead of
    walking up to the nearest existing ancestor.
2026-08-24 15:38:49 +03:00

352 lines
14 KiB
Python

"""`repoctl`: thin argparse CLI adapter over the stewardship library.
Exit codes (specification.md 19.2): 0 success, 1 validation/operation failure,
2 invalid invocation/input, 3 repository not found, 4 stale/incomplete strict
context, 5 approval required or denied.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from typing import Any
from . import adoption, bootstrap, config, discovery, io
from .constants import CONTRACT_PATH
from .context import build_context
from .paths import find_repository_root
from .render import build_envelope, emit
from .schema_loader import validate_against_kind
from .types import Finding
from .validate import validate_repository
EXIT_SUCCESS = 0
EXIT_VALIDATION_FAILURE = 1
EXIT_INVALID_INPUT = 2
EXIT_NOT_FOUND = 3
EXIT_STRICT_INCOMPLETE = 4
EXIT_APPROVAL = 5
class CliError(Exception):
def __init__(self, message: str, exit_code: int = EXIT_INVALID_INPUT):
super().__init__(message)
self.exit_code = exit_code
def _resolve_repo(repo_arg: str | None, roots: list[str] | None) -> Path:
if repo_arg:
candidate = Path(repo_arg).expanduser()
if candidate.exists():
root = find_repository_root(candidate)
if root is None:
raise CliError(f"No .git ancestor found for {candidate}", EXIT_NOT_FOUND)
return root
found, _ = discovery.discover_repositories(config.resolve_roots(roots))
for repo in found:
name = (repo.contract.get("metadata") or {}).get("name")
if name == repo_arg:
return repo.path
raise CliError(f"Repository not found: {repo_arg}", EXIT_NOT_FOUND)
root = find_repository_root(Path.cwd())
if root is None:
raise CliError("No .git ancestor found from current directory", EXIT_NOT_FOUND)
return root
def _write(envelope: dict[str, Any], output: str) -> None:
emit(envelope, output)
def cmd_config(args: argparse.Namespace) -> int:
if args.config_action == "show":
data = config.load_config()
_write(build_envelope("config show", "success", data, []), args.output)
return EXIT_SUCCESS
if args.config_action == "add-root":
data = config.add_root(args.path)
_write(build_envelope("config add-root", "success", data, []), args.output)
return EXIT_SUCCESS
if args.config_action == "remove-root":
data = config.remove_root(args.path)
_write(build_envelope("config remove-root", "success", data, []), args.output)
return EXIT_SUCCESS
raise CliError("Unknown config action")
def cmd_validate(args: argparse.Namespace) -> int:
root = _resolve_repo(args.repo, args.root)
result = validate_repository(root)
outcome = "success" if result.ok else "failure"
data = {"repository": str(root), "valid": result.ok}
_write(build_envelope("validate", outcome, data, result.findings), args.output)
return EXIT_SUCCESS if result.ok else EXIT_VALIDATION_FAILURE
def cmd_discover(args: argparse.Namespace) -> int:
roots = config.resolve_roots(args.root)
catalog, findings = discovery.build_catalog_index(roots)
has_error = any(f.severity == "error" for f in findings)
_write(build_envelope("discover", "failure" if has_error else "success", catalog, findings), args.output)
return EXIT_VALIDATION_FAILURE if has_error else EXIT_SUCCESS
def cmd_describe(args: argparse.Namespace) -> int:
root = _resolve_repo(args.repo, args.root)
contract_path = root / CONTRACT_PATH
if not contract_path.exists():
raise CliError(f"{CONTRACT_PATH} not found under {root}", EXIT_NOT_FOUND)
contract = io.load_yaml(contract_path)
errors = validate_against_kind("RepositoryContract", contract) if isinstance(contract, dict) else ["not a mapping"]
findings = [Finding("error", "CONTRACT_SCHEMA_INVALID", e) for e in errors]
outcome = "failure" if findings else "success"
_write(build_envelope("describe", outcome, contract, findings), args.output)
return EXIT_VALIDATION_FAILURE if findings else EXIT_SUCCESS
def cmd_context(args: argparse.Namespace) -> int:
root = _resolve_repo(args.repo, args.root)
result = build_context(
root,
args.intent,
include_related=args.include_related,
materialize=args.materialize,
budget_bytes=args.budget_bytes,
strict=args.strict,
)
data = dict(result.bundle)
if result.materialized:
data["spec"] = dict(data["spec"])
data["spec"]["materializedContent"] = [
{"document": m.document_id, "path": m.path, "bytes": m.bytes_used, "content": m.content}
for m in result.materialized
]
findings = [
Finding(w.split(":", 2)[0], w.split(":", 2)[1], w.split(":", 2)[2])
for w in result.bundle["spec"]["warnings"]
]
outcome = "success"
exit_code = EXIT_SUCCESS
if (result.truncated or result.incomplete) and args.strict:
outcome = "failure"
exit_code = EXIT_STRICT_INCOMPLETE
_write(build_envelope("context", outcome, data, findings), args.output)
return exit_code
def cmd_init(args: argparse.Namespace) -> int:
repo_path = Path(args.repo).expanduser()
if args.apply:
if not args.plan or not args.approve:
raise CliError("--apply requires --plan and --approve", EXIT_INVALID_INPUT)
plan = io.load_yaml(Path(args.plan))
repo_path.mkdir(parents=True, exist_ok=True)
try:
written = bootstrap.apply_bootstrap_plan(repo_path, plan, args.approve)
except ValueError as exc:
_write(build_envelope("init apply", "failure", None, [Finding("error", "APPROVAL_FAILED", str(exc))]), args.output)
return EXIT_APPROVAL
except FileExistsError as exc:
_write(build_envelope("init apply", "failure", None, [Finding("error", "ADOPT_PATH_COLLISION", str(exc))]), args.output)
return EXIT_VALIDATION_FAILURE
_write(build_envelope("init apply", "success", {"written": written}, []), args.output)
return EXIT_SUCCESS
if args.answers:
answers_data = io.load_yaml(Path(args.answers))
else:
answers_data = {}
if args.name:
answers_data["name"] = args.name
if args.type:
answers_data["repositoryType"] = args.type
if args.title:
answers_data["title"] = args.title
if args.owner:
answers_data["owners"] = list(args.owner)
if args.lifecycle:
answers_data["lifecycle"] = args.lifecycle
if args.git_init:
answers_data["gitInit"] = True
missing = [f for f in ("name", "repositoryType") if f not in answers_data]
if missing:
raise CliError(f"Missing required answers: {', '.join(missing)}", EXIT_INVALID_INPUT)
answers = bootstrap.BootstrapAnswers.from_mapping(answers_data)
plan = bootstrap.build_bootstrap_plan(answers)
_write(build_envelope("init plan", "success", plan, []), args.output)
return EXIT_SUCCESS
def cmd_adopt(args: argparse.Namespace) -> int:
repo_path = Path(args.repo).expanduser()
if not repo_path.exists():
raise CliError(f"Path does not exist: {repo_path}", EXIT_NOT_FOUND)
if args.mode == "assess":
result = adoption.assess(repo_path)
findings = [
Finding(f["severity"], f["code"], f.get("message", f["code"]), path=f.get("path"))
for f in result["findings"]
]
blocker = any(f.severity == "error" for f in findings)
_write(build_envelope("adopt assess", "failure" if blocker else "success", result, findings), args.output)
return EXIT_VALIDATION_FAILURE if blocker else EXIT_SUCCESS
if args.mode == "plan":
assessment = adoption.assess(repo_path)
if args.answers:
answers = io.load_yaml(Path(args.answers))
else:
answers = {}
name = answers.get("name") or repo_path.name.lower()
plan = adoption.build_plan(
repo_path,
assessment,
confirmed_name=name,
confirmed_title=answers.get("title"),
confirmed_owners=answers.get("owners"),
confirmed_lifecycle=answers.get("lifecycle", "active"),
strategy=args.strategy,
)
_write(build_envelope("adopt plan", "success", plan, []), args.output)
return EXIT_SUCCESS
if args.mode == "apply":
if not args.plan or not args.approve:
raise CliError("--mode apply requires --plan and --approve", EXIT_INVALID_INPUT)
plan = io.load_yaml(Path(args.plan))
try:
written = adoption.apply_plan(repo_path, plan, args.approve)
except ValueError as exc:
code = "APPROVAL_FAILED" if "Approval" in str(exc) or "hash" in str(exc) else "ADOPT_BASELINE_CHANGED"
_write(build_envelope("adopt apply", "failure", None, [Finding("error", code, str(exc))]), args.output)
return EXIT_APPROVAL
except FileExistsError as exc:
_write(build_envelope("adopt apply", "failure", None, [Finding("error", "ADOPT_PATH_COLLISION", str(exc))]), args.output)
return EXIT_VALIDATION_FAILURE
_write(build_envelope("adopt apply", "success", {"written": written}, []), args.output)
return EXIT_SUCCESS
if args.mode == "verify":
verify_plan = io.load_yaml(Path(args.plan)) if args.plan else None
report = adoption.verify(repo_path, verify_plan)
outcome = "failure" if report["outcome"] == "fail" else "success"
_write(build_envelope("adopt verify", outcome, report, []), args.output)
return EXIT_VALIDATION_FAILURE if report["outcome"] == "fail" else EXIT_SUCCESS
raise CliError(f"Unknown adopt mode: {args.mode}", EXIT_INVALID_INPUT)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="repoctl", description="Repository Stewardship CLI")
sub = parser.add_subparsers(dest="command", required=True)
def add_common(p: argparse.ArgumentParser) -> None:
p.add_argument("--output", choices=["human", "yaml", "json"], default="human")
p_config = sub.add_parser("config")
add_common(p_config)
config_sub = p_config.add_subparsers(dest="config_action", required=True)
config_sub.add_parser("show")
p_add_root = config_sub.add_parser("add-root")
p_add_root.add_argument("path")
p_remove_root = config_sub.add_parser("remove-root")
p_remove_root.add_argument("path")
p_config.set_defaults(func=cmd_config)
p_validate = sub.add_parser("validate")
add_common(p_validate)
p_validate.add_argument("--repo")
p_validate.add_argument("--root", action="append")
p_validate.set_defaults(func=cmd_validate)
p_discover = sub.add_parser("discover")
add_common(p_discover)
p_discover.add_argument("--root", action="append")
p_discover.set_defaults(func=cmd_discover)
p_describe = sub.add_parser("describe")
add_common(p_describe)
p_describe.add_argument("--repo")
p_describe.add_argument("--root", action="append")
p_describe.set_defaults(func=cmd_describe)
p_context = sub.add_parser("context")
add_common(p_context)
p_context.add_argument("--repo")
p_context.add_argument("--root", action="append")
p_context.add_argument("--intent", required=True)
p_context.add_argument("--include-related", action="store_true")
p_context.add_argument("--materialize", action="store_true")
p_context.add_argument("--budget-bytes", type=int, default=None)
p_context.add_argument("--strict", action="store_true")
p_context.set_defaults(func=cmd_context)
p_init = sub.add_parser("init")
add_common(p_init)
p_init.add_argument("--repo", required=True)
p_init.add_argument("--answers")
p_init.add_argument("--name")
p_init.add_argument("--type", dest="type", choices=["infrastructure-config", "service-config", "software", "project"])
p_init.add_argument("--title")
p_init.add_argument("--owner", action="append")
p_init.add_argument("--lifecycle")
p_init.add_argument("--git-init", action="store_true")
p_init.add_argument("--no-git-init", dest="git_init", action="store_false")
p_init.set_defaults(git_init=None)
p_init.add_argument("--apply", action="store_true")
p_init.add_argument("--plan")
p_init.add_argument("--approve")
p_init.set_defaults(func=cmd_init)
p_adopt = sub.add_parser("adopt")
add_common(p_adopt)
p_adopt.add_argument("--repo", required=True)
p_adopt.add_argument("--mode", required=True, choices=["assess", "plan", "apply", "verify"])
p_adopt.add_argument("--answers")
p_adopt.add_argument("--strategy", default="overlay", choices=["overlay", "normalize"])
p_adopt.add_argument("--recipe")
p_adopt.add_argument("--plan")
p_adopt.add_argument("--approve")
p_adopt.set_defaults(func=cmd_adopt)
return parser
def _force_utf8_streams() -> None:
"""Force UTF-8 stdout/stderr regardless of the host locale/console codepage.
Machine output (YAML/JSON) must be reliably UTF-8 for downstream parsers; on
Windows, sys.stdout otherwise defaults to the console codepage when not attached
to a UTF-8 terminal, which can corrupt or fail to decode non-ASCII content.
"""
for stream in (sys.stdout, sys.stderr):
reconfigure = getattr(stream, "reconfigure", None)
if callable(reconfigure):
try:
reconfigure(encoding="utf-8")
except (ValueError, OSError):
pass
def main(argv: list[str] | None = None) -> int:
_force_utf8_streams()
parser = build_parser()
args = parser.parse_args(argv)
try:
result: int = args.func(args)
return result
except CliError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return exc.exit_code
except Exception as exc: # noqa: BLE001 - top-level CLI safety net
print(f"ERROR: {exc}", file=sys.stderr)
return EXIT_VALIDATION_FAILURE
if __name__ == "__main__":
raise SystemExit(main())