fix(adopt): decide the adapter path by content too

The rule that a knowledge file's format comes from validating it, never from
the path it occupies, was applied to `kdb/kdb.yaml` and stopped there. The
first branch of _plan_knowledge declared `ops/knowledge.yaml` the entrypoint
without ever looking at its assessed action, so a repository holding a
non-conformant file at the adapter path was adopted with the contract pointing
straight at something that fails the KnowledgeBase schema -- the same defect,
one path over, with the same consequence: it surfaces only at verify and gets
repaired by hand outside the approved plan hash. assess had the answer all
along and build_plan discarded it.

Choosing the free canonical slot makes several legacy sources reachable at
once, so the generated index registers all of them rather than the first;
indexing one and dropping the rest in silence would be a new instance of the
omission runbook 11.1 exists to prevent. That also implements the table's last
row, which had no branch until now.

When both canonical paths hold non-conformant files there is no free slot and
neither occupant may be overwritten, so adoption refuses to plan. The plan
schema is closed and carries no findings field, which leaves nowhere to record
a decision left unresolved -- the same reason malformed markers raise instead
of being guessed at.

- gate the adapter branch on the assessed action, not on the file existing
- give each indexed document an id derived from its own path
- add ADOPT_KNOWLEDGE_UNRESOLVED for the dead end, and document it
- bind the four previously untested rows of 11.1 to the parametrized table

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Alexander Baranov
2026-08-24 22:56:50 +03:00
co-authored by Claude Opus 5
parent 1974155281
commit 6c6dfb6fb6
3 changed files with 162 additions and 42 deletions
+10 -2
View File
@@ -362,9 +362,16 @@ Plan MUST содержать rendered file contents или exact patch для к
| `kdb/kdb.yaml` уже соответствует Stewardship | использовать без переписывания |
| legacy KDB находится в другом path | создать `kdb/kdb.yaml` как небольшой index/adapter |
| legacy/custom KDB уже занимает `kdb/kdb.yaml` | создать `ops/knowledge.yaml` и указать его в contract |
| несколько knowledge sources | index с topics/documents и явным authority |
| `ops/knowledge.yaml` уже соответствует Stewardship | использовать без переписывания; занятый `kdb/kdb.yaml` — preserve и forbid |
| legacy/custom файл занимает `ops/knowledge.yaml`, а `kdb/kdb.yaml` свободен | создать `kdb/kdb.yaml` как index; занятый adapter path — preserve и forbid |
| оба canonical path заняты non-conformant файлами | отказать в `plan` с `ADOPT_KNOWLEDGE_UNRESOLVED` |
| несколько knowledge sources | index с topics/documents и явным authority; регистрируются **все** источники |
Выбор между второй и четвёртой строкой определяется **валидацией содержимого** против schema `KnowledgeBase`, а не расположением файла. Файл не является conformant KDB только потому, что лежит в каноническом path: ранняя реализация делала именно это допущение и в результате указывала contract на файл, не проходящий schema, что обнаруживалось только на `verify`.
Выбор строки определяется **валидацией содержимого** против schema `KnowledgeBase`, а не расположением файла. Файл не является conformant KDB только потому, что лежит в каноническом path: ранняя реализация делала именно это допущение и в результате указывала contract на файл, не проходящий schema, что обнаруживалось только на `verify`.
Это правило распространяется на `ops/knowledge.yaml` ровно так же, как на `kdb/kdb.yaml`. Adapter path — это место, куда adoption **кладёт** сгенерированный index, а не доказательство того, что лежащий там файл им является.
Последняя строка — тупик, а не выбор по умолчанию. Свободного canonical path под conformant index не остаётся, а перезапись любого из двух занятых противоречит разделу 3; schema `adoption-plan` закрыта и поля findings не имеет, поэтому записать нерешённое решение в план некуда. Adoption отказывается планировать и оставляет разрешение конфликта владельцу.
Сгенерированный index создаётся с пустым `topics`. Какие секции legacy source заслуживают отдельного intent — решение владельца, а не вывод инструмента: adoption регистрирует документ и оставляет routing на осознанный следующий шаг.
@@ -583,6 +590,7 @@ findingCodes:
ADOPT_PATH_OUTSIDE_REPOSITORY: blocker
ADOPT_FORBIDDEN_PATH: blocker
ADOPT_MANAGED_BLOCK_MALFORMED: blocker
ADOPT_KNOWLEDGE_UNRESOLVED: blocker
ADOPT_PRESERVED_MODIFIED: blocker
ADOPT_DIFF_OUTSIDE_PLAN: warning
ADOPT_REPORT_UNSCOPED: warning
+75 -40
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import fnmatch
import os
import re
from pathlib import Path
from typing import Any
@@ -398,26 +399,43 @@ This repository is adopted at L1. Before reading anything else:
)
def _knowledge_base(name: str, legacy_path: str | None) -> dict[str, Any]:
"""A minimal KnowledgeBase, indexing ``legacy_path`` when one was found.
def _legacy_document_id(rel_path: str) -> str:
"""A schema-valid document id derived from the legacy file's own path.
Distinct ids matter as soon as more than one legacy source is indexed: the
KnowledgeBase schema constrains ids to ``^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$``,
so a single hardcoded id could only ever register one document.
"""
stem = rel_path.rsplit(".", 1)[0] if "." in Path(rel_path).name else rel_path
slug = re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-")
return f"legacy-{slug}" if slug else "legacy-knowledge-base"
def _knowledge_base(name: str, legacy_paths: list[str]) -> dict[str, Any]:
"""A minimal KnowledgeBase, indexing every legacy source that was found.
Takes a list rather than a single path because the last row of runbook 11.1
-- several knowledge sources -- becomes reachable as soon as a canonical
path is free while both a root ``kdb.yaml`` and a non-conformant
``ops/knowledge.yaml`` exist. Registering one and dropping the other in
silence would repeat the omission this table exists to prevent.
Topics stay empty on purpose: which sections of a legacy file matter is a
judgement call the tool cannot make, so adoption registers the document and
leaves routing to be authored deliberately afterwards.
"""
documents: list[dict[str, Any]] = []
if legacy_path:
documents.append(
{
"id": "legacy-knowledge-base",
"title": "Existing knowledge base",
"role": "reference",
"path": legacy_path,
"mediaType": "application/yaml",
"authority": "local-canonical",
"status": "verified",
}
)
documents: list[dict[str, Any]] = [
{
"id": _legacy_document_id(legacy_path),
"title": f"Existing knowledge base ({legacy_path})",
"role": "reference",
"path": legacy_path,
"mediaType": "application/yaml",
"authority": "local-canonical",
"status": "verified",
}
for legacy_path in legacy_paths
]
return {
"apiVersion": API_VERSION,
"kind": "KnowledgeBase",
@@ -450,44 +468,61 @@ def _plan_knowledge(
adapter = entries.get("ops/knowledge.yaml")
root_legacy = entries.get("kdb.yaml")
if adapter is not None:
changes.append({"action": "preserve", "path": "ops/knowledge.yaml", "ownership": "repository"})
def conformant(entry: dict[str, Any] | None) -> bool:
return entry is not None and entry["action"] == "keep-or-validate"
def keep(rel: str, *, forbid: bool) -> None:
changes.append({"action": "preserve", "path": rel, "ownership": "repository"})
if forbid:
forbidden.append(rel)
if conformant(adapter):
keep("ops/knowledge.yaml", forbid=False)
if canonical is not None:
changes.append({"action": "preserve", "path": "kdb/kdb.yaml", "ownership": "repository"})
forbidden.append("kdb/kdb.yaml")
keep("kdb/kdb.yaml", forbid=True)
return "ops/knowledge.yaml", changes, forbidden
if canonical is not None and canonical["action"] == "keep-or-validate":
changes.append({"action": "preserve", "path": "kdb/kdb.yaml", "ownership": "repository"})
if conformant(canonical):
keep("kdb/kdb.yaml", forbid=False)
if adapter is not None:
keep("ops/knowledge.yaml", forbid=True)
return "kdb/kdb.yaml", changes, forbidden
if canonical is not None:
changes.append({"action": "preserve", "path": "kdb/kdb.yaml", "ownership": "repository"})
forbidden.append("kdb/kdb.yaml")
changes.append(
{
"action": "create",
"path": "ops/knowledge.yaml",
"ownership": "stewardship",
"reason": "Compatibility index; kdb/kdb.yaml holds a non-conformant knowledge base",
"content": io.yaml_text(_knowledge_base(confirmed_name, "kdb/kdb.yaml")),
}
if canonical is not None and adapter is not None:
# Both canonical slots hold knowledge bases that fail the schema.
# Overwriting either is precisely what adoption promises not to do, and
# the plan schema carries no field in which to record a decision left
# unresolved -- so refuse, rather than emit a contract whose entrypoint
# cannot validate and only fails later, at `verify`.
raise AdoptionError(
"ADOPT_KNOWLEDGE_UNRESOLVED",
"kdb/kdb.yaml and ops/knowledge.yaml both hold non-conformant knowledge bases; "
"neither may be overwritten and no canonical path is free for a generated index",
)
return "ops/knowledge.yaml", changes, forbidden
legacy_path = root_legacy["path"] if root_legacy is not None else None
if legacy_path:
forbidden.append(legacy_path)
# At most one canonical path is occupied here, so the other is free to hold
# the generated index; everything that was already there becomes a document
# it registers rather than a file adoption rewrites.
target = "ops/knowledge.yaml" if canonical is not None else "kdb/kdb.yaml"
legacy_paths: list[str] = []
for entry in (canonical, adapter, root_legacy):
if entry is None:
continue
legacy_paths.append(entry["path"])
keep(entry["path"], forbid=True)
changes.append(
{
"action": "create",
"path": "kdb/kdb.yaml",
"path": target,
"ownership": "stewardship",
"reason": "Compatibility index for legacy knowledge base" if legacy_path else "Minimal KDB",
"content": io.yaml_text(_knowledge_base(confirmed_name, legacy_path)),
"reason": (
"Compatibility index for legacy knowledge base" if legacy_paths else "Minimal KDB"
),
"content": io.yaml_text(_knowledge_base(confirmed_name, legacy_paths)),
}
)
return "kdb/kdb.yaml", changes, forbidden
return target, changes, forbidden
def build_plan(
+77
View File
@@ -67,6 +67,30 @@ def _contract(plan):
{"ops/knowledge.yaml": "create", "kdb/kdb.yaml": "preserve"},
id="legacy-occupying-canonical-path-gets-an-adapter",
),
pytest.param(
{"ops/knowledge.yaml": CONFORMANT_KDB},
"ops/knowledge.yaml",
{"ops/knowledge.yaml": "preserve"},
id="conformant-adapter-is-kept",
),
pytest.param(
{"ops/knowledge.yaml": LEGACY_KDB},
"kdb/kdb.yaml",
{"kdb/kdb.yaml": "create", "ops/knowledge.yaml": "preserve"},
id="legacy-occupying-adapter-path-is-not-the-entrypoint",
),
pytest.param(
{"kdb/kdb.yaml": LEGACY_KDB, "ops/knowledge.yaml": CONFORMANT_KDB},
"ops/knowledge.yaml",
{"ops/knowledge.yaml": "preserve", "kdb/kdb.yaml": "preserve"},
id="conformant-adapter-wins-over-legacy-canonical",
),
pytest.param(
{"kdb/kdb.yaml": CONFORMANT_KDB, "ops/knowledge.yaml": LEGACY_KDB},
"kdb/kdb.yaml",
{"kdb/kdb.yaml": "preserve", "ops/knowledge.yaml": "preserve"},
id="conformant-canonical-wins-over-legacy-adapter",
),
],
)
def test_knowledge_compatibility_table(synthetic_repo, files, expected_entrypoint, expected_actions):
@@ -99,6 +123,59 @@ def test_generated_adapter_registers_the_legacy_file_and_validates(synthetic_rep
assert "kdb/kdb.yaml" in plan["forbiddenChanges"]
def test_adapter_path_is_not_evidence_of_format(synthetic_repo):
"""The same misreading as `kdb/kdb.yaml`, one path over.
`ops/knowledge.yaml` is where adoption *puts* a generated index; a file
already sitting there is not one until it validates. Declaring it the
entrypoint regardless produced a contract that failed the KnowledgeBase
schema and only surfaced at `verify`.
"""
repo = synthetic_repo({**BASE, "ops/knowledge.yaml": LEGACY_KDB})
assessment, plan = _plan_for(repo)
entry = next(e for e in assessment["knowledge"] if e["path"] == "ops/knowledge.yaml")
assert entry["action"] == "wrap"
assert _contract(plan)["spec"]["knowledge"]["entrypoint"] == "kdb/kdb.yaml"
assert "ops/knowledge.yaml" in plan["forbiddenChanges"]
index = next(c for c in plan["changes"] if c["path"] == "kdb/kdb.yaml")
document = load_yaml_text(index["content"])
assert validate_against_kind("KnowledgeBase", document) == []
assert document["spec"]["documents"][0]["path"] == "ops/knowledge.yaml"
def test_several_knowledge_sources_are_all_registered(synthetic_repo):
"""Runbook 11.1, last row: index every source, with an id per document."""
repo = synthetic_repo(
{**BASE, "ops/knowledge.yaml": LEGACY_KDB, "kdb.yaml": LEGACY_KDB}
)
_, plan = _plan_for(repo)
index = next(c for c in plan["changes"] if c["path"] == "kdb/kdb.yaml")
document = load_yaml_text(index["content"])
assert validate_against_kind("KnowledgeBase", document) == []
indexed = {d["path"] for d in document["spec"]["documents"]}
assert indexed == {"ops/knowledge.yaml", "kdb.yaml"}
ids = [d["id"] for d in document["spec"]["documents"]]
assert len(set(ids)) == len(ids)
for path in indexed:
assert path in plan["forbiddenChanges"]
def test_both_canonical_paths_occupied_refuses_to_plan(synthetic_repo):
"""No canonical path is free, and neither occupant may be overwritten."""
repo = synthetic_repo(
{**BASE, "kdb/kdb.yaml": LEGACY_KDB, "ops/knowledge.yaml": LEGACY_KDB}
)
assessment = adoption.assess(repo)
with pytest.raises(adoption.AdoptionError) as excinfo:
adoption.build_plan(repo, assessment, confirmed_name="sample")
assert excinfo.value.code == "ADOPT_KNOWLEDGE_UNRESOLVED"
# --- runbook 11.2: agent entrypoints ----------------------------------------
@pytest.mark.parametrize(