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:
Alexander Baranov
2026-08-27 11:53:07 +03:00
co-authored by Claude Opus 5
parent 5b9c97fdcd
commit 8b6c01e942
2 changed files with 106 additions and 29 deletions
+68 -29
View File
@@ -409,33 +409,66 @@ def _proposed_identity(root: Path) -> dict[str, str]:
return {"name": fallback, "source": "directory"} return {"name": fallback, "source": "directory"}
def _repeated_shape_root(root: Path, taken: set[str]) -> dict[str, Any] | None: def _child_directories(parent: Path, taken: set[str], prefix: str = "") -> list[str]:
"""Propose one file-set root for N sibling directories sharing a marker file. """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 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 at, and enumerating twenty of them describes the layout rather than the
content. Runbook 7.2 states the intended shape directly: `path: "."`, content. Runbook 7.2 states the intended shape directly: `kind: file-set`
`kind: file-set`, and a selector. 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( proposed: list[dict[str, Any]] = []
entry.name seen_ids: set[str] = set()
for entry in root.iterdir() parents: list[tuple[Path, str]] = [(root, ".")]
if entry.is_dir() and not entry.name.startswith(".") and entry.name not in taken parents.extend(
(root / name, name) for name in _child_directories(root, taken)
) )
for marker, selector, role in _REPEATED_SHAPE_MARKERS: for parent, rel in parents:
members = [name for name in directories if (root / name / marker).is_file()] prefix = "" if rel == "." else f"{rel}/"
if len(members) < _REPEATED_SHAPE_MIN_SIBLINGS: directories = _child_directories(parent, taken, prefix)
continue for marker, selector, role in _REPEATED_SHAPE_MARKERS:
return { members = [name for name in directories if (parent / name / marker).is_file()]
"id": _slug(role) or "stacks", if len(members) < _REPEATED_SHAPE_MIN_SIBLINGS:
"path": ".", continue
"role": role, identifier = _slug(rel if rel != "." else "", role) or "stacks"
"kind": "file-set", if identifier in seen_ids:
"selector": selector, break
"authority": "source", seen_ids.add(identifier)
"writePolicy": "managed", proposed.append(
} {
return None "id": identifier,
"path": rel,
"role": role,
"kind": "file-set",
"selector": selector,
"authority": "source",
"writePolicy": "managed",
}
)
break
return proposed
def _propose_content_roots(root: Path) -> list[dict[str, Any]]: def _propose_content_roots(root: Path) -> list[dict[str, Any]]:
@@ -477,9 +510,9 @@ def _propose_content_roots(root: Path) -> list[dict[str, Any]]:
proposed.append(entry) proposed.append(entry)
claimed.add(marker) claimed.add(marker)
repeated = _repeated_shape_root(root, claimed) for repeated in _repeated_shape_roots(root, claimed):
if repeated and not any(entry["id"] == repeated["id"] for entry in proposed): if not any(entry["id"] == repeated["id"] for entry in proposed):
proposed.append(repeated) proposed.append(repeated)
return proposed return proposed
@@ -861,10 +894,16 @@ def build_plan(
entry["generatedFrom"] = cr["generatedFrom"] entry["generatedFrom"] = cr["generatedFrom"]
content_roots.append(entry) content_roots.append(entry)
for cr in content_roots: for cr in content_roots:
# A file-set root sits at `.` with a selector; `./**` would forbid the # A file-set root carries a selector instead of owning its directory;
# whole repository, including the paths this plan has to write. # `./**` would forbid the whole repository, including the paths this
if cr.get("selector"): # plan has to write. Per spec 6.2 the selector is read relative to
forbidden.append(cr["selector"]) # `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: else:
forbidden.append(f"{cr['path']}/**") forbidden.append(f"{cr['path']}/**")
+38
View File
@@ -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) 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: def test_defaulted_authority_asks_instead_of_asserting(synthetic_repo) -> None:
repo = synthetic_repo({**BASE, "docs/guide.md": "# G\n"}) repo = synthetic_repo({**BASE, "docs/guide.md": "# G\n"})
assessment = adoption.assess(repo) assessment = adoption.assess(repo)