fix(adopt,init): decide by evidence, refuse instead of defaulting

Running a full assess -> plan -> apply -> verify against Infra/LXD and
Infra/Docker in throwaway worktrees, and a bootstrap into a scratch
directory, surfaced the same two mistakes repeated across both commands:
a shape was read where evidence was available, and a missing answer became
a silent default rather than a refusal.

adopt:

- classify secret-shaped paths by content, not by filename. A live
  credential blocks; a file tracked against the repository's own ignore
  rules and a name-only match are warnings; findings name keys, never
  values. In Infra/Docker this turned 14 false blockers into 2 true ones
  and surfaced 14 files committed despite `**/.env`.
- carry assess findings into the plan and refuse while an error-severity
  finding is unresolved. An owner may accept one through
  `acknowledgedFindings` with a reason; the acknowledgement enters the
  plan and therefore planHash, so approval covers it.
- derive metadata.name from the git remote instead of the clone directory,
  and refuse to plan without a confirmed owner (runbook section 9).
- propose content roots from the whole content vocabulary rather than the
  winning type's markers, and recognise N sibling directories sharing a
  marker file as one file-set root with a selector, as runbook 7.2 already
  specified. Authority defaulted rather than derived now asks.

init: apply the guards adopt already had. Answers are validated against
the vocabularies that already existed in constants (name, type, lifecycle,
access) so init can no longer create a repository that fails its own
validate; owners are required; a directory that already holds the planned
paths is refused at plan time and pointed at adopt; and every path from a
plan is confined before the first byte is written -- init wrote outside
the repository from an edited plan.

validate: mask fenced blocks and inline code spans before scanning for
Markdown links. A PowerShell snippet in Infra/Docker's CLAUDE.md parsed as
a link and kept validate red for a reason unrelated to the repository.

paths: allow "." as a whole content-root path, never as a segment, so the
file-set root runbook 7.2 describes can be declared.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Alexander Baranov
2026-08-25 18:10:59 +03:00
co-authored by Claude Opus 5
parent 693211cee9
commit 1ab02a257c
19 changed files with 1177 additions and 88 deletions
+12 -4
View File
@@ -38,10 +38,13 @@ repoctl describe --repo NAME|PATH [--root PATH ...]
repoctl context --repo NAME|PATH --intent INTENT
[--include-related] [--materialize]
[--budget-bytes N] [--strict]
repoctl init --repo PATH [--answers FILE] [--git-init|--no-git-init]
repoctl init --repo PATH --name NAME --type TYPE --owner NAME
[--answers FILE] [--title T] [--lifecycle L]
[--git-init|--no-git-init]
repoctl init --repo PATH --apply --plan FILE --approve SHA256
repoctl adopt --repo PATH --mode assess|plan|apply|verify
[--answers FILE] [--strategy overlay|normalize]
[--answers FILE] [--owner NAME] [--type TYPE]
[--strategy overlay|normalize]
[--recipe ID] [--plan FILE] [--approve SHA256]
```
@@ -56,6 +59,8 @@ repoctl adopt --repo PATH --mode assess|plan|apply|verify
- Budget считается в UTF-8 bytes только для materialized content. Элементы сортируются детерминированно; усечение всегда отражается warning и при `--strict` даёт exit `4`.
- Для хешей ресурсов используется canonical JSON representation, а не платформенные окончания строк. Время передаётся через clock abstraction, чтобы тестовые результаты были воспроизводимыми.
`init` проверяет ответы до сборки плана (`name` против `ID_PATTERN`, type/lifecycle/access против enum, обязательный owner), отказывается планировать в каталог, где уже лежит любой из создаваемых путей, и confine'ит каждый путь плана при записи. Отказы — конверты с кодами `INIT_*`, а не строки в stderr.
`init`:
- собирает ответы через CLI или YAML answers file; CLI имеет приоритет;
@@ -75,7 +80,10 @@ repoctl adopt --repo PATH --mode assess|plan|apply|verify
- для legacy root `kdb.yaml` предлагает небольшой `kdb/kdb.yaml` adapter;
- если legacy KDB уже занимает `kdb/kdb.yaml`, предлагает `ops/knowledge.yaml`;
- существующие skills, handlers, KDB и agent instructions не переписывает;
- tracked secret является blocker; untracked secret-shaped paths показываются path-only без содержимого;
- secret-shaped путь классифицируется по содержимому: живой credential — blocker, tracked вопреки ignore-правилам и совпадение только по имени — warnings, untracked — info; наружу выходят имена ключей, не значения;
- `plan` требует подтверждённого owner и отказывается строиться при неразрешённой находке severity `error`; принятие находки явное, с причиной, и входит в `planHash`;
- имя репозитория выводится из remote, а не из имени каталога клона;
- content roots предлагаются по всему словарю содержимого; репозиторий из однотипных каталогов объявляется одним `file-set` корнем с селектором;
- `documents-to-content-root` выполняется только как явно выбранная normalization recipe с rename map, conservative Markdown/frontmatter/YAML rewrites и collision checks;
- apply повторно проверяет baseline и plan hash, пишет только перечисленные paths, использует временные файлы и восстанавливает исходное состояние при локальной ошибке;
- никогда не делает commit, push, clone или external operation.
@@ -109,7 +117,7 @@ repoctl adopt --repo PATH --mode assess|plan|apply|verify
- Antivirus fixture сохраняет custom `kdb/kdb.yaml` и предлагает `ops/knowledge.yaml`.
- Normalization tests отложены вместе с самой normalization: `--strategy normalize` и recipes не реализованы и не предлагаются CLI.
- Самопроверка: `repoctl validate --repo .`, unit/integration tests, Ruff, strict typing и сборка wheel с проверкой наличия schemas/templates.
- `Infra/LXD` используется только для read-only `assess` и `plan`; Git status до и после должен совпасть.
- `Infra/LXD` и `Infra/Docker` используются только для read-only `assess` и `plan`, либо для полного цикла в одноразовом `git worktree`; Git status рабочего дерева до и после должен совпасть.
- `Services/Antivirus` — пилот Wave 1, adopted по решению владельца. `apply` к нему выполняется осознанно: через утверждённый `planHash`, с предварительным прогоном на копии и последующим `verify --plan`. Остальные реальные репозитории остаются read-only до расширения wave.
## Зафиксированные ограничения