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>
This commit is contained in:
Alexander Baranov
2026-08-24 14:57:34 +03:00
co-authored by Claude Sonnet 5
parent 9a39b8a941
commit 96d4d08230
75 changed files with 4259 additions and 0 deletions
+235
View File
@@ -0,0 +1,235 @@
"""`repoctl init`: plan-then-apply bootstrap of a new repository.
Content roots are declared in the contract but their directories are not created —
this repository's self-hosting rule forbids placeholder directories and fictional
domain artifacts. `init` never commits, pushes or creates a remote.
"""
from __future__ import annotations
import subprocess
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from . import io
from .clock import DEFAULT_CLOCK
from .constants import API_VERSION
from .skills_content import (
REPO_HANDOFF_SKILL,
REPOSITORY_ADOPTION_SKILL,
REPOSITORY_BOOTSTRAP_SKILL,
)
TEMPLATE_IDS = {
"infrastructure-config": "repository.infrastructure",
"service-config": "repository.service",
"software": "repository.software",
"project": "repository.project",
}
TEMPLATE_VERSION = "0.1.0"
_DEFAULT_CONTENT_ROOTS: dict[str, list[dict[str, str]]] = {
"infrastructure-config": [
{"id": "desired-state", "role": "desired", "path": "desired", "kind": "directory", "authority": "source", "writePolicy": "managed"},
{"id": "inventory", "role": "inventory", "path": "inventory", "kind": "directory", "authority": "source", "writePolicy": "managed"},
],
"service-config": [
{"id": "policies", "role": "policies", "path": "policies", "kind": "directory", "authority": "source", "writePolicy": "managed"},
{"id": "acceptance", "role": "acceptance", "path": "acceptance", "kind": "directory", "authority": "source", "writePolicy": "managed"},
],
"software": [
{"id": "source", "role": "source", "path": "src", "kind": "directory", "authority": "source", "writePolicy": "managed"},
{"id": "tests", "role": "tests", "path": "tests", "kind": "directory", "authority": "source", "writePolicy": "managed"},
],
"project": [
{"id": "deliverables", "role": "deliverables", "path": "deliverables", "kind": "directory", "authority": "source", "writePolicy": "managed"},
{"id": "decisions", "role": "decisions", "path": "decisions", "kind": "directory", "authority": "source", "writePolicy": "managed"},
],
}
SSH_RECOMMENDATION = (
"Consider a repository-scoped SSH deploy key: read-only by default, private key kept "
"outside Git, and scoped to only this repository. repoctl does not generate or store "
"the key; use the gen-ssh-eddsa workflow or your Git host's deploy key feature."
)
@dataclass
class BootstrapAnswers:
name: str
title: str
owners: list[str]
repository_type: str
lifecycle: str = "active"
namespace: str | None = None
access: str | None = None
summary: str | None = None
content_roots: list[dict[str, str]] | None = None
git_init: bool = False
@staticmethod
def from_mapping(data: dict[str, Any]) -> BootstrapAnswers:
return BootstrapAnswers(
name=data["name"],
title=data.get("title", data["name"]),
owners=list(data.get("owners", [])),
repository_type=data["repositoryType"],
lifecycle=data.get("lifecycle", "active"),
namespace=data.get("namespace"),
access=data.get("access"),
summary=data.get("summary"),
content_roots=data.get("contentRoots"),
git_init=bool(data.get("gitInit", False)),
)
def _render_contract(answers: BootstrapAnswers) -> str:
content_roots = answers.content_roots if answers.content_roots is not None else _DEFAULT_CONTENT_ROOTS.get(answers.repository_type, [])
contract: dict[str, Any] = {
"apiVersion": API_VERSION,
"kind": "RepositoryContract",
"metadata": {
"name": answers.name,
"title": answers.title,
"owners": answers.owners,
},
"spec": {
"summary": answers.summary or f"{answers.title} repository",
"repository": {
"type": answers.repository_type,
"lifecycle": answers.lifecycle,
**({"namespace": answers.namespace} if answers.namespace else {}),
**({"access": answers.access} if answers.access else {}),
},
"template": {
"id": TEMPLATE_IDS[answers.repository_type],
"version": TEMPLATE_VERSION,
"source": "repo:repository-stewardship",
"answersRef": "ops/template-answers.yaml",
"mode": "generated",
},
"agent": {"primary": "CLAUDE.md", "portable": "AGENTS.md"},
"knowledge": {"entrypoint": "kdb/kdb.yaml"},
"contentRoots": content_roots,
},
}
return io.yaml_text(contract)
def _render_kdb(answers: BootstrapAnswers) -> str:
kdb = {
"apiVersion": API_VERSION,
"kind": "KnowledgeBase",
"metadata": {"name": f"{answers.name}-kdb", "title": f"{answers.title} knowledge base"},
"spec": {
"repository": f"repo:{answers.name}",
"defaultLanguage": "en",
"topics": [],
"documents": [],
},
}
return io.yaml_text(kdb)
def render_agents_md(answers: BootstrapAnswers) -> str:
return f"""# Repository instructions
## Purpose
{answers.summary or answers.title}
## Start here
1. Read `ops/contract.yaml` to identify the repository and authoritative content roots.
2. Read the small index in `kdb/kdb.yaml`.
3. Match the task to an exact topic intent.
4. Open only the documents and headings named by that topic's `data.readHints`.
## Safety
- Do not run destructive operations without an approved plan.
- Do not place secrets, tokens or private keys in this repository.
- Use `repoctl validate --repo .` before proposing changes to contract or KDB.
"""
def render_claude_md() -> str:
return """# CLAUDE.md
@AGENTS.md
## Claude-specific guidance
Use `repoctl context` before loading detailed knowledge or running repository operations.
"""
def _render_template_answers(answers: BootstrapAnswers) -> str:
return io.yaml_text(
{
"schema": "stewardship/template-answers@0.1",
"templateId": TEMPLATE_IDS[answers.repository_type],
"templateVersion": TEMPLATE_VERSION,
"name": answers.name,
"title": answers.title,
"owners": answers.owners,
"repositoryType": answers.repository_type,
"lifecycle": answers.lifecycle,
}
)
def _render_gitignore() -> str:
return "ops/runs/\n.venv/\n__pycache__/\n"
def build_bootstrap_plan(answers: BootstrapAnswers) -> dict[str, Any]:
contract_text = _render_contract(answers)
files = [
{"path": "ops/contract.yaml", "content": contract_text},
{"path": "kdb/kdb.yaml", "content": _render_kdb(answers)},
{"path": "AGENTS.md", "content": render_agents_md(answers)},
{"path": "CLAUDE.md", "content": render_claude_md()},
{"path": "ops/template-answers.yaml", "content": _render_template_answers(answers)},
{"path": ".gitignore", "content": _render_gitignore()},
{"path": ".claude/skills/repository-bootstrap/SKILL.md", "content": REPOSITORY_BOOTSTRAP_SKILL},
{"path": ".claude/skills/repository-adoption/SKILL.md", "content": REPOSITORY_ADOPTION_SKILL},
{"path": ".claude/skills/repo-handoff/SKILL.md", "content": REPO_HANDOFF_SKILL},
]
plan: dict[str, Any] = {
"schema": "stewardship/bootstrap-plan@0.1",
"repository": answers.name,
"repositoryType": answers.repository_type,
"createdAt": DEFAULT_CLOCK.now_iso(),
"gitInit": answers.git_init,
"files": files,
"recommendations": [SSH_RECOMMENDATION],
}
plan_hash = io.sha256({k: v for k, v in plan.items() if k != "planHash"})
plan["planHash"] = plan_hash
return plan
def apply_bootstrap_plan(root: Path, plan: dict[str, Any], approve_hash: str) -> list[str]:
expected_hash = io.sha256({k: v for k, v in plan.items() if k != "planHash"})
if expected_hash != plan.get("planHash"):
raise ValueError("Plan hash does not match plan content; re-plan before apply")
if approve_hash != plan["planHash"]:
raise ValueError("Approval hash does not match plan hash")
written: list[str] = []
for file_entry in plan["files"]:
target = root / file_entry["path"]
if target.exists():
raise FileExistsError(f"Refusing to overwrite existing file: {file_entry['path']}")
for file_entry in plan["files"]:
target = root / file_entry["path"]
io.write_text_atomic(target, file_entry["content"])
written.append(file_entry["path"])
if plan.get("gitInit") and not (root / ".git").exists():
subprocess.run(["git", "init"], cwd=root, check=True, capture_output=True)
return written