fix(adopt): find the repeated shape below the root, and forbid the depth it is at
Правило повторяющейся формы искало каталоги-братья только среди прямых детей корня. Репозиторий, группирующий стеки по модели деплоя, держит их в `swarm/<stack>/` — ровно ту раскладку, ради описания которой правило и существует, оно не видело. На Infra/Docker это давало один content root (`docs`) и ни одного упоминания 20 стеков. - `_repeated_shape_root` -> `_repeated_shape_roots`: кандидатами в родители становятся и корень, и каждый его прямой подкаталог; предлагаются ВСЕ подошедшие, потому что `swarm/` и `compose/` — два разных content root, а не конкурс между ними. Идентификатор включает путь, чтобы они не схлопнулись в один `stacks`. - `forbiddenChanges`: селектор по spec 6.2 читается относительно `path`, но подставлялся в запрет как есть. Для корня на глубине это защищало не тот уровень: `swarm/` публиковал бы `*/docker-compose.y*ml`, под который ни один из его файлов не попадает. Теперь путь приклеивается обратно. Тесты: три новых в test_adoption_gates.py — обнаружение под корнем, запрет на верной глубине, два родителя одновременно. Существующий test_two_siblings_are_not_a_repeated_shape продолжает держать порог в 3. 153 passed, mypy strict чист, repoctl validate на самом репозитории success. Пять падений в tests-universal существовали до этого изменения и им не затронуты — это рассинхрон спецификации с owner-гейтом, отдельная задача. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
5b9c97fdcd
commit
8b6c01e942
+58
-19
@@ -409,33 +409,66 @@ def _proposed_identity(root: Path) -> dict[str, str]:
|
||||
return {"name": fallback, "source": "directory"}
|
||||
|
||||
|
||||
def _repeated_shape_root(root: Path, taken: set[str]) -> dict[str, Any] | None:
|
||||
"""Propose one file-set root for N sibling directories sharing a marker file.
|
||||
def _child_directories(parent: Path, taken: set[str], prefix: str = "") -> list[str]:
|
||||
"""Directory names directly under ``parent``, skipping dotdirs and claimed roots."""
|
||||
try:
|
||||
entries = list(parent.iterdir())
|
||||
except OSError:
|
||||
return []
|
||||
return sorted(
|
||||
entry.name
|
||||
for entry in entries
|
||||
if entry.is_dir()
|
||||
and not entry.name.startswith(".")
|
||||
and f"{prefix}{entry.name}" not in taken
|
||||
)
|
||||
|
||||
|
||||
def _repeated_shape_roots(root: Path, taken: set[str]) -> list[dict[str, Any]]:
|
||||
"""Propose a file-set root wherever N sibling directories share a marker file.
|
||||
|
||||
A repository holding a directory per stack has no single directory to point
|
||||
at, and enumerating twenty of them describes the layout rather than the
|
||||
content. Runbook 7.2 states the intended shape directly: `path: "."`,
|
||||
`kind: file-set`, and a selector.
|
||||
content. Runbook 7.2 states the intended shape directly: `kind: file-set`
|
||||
plus a selector, with the selector read relative to `path` (spec 6.2).
|
||||
|
||||
The siblings are not always children of the repository root. A repository
|
||||
that groups its stacks by deployment model keeps them at `swarm/<stack>/`,
|
||||
and searching only the root's own children found nothing there -- the very
|
||||
layout the rule exists to describe. So each direct child directory is also
|
||||
considered as a parent, and every parent that qualifies is proposed, because
|
||||
`swarm/` and `compose/` are two content roots, not a contest between them.
|
||||
"""
|
||||
directories = sorted(
|
||||
entry.name
|
||||
for entry in root.iterdir()
|
||||
if entry.is_dir() and not entry.name.startswith(".") and entry.name not in taken
|
||||
proposed: list[dict[str, Any]] = []
|
||||
seen_ids: set[str] = set()
|
||||
parents: list[tuple[Path, str]] = [(root, ".")]
|
||||
parents.extend(
|
||||
(root / name, name) for name in _child_directories(root, taken)
|
||||
)
|
||||
for parent, rel in parents:
|
||||
prefix = "" if rel == "." else f"{rel}/"
|
||||
directories = _child_directories(parent, taken, prefix)
|
||||
for marker, selector, role in _REPEATED_SHAPE_MARKERS:
|
||||
members = [name for name in directories if (root / name / marker).is_file()]
|
||||
members = [name for name in directories if (parent / name / marker).is_file()]
|
||||
if len(members) < _REPEATED_SHAPE_MIN_SIBLINGS:
|
||||
continue
|
||||
return {
|
||||
"id": _slug(role) or "stacks",
|
||||
"path": ".",
|
||||
identifier = _slug(rel if rel != "." else "", role) or "stacks"
|
||||
if identifier in seen_ids:
|
||||
break
|
||||
seen_ids.add(identifier)
|
||||
proposed.append(
|
||||
{
|
||||
"id": identifier,
|
||||
"path": rel,
|
||||
"role": role,
|
||||
"kind": "file-set",
|
||||
"selector": selector,
|
||||
"authority": "source",
|
||||
"writePolicy": "managed",
|
||||
}
|
||||
return None
|
||||
)
|
||||
break
|
||||
return proposed
|
||||
|
||||
|
||||
def _propose_content_roots(root: Path) -> list[dict[str, Any]]:
|
||||
@@ -477,8 +510,8 @@ def _propose_content_roots(root: Path) -> list[dict[str, Any]]:
|
||||
proposed.append(entry)
|
||||
claimed.add(marker)
|
||||
|
||||
repeated = _repeated_shape_root(root, claimed)
|
||||
if repeated and not any(entry["id"] == repeated["id"] for entry in proposed):
|
||||
for repeated in _repeated_shape_roots(root, claimed):
|
||||
if not any(entry["id"] == repeated["id"] for entry in proposed):
|
||||
proposed.append(repeated)
|
||||
return proposed
|
||||
|
||||
@@ -861,10 +894,16 @@ def build_plan(
|
||||
entry["generatedFrom"] = cr["generatedFrom"]
|
||||
content_roots.append(entry)
|
||||
for cr in content_roots:
|
||||
# A file-set root sits at `.` with a selector; `./**` would forbid the
|
||||
# whole repository, including the paths this plan has to write.
|
||||
if cr.get("selector"):
|
||||
forbidden.append(cr["selector"])
|
||||
# A file-set root carries a selector instead of owning its directory;
|
||||
# `./**` would forbid the whole repository, including the paths this
|
||||
# plan has to write. Per spec 6.2 the selector is read relative to
|
||||
# `path`, so a root below the top level has to be joined back on --
|
||||
# otherwise `swarm/` would publish `*/docker-compose.y*ml` and protect
|
||||
# a depth the files are not at.
|
||||
selector = cr.get("selector")
|
||||
if selector:
|
||||
path = cr["path"]
|
||||
forbidden.append(selector if path == "." else f"{path}/{selector}")
|
||||
else:
|
||||
forbidden.append(f"{cr['path']}/**")
|
||||
|
||||
|
||||
@@ -238,6 +238,44 @@ def test_file_set_root_does_not_forbid_the_whole_repository(synthetic_repo) -> N
|
||||
assert not any(adoption.is_forbidden(path, plan["forbiddenChanges"]) for path in written)
|
||||
|
||||
|
||||
def test_repeated_shape_is_found_below_the_root(synthetic_repo) -> None:
|
||||
"""Stacks grouped by deployment model sit at `swarm/<stack>/`, not at the root."""
|
||||
files = {**BASE}
|
||||
for stack in ("grafana", "loki", "n8n"):
|
||||
files[f"swarm/{stack}/docker-compose.yaml"] = "services: {}\n"
|
||||
repo = synthetic_repo(files)
|
||||
roots = [cr for cr in adoption.assess(repo)["proposedContentRoots"] if cr.get("kind") == "file-set"]
|
||||
assert len(roots) == 1
|
||||
assert roots[0]["path"] == "swarm"
|
||||
assert roots[0]["selector"] == "*/docker-compose.y*ml"
|
||||
|
||||
|
||||
def test_nested_file_set_forbids_the_depth_its_files_are_at(synthetic_repo) -> None:
|
||||
"""The selector is relative to `path`, so the forbidden glob must carry `path`."""
|
||||
files = {**BASE}
|
||||
for stack in ("grafana", "loki", "n8n"):
|
||||
files[f"swarm/{stack}/docker-compose.yaml"] = "services: {}\n"
|
||||
repo = synthetic_repo(files)
|
||||
plan = _owners_plan(repo)
|
||||
assert "swarm/*/docker-compose.y*ml" in plan["forbiddenChanges"]
|
||||
assert "*/docker-compose.y*ml" not in plan["forbiddenChanges"]
|
||||
assert adoption.is_forbidden("swarm/grafana/docker-compose.yaml", plan["forbiddenChanges"])
|
||||
written = {c["path"] for c in plan["changes"] if c["action"] == "create"}
|
||||
assert not any(adoption.is_forbidden(path, plan["forbiddenChanges"]) for path in written)
|
||||
|
||||
|
||||
def test_two_parents_both_repeat_the_shape(synthetic_repo) -> None:
|
||||
"""`swarm/` and `compose/` are two content roots, not a contest between them."""
|
||||
files = {**BASE}
|
||||
for stack in ("grafana", "loki", "n8n"):
|
||||
files[f"swarm/{stack}/docker-compose.yaml"] = "services: {}\n"
|
||||
for stack in ("portainer", "proxy", "agent"):
|
||||
files[f"compose/{stack}/docker-compose.yaml"] = "services: {}\n"
|
||||
repo = synthetic_repo(files)
|
||||
roots = [cr for cr in adoption.assess(repo)["proposedContentRoots"] if cr.get("kind") == "file-set"]
|
||||
assert {cr["path"] for cr in roots} == {"swarm", "compose"}
|
||||
assert len({cr["id"] for cr in roots}) == 2
|
||||
|
||||
def test_defaulted_authority_asks_instead_of_asserting(synthetic_repo) -> None:
|
||||
repo = synthetic_repo({**BASE, "docs/guide.md": "# G\n"})
|
||||
assessment = adoption.assess(repo)
|
||||
|
||||
Reference in New Issue
Block a user