Files
repoctl/src/stewardship/io.py
T
Alexander BaranovandClaude Sonnet 5 96d4d08230 feat: implement repoctl L1 core (models, schemas, validate, discover, context, init, adopt)
Adds the repository-stewardship Python package (src/stewardship) with:
- JSON Schemas (Draft 2020-12) for RepositoryContract, KnowledgeBase, CatalogIndex,
  ContextBundle, BootstrapPlan, AdoptionAssessment/Plan/Report, user config and the
  repoctl-result envelope.
- Safe YAML I/O, path confinement, deterministic clock and canonical-JSON hashing.
- validate: schema, ID uniqueness, path safety, KDB references, freshness, secret-shaped
  fields, shell-string detection, and Markdown frontmatter/fence/link checks.
- discover/CatalogIndex with deterministic sorting and duplicate-name detection.
- describe (contract-only) and context (intent-scoped ContextBundle with budgeted
  materialization and --strict truncation).
- init: plan-then-apply bootstrap with SHA-256 plan-hash approval, no fake domain
  artifacts, bundled Claude skills.
- adopt: assess/plan/apply/verify overlay workflow per docs/adoption-runbook.md,
  preserving legacy content roots and KDB, with baseline-hash re-check and rollback.
- argparse-based `repoctl` CLI with human/yaml/json output and spec exit codes.
- pytest suite (39 tests) covering positive/negative fixtures, discovery, context,
  bootstrap and adoption (including LXD- and Antivirus-shaped legacy layouts).

Managed with uv (.venv), ruff clean, mypy --strict clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 14:57:34 +03:00

87 lines
2.4 KiB
Python

from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Any
from ruamel.yaml import YAML
from ruamel.yaml.error import YAMLError
class ResourceError(ValueError):
"""Input cannot be safely parsed as an expected resource."""
def _safe_yaml() -> YAML:
yaml = YAML(typ="safe", pure=True)
yaml.allow_duplicate_keys = False
return yaml
def _output_yaml() -> YAML:
yaml = YAML()
yaml.default_flow_style = False
yaml.allow_unicode = True
yaml.indent(mapping=2, sequence=4, offset=2)
return yaml
def load_yaml(path: Path) -> Any:
try:
with path.open("r", encoding="utf-8") as handle:
return _safe_yaml().load(handle)
except (OSError, YAMLError) as exc:
raise ResourceError(f"Cannot parse YAML: {exc}") from exc
def yaml_text(data: Any) -> str:
from io import StringIO
stream = StringIO()
_output_yaml().dump(data, stream)
return stream.getvalue()
def primitive(value: Any) -> Any:
if isinstance(value, dict):
return {str(key): primitive(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [primitive(item) for item in value]
if hasattr(value, "isoformat") and not isinstance(value, str):
return value.isoformat()
return value
def canonical_json(value: Any) -> str:
return json.dumps(primitive(value), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def sha256(value: Any) -> str:
return "sha256:" + hashlib.sha256(canonical_json(value).encode("utf-8")).hexdigest()
def file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def write_text_atomic(path: Path, content: str) -> None:
"""Write ``content`` to ``path`` via a temp file in the same directory, then replace.
Uses ``\\n`` line endings unconditionally so hashes and diffs are platform independent.
"""
path.parent.mkdir(parents=True, exist_ok=True)
normalized = content.replace("\r\n", "\n")
tmp = path.parent / f".{path.name}.repoctl-tmp"
with tmp.open("w", encoding="utf-8", newline="\n") as handle:
handle.write(normalized)
tmp.replace(path)
def dump_json(value: Any) -> str:
return json.dumps(primitive(value), ensure_ascii=False, indent=2, sort_keys=False) + "\n"