diff --git a/docs/PLAN.md b/docs/PLAN.md index 5355959..354f01d 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -53,7 +53,7 @@ repoctl adopt --repo PATH --mode assess|plan|apply|verify ## Поведение инструментов - `validate` проверяет schemas, IDs, ссылки, content roots, path/symlink confinement, freshness, provenance, secret-shaped поля, operations без shell strings, Markdown links/frontmatter/YAML fences, сбалансированные code fences и статический синтаксис Mermaid. -- `discover` ищет `ops/contract.yaml`, не следует по symlink/junction, пропускает `.git`, virtual environments и dependency caches, строит детерминированный `CatalogIndex`, capability/requirement/binding relations и выявляет дубликаты repository ID. +- `discover` ищет `ops/contract.yaml`, не следует по symlink/junction, пропускает `.git`, virtual environments и dependency caches, не считает репозиторием контракт, лежащий внутри рабочего дерева другого репозитория (fixture, example, vendored copy — это его содержимое, а не равноправный сосед; такой путь сообщается как `CATALOG_NESTED_CONTRACT_SKIPPED`), строит детерминированный `CatalogIndex`, capability/requirement/binding relations и выявляет дубликаты repository ID. - `describe` читает только contract и никогда не загружает KDB. - `context` по умолчанию возвращает компактный bundle: topic data, document metadata, selectors/headings, operations и content roots. `--materialize` извлекает только явно выбранные Markdown-разделы или ограниченные YAML key paths; сеть не используется. - Budget считается в UTF-8 bytes только для materialized content. Элементы сортируются детерминированно; усечение всегда отражается warning и при `--strict` даёт exit `4`. diff --git a/docs/repoctl.md b/docs/repoctl.md index a68d1e7..9c2cb75 100644 --- a/docs/repoctl.md +++ b/docs/repoctl.md @@ -78,6 +78,8 @@ repoctl discover --root C:/Users/example/Git --output json Обходит указанный каталог, находит все `ops/contract.yaml`, строит `CatalogIndex` — детерминированно отсортированный список репозиториев с их типом, lifecycle и hash контракта. Не следует по symlink, пропускает `.git`, `.venv`, `node_modules` и подобные. Дублирующиеся имена репозиториев — ошибка (`CATALOG_REPOSITORY_DUPLICATE`). +Репозиторием считается корень git-репозитория. Контракт, лежащий внутри рабочего дерева другого репозитория — fixture, example, vendored copy — это его содержимое, а не равноправный сосед: такой путь в каталог не попадает и сообщается как `CATALOG_NESTED_CONTRACT_SKIPPED` (severity `info`). + ### `describe` — паспорт одного репозитория ```bash diff --git a/src/stewardship/discovery.py b/src/stewardship/discovery.py index dfcf564..d6333bc 100644 --- a/src/stewardship/discovery.py +++ b/src/stewardship/discovery.py @@ -10,6 +10,7 @@ from typing import Any from .clock import DEFAULT_CLOCK from .constants import CONTRACT_PATH from .io import file_sha256 +from .paths import find_repository_root from .types import Finding, sort_findings from .validate import validate_repository @@ -60,6 +61,22 @@ def _iter_contract_dirs(root: Path) -> Iterator[Path]: stack.append(entry) +def _owning_repository(contract_dir: Path) -> Path | None: + """Return the repository this contract belongs to, when it is not its own. + + A repository is the root of a git repository. A directory holding + `ops/contract.yaml` somewhere inside another repository's working tree is + material of that repository -- a fixture, an example, a vendored copy -- + and counting it as a peer pollutes every catalog-wide question. Returns + None when the directory is its own repository root, or when no git + repository owns it at all. + """ + root = find_repository_root(contract_dir) + if root is None or root == contract_dir: + return None + return root + + def discover_repositories(roots: list[Path]) -> tuple[list[DiscoveredRepository], list[Finding]]: findings: list[Finding] = [] found: list[DiscoveredRepository] = [] @@ -70,6 +87,22 @@ def discover_repositories(roots: list[Path]) -> tuple[list[DiscoveredRepository] if resolved in seen_paths: continue seen_paths.add(resolved) + owner = _owning_repository(resolved) + if owner is not None: + # A contract inside another repository's tree is that + # repository's content, not a repository of its own: this + # project's own test fixtures carry four valid contracts and + # appeared in the catalog beside production repositories, + # indistinguishable from them. + findings.append( + Finding( + "info", + "CATALOG_NESTED_CONTRACT_SKIPPED", + f"Contract belongs to {owner.as_posix()} rather than being its own repository", + path=resolved.as_posix(), + ) + ) + continue validation = validate_repository(repo_dir) if validation.contract is None: findings.extend(validation.findings) diff --git a/tests/test_discovery.py b/tests/test_discovery.py index 2d370bb..2d07511 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -1,7 +1,11 @@ from __future__ import annotations +from pathlib import Path + from stewardship.discovery import build_catalog_index +FIXTURES = Path(__file__).parent / "fixtures" + def test_catalog_finds_all_positive_fixtures_and_is_deterministic(tmp_path, make_repo): make_repo("positive/infra-lxd") @@ -62,3 +66,28 @@ def test_catalog_detects_duplicate_repository_name(tmp_path, make_repo): _, findings = build_catalog_index([tmp_path]) assert any(f.code == "CATALOG_DUPLICATE_REPOSITORY_NAME" for f in findings) + + +def test_a_contract_inside_another_repository_is_not_a_repository(tmp_path, make_repo) -> None: + """A fixture, example or vendored copy is content, not a peer. + + This project's own `tests/fixtures/positive/` holds four valid contracts. + They appeared in the catalog beside production repositories and were + indistinguishable from them, which corrupts every catalog-wide question. + """ + outer = make_repo("positive/project-example") + nested = outer / "examples" / "vendored" + (nested / "ops").mkdir(parents=True) + (nested / "ops" / "contract.yaml").write_text( + (FIXTURES / "positive" / "software-example" / "ops" / "contract.yaml").read_text( + encoding="utf-8" + ), + encoding="utf-8", + ) + + index, findings = build_catalog_index([outer]) + refs = {entry["ref"] for entry in index["spec"]["repositories"]} + assert refs == {"repo:example-project"} + skipped = [f for f in findings if f.code == "CATALOG_NESTED_CONTRACT_SKIPPED"] + assert len(skipped) == 1 + assert "vendored" in skipped[0].path