fix(discover): a contract inside another repository is not a repository
`tests/fixtures/positive/` holds four valid contracts. Running `discover` over the machine's Git directory returned six repositories: two real ones and those four, with nothing in the output to tell them apart. Any catalog-wide question -- which repositories lack an owner, which are behind the template version -- was answered over a set that included this project's own test material. A repository is the root of a git repository. A directory holding ops/contract.yaml somewhere inside another repository's working tree is that repository's content: a fixture, an example, a vendored copy. Skip it, and say so with CATALOG_NESTED_CONTRACT_SKIPPED rather than silently, so a genuinely misplaced contract is still visible. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
d7a506a5d9
commit
c21ffceef3
+1
-1
@@ -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.
|
- `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.
|
- `describe` читает только contract и никогда не загружает KDB.
|
||||||
- `context` по умолчанию возвращает компактный bundle: topic data, document metadata, selectors/headings, operations и content roots. `--materialize` извлекает только явно выбранные Markdown-разделы или ограниченные YAML key paths; сеть не используется.
|
- `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`.
|
- Budget считается в UTF-8 bytes только для materialized content. Элементы сортируются детерминированно; усечение всегда отражается warning и при `--strict` даёт exit `4`.
|
||||||
|
|||||||
@@ -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`).
|
Обходит указанный каталог, находит все `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` — паспорт одного репозитория
|
### `describe` — паспорт одного репозитория
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from typing import Any
|
|||||||
from .clock import DEFAULT_CLOCK
|
from .clock import DEFAULT_CLOCK
|
||||||
from .constants import CONTRACT_PATH
|
from .constants import CONTRACT_PATH
|
||||||
from .io import file_sha256
|
from .io import file_sha256
|
||||||
|
from .paths import find_repository_root
|
||||||
from .types import Finding, sort_findings
|
from .types import Finding, sort_findings
|
||||||
from .validate import validate_repository
|
from .validate import validate_repository
|
||||||
|
|
||||||
@@ -60,6 +61,22 @@ def _iter_contract_dirs(root: Path) -> Iterator[Path]:
|
|||||||
stack.append(entry)
|
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]]:
|
def discover_repositories(roots: list[Path]) -> tuple[list[DiscoveredRepository], list[Finding]]:
|
||||||
findings: list[Finding] = []
|
findings: list[Finding] = []
|
||||||
found: list[DiscoveredRepository] = []
|
found: list[DiscoveredRepository] = []
|
||||||
@@ -70,6 +87,22 @@ def discover_repositories(roots: list[Path]) -> tuple[list[DiscoveredRepository]
|
|||||||
if resolved in seen_paths:
|
if resolved in seen_paths:
|
||||||
continue
|
continue
|
||||||
seen_paths.add(resolved)
|
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)
|
validation = validate_repository(repo_dir)
|
||||||
if validation.contract is None:
|
if validation.contract is None:
|
||||||
findings.extend(validation.findings)
|
findings.extend(validation.findings)
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from stewardship.discovery import build_catalog_index
|
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):
|
def test_catalog_finds_all_positive_fixtures_and_is_deterministic(tmp_path, make_repo):
|
||||||
make_repo("positive/infra-lxd")
|
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])
|
_, findings = build_catalog_index([tmp_path])
|
||||||
assert any(f.code == "CATALOG_DUPLICATE_REPOSITORY_NAME" for f in findings)
|
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
|
||||||
|
|||||||
Reference in New Issue
Block a user