Author SHA1 Message Date
Alexander BaranovandClaude Opus 5 c10df0e3af feat(cli): add repoctl kdb, the one command whose human output is content
Обзор базы знаний жил как `python -m stewardship.kdb_table` - работало, но не
как остальной инструмент. Теперь это обычная подкоманда:

    repoctl kdb --repo .

Вписана в контракт, а не рядом с ним: `--output json|yaml` возвращает штатный
конверт с `stewardship/knowledge-overview@0.1` внутри, находки уходят в stderr,
коды возврата прежние (0, и 3 при отсутствии базы знаний).

Одно осознанное отличие от прочих команд: `--output human` печатает саму
таблицу, а не строку статуса. Для `emit` это не исключение - параметр
`human_renderer` был предусмотрен и до сих пор не использовался. Вопрос «что в
базе знаний» отвечается содержимым; строка «kdb: success» на него не отвечает.
Таблица идёт в stdout, поэтому `repoctl kdb > kdb.md` даёт чистый markdown.

Точка входа берётся из `spec.knowledge.entrypoint` контракта с откатом на
`kdb/kdb.yaml` - репозиторий, держащий базу в другом месте, не будет объявлен
не имеющим её.

Скилл kdb-table переписан на команду вместо вызова модуля. docs/repoctl.md
получил раздел. Спецификацию править не пришлось: закрытого перечня команд она
не содержит.

Тесты: три на CLI (таблица в stdout и находки в stderr, конверт в json, отказ с
кодом 3), плюс прежние два на разбор entrypoint. 159 passed, mypy strict чист.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 13:07:36 +03:00
Alexander BaranovandClaude Opus 5 39c7da3eb1 feat(kdb-table): render a knowledge base as a table a human can read
База знаний машиночитаема и длинна: чтобы ответить «что там вообще есть»,
приходилось читать файл целиком. Теперь есть отдельный вывод для человека.

- `stewardship.kdb_table` - модуль, а не файл рядом со скиллом: `skills install`
  переносит только SKILL.md, поэтому скрипт в каталоге скилла не доехал бы до
  репозитория, куда скилл поставили. Как модуль он доступен везде, где есть
  repoctl: `python -m stewardship.kdb_table --repo <path>`.
- Путь к базе знаний не угадывается: берётся `spec.knowledge.entrypoint` из
  `ops/contract.yaml` целевого репозитория, с откатом на `kdb/kdb.yaml`. Значит
  работает на любом adopted-репозитории, а не только там, где путь канонический.
- Репозиторий без базы знаний получает одну строку и нулевой код возврата,
  а не трейсбек.
- Читает через `stewardship.io`, то есть тем же ruamel, что и остальной код -
  новой зависимости нет.
- Вне командной поверхности CLI намеренно: контракт `repoctl` - машинный вывод,
  а это пособие для чтения. Спецификацию менять не пришлось.

Скилл `kdb-table` зарегистрирован в SKILLS, поэтому расходится штатным
`repoctl skills install` вместе с остальными тремя. Он тонкий: зовёт модуль,
печатает markdown как есть и отправляет за контекстом под задачу в
`repoctl context --intent`.

Проверено: 156 тестов, mypy strict чист, validate на самом репозитории success.
Два новых теста закрепляют чтение entrypoint из контракта (включая нестандартный
путь) и внятный отказ при отсутствии базы.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 12:23:32 +03:00
Alexander BaranovandClaude Opus 5 c607a14f8b fix(markdown): decode a percent-encoded link before checking that it exists
Каждый markdown-рендерер процентно кодирует ссылку на файл с пробелами или
не-ASCII в имени. Проверка сравнивала закодированную форму с файловой системой и
объявляла отсутствующим файл, который лежит на месте:

  MARKDOWN_LINK_TARGET_MISSING: GitLab%2017.10.0%20%E2%86%92%20Docker%20Migration.md

Ложное срабатывание блокировало `validate` на репозитории Infra/Docker. Ссылка
декодируется перед резолвом; тест закрепляет и пробел, и то, что настоящая
битая ссылка по-прежнему находится.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 12:16:05 +03:00
Alexander BaranovandClaude Opus 5 8b6c01e942 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>
2026-08-27 11:53:07 +03:00
Alexander BaranovandClaude Opus 5 5b9c97fdcd fix(init): stop the entry point from disabling the command it reaches
A field report from bootstrapping Services/Vault: ~20 CLI calls produced
three productive writes, and four of those calls were deliberate failures
sent only to discover a vocabulary.

The worst of it was self-inflicted and new. `repoctl skills install` is the
documented way to make the bootstrap skill reachable, and it writes the
three skill files -- which `init` then reported as INIT_PATH_COLLISION and
redirected to `adopt`. Every skill-driven bootstrap of an empty repository
was pushed onto the adoption path. The collision check exists to protect
content the tool did not author, and identical bytes are nothing to
protect: a path already holding exactly what the plan would write is no
longer a collision, at plan time or at write time, while a file whose
content differs still is. `init` reports only the files it actually wrote.

`--lifecycle` advertised no choices, so its vocabulary was reachable only
by sending a wrong value and reading the refusal; it now carries `choices`
like `--type` does.

`--answers-template` prints a commented answers file naming every key, its
allowed values and its default. The answers keys are not the flag names
(`--type` sets `repositoryType`) and nothing printed the mapping. It lists
`summary` and `namespace` too, which are cheap to answer once and otherwise
survive as generated placeholders in the contract.

`--repo .` proposed the name `adopted-repository`: `Path(".").name` is the
empty string, so the ordinary way to name the current repository fell
through to the generic fallback. Resolve before deriving.

Both skills gained what the report had to discover by hand: that `--plan`
already unwraps a saved result envelope, and that sibling repositories are
where a naming convention comes from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 14:56:49 +03:00
Alexander BaranovandClaude Opus 5 c80d39cc73 feat(skills): install the agent skills into any repository
The stewardship skills were written by exactly one code path: `init`, which
only runs on a new repository. Adopting an existing one starts from the
repository-adoption skill, and nothing could put that skill there -- so the
entry point to the procedure depended on the operator already having it
from somewhere else. Services/Monitoring carries three domain skills of its
own and no stewardship skill; `adopt` lists `.claude/skills` among its
collision paths and installs nothing.

    repoctl skills install --repo .    # travels with the repository
    repoctl skills install --global    # follows the operator everywhere
    repoctl skills status --repo .

Scope is stated, never guessed: the two answers differ in who ends up with
the skills, and neither is the obvious default.

No plan and no approval hash. That discipline protects a repository's own
content; this writes only tool-owned files, in a fixed subdirectory, whose
content is fully determined by the installed version. The house rule it
does keep is that a write never destroys what it did not author: a skill
whose content differs is reported as SKILLS_MODIFIED and left alone until
`--force` says otherwise, and the check covers every skill before the first
byte is written, so a refusal leaves nothing half-updated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 14:35:38 +03:00
Alexander BaranovandClaude Opus 5 c21ffceef3 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>
2026-08-25 18:17:11 +03:00
Alexander BaranovandClaude Opus 5 d7a506a5d9 chore(contract): classify this repository as software
It was declared `project` when it held only a specification. It now ships
a Python package and a CLI, and its own classifier says so with high
confidence on pyproject.toml and src/. Self-hosting is worth little if the
contract disagrees with what the tool would conclude about the repository.

This also names a gap: a repository crossing from project or research into
software or service is normal, and the model has no operation for it. The
type is a birth attribute, and changing it by hand leaves template.id and
the type's default content roots pointing at the old answer with nothing
to object.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 18:11:25 +03:00
Alexander BaranovandClaude Opus 5 79ea43d5bf fix(skills): sync the distributed adoption skill and pin it to the repo copy
`init` writes .claude/skills/*/SKILL.md into every new repository from the
constants in skills_content, so each skill exists twice: once as the copy
this repository uses, once as the copy it ships. Editing one and not the
other went unnoticed by validate and by every test.

It had already happened. The shipped repository-adoption skill still told
its reader to use `--strategy normalize --recipe documents-to-content-root`
-- an operation the CLI does not offer and CLAUDE.md forbids claiming --
and said nothing about the owner requirement or acknowledged findings.
Every repository bootstrapped since would have received that copy.

Sync both, and add a test that compares each shipped skill against the
checked-in one so the next divergence fails instead of shipping.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 18:11:13 +03:00
Alexander BaranovandClaude Opus 5 1ab02a257c 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>
2026-08-25 18:10:59 +03:00
33 changed files with 2237 additions and 115 deletions
+47
View File
@@ -0,0 +1,47 @@
---
name: kdb-table
description: Show a repository's knowledge base (its KnowledgeBase entrypoint) to a human as a compact Markdown table of topics, intents and documents. Use when asked what is in the kdb, which topics or intents exist, where a topic routes, what can be passed to `repoctl context`, or for an overview of the knowledge base. Read-only.
---
# kdb-table
Thin wrapper. The knowledge base is machine-readable and long: reading the whole
file to answer "what is in there" is the thing this skill exists to avoid.
```bash
repoctl kdb --repo <path>
```
Like every other command it emits a result envelope; `--output human` renders
the table instead of the usual one-line outcome, and findings still go to stderr,
so piping stdout gives clean Markdown. The entrypoint is read from the
repository's own `ops/contract.yaml`
(`spec.knowledge.entrypoint`), falling back to `kdb/kdb.yaml`, so no path needs
to be guessed and the same command works on any adopted repository. A
repository with no knowledge base gets a `KNOWLEDGE_ENTRYPOINT_MISSING` warning
and exit code 3, not a traceback.
Print the Markdown it emits as-is; do not paraphrase it. Two tables:
- **topics**, by descending `priority`: id, declared intents, the documents the
topic routes to, and the top-level keys of its `data` (what facts sit inside);
- **documents**: id, path, role, status. `stale` is marked `(!)` - such a
document is out of date, and `repoctl context` warns about it when it hands
it over.
## When an overview is not what is wanted
This answers "what exists". To get only what a specific task needs, take an
intent from the Intents column and ask the tool instead:
```bash
repoctl context --repo <path> --intent <intent>
```
An unknown intent is answered with the closest known ones, so the table is
mainly for the human - an agent can afford to guess once.
## Out of scope
It neither edits nor validates the knowledge base. Schema conformance is
`repoctl validate --repo <path>`; run that after editing the entrypoint.
+10 -4
View File
@@ -14,14 +14,20 @@ with machine output, and explains findings. It must not duplicate the runbook lo
1. Run `repoctl adopt --repo <path> --mode assess --output json` (read-only). 1. Run `repoctl adopt --repo <path> --mode assess --output json` (read-only).
2. Present the classification, detected content roots, and any `questions` that need 2. Present the classification, detected content roots, and any `questions` that need
owner confirmation. owner confirmation.
3. Run `repoctl adopt --repo <path> --mode plan --output json` once open questions are 3. Run `repoctl adopt --repo <path> --mode plan --owner <owner> --output json` once open
resolved. This is still read-only and returns an `AdoptionPlan` with a `planHash`. questions are resolved. This is still read-only and returns an `AdoptionPlan` with a
`planHash`. `plan` refuses without a confirmed owner, and refuses while `assess` left
an error-severity finding; an owner who accepts one lists it under
`acknowledgedFindings` (with a `reason`) in the `--answers` file.
4. Show the full plan (files created, patched managed blocks, preserved paths, 4. Show the full plan (files created, patched managed blocks, preserved paths,
forbidden changes) before asking for approval. forbidden changes) before asking for approval.
5. Only after explicit approval, run 5. Only after explicit approval, run
`repoctl adopt --repo <path> --mode apply --plan <plan-file> --approve <planHash>`. `repoctl adopt --repo <path> --mode apply --plan <plan-file> --approve <planHash>`.
`--plan` accepts the file exactly as `--output json > plan.json` wrote it: the
result envelope is unwrapped for you, so do not strip it down to `data` by hand.
6. Run `repoctl adopt --repo <path> --mode verify --output json` and report the 6. Run `repoctl adopt --repo <path> --mode verify --output json` and report the
`AdoptionReport`, including any `unresolvedFindings`. `AdoptionReport`, including any `unresolvedFindings`.
Default strategy is `overlay`. Only use `--strategy normalize --recipe The only implemented strategy is `overlay`. Normalization recipes are specified in the
documents-to-content-root` when the owner explicitly asks to reorganize root documents. runbook but not implemented, and the CLI does not offer them: do not describe
`--strategy normalize` or `--recipe` as available.
+12 -4
View File
@@ -10,10 +10,18 @@ rendering or validation here - call the CLI and explain its output.
## Procedure ## Procedure
1. Collect the missing decisions from the user: repository type 1. Run `repoctl init --answers-template > answers.yaml`. It names every key, its
(`infrastructure-config` | `service-config` | `software` | `project`), `metadata.name`, allowed values and its default; the answers keys are not the flag names
`title`, `owners`, `lifecycle`. (`--type` sets `repositoryType`). Fill it in with the user.
2. Run `repoctl init --repo <path> --answers <answers-file> --output json` to obtain a Answer `summary` and `namespace` too: they are cheap now and otherwise stay
as placeholders in the contract.
All values are refused rather than guessed -- `name` must match
`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`, `owners` must be non-empty -- and before
choosing a name, look at the sibling repositories and follow their convention.
If the target already holds `ops/contract.yaml`, this is an existing
repository: use `repository-adoption`, not `init`. Skill files left by
`repoctl skills install` are not a collision.
2. Run `repoctl init --repo <path> --answers answers.yaml --output json` to obtain a
`BootstrapPlan` (this performs no writes). `BootstrapPlan` (this performs no writes).
3. Show the user the planned files and the `planHash`. 3. Show the user the planned files and the `planHash`.
4. Only after explicit approval, run 4. Only after explicit approval, run
+7 -2
View File
@@ -6,8 +6,13 @@ This repository defines Repository Stewardship: harness-neutral contracts, knowl
It now ships an L1 implementation: the `repoctl` CLI (Python package It now ships an L1 implementation: the `repoctl` CLI (Python package
`repository-stewardship`, module `stewardship`, run via `uv run repoctl`) implements `repository-stewardship`, module `stewardship`, run via `uv run repoctl`) implements
`config`, `validate`, `discover`, `describe`, `context`, `init` and `adopt`. Executable `config`, `skills`, `validate`, `discover`, `describe`, `context`, `init` and `adopt`.
`ops/handlers/`, the L2 handler ABI and an MCP server remain planned, not implemented. Executable `ops/handlers/`, the L2 handler ABI and an MCP server remain planned, not
implemented.
To work with another repository, put the skills where its agent looks first:
`uv run repoctl skills install --repo <path>` (or `--global` once, for every
repository). Adoption then starts from the `repository-adoption` skill.
## Start here ## Start here
+1 -1
View File
@@ -27,7 +27,7 @@ approval для любых записей. `ops/handlers/`, execution runner и
| `src/stewardship/schemas/` | JSON Schemas (Draft 2020-12) для всех kinds | | `src/stewardship/schemas/` | JSON Schemas (Draft 2020-12) для всех kinds |
| `tests/` | unit pytest-набор (позитивные, негативные, adoption fixtures) | | `tests/` | unit pytest-набор (позитивные, негативные, adoption fixtures) |
| `tests-universal/` | spec-driven CLI-контрактный набор, независимый от реализации | | `tests-universal/` | spec-driven CLI-контрактный набор, независимый от реализации |
| `.claude/skills/` | три тонких Claude skill-адаптера над `repoctl` | | `.claude/skills/` | четыре тонких Claude skill-адаптера над `repoctl` |
### Установка и запуск ### Установка и запуск
+15 -5
View File
@@ -38,10 +38,15 @@ repoctl describe --repo NAME|PATH [--root PATH ...]
repoctl context --repo NAME|PATH --intent INTENT repoctl context --repo NAME|PATH --intent INTENT
[--include-related] [--materialize] [--include-related] [--materialize]
[--budget-bytes N] [--strict] [--budget-bytes N] [--strict]
repoctl init --repo PATH [--answers FILE] [--git-init|--no-git-init] repoctl skills install --repo PATH | --global [--force]
repoctl skills status --repo PATH | --global
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 init --repo PATH --apply --plan FILE --approve SHA256
repoctl adopt --repo PATH --mode assess|plan|apply|verify 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] [--recipe ID] [--plan FILE] [--approve SHA256]
``` ```
@@ -50,12 +55,14 @@ 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`.
- Для хешей ресурсов используется canonical JSON representation, а не платформенные окончания строк. Время передаётся через clock abstraction, чтобы тестовые результаты были воспроизводимыми. - Для хешей ресурсов используется canonical JSON representation, а не платформенные окончания строк. Время передаётся через clock abstraction, чтобы тестовые результаты были воспроизводимыми.
`init` проверяет ответы до сборки плана (`name` против `ID_PATTERN`, type/lifecycle/access против enum, обязательный owner), отказывается планировать в каталог, где уже лежит любой из создаваемых путей, и confine'ит каждый путь плана при записи. Отказы — конверты с кодами `INIT_*`, а не строки в stderr.
`init`: `init`:
- собирает ответы через CLI или YAML answers file; CLI имеет приоритет; - собирает ответы через CLI или YAML answers file; CLI имеет приоритет;
@@ -75,7 +82,10 @@ repoctl adopt --repo PATH --mode assess|plan|apply|verify
- для legacy root `kdb.yaml` предлагает небольшой `kdb/kdb.yaml` adapter; - для legacy root `kdb.yaml` предлагает небольшой `kdb/kdb.yaml` adapter;
- если legacy KDB уже занимает `kdb/kdb.yaml`, предлагает `ops/knowledge.yaml`; - если legacy KDB уже занимает `kdb/kdb.yaml`, предлагает `ops/knowledge.yaml`;
- существующие skills, handlers, KDB и agent instructions не переписывает; - существующие 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; - `documents-to-content-root` выполняется только как явно выбранная normalization recipe с rename map, conservative Markdown/frontmatter/YAML rewrites и collision checks;
- apply повторно проверяет baseline и plan hash, пишет только перечисленные paths, использует временные файлы и восстанавливает исходное состояние при локальной ошибке; - apply повторно проверяет baseline и plan hash, пишет только перечисленные paths, использует временные файлы и восстанавливает исходное состояние при локальной ошибке;
- никогда не делает commit, push, clone или external operation. - никогда не делает commit, push, clone или external operation.
@@ -109,7 +119,7 @@ repoctl adopt --repo PATH --mode assess|plan|apply|verify
- Antivirus fixture сохраняет custom `kdb/kdb.yaml` и предлагает `ops/knowledge.yaml`. - Antivirus fixture сохраняет custom `kdb/kdb.yaml` и предлагает `ops/knowledge.yaml`.
- Normalization tests отложены вместе с самой normalization: `--strategy normalize` и recipes не реализованы и не предлагаются CLI. - Normalization tests отложены вместе с самой normalization: `--strategy normalize` и recipes не реализованы и не предлагаются CLI.
- Самопроверка: `repoctl validate --repo .`, unit/integration tests, Ruff, strict typing и сборка wheel с проверкой наличия schemas/templates. - Самопроверка: `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. - `Services/Antivirus` — пилот Wave 1, adopted по решению владельца. `apply` к нему выполняется осознанно: через утверждённый `planHash`, с предварительным прогоном на копии и последующим `verify --plan`. Остальные реальные репозитории остаются read-only до расширения wave.
## Зафиксированные ограничения ## Зафиксированные ограничения
+43 -3
View File
@@ -219,7 +219,11 @@ contentRoots:
selector: "*/compose.y*ml" selector: "*/compose.y*ml"
``` ```
Нельзя объявлять mirror как source только потому, что его YAML выглядит полнее. Нельзя объявлять mirror как source только потому, что его YAML выглядит полнее. Когда authority выбрана по умолчанию словаря, а не выведена из пары `generatedFrom`, assess помечает корень `ADOPT_SOURCE_MIRROR_AMBIGUOUS` и спрашивает владельца.
Content roots ищутся по всему словарю содержимого, а не только по маркерам предложенного type: `docs/` числится evidence для `project`, и привязка поиска к победившему типу означала, что в infrastructure-репозитории он не объявлялся никогда. Type отвечает на вопрос «для чего репозиторий», content roots — «что в нём лежит».
Репозиторий из однотипных каталогов (стек на каталог) не имеет одного каталога, на который можно показать, а перечисление двадцати описывает раскладку вместо содержимого. Когда не менее трёх каталогов первого уровня несут общий маркерный файл (`compose.y*ml`, `docker-compose.y*ml`, `Chart.yaml`, `main.tf`, `Dockerfile`), объявляется один `file-set` корень с `path: .` и селектором — форма `docker-stacks` из примера выше. `path: .` допустим только как целый путь content root и никогда как write target.
### 7.3. Найти знания и provenance ### 7.3. Найти знания и provenance
@@ -234,6 +238,8 @@ contentRoots:
- freshness signals; - freshness signals;
- наличие потенциальных secret-shaped paths или keys без вывода values. - наличие потенциальных secret-shaped paths или keys без вывода values.
Содержимое secret-shaped файла читать разрешено — именно чтение отличает credential от документа о credentials, — но наружу выходят только имена ключей. Значения не попадают ни в findings, ни в логи, ни в assessment.
### 7.4. Найти agent entrypoints и automation ### 7.4. Найти agent entrypoints и automation
Определить: Определить:
@@ -267,6 +273,9 @@ runbookOutput:
path: Infra/LXD path: Infra/LXD
baselineRevision: 0123456789abcdef baselineRevision: 0123456789abcdef
dirty: false dirty: false
identity:
name: optools-lxd
source: git-remote
classification: classification:
proposedType: infrastructure-config proposedType: infrastructure-config
confidence: high confidence: high
@@ -311,10 +320,27 @@ Assessment MUST distinguish `detected`, `inferred` and `confirmed` values.
Остальные безопасные defaults могут быть предложены в plan без отдельного диалога. Остальные безопасные defaults могут быть предложены в plan без отдельного диалога.
Граница подтверждения — не рекомендация. `plan` MUST отказываться строиться без подтверждённого owner (`ADOPT_OWNER_UNKNOWN`): контракт с `owners: []` выглядит подтверждённым, хотя на вопрос никто не ответил.
Имя репозитория выводится из URL remote — последние два сегмента пути, приведённые к `metadata.name` (`.../OpTools/LXD.git` → `optools-lxd`). Каталог клона именем не является: два клона одного репозитория дали бы разные ответы, а worktree — третий. При отсутствии remote assess берёт имя каталога и помечает это `ADOPT_NAME_INFERRED`.
## 10. Phase 4 — adoption plan ## 10. Phase 4 — adoption plan
Plan строится относительно immutable baseline revision и содержит только операции `create`, `patch-managed-block` или `preserve`. Plan строится относительно immutable baseline revision и содержит только операции `create`, `patch-managed-block` или `preserve`.
Plan MUST переносить findings из assessment в поле `findings` и MUST отказываться строиться, пока остаётся хотя бы одна неразрешённая находка severity `error` (`ADOPT_ASSESS_BLOCKERS_UNRESOLVED`). Иначе единственный жёсткий результат assessment теряется на следующем шаге, а `apply` и `verify` возвращают success поверх репозитория, о котором assess сказал «блокер».
Владелец может принять конкретную находку, перечислив её в `acknowledgedFindings` с обязательным `reason`:
```yaml
acknowledgedFindings:
- code: ADOPT_SECRET_CONTENT_VERIFIED
path: airflow/.env
reason: rotation scheduled, tracked separately
```
Acknowledgement входит в plan, а значит в `planHash`, а значит в предмет approval: принять находку молча нельзя, и принятая находка не исчезает — `verify` возвращает её в `unresolvedFindings`.
```yaml ```yaml
runbookOutput: runbookOutput:
schema: stewardship/adoption-plan@0.1 schema: stewardship/adoption-plan@0.1
@@ -578,8 +604,13 @@ findingCodes:
ADOPT_KDB_CANONICAL_PATH_OCCUPIED: warning ADOPT_KDB_CANONICAL_PATH_OCCUPIED: warning
ADOPT_ENTRYPOINT_DIRECTION_LEGACY: warning ADOPT_ENTRYPOINT_DIRECTION_LEGACY: warning
ADOPT_ENTRYPOINT_CONFLICT: blocker ADOPT_ENTRYPOINT_CONFLICT: blocker
ADOPT_SECRET_TRACKED: blocker ADOPT_SECRET_CONTENT_VERIFIED: blocker
ADOPT_SECRET_IGNORED_BUT_TRACKED: warning
ADOPT_SECRET_NAME_SHAPED: warning
ADOPT_SECRET_SHAPED_UNTRACKED: info ADOPT_SECRET_SHAPED_UNTRACKED: info
ADOPT_NAME_INFERRED: info
ADOPT_ASSESS_BLOCKERS_UNRESOLVED: blocker
ADOPT_ACKNOWLEDGEMENT_INCOMPLETE: blocker
ADOPT_SOURCE_MIRROR_AMBIGUOUS: confirmation-required ADOPT_SOURCE_MIRROR_AMBIGUOUS: confirmation-required
ADOPT_BASELINE_CHANGED: blocker ADOPT_BASELINE_CHANGED: blocker
ADOPT_EXTERNAL_WRITE_DETECTED: blocker ADOPT_EXTERNAL_WRITE_DETECTED: blocker
@@ -597,7 +628,16 @@ findingCodes:
APPROVAL_FAILED: blocker APPROVAL_FAILED: blocker
``` ```
`ADOPT_SECRET_TRACKED` относится только к **tracked** путям. Untracked путь с secret-shaped именем получает отдельный `ADOPT_SECRET_SHAPED_UNTRACKED`, а путь, который репозиторий явно игнорирует, не сообщается вовсе: blocker-код, срабатывающий на игнорируемых файлах, приучает игнорировать blocker. Secret-shaped путь классифицируется по тому, что о нём действительно известно, а не по имени файла. Один blocker на совпадение имени давал в реальном репозитории 14 ложных находок из 16 и приучал пропускать все шестнадцать.
| Код | Severity | Что установлено |
|---|---|---|
| `ADOPT_SECRET_CONTENT_VERIFIED` | blocker | в содержимом есть присваивание credential-ключа с реальным значением либо PEM private key block |
| `ADOPT_SECRET_IGNORED_BUT_TRACKED` | warning | путь отслеживается вопреки собственным ignore-правилам репозитория |
| `ADOPT_SECRET_NAME_SHAPED` | warning | совпало только имя; содержимое credential не несёт |
| `ADOPT_SECRET_SHAPED_UNTRACKED` | info | untracked и неигнорируемый путь |
Содержимое читается только чтобы отличить credential от документа о credentials, и наружу выходят **имена ключей**, никогда значения (см. 7.3). Значения вида `<SECRET:name>`, `${VAR}`, `{{ var }}`, `changeme` и подобные плейсхолдеры credential не считаются. Путь, который репозиторий игнорирует и который не отслеживается, не сообщается вовсе.
`ADOPT_WORKTREE_DIRTY` на этапе `assess` остаётся warning и не мешает планированию. На этапе `apply` он становится blocker, но только когда грязный путь входит в число тех, которые план записывает: незакоммиченная работа владельца в стороне от плана — не препятствие. `ADOPT_WORKTREE_DIRTY` на этапе `assess` остаётся warning и не мешает планированию. На этапе `apply` он становится blocker, но только когда грязный путь входит в число тех, которые план записывает: незакоммиченная работа владельца в стороне от плана — не препятствие.
+4
View File
@@ -819,6 +819,10 @@ Bootstrap предлагает, но не навязывает:
Для существующего репозитория используется другая операция — `repoctl adopt`. Она не раскладывает старый repository как новый шаблон, а сначала картографирует уже существующие источники истины, agent instructions, KDB и штатные места результата. Для существующего репозитория используется другая операция — `repoctl adopt`. Она не раскладывает старый repository как новый шаблон, а сначала картографирует уже существующие источники истины, agent instructions, KDB и штатные места результата.
Перед планом adoption обязана получить ответ на то, что нельзя вывести: кто владелец. Пустой список владельцев в контракте выглядит как подтверждённый ответ, хотя никто не отвечал, поэтому `plan` без владельца просто не строится. Имя репозитория при этом берётся из remote, а не из имени каталога, в который его склонировали.
Найденные секреты различаются по тому, что о них известно. Файл с живым паролем внутри — блокер: план не построится, пока владелец либо не уберёт секрет, либо не примет находку явно и с причиной. Файл, чьё имя лишь похоже на секрет (например, документ `SECRETS.md` про конвенцию плейсхолдеров), и файл, закоммиченный вопреки собственному `.gitignore`, — предупреждения. Содержимое при этом читается только для этой классификации, и наружу выходят имена ключей, но никогда значения.
По умолчанию adoption добавляет overlay и ничего не переносит. Если владелец отдельно просит упорядочить дерево, используется именованная normalization recipe. Например, `documents-to-content-root` оставляет в корне `README.md`, `AGENTS.md` и `CLAUDE.md`, переносит только подтверждённые длинные документы и одновременно переписывает contract, KDB, frontmatter и Markdown links. По умолчанию adoption добавляет overlay и ничего не переносит. Если владелец отдельно просит упорядочить дерево, используется именованная normalization recipe. Например, `documents-to-content-root` оставляет в корне `README.md`, `AGENTS.md` и `CLAUDE.md`, переносит только подтверждённые длинные документы и одновременно переписывает contract, KDB, frontmatter и Markdown links.
```mermaid ```mermaid
+73 -3
View File
@@ -70,6 +70,22 @@ repoctl validate --repo . --output json
При ошибке `outcome` становится `"failure"`, `findings` заполняется, а процесс завершается кодом `1`. При ошибке `outcome` становится `"failure"`, `findings` заполняется, а процесс завершается кодом `1`.
### `skills` — поставить агентские скиллы туда, где агент их ищет
```bash
repoctl skills install --repo . # в этот репозиторий, .claude/skills/
repoctl skills install --global # в ~/.claude/skills/, для всех репозиториев
repoctl skills status --repo . # что установлено и не разошлось ли
```
Ставит `repository-adoption`, `repository-bootstrap` и `repo-handoff`. Это точка входа: до появления команды скиллы записывал только `init`, то есть они попадали исключительно в **новые** репозитории, а для приёма существующего нужен был скилл, который туда нечем было положить.
Область обязательно указывается явно — `--repo` или `--global`: локальная установка едет вместе с репозиторием и достаётся тому, кто его склонирует, глобальная следует за оператором в том числе в ещё не принятые репозитории. Угадывать между ними команда не будет (`SKILLS_SCOPE_MISSING`).
Повторный запуск идемпотентен. Скилл, содержимое которого отличается от поставляемого этой версией, **не перезаписывается**: команда сообщает `SKILLS_MODIFIED` и завершается кодом `1`, заменить его можно явным `--force`. Различить «оператор поправил файл» и «repoctl ушёл вперёд» нельзя, поэтому оба случая требуют подтверждения. Проверка проходит по всем скиллам до первой записи, так что отказ не оставляет каталог наполовину обновлённым.
В отличие от `init` и `adopt`, здесь нет плана и подтверждения по хэшу: эта дисциплина защищает содержимое репозитория, а команда пишет только файлы, принадлежащие инструменту, в фиксированный подкаталог.
### `discover` — что есть в каталоге репозиториев ### `discover` — что есть в каталоге репозиториев
```bash ```bash
@@ -78,6 +94,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
@@ -86,6 +104,28 @@ repoctl describe --repo some-repo-name --output json
Возвращает нормализованный `RepositoryContract` — только контракт, без загрузки KDB. Полезно, чтобы быстро узнать тип, владельца и content roots репозитория, не читая ничего лишнего. Возвращает нормализованный `RepositoryContract` — только контракт, без загрузки KDB. Полезно, чтобы быстро узнать тип, владельца и content roots репозитория, не читая ничего лишнего.
### `kdb` — что вообще есть в базе знаний
```bash
repoctl kdb --repo .
```
Единственная команда, чей `--output human` печатает не строку статуса, а само
содержимое: markdown-таблицу тем (id, объявленные intent-ы, документы, к которым
тема маршрутизирует, и ключи верхнего уровня в `data`) и таблицу документов
(id, путь, роль, статус; `stale` помечен `(!)`). Это сделано намеренно —
вопрос «что в базе знаний» отвечается содержимым, а не статусом.
Находки по-прежнему уходят в stderr, таблица в stdout, поэтому
`repoctl kdb > kdb.md` даёт чистый markdown. `--output json` и `--output yaml`
возвращают обычный конверт с `stewardship/knowledge-overview@0.1` внутри.
Точка входа не угадывается: берётся `spec.knowledge.entrypoint` из
`ops/contract.yaml`, с откатом на `kdb/kdb.yaml`. Репозиторий без базы знаний
получает предупреждение `KNOWLEDGE_ENTRYPOINT_MISSING` и код возврата `3`.
Таблица отвечает «что есть». Чтобы получить только нужное под конкретную
задачу, возьмите intent из колонки Intents и спросите `context`.
### `context` — только нужные знания под задачу ### `context` — только нужные знания под задачу
Главная команда для агента. Вместо чтения всей документации репозитория: Главная команда для агента. Вместо чтения всей документации репозитория:
@@ -101,10 +141,27 @@ repoctl context --repo . --intent domain.action --output json
Двухшаговый процесс: сначала план, затем — только после ревью — применение. Двухшаговый процесс: сначала план, затем — только после ревью — применение.
```bash ```bash
# Шаг 0: получить шаблон ответов — он называет все ключи и их допустимые значения
repoctl init --answers-template > answers.yaml
# Шаг 1: построить план (ничего не пишет на диск) # Шаг 1: построить план (ничего не пишет на диск)
repoctl init --repo ../new-repo --name new-repo --type project --owner team-name --output json > plan.json repoctl init --repo ../new-repo --answers answers.yaml --output json > plan.json
``` ```
Ключи файла ответов — не имена флагов (`--type` задаёт `repositoryType`), поэтому шаблон и существует. `summary` и `namespace` стоит заполнить сразу: они дёшевы, а иначе навсегда остаются заглушками в контракте.
Файлы скиллов, оставленные `repoctl skills install`, коллизией **не** считаются: путь, уже содержащий ровно то, что план собирался записать, — не конфликт. Файл с другим содержимым конфликтом остаётся.
Ответы проверяются до сборки плана, чтобы `init` не мог создать репозиторий, который не проходит собственный `validate`:
| Код | Когда |
|---|---|
| `INIT_ANSWERS_INCOMPLETE` | нет `--name` или `--type` |
| `INIT_NAME_INVALID` | имя не подходит под `^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`; в сообщении есть готовая замена (`Services/Mail` → `services-mail`) |
| `INIT_TYPE_UNKNOWN`, `INIT_LIFECYCLE_UNKNOWN`, `INIT_ACCESS_UNKNOWN` | значение вне enum схемы |
| `INIT_OWNER_UNKNOWN` | владелец не подтверждён — та же граница, что у `adopt` |
| `INIT_PATH_COLLISION` | каталог уже содержит один из создаваемых путей; для существующего репозитория нужен `adopt`, а не `init` |
В ответе — полный список файлов, которые будут созданы (`ops/contract.yaml`, `kdb/kdb.yaml`, `AGENTS.md`, `CLAUDE.md`, `.claude/skills/*`, и т.д.) и `planHash`. Прочитайте план, убедитесь, что он ожидаем. В ответе — полный список файлов, которые будут созданы (`ops/contract.yaml`, `kdb/kdb.yaml`, `AGENTS.md`, `CLAUDE.md`, `.claude/skills/*`, и т.д.) и `planHash`. Прочитайте план, убедитесь, что он ожидаем.
```bash ```bash
@@ -120,11 +177,23 @@ repoctl init --repo ../new-repo --apply --plan plan.json --approve sha256:<planH
```bash ```bash
repoctl adopt --repo ../legacy-repo --mode assess --output json # инвентаризация, ничего не пишет repoctl adopt --repo ../legacy-repo --mode assess --output json # инвентаризация, ничего не пишет
repoctl adopt --repo ../legacy-repo --mode plan --output json # предлагаемый diff + planHash, ничего не пишет repoctl adopt --repo ../legacy-repo --mode plan --owner infra --output json # предлагаемый diff + planHash, ничего не пишет
repoctl adopt --repo ../legacy-repo --mode apply --plan plan.json --approve sha256:<planHash> --output json repoctl adopt --repo ../legacy-repo --mode apply --plan plan.json --approve sha256:<planHash> --output json
repoctl adopt --repo ../legacy-repo --mode verify --output json # отчёт о совместимости после apply repoctl adopt --repo ../legacy-repo --mode verify --output json # отчёт о совместимости после apply
``` ```
`plan` требует подтверждённого владельца — `--owner` (можно повторять) либо `owners:` в `--answers`; без него он отказывается строиться, а не выпускает контракт с пустым `owners`. Имя репозитория берётся из URL remote (последние два сегмента: `.../OpTools/LXD.git` → `optools-lxd`), либо задаётся `name:` в файле ответов.
`plan` также отказывается строиться, пока `assess` оставил находку severity `error` — например, файл с живым credential в git. Принять такую находку осознанно можно в файле ответов; `reason` обязателен, а сам acknowledgement входит в `planHash`:
```yaml
owners: [infrastructure]
acknowledgedFindings:
- code: ADOPT_SECRET_CONTENT_VERIFIED
path: airflow/.env
reason: rotation scheduled, tracked separately
```
По умолчанию используется стратегия `overlay`: existing domain-native layout (например, `profiles-source/`, существующий `kdb.yaml` в корне) не перемещается и не переписывается — поверх него добавляется только недостающая метадата Stewardship. Если в репозитории уже занят путь `kdb/kdb.yaml`, `adopt` предложит `ops/knowledge.yaml` вместо конфликта. `apply` никогда не делает `git commit`, `push` или `clone`. По умолчанию используется стратегия `overlay`: existing domain-native layout (например, `profiles-source/`, существующий `kdb.yaml` в корне) не перемещается и не переписывается — поверх него добавляется только недостающая метадата Stewardship. Если в репозитории уже занят путь `kdb/kdb.yaml`, `adopt` предложит `ops/knowledge.yaml` вместо конфликта. `apply` никогда не делает `git commit`, `push` или `clone`.
## Коды возврата ## Коды возврата
@@ -145,5 +214,6 @@ repoctl adopt --repo ../legacy-repo --mode verify --output json # отчёт
- **`ERROR: No .git ancestor found`** — команда запущена вне git-репозитория и `--repo` не указан явно; передайте `--repo <путь>` или запустите `git init` в целевом каталоге. - **`ERROR: No .git ancestor found`** — команда запущена вне git-репозитория и `--repo` не указан явно; передайте `--repo <путь>` или запустите `git init` в целевом каталоге.
- **`APPROVAL_FAILED` при `init --apply`/`adopt --mode apply`** — переданный `--approve` не совпадает с `planHash` в файле плана; пересчитайте план заново (сравнение файла плана и `planHash` в нём — самопроверка от случайной правки плана вручную). - **`APPROVAL_FAILED` при `init --apply`/`adopt --mode apply`** — переданный `--approve` не совпадает с `planHash` в файле плана; пересчитайте план заново (сравнение файла плана и `planHash` в нём — самопроверка от случайной правки плана вручную).
- **`ADOPT_BASELINE_CHANGED`** — репозиторий изменился между `--mode plan` и `--mode apply` (кто-то создал файл из плана вручную); постройте план заново. - **`ADOPT_BASELINE_CHANGED`** — репозиторий изменился между `--mode plan` и `--mode apply` (кто-то создал файл из плана вручную); постройте план заново.
- **`ADOPT_PATH_COLLISION` / `init` отказывается писать** — план целится в уже существующий файл; `repoctl` намеренно не перезаписывает существующее содержимое — удалите или переименуйте конфликтующий файл вручную и постройте план заново. - **`ADOPT_PATH_COLLISION` / `init` отказывается писать** — план целится в уже существующий файл; `repoctl` намеренно не перезаписывает существующее содержимое — удалите или переименуйте конфликтующий файл вручную и постройте план заново. `INIT_PATH_COLLISION` на этапе плана означает, что каталог уже является репозиторием: используйте `adopt`.
- **`INIT_PATH_OUTSIDE_REPOSITORY`** — путь в файле плана ведёт наружу репозитория. План — обычный файл; если он был отредактирован вручную или перенесён между машинами, постройте его заново вместо правки.
- **Windows: кириллица или спецсимволы искажены в выводе** — используйте актуальную версию `repoctl`; вывод принудительно кодируется в UTF-8 независимо от кодовой страницы консоли. - **Windows: кириллица или спецсимволы искажены в выводе** — используйте актуальную версию `repoctl`; вывод принудительно кодируется в UTF-8 независимо от кодовой страницы консоли.
+12 -1
View File
@@ -923,6 +923,10 @@ MCP является transport/discovery layer и MUST NOT становитьс
### 18.1. `repoctl init` ### 18.1. `repoctl init`
`init` — единственный путь, где инструмент контролирует каждый байт результата, поэтому созданный им репозиторий MUST проходить `repoctl validate` по построению. Ответы MUST проверяться до сборки плана: `metadata.name` против `ID_PATTERN`, type против набора типов, lifecycle и access против своих enum. Owner MUST быть подтверждён — та же граница, что и в `adopt`: контракт не знает, какая команда его создала.
`init` MUST отказываться планировать в каталог, где уже лежит любой из создаваемых им путей, и указывать на `adopt` как на правильную операцию. `apply` MUST confine каждый путь из плана внутрь репозитория: план — обычный файл, который можно отредактировать вручную.
MVP bootstrap SHOULD: MVP bootstrap SHOULD:
1. определить repository type; 1. определить repository type;
@@ -951,6 +955,9 @@ Adoption MUST:
- создавать совместимый KDB index рядом, если канонический путь занят legacy-форматом; - создавать совместимый KDB index рядом, если канонический путь занят legacy-форматом;
- показывать полный diff до записи; - показывать полный diff до записи;
- разделять автоматически найденные факты и подтверждённые владельцем решения; - разделять автоматически найденные факты и подтверждённые владельцем решения;
- отказываться строить plan без подтверждённого owner и выводить `metadata.name` из remote, а не из имени каталога клона;
- переносить findings из assessment в plan и отказываться строить plan, пока остаётся неразрешённая находка severity `error`; принятие такой находки MUST быть явным, с указанием причины, и входить в `planHash`;
- классифицировать secret-shaped пути по содержимому, а не только по имени, и не выводить значения — только имена ключей;
- допускать остановку после `assess` или `plan` без изменения репозитория; - допускать остановку после `assess` или `plan` без изменения репозитория;
- при `overlay` изменять только repository-local metadata после явного подтверждения; - при `overlay` изменять только repository-local metadata после явного подтверждения;
- при `normalize` изменять только paths из подтверждённой recipe и обновлять все contract/KDB/Markdown references атомарно; - при `normalize` изменять только paths из подтверждённой recipe и обновлять все contract/KDB/Markdown references атомарно;
@@ -1159,7 +1166,11 @@ MVP считается готовым, когда:
17. adoption LXD сохраняет `profiles-source/`, `profiles/` и root `kdb.yaml` на месте; 17. adoption LXD сохраняет `profiles-source/`, `profiles/` и root `kdb.yaml` на месте;
18. adoption Antivirus не перезаписывает существующий custom `kdb/kdb.yaml`. 18. adoption Antivirus не перезаписывает существующий custom `kdb/kdb.yaml`.
19. `documents-to-content-root` не перемещает `README.md`, `AGENTS.md`, `CLAUDE.md`, license и community files; 19. `documents-to-content-root` не перемещает `README.md`, `AGENTS.md`, `CLAUDE.md`, license и community files;
20. normalization plan включает rename map и обновляет contract, KDB, frontmatter и Markdown links до записи. 20. normalization plan включает rename map и обновляет contract, KDB, frontmatter и Markdown links до записи;
21. `adopt --mode plan` отказывается строиться без подтверждённого owner и при неразрешённой находке severity `error`;
22. содержимое secret-shaped файла может читаться для классификации, но значения не попадают ни в один вывод;
23. content roots предлагаются по всему словарю содержимого, а не только по маркерам предложенного type;
24. репозиторий из однотипных каталогов объявляется одним `file-set` корнем с селектором, а не N директориями.
## 25. Сквозной пример contract: infrastructure provider ## 25. Сквозной пример contract: infrastructure provider
+2
View File
@@ -69,11 +69,13 @@ spec:
- 3. Safety invariants - 3. Safety invariants
- 6. Phase 1 — preflight - 6. Phase 1 — preflight
- 7. Phase 2 — assessment - 7. Phase 2 — assessment
- 9. Phase 3 — confirmation boundary
- 10. Phase 4 — adoption plan - 10. Phase 4 — adoption plan
- 11. Compatibility rules - 11. Compatibility rules
- 11.5. Normalization recipe documents-to-content-root - 11.5. Normalization recipe documents-to-content-root
- 12. Phase 5 — apply - 12. Phase 5 — apply
- 13. Phase 6 — verify - 13. Phase 6 — verify
- 14. Finding codes
- id: stewardship-model - id: stewardship-model
title: Understand or evolve the model title: Understand or evolve the model
summary: Definitions, invariants, schemas and the reasoning behind Repository Stewardship summary: Definitions, invariants, schemas and the reasoning behind Repository Stewardship
+1 -1
View File
@@ -14,7 +14,7 @@ metadata:
spec: spec:
summary: Standards, templates and the repoctl L1 CLI for AI-assisted repository management summary: Standards, templates and the repoctl L1 CLI for AI-assisted repository management
repository: repository:
type: project type: software
lifecycle: active lifecycle: active
agent: agent:
primary: CLAUDE.md primary: CLAUDE.md
+378 -39
View File
@@ -125,6 +125,28 @@ _SECRET_BINARY_SUFFIXES = (
".zip", ".gz", ".tar", ".7z", ".xz", ".mp4", ".exe", ".msi", ".zip", ".gz", ".tar", ".7z", ".xz", ".mp4", ".exe", ".msi",
) )
_SECRET_SKIP_DIRS = {".git", ".venv", "node_modules", "__pycache__"} _SECRET_SKIP_DIRS = {".git", ".venv", "node_modules", "__pycache__"}
# Reading content is what separates a credential from a document about
# credentials. Runbook 7.3 allows recording *keys* without emitting values, so
# these patterns are only ever used to produce key names.
_SECRET_KEY_RE = re.compile(
r"^[ \t]*(?:export[ \t]+)?(?P<key>"
# Words that name a credential wherever they appear in the key.
r"[A-Za-z0-9_.\-]*(?:PASSWORD|PASSWD|PASSPHRASE|SECRET|TOKEN|CREDENTIAL)[A-Za-z0-9_.\-]*"
r"|"
# "KEY" only as a suffix: AIRFLOW_FERNET_KEY is a credential, KEY_PATH and
# KEYBOARD_LAYOUT are not, and a bare substring match cannot tell them apart.
r"(?:[A-Za-z0-9_.\-]*[_.\-](?:KEY|APIKEY)|KEY|APIKEY)"
r")[ \t]*[:=][ \t]*(?P<value>\S.*)$",
re.IGNORECASE | re.MULTILINE,
)
_PEM_RE = re.compile(r"-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----")
_PLACEHOLDER_VALUES = {
"changeme", "change-me", "change_me", "example", "placeholder", "redacted",
"todo", "tbd", "xxx", "none", "null", "unset", "secret", "password",
}
# A credential large enough to matter is never in a multi-megabyte file, and
# reading one to decide would make assess proportional to repository size.
_SECRET_CONTENT_MAX_BYTES = 256 * 1024
# Weighted because presence alone is weak evidence: `docs/` exists in almost # Weighted because presence alone is weak evidence: `docs/` exists in almost
# every repository and must not outvote a marker that actually identifies the # every repository and must not outvote a marker that actually identifies the
@@ -162,8 +184,27 @@ _CONTENT_ROOT_SPECS: dict[str, dict[str, Any]] = {
"deliverables": {"role": "deliverables", "authority": "source", "writePolicy": "managed"}, "deliverables": {"role": "deliverables", "authority": "source", "writePolicy": "managed"},
"decisions": {"role": "decisions", "authority": "source", "writePolicy": "managed"}, "decisions": {"role": "decisions", "authority": "source", "writePolicy": "managed"},
"docs": {"role": "documentation", "authority": "source", "writePolicy": "managed"}, "docs": {"role": "documentation", "authority": "source", "writePolicy": "managed"},
"scripts": {"role": "automation", "authority": "source", "writePolicy": "managed"},
"services": {"role": "services", "authority": "source", "writePolicy": "managed"},
"apps": {"role": "apps", "authority": "source", "writePolicy": "managed"},
"templates": {"role": "templates", "authority": "source", "writePolicy": "managed"},
"projects": {"role": "projects", "authority": "source", "writePolicy": "managed"},
} }
# Runbook 7.2 declares a repository of sibling stack directories as one file-set
# root with a selector, not as N directory roots. Recognising the shape needs a
# marker the siblings share; a lone directory carrying one proves nothing.
_REPEATED_SHAPE_MARKERS: list[tuple[str, str, str]] = [
("compose.yaml", "*/compose.y*ml", "stacks"),
("compose.yml", "*/compose.y*ml", "stacks"),
("docker-compose.yaml", "*/docker-compose.y*ml", "stacks"),
("docker-compose.yml", "*/docker-compose.y*ml", "stacks"),
("Chart.yaml", "*/Chart.yaml", "charts"),
("main.tf", "*/main.tf", "desired"),
("Dockerfile", "*/Dockerfile", "images"),
]
_REPEATED_SHAPE_MIN_SIBLINGS = 3
def _finding(severity: str, code: str, path: str | None = None, message: str | None = None) -> dict[str, Any]: def _finding(severity: str, code: str, path: str | None = None, message: str | None = None) -> dict[str, Any]:
item: dict[str, Any] = {"severity": severity, "code": code} item: dict[str, Any] = {"severity": severity, "code": code}
@@ -174,6 +215,44 @@ def _finding(severity: str, code: str, path: str | None = None, message: str | N
return item return item
def _is_placeholder(value: str) -> bool:
"""True when an assignment's value is a stand-in rather than a live credential."""
value = value.strip().split("#", 1)[0].strip().strip("\"'").strip()
if not value:
return True
# `<SECRET:name>`, `${VAR}` and `{{ var }}` are all "filled in elsewhere".
if value.startswith(("<", "${", "{{")):
return True
return value.lower() in _PLACEHOLDER_VALUES
def _secret_content_evidence(path: Path) -> list[str]:
"""Return the *names* of credential-shaped keys carrying a real value.
Never returns, logs or stores a value: the caller puts this straight into a
finding message, and a scanner that leaks the secret it found is worse than
no scanner. Unreadable, oversized and binary files yield nothing rather than
raising, because assess must survive whatever an existing repository holds.
"""
try:
if path.stat().st_size > _SECRET_CONTENT_MAX_BYTES:
return []
text = path.read_text(encoding="utf-8", errors="ignore")
except OSError:
return []
keys: list[str] = []
if _PEM_RE.search(text):
keys.append("PEM private key block")
for match in _SECRET_KEY_RE.finditer(text):
if _is_placeholder(match.group("value")):
continue
key = match.group("key")
if key not in keys:
keys.append(key)
return keys
def _detect_secret_shaped_paths(root: Path) -> list[tuple[str, str]]: def _detect_secret_shaped_paths(root: Path) -> list[tuple[str, str]]:
"""Return (relative_path, "tracked" | "untracked") for secret-shaped filenames. """Return (relative_path, "tracked" | "untracked") for secret-shaped filenames.
@@ -212,6 +291,66 @@ def _detect_secret_shaped_paths(root: Path) -> list[tuple[str, str]]:
] ]
def _classify_secret_paths(root: Path) -> list[dict[str, Any]]:
"""Sort secret-shaped paths into what is actually known about each one.
A single blocker keyed on the filename made 14 of 16 findings in a real
repository false, and taught the reader to skip all of them. The three
classes say different things and deserve different severities: content that
really is a credential blocks; a name-only match and a file committed
against the repository's own ignore rules are warnings worth acting on.
"""
candidates = _detect_secret_shaped_paths(root)
tracked_paths = [rel for rel, status in candidates if status == "tracked"]
# Without --no-index Git stays silent about tracked paths, which is exactly
# the contradiction being looked for here.
rule_matched = gitutil.ignored(root, tracked_paths, no_index=True)
findings: list[dict[str, Any]] = []
for rel, status in candidates:
if status != "tracked":
findings.append(
_finding(
"info",
"ADOPT_SECRET_SHAPED_UNTRACKED",
rel,
"Untracked and unignored secret-shaped path (path only, content not read)",
)
)
continue
if rel in rule_matched:
findings.append(
_finding(
"warning",
"ADOPT_SECRET_IGNORED_BUT_TRACKED",
rel,
"Tracked although the repository's own ignore rules exclude it",
)
)
keys = _secret_content_evidence(root / rel)
if keys:
findings.append(
_finding(
"error",
"ADOPT_SECRET_CONTENT_VERIFIED",
rel,
"Credential-shaped assignment with a live value: " + ", ".join(keys),
)
)
elif rel not in rule_matched:
findings.append(
_finding(
"warning",
"ADOPT_SECRET_NAME_SHAPED",
rel,
"Filename matches a secret-shaped pattern; content carries no credential",
)
)
return findings
def _knowledge_format(path: Path) -> str: def _knowledge_format(path: Path) -> str:
"""Return ``stewardship-yaml`` only when the file really is a KnowledgeBase. """Return ``stewardship-yaml`` only when the file really is a KnowledgeBase.
@@ -235,6 +374,148 @@ def _knowledge_entry(root: Path, rel: str) -> dict[str, str]:
return {"path": rel, "format": fmt, "action": action} return {"path": rel, "format": fmt, "action": action}
_NAME_RE = re.compile(r"^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$")
def _slug(*parts: str) -> str | None:
"""Join ``parts`` into a contract-legal ``metadata.name``, or None if impossible."""
joined = "-".join(part for part in parts if part)
slug = re.sub(r"[^a-z0-9]+", "-", joined.lower()).strip("-")
slug = re.sub(r"-{2,}", "-", slug)
return slug if slug and _NAME_RE.match(slug) else None
def _proposed_identity(root: Path) -> dict[str, str]:
"""Propose a repository name from the remote, falling back to the directory.
The directory basename is not an identity: it is wherever this clone happens
to sit, so two clones of one repository disagree and a worktree invents a
third answer. The remote path is something the owner chose. Two segments are
kept because the last one alone ("lxd", "docker") collides across groups.
"""
# `--repo .` is the ordinary way to name the current repository, and
# `Path(".").name` is the empty string: without resolving first, every such
# invocation fell through to the generic fallback name.
root = root.resolve()
url = gitutil.remote_url(root)
if url:
path = re.sub(r"\.git$", "", url.split("#", 1)[0].rstrip("/"))
# Both ssh://host:port/a/b and scp-style host:a/b reduce to their segments.
segments = [seg for seg in re.split(r"[/:]", path) if seg]
name = _slug(*segments[-2:]) or _slug(*segments[-1:])
if name:
return {"name": name, "source": "git-remote"}
fallback = _slug(root.name) or "adopted-repository"
return {"name": fallback, "source": "directory"}
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: `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.
"""
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 (parent / name / marker).is_file()]
if len(members) < _REPEATED_SHAPE_MIN_SIBLINGS:
continue
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",
}
)
break
return proposed
def _propose_content_roots(root: Path) -> list[dict[str, Any]]:
"""Propose content roots from every vocabulary, not only the winning type's.
Scoping the search to the proposed type meant an infrastructure repository
never had its `docs/` declared, because `docs` happens to be listed as
evidence for `project`. Type and content roots answer different questions:
what the repository is for, and what it actually holds.
"""
# Two different vocabularies: _TYPE_EVIDENCE says what a repository is for,
# _CONTENT_ROOT_SPECS says how a directory should be declared. A directory
# can be worth declaring without being evidence of any type.
markers = sorted(
{marker for _type, table in _TYPE_EVIDENCE for marker in table} | set(_CONTENT_ROOT_SPECS)
)
proposed: list[dict[str, Any]] = []
claimed: set[str] = set()
for marker in markers:
if not (root / marker).is_dir():
continue
spec = _CONTENT_ROOT_SPECS.get(
marker, {"role": marker, "authority": "source", "writePolicy": "managed"}
)
entry: dict[str, Any] = {
"id": marker.replace("/", "-").lower(),
"path": marker,
"role": spec["role"],
"kind": "directory",
"authority": spec["authority"],
"writePolicy": spec["writePolicy"],
}
sources = spec.get("generatedFrom") or []
if sources and all((root / source).exists() for source in sources):
entry["generatedFrom"] = [source.replace("/", "-").lower() for source in sources]
elif sources:
# Nothing generates it here, so it is the source in this repository.
entry.update(authority="source", writePolicy="managed", role=marker)
proposed.append(entry)
claimed.add(marker)
for repeated in _repeated_shape_roots(root, claimed):
if not any(entry["id"] == repeated["id"] for entry in proposed):
proposed.append(repeated)
return proposed
def _classify_type(root: Path) -> tuple[str, str, list[str], bool]: def _classify_type(root: Path) -> tuple[str, str, list[str], bool]:
"""Propose a repository type, its confidence, its evidence, and whether it tied. """Propose a repository type, its confidence, its evidence, and whether it tied.
@@ -300,33 +581,21 @@ def assess(root: Path) -> dict[str, Any]:
if entry["action"] == "wrap": if entry["action"] == "wrap":
findings.append(_finding("info", "ADOPT_KDB_LEGACY", rel)) findings.append(_finding("info", "ADOPT_KDB_LEGACY", rel))
proposed_content_roots: list[dict[str, Any]] = [] proposed_content_roots = _propose_content_roots(root)
for repo_type, markers in _TYPE_EVIDENCE: for content_root in proposed_content_roots:
if repo_type != proposed_type: if content_root.get("authority") == "source" and not content_root.get("generatedFrom"):
continue # Runbook 7.2: calling a generated mirror a source is the named
for marker in sorted(markers): # mistake. Where the pairing is not evidenced by a generatedFrom
candidate = root / marker # partner, "source" is this table's default rather than a finding
if not candidate.is_dir(): # about this repository, and the owner has to say which it is.
continue findings.append(
spec = _CONTENT_ROOT_SPECS.get( _finding(
marker, {"role": marker, "authority": "source", "writePolicy": "managed"} "warning",
"ADOPT_SOURCE_MIRROR_AMBIGUOUS",
content_root["path"],
"Authority defaulted to source; confirm it is not a generated mirror",
)
) )
content_root: dict[str, Any] = {
"id": marker.replace("/", "-").lower(),
"path": marker,
"role": spec["role"],
"authority": spec["authority"],
"writePolicy": spec["writePolicy"],
}
sources = spec.get("generatedFrom") or []
if sources and all((root / source).exists() for source in sources):
content_root["generatedFrom"] = [
source.replace("/", "-").lower() for source in sources
]
elif sources:
# Nothing generates it here, so it is the source in this repository.
content_root.update(authority="source", writePolicy="managed", role=marker)
proposed_content_roots.append(content_root)
collisions: list[str] = [] collisions: list[str] = []
for rel in _COLLISION_PATHS: for rel in _COLLISION_PATHS:
@@ -335,18 +604,7 @@ def assess(root: Path) -> dict[str, Any]:
if (root / "kdb" / "kdb.yaml").exists() and (root / "kdb.yaml").exists(): if (root / "kdb" / "kdb.yaml").exists() and (root / "kdb.yaml").exists():
findings.append(_finding("warning", "ADOPT_KDB_CANONICAL_PATH_OCCUPIED", "kdb/kdb.yaml")) findings.append(_finding("warning", "ADOPT_KDB_CANONICAL_PATH_OCCUPIED", "kdb/kdb.yaml"))
for rel, status in _detect_secret_shaped_paths(root): findings.extend(_classify_secret_paths(root))
if status == "tracked":
findings.append(_finding("error", "ADOPT_SECRET_TRACKED", rel, "Tracked path matches a secret-shaped filename pattern"))
else:
findings.append(
_finding(
"info",
"ADOPT_SECRET_SHAPED_UNTRACKED",
rel,
"Untracked and unignored secret-shaped path (path only, content not read)",
)
)
if dirty: if dirty:
findings.append(_finding("warning", "ADOPT_WORKTREE_DIRTY")) findings.append(_finding("warning", "ADOPT_WORKTREE_DIRTY"))
@@ -356,15 +614,36 @@ def assess(root: Path) -> dict[str, Any]:
_finding("warning", "ADOPT_TYPE_AMBIGUOUS", None, f"Type evidence ties with {proposed_type}") _finding("warning", "ADOPT_TYPE_AMBIGUOUS", None, f"Type evidence ties with {proposed_type}")
) )
identity = _proposed_identity(root)
if identity["source"] == "directory":
findings.append(
_finding(
"info",
"ADOPT_NAME_INFERRED",
None,
f"No git remote; name {identity['name']!r} inferred from the directory",
)
)
# Runbook section 9 lists owner among the answers that cannot be derived, so
# assess always asks. `plan` is where the refusal lives; failing assess on a
# question it exists to raise would make the read-only step unusable.
findings.append(
_finding("warning", "ADOPT_OWNER_UNKNOWN", None, "Owner is not confirmed yet")
)
questions: list[str] = [] questions: list[str] = []
confirmation_required = confidence != "high" confirmation_required = confidence != "high"
if confirmation_required: if confirmation_required:
questions.append("Confirm repository type and confidence evidence") questions.append("Confirm repository type and confidence evidence")
questions.append("Confirm owner(s) and lifecycle") questions.append("Confirm owner(s) and lifecycle")
questions.append(f"Confirm repository name (proposed {identity['name']!r} from {identity['source']})")
if any(f["code"] == "ADOPT_SOURCE_MIRROR_AMBIGUOUS" for f in findings):
questions.append("Confirm which content roots are sources and which are generated mirrors")
return { return {
"schema": "stewardship/adoption-assessment@0.1", "schema": "stewardship/adoption-assessment@0.1",
"repository": {"path": str(root), "baselineRevision": head, "dirty": dirty}, "repository": {"path": str(root), "baselineRevision": head, "dirty": dirty},
"identity": identity,
"classification": { "classification": {
"proposedType": proposed_type, "proposedType": proposed_type,
"confidence": confidence, "confidence": confidence,
@@ -535,10 +814,52 @@ def build_plan(
confirmed_lifecycle: str = "active", confirmed_lifecycle: str = "active",
confirmed_type: str | None = None, confirmed_type: str | None = None,
strategy: str = "overlay", strategy: str = "overlay",
acknowledged: list[dict[str, Any]] | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
if strategy != "overlay": if strategy != "overlay":
raise ValueError("Only the overlay strategy is implemented; normalize requires an explicit recipe run") raise ValueError("Only the overlay strategy is implemented; normalize requires an explicit recipe run")
if not confirmed_owners:
# Runbook section 9: owner is one of the answers adoption cannot derive.
# Emitting `owners: []` produced a contract that looked confirmed while
# nobody had answered, which is worse than refusing to build one.
raise AdoptionError(
"ADOPT_OWNER_UNKNOWN",
"Owners must be confirmed before a plan can be built (--owner, or owners: in --answers)",
)
# Questions the plan's own answers settle must not be carried forward as if
# they were still open: reaching this point means an owner was confirmed.
assessment_findings = [
dict(f) for f in assessment.get("findings", []) if f["code"] != "ADOPT_OWNER_UNKNOWN"
]
acknowledgements = [dict(item) for item in (acknowledged or [])]
for item in acknowledgements:
if not item.get("code") or not str(item.get("reason", "")).strip():
raise AdoptionError(
"ADOPT_ACKNOWLEDGEMENT_INCOMPLETE",
"Each acknowledged finding needs a code and a reason",
)
acknowledged_keys = {(item["code"], item.get("path")) for item in acknowledgements}
unresolved = [
f
for f in assessment_findings
if f["severity"] == "error"
and (f["code"], f.get("path")) not in acknowledged_keys
and (f["code"], None) not in acknowledged_keys
]
if unresolved:
# `assess` used to report a blocker and `plan` then returned success with
# an empty findings list, so the one hard result of the whole run was
# silently dropped one step later.
detail = ", ".join(
f"{f['code']}({f['path']})" if f.get("path") else f["code"] for f in unresolved
)
raise AdoptionError(
"ADOPT_ASSESS_BLOCKERS_UNRESOLVED",
f"assess left {len(unresolved)} unresolved error finding(s): {detail}",
)
baseline = assessment["repository"]["baselineRevision"] baseline = assessment["repository"]["baselineRevision"]
classification = assessment["classification"] classification = assessment["classification"]
repository_type = confirmed_type or classification["proposedType"] repository_type = confirmed_type or classification["proposedType"]
@@ -563,14 +884,27 @@ def build_plan(
"id": cr["id"], "id": cr["id"],
"role": cr["role"], "role": cr["role"],
"path": cr["path"], "path": cr["path"],
"kind": "directory", "kind": cr.get("kind", "directory"),
"authority": cr.get("authority", "source"), "authority": cr.get("authority", "source"),
"writePolicy": cr.get("writePolicy", "managed"), "writePolicy": cr.get("writePolicy", "managed"),
} }
if cr.get("selector"):
entry["selector"] = cr["selector"]
if cr.get("generatedFrom"): if cr.get("generatedFrom"):
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 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']}/**") forbidden.append(f"{cr['path']}/**")
knowledge_entrypoint, knowledge_changes, knowledge_forbidden = _plan_knowledge( knowledge_entrypoint, knowledge_changes, knowledge_forbidden = _plan_knowledge(
@@ -664,6 +998,9 @@ def build_plan(
"baselineRevision": baseline, "baselineRevision": baseline,
"strategy": strategy, "strategy": strategy,
"changes": changes, "changes": changes,
# Carried so the plan is self-contained evidence of what assess saw, and
# so an acknowledgement is covered by planHash and therefore by approval.
"findings": assessment_findings,
"forbiddenChanges": sorted(set(forbidden)), "forbiddenChanges": sorted(set(forbidden)),
"validations": [ "validations": [
"stewardship-schema", "stewardship-schema",
@@ -673,6 +1010,8 @@ def build_plan(
], ],
"approval": {"required": True}, "approval": {"required": True},
} }
if acknowledgements:
plan["acknowledgedFindings"] = acknowledgements
plan_hash = io.sha256({k: v for k, v in plan.items() if k != "planHash"}) plan_hash = io.sha256({k: v for k, v in plan.items() if k != "planHash"})
plan["planHash"] = plan_hash plan["planHash"] = plan_hash
return plan return plan
+183 -9
View File
@@ -7,6 +7,7 @@ domain artifacts. `init` never commits, pushes or creates a remote.
from __future__ import annotations from __future__ import annotations
import re
import subprocess import subprocess
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
@@ -14,7 +15,14 @@ from typing import Any
from . import io from . import io
from .clock import DEFAULT_CLOCK from .clock import DEFAULT_CLOCK
from .constants import API_VERSION from .constants import (
ACCESS_VALUES,
API_VERSION,
ID_PATTERN,
LIFECYCLES,
REPOSITORY_TYPES,
)
from .paths import PathViolation, confined_path
from .skills_content import ( from .skills_content import (
REPO_HANDOFF_SKILL, REPO_HANDOFF_SKILL,
REPOSITORY_ADOPTION_SKILL, REPOSITORY_ADOPTION_SKILL,
@@ -56,6 +64,118 @@ SSH_RECOMMENDATION = (
) )
def answers_template() -> str:
"""A commented answers file naming every key, its vocabulary and its default.
The answers keys are not the flag names (`--type` sets `repositoryType`),
and nothing printed the mapping: the vocabularies were reachable only by
sending a wrong value on purpose and reading the refusal. `summary` and
`namespace` are listed because they are cheap to answer and otherwise stay
as generated placeholders in the contract forever.
"""
return f"""# Answers for `repoctl init --answers <this file>`.
# Command-line flags of the same meaning override these values.
# Required.
name: my-repository # must match {ID_PATTERN}
repositoryType: project # {" | ".join(sorted(REPOSITORY_TYPES))}
owners: # at least one; a person or a team
- team-or-person
# Optional, but answer them now: each one otherwise stays a placeholder.
title: My repository # defaults to `name`
summary: What this repository is for and what it is not
lifecycle: active # {" | ".join(sorted(LIFECYCLES))}
namespace: Services # the group this repository belongs to
access: internal # {" | ".join(sorted(ACCESS_VALUES))}
gitInit: false # run `git init` when applying
# Optional: declare the content roots yourself instead of taking the
# defaults for `repositoryType`. Each needs id, role, path, kind, authority.
# contentRoots:
# - id: policies
# role: policies
# path: policies
# kind: directory
# authority: source
# writePolicy: managed
"""
class BootstrapError(ValueError):
"""`init` refused to proceed, carrying a stable finding code.
Mirrors ``adoption.AdoptionError``: without a code the CLI can only print a
message, which breaks the machine-readable contract `--output json` makes.
"""
def __init__(self, code: str, message: str) -> None:
super().__init__(f"{code}: {message}")
self.code = code
_NAME_RE = re.compile(ID_PATTERN)
def _suggest_name(value: str) -> str | None:
"""Offer a legal name for a rejected one, so the error is actionable."""
slug = re.sub(r"[^a-z0-9]+", "-", str(value).lower()).strip("-")
slug = re.sub(r"-{2,}", "-", slug)
return slug if slug and _NAME_RE.match(slug) else None
def validate_answers(data: dict[str, Any]) -> None:
"""Reject answers that would produce a repository failing `repoctl validate`.
`init` is the one path where the tool controls every byte it writes, so
emitting a contract that does not match its own schema has no excuse. The
vocabularies live in `constants` and were simply never consulted here.
"""
missing = [field for field in ("name", "repositoryType") if not data.get(field)]
if missing:
raise BootstrapError(
"INIT_ANSWERS_INCOMPLETE", f"Missing required answers: {', '.join(missing)}"
)
name = data["name"]
if not isinstance(name, str) or not _NAME_RE.match(name):
suggestion = _suggest_name(name)
hint = f"; use {suggestion!r}" if suggestion else ""
raise BootstrapError(
"INIT_NAME_INVALID",
f"Repository name {name!r} does not match {ID_PATTERN}{hint}",
)
if data["repositoryType"] not in REPOSITORY_TYPES:
raise BootstrapError(
"INIT_TYPE_UNKNOWN",
f"Unknown repository type {data['repositoryType']!r}; expected one of "
+ ", ".join(sorted(REPOSITORY_TYPES)),
)
lifecycle = data.get("lifecycle", "active")
if lifecycle not in LIFECYCLES:
raise BootstrapError(
"INIT_LIFECYCLE_UNKNOWN",
f"Unknown lifecycle {lifecycle!r}; expected one of " + ", ".join(sorted(LIFECYCLES)),
)
access = data.get("access")
if access is not None and access not in ACCESS_VALUES:
raise BootstrapError(
"INIT_ACCESS_UNKNOWN",
f"Unknown access {access!r}; expected one of " + ", ".join(sorted(ACCESS_VALUES)),
)
# The same confirmation boundary `adopt` enforces. Which command created the
# contract does not change the fact that nobody answered the owner question.
if not data.get("owners"):
raise BootstrapError(
"INIT_OWNER_UNKNOWN",
"Owners must be confirmed before a plan can be built (--owner, or owners: in --answers)",
)
@dataclass @dataclass
class BootstrapAnswers: class BootstrapAnswers:
name: str name: str
@@ -71,6 +191,7 @@ class BootstrapAnswers:
@staticmethod @staticmethod
def from_mapping(data: dict[str, Any]) -> BootstrapAnswers: def from_mapping(data: dict[str, Any]) -> BootstrapAnswers:
validate_answers(data)
return BootstrapAnswers( return BootstrapAnswers(
name=data["name"], name=data["name"],
title=data.get("title", data["name"]), title=data.get("title", data["name"]),
@@ -185,7 +306,30 @@ def _render_gitignore() -> str:
return "ops/runs/\n.venv/\n__pycache__/\n" return "ops/runs/\n.venv/\n__pycache__/\n"
def build_bootstrap_plan(answers: BootstrapAnswers) -> dict[str, Any]: def _already_holds(root: Path, file_entry: dict[str, Any]) -> bool:
"""True when the repository already holds exactly what this entry would write.
The collision check protects content the tool did not author, and identical
bytes are nothing to protect. Without this, `repoctl skills install` -- the
documented way to make the bootstrap skill reachable at all -- writes the
three skill files and thereby makes `init` refuse the very repository it was
installed to bootstrap.
"""
try:
current = (root / file_entry["path"]).read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError):
return False
return bool(current.strip() == str(file_entry["content"]).strip())
def build_bootstrap_plan(answers: BootstrapAnswers, root: Path | None = None) -> dict[str, Any]:
"""Build the plan, refusing up front what `apply` would refuse anyway.
``root`` is optional only so existing callers that plan without a target keep
working. When it is given, a path the repository already holds is reported
here rather than after the owner has read and approved a plan that could
never be applied.
"""
contract_text = _render_contract(answers) contract_text = _render_contract(answers)
files = [ files = [
{"path": "ops/contract.yaml", "content": contract_text}, {"path": "ops/contract.yaml", "content": contract_text},
@@ -198,6 +342,20 @@ def build_bootstrap_plan(answers: BootstrapAnswers) -> dict[str, Any]:
{"path": ".claude/skills/repository-adoption/SKILL.md", "content": REPOSITORY_ADOPTION_SKILL}, {"path": ".claude/skills/repository-adoption/SKILL.md", "content": REPOSITORY_ADOPTION_SKILL},
{"path": ".claude/skills/repo-handoff/SKILL.md", "content": REPO_HANDOFF_SKILL}, {"path": ".claude/skills/repo-handoff/SKILL.md", "content": REPO_HANDOFF_SKILL},
] ]
if root is not None:
occupied = [
entry["path"]
for entry in files
if (root / entry["path"]).exists() and not _already_holds(root, entry)
]
if occupied:
raise BootstrapError(
"INIT_PATH_COLLISION",
"Repository already holds paths this plan would create: "
+ ", ".join(occupied)
+ ". Use `repoctl adopt` for an existing repository.",
)
plan: dict[str, Any] = { plan: dict[str, Any] = {
"schema": "stewardship/bootstrap-plan@0.1", "schema": "stewardship/bootstrap-plan@0.1",
"repository": answers.name, "repository": answers.name,
@@ -219,15 +377,31 @@ def apply_bootstrap_plan(root: Path, plan: dict[str, Any], approve_hash: str) ->
if approve_hash != plan["planHash"]: if approve_hash != plan["planHash"]:
raise ValueError("Approval hash does not match plan hash") raise ValueError("Approval hash does not match plan hash")
written: list[str] = [] # A plan is an ordinary file that can be hand-edited or moved between
# machines. `root / path` silently discards `root` for an absolute path and
# happily walks out of the repository for a relative one, so every target is
# confined before anything is written -- the same boundary `adopt` applies.
targets: list[tuple[str, Path, str]] = []
already_present: list[str] = []
for file_entry in plan["files"]: for file_entry in plan["files"]:
target = root / file_entry["path"] rel_path = file_entry["path"]
try:
target = confined_path(root, rel_path)
except PathViolation as exc:
raise BootstrapError("INIT_PATH_OUTSIDE_REPOSITORY", f"{rel_path}: {exc}") from exc
if target.exists(): if target.exists():
raise FileExistsError(f"Refusing to overwrite existing file: {file_entry['path']}") if _already_holds(root, file_entry):
for file_entry in plan["files"]: already_present.append(rel_path)
target = root / file_entry["path"] continue
io.write_text_atomic(target, file_entry["content"]) raise FileExistsError(f"Refusing to overwrite existing file: {rel_path}")
written.append(file_entry["path"]) targets.append((rel_path, target, file_entry["content"]))
# `already_present` is intentionally not written and not reported as
# written: `init` claims only the files it actually authored.
written: list[str] = []
for rel_path, target, content in targets:
io.write_text_atomic(target, content)
written.append(rel_path)
if plan.get("gitInit") and not (root / ".git").exists(): if plan.get("gitInit") and not (root / ".git").exists():
subprocess.run(["git", "init"], cwd=root, check=True, capture_output=True) subprocess.run(["git", "init"], cwd=root, check=True, capture_output=True)
+130 -18
View File
@@ -12,8 +12,9 @@ import sys
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from . import adoption, bootstrap, config, discovery, io from . import adoption, bootstrap, config, discovery, io, skills
from .constants import CONTRACT_PATH, REPOSITORY_TYPES, RESULT_SCHEMA from . import kdb_table
from .constants import CONTRACT_PATH, LIFECYCLES, REPOSITORY_TYPES, RESULT_SCHEMA
from .context import build_context from .context import build_context
from .paths import find_repository_root from .paths import find_repository_root
from .render import build_envelope, emit from .render import build_envelope, emit
@@ -87,6 +88,35 @@ def cmd_config(args: argparse.Namespace) -> int:
raise CliError("Unknown config action") raise CliError("Unknown config action")
def cmd_skills(args: argparse.Namespace) -> int:
repo = Path(args.repo).expanduser() if args.repo else None
try:
base = skills.target_base(repo, global_scope=args.global_scope)
if args.skills_action == "status":
report = skills.status(base)
findings = [
Finding("info", f"SKILL_{item['state'].upper()}", item["skill"], path=item["path"])
for item in report
]
_write(
build_envelope(
"skills status", "success", {"target": skills.skills_dir(base).as_posix(), "skills": report}, findings
),
args.output,
)
return EXIT_SUCCESS
result = skills.install(base, force=args.force)
except skills.SkillsError as exc:
# Same envelope path as init/adopt: a refusal stays machine-readable.
_write(
build_envelope("skills " + args.skills_action, "failure", None, [Finding("error", exc.code, str(exc).split(": ", 1)[1])]),
args.output,
)
return EXIT_VALIDATION_FAILURE
_write(build_envelope("skills install", "success", result, []), args.output)
return EXIT_SUCCESS
def cmd_validate(args: argparse.Namespace) -> int: def cmd_validate(args: argparse.Namespace) -> int:
root = _resolve_repo(args.repo, args.root) root = _resolve_repo(args.repo, args.root)
result = validate_repository(root) result = validate_repository(root)
@@ -117,6 +147,26 @@ def cmd_describe(args: argparse.Namespace) -> int:
return EXIT_VALIDATION_FAILURE if findings else EXIT_SUCCESS return EXIT_VALIDATION_FAILURE if findings else EXIT_SUCCESS
def cmd_kdb(args: argparse.Namespace) -> int:
"""Show what the knowledge base holds, for a human to read."""
root = _resolve_repo(args.repo, args.root)
data = kdb_table.collect(root)
if data is None:
rel = kdb_table.entrypoint(root)
finding = Finding(
"warning",
"KNOWLEDGE_ENTRYPOINT_MISSING",
f"No knowledge base at {rel}",
path=CONTRACT_PATH,
)
_write(build_envelope("kdb", "failure", {"repository": str(root)}, [finding]), args.output)
return EXIT_NOT_FOUND
envelope = build_envelope("kdb", "success", data, [])
# Findings still go to stderr; the table goes to stdout, so piping it
# out yields clean Markdown.
emit(envelope, args.output, lambda e: print(kdb_table.markdown(e["data"])))
return EXIT_SUCCESS
def cmd_context(args: argparse.Namespace) -> int: def cmd_context(args: argparse.Namespace) -> int:
root = _resolve_repo(args.repo, args.root) root = _resolve_repo(args.repo, args.root)
result = build_context( result = build_context(
@@ -148,6 +198,14 @@ def cmd_context(args: argparse.Namespace) -> int:
def cmd_init(args: argparse.Namespace) -> int: def cmd_init(args: argparse.Namespace) -> int:
if args.answers_template:
# A template is a document to save and edit, not a result to parse, so
# it is printed as the YAML file it is meant to become:
# repoctl init --answers-template > answers.yaml
print(bootstrap.answers_template(), end="")
return EXIT_SUCCESS
if not args.repo:
raise CliError("--repo is required (or use --answers-template)", EXIT_INVALID_INPUT)
repo_path = Path(args.repo).expanduser() repo_path = Path(args.repo).expanduser()
if args.apply: if args.apply:
if not args.plan or not args.approve: if not args.plan or not args.approve:
@@ -156,6 +214,8 @@ def cmd_init(args: argparse.Namespace) -> int:
repo_path.mkdir(parents=True, exist_ok=True) repo_path.mkdir(parents=True, exist_ok=True)
try: try:
written = bootstrap.apply_bootstrap_plan(repo_path, plan, args.approve) written = bootstrap.apply_bootstrap_plan(repo_path, plan, args.approve)
except bootstrap.BootstrapError as exc:
return _adoption_failure("init apply", exc, args.output)
except ValueError as exc: except ValueError as exc:
_write(build_envelope("init apply", "failure", None, [Finding("error", "APPROVAL_FAILED", str(exc))]), args.output) _write(build_envelope("init apply", "failure", None, [Finding("error", "APPROVAL_FAILED", str(exc))]), args.output)
return EXIT_APPROVAL return EXIT_APPROVAL
@@ -182,26 +242,34 @@ def cmd_init(args: argparse.Namespace) -> int:
if args.git_init: if args.git_init:
answers_data["gitInit"] = True answers_data["gitInit"] = True
missing = [f for f in ("name", "repositoryType") if f not in answers_data] try:
if missing:
raise CliError(f"Missing required answers: {', '.join(missing)}", EXIT_INVALID_INPUT)
answers = bootstrap.BootstrapAnswers.from_mapping(answers_data) answers = bootstrap.BootstrapAnswers.from_mapping(answers_data)
plan = bootstrap.build_bootstrap_plan(answers) # Passing the target lets `plan` refuse a directory that is already a
# repository, instead of leaving the collision for `apply` to discover
# after the owner has reviewed and approved.
plan = bootstrap.build_bootstrap_plan(answers, repo_path)
except bootstrap.BootstrapError as exc:
return _adoption_failure("init plan", exc, args.output)
_write(build_envelope("init plan", "success", plan, []), args.output) _write(build_envelope("init plan", "success", plan, []), args.output)
return EXIT_SUCCESS return EXIT_SUCCESS
def _adoption_failure(command: str, exc: adoption.AdoptionError, output: str) -> int: def _adoption_failure(
"""Report a refused adoption step as an envelope, not as a bare stderr line. command: str, exc: adoption.AdoptionError | bootstrap.BootstrapError, output: str
) -> int:
"""Report a refused init/adoption step as an envelope, not a bare stderr line.
Every mode of `adopt` can now raise `AdoptionError`, including `plan`, which Every mode of `adopt` can now raise `AdoptionError`, including `plan`, which
validates the managed block of an existing entrypoint and decides the validates the managed block of an existing entrypoint and decides the
knowledge entrypoint by content. Letting those reach the top-level safety net knowledge entrypoint by content, and `init` raises `BootstrapError` for
would print a message and exit, breaking the machine-readable contract that answers that would produce an invalid repository. Letting those reach the
`--output json` promises. top-level safety net would print a message and exit, breaking the
machine-readable contract that `--output json` promises.
""" """
_write(build_envelope(command, "failure", None, [Finding("error", exc.code, str(exc))]), output) # `str(exc)` is already "CODE: message" and the finding carries the code, so
# rendering both repeats it back to the reader.
message = str(exc).removeprefix(f"{exc.code}: ")
_write(build_envelope(command, "failure", None, [Finding("error", exc.code, message)]), output)
return EXIT_APPROVAL if exc.code == "APPROVAL_FAILED" else EXIT_VALIDATION_FAILURE return EXIT_APPROVAL if exc.code == "APPROVAL_FAILED" else EXIT_VALIDATION_FAILURE
@@ -226,7 +294,10 @@ def cmd_adopt(args: argparse.Namespace) -> int:
answers = io.load_yaml(Path(args.answers)) answers = io.load_yaml(Path(args.answers))
else: else:
answers = {} answers = {}
name = answers.get("name") or repo_path.name.lower() # The clone directory is not an identity; assess proposes one from the
# remote and only falls back to the directory when there is none.
name = answers.get("name") or assessment["identity"]["name"]
owners = list(args.owner or []) or answers.get("owners")
confirmed_type = args.type or answers.get("repositoryType") confirmed_type = args.type or answers.get("repositoryType")
if confirmed_type is not None and confirmed_type not in REPOSITORY_TYPES: if confirmed_type is not None and confirmed_type not in REPOSITORY_TYPES:
raise CliError( raise CliError(
@@ -238,14 +309,21 @@ def cmd_adopt(args: argparse.Namespace) -> int:
assessment, assessment,
confirmed_name=name, confirmed_name=name,
confirmed_title=answers.get("title"), confirmed_title=answers.get("title"),
confirmed_owners=answers.get("owners"), confirmed_owners=owners,
confirmed_lifecycle=answers.get("lifecycle", "active"), confirmed_lifecycle=answers.get("lifecycle", "active"),
confirmed_type=confirmed_type, confirmed_type=confirmed_type,
strategy=args.strategy, strategy=args.strategy,
acknowledged=answers.get("acknowledgedFindings"),
) )
except adoption.AdoptionError as exc: except adoption.AdoptionError as exc:
return _adoption_failure("adopt plan", exc, args.output) return _adoption_failure("adopt plan", exc, args.output)
_write(build_envelope("adopt plan", "success", plan, []), args.output) # A plan that carried findings but reported none made the warnings assess
# raised invisible at exactly the step the owner reads before approving.
plan_findings = [
Finding(f["severity"], f["code"], f.get("message", f["code"]), path=f.get("path"))
for f in plan.get("findings", [])
]
_write(build_envelope("adopt plan", "success", plan, plan_findings), args.output)
return EXIT_SUCCESS return EXIT_SUCCESS
if args.mode == "apply": if args.mode == "apply":
@@ -292,6 +370,24 @@ def build_parser() -> argparse.ArgumentParser:
p_remove_root.add_argument("path") p_remove_root.add_argument("path")
p_config.set_defaults(func=cmd_config) p_config.set_defaults(func=cmd_config)
p_skills = sub.add_parser("skills")
add_common(p_skills)
skills_sub = p_skills.add_subparsers(dest="skills_action", required=True)
for action in ("install", "status"):
p_action = skills_sub.add_parser(action)
add_common(p_action)
p_action.add_argument("--repo")
p_action.add_argument("--global", dest="global_scope", action="store_true")
if action == "install":
p_action.add_argument(
"--force",
action="store_true",
help="Replace a skill whose content differs from the one this version ships",
)
else:
p_action.set_defaults(force=False)
p_skills.set_defaults(func=cmd_skills)
p_validate = sub.add_parser("validate") p_validate = sub.add_parser("validate")
add_common(p_validate) add_common(p_validate)
p_validate.add_argument("--repo") p_validate.add_argument("--repo")
@@ -309,6 +405,11 @@ def build_parser() -> argparse.ArgumentParser:
p_describe.add_argument("--root", action="append") p_describe.add_argument("--root", action="append")
p_describe.set_defaults(func=cmd_describe) p_describe.set_defaults(func=cmd_describe)
p_kdb = sub.add_parser("kdb")
p_kdb.add_argument("--output", choices=["human", "yaml", "json"], default="human")
p_kdb.add_argument("--repo")
p_kdb.add_argument("--root", action="append")
p_kdb.set_defaults(func=cmd_kdb)
p_context = sub.add_parser("context") p_context = sub.add_parser("context")
add_common(p_context) add_common(p_context)
p_context.add_argument("--repo") p_context.add_argument("--repo")
@@ -322,13 +423,19 @@ def build_parser() -> argparse.ArgumentParser:
p_init = sub.add_parser("init") p_init = sub.add_parser("init")
add_common(p_init) add_common(p_init)
p_init.add_argument("--repo", required=True) p_init.add_argument("--repo")
p_init.add_argument(
"--answers-template",
dest="answers_template",
action="store_true",
help="Print a commented answers file naming every key and its allowed values, then exit",
)
p_init.add_argument("--answers") p_init.add_argument("--answers")
p_init.add_argument("--name") p_init.add_argument("--name")
p_init.add_argument("--type", dest="type", choices=["infrastructure-config", "service-config", "software", "project"]) p_init.add_argument("--type", dest="type", choices=["infrastructure-config", "service-config", "software", "project"])
p_init.add_argument("--title") p_init.add_argument("--title")
p_init.add_argument("--owner", action="append") p_init.add_argument("--owner", action="append")
p_init.add_argument("--lifecycle") p_init.add_argument("--lifecycle", choices=sorted(LIFECYCLES))
p_init.add_argument("--git-init", action="store_true") p_init.add_argument("--git-init", action="store_true")
p_init.add_argument("--no-git-init", dest="git_init", action="store_false") p_init.add_argument("--no-git-init", dest="git_init", action="store_false")
p_init.set_defaults(git_init=None) p_init.set_defaults(git_init=None)
@@ -342,6 +449,11 @@ def build_parser() -> argparse.ArgumentParser:
p_adopt.add_argument("--repo", required=True) p_adopt.add_argument("--repo", required=True)
p_adopt.add_argument("--mode", required=True, choices=["assess", "plan", "apply", "verify"]) p_adopt.add_argument("--mode", required=True, choices=["assess", "plan", "apply", "verify"])
p_adopt.add_argument("--answers") p_adopt.add_argument("--answers")
p_adopt.add_argument(
"--owner",
action="append",
help="Confirm an owner; required before a plan can be built",
)
p_adopt.add_argument( p_adopt.add_argument(
"--type", "--type",
dest="type", dest="type",
+33
View File
@@ -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)
+21 -2
View File
@@ -67,19 +67,38 @@ def dirty_paths(root: Path) -> set[str]:
return paths return paths
def ignored(root: Path, relative_paths: list[str]) -> set[str]: def remote_url(root: Path, name: str = "origin") -> str | None:
"""Return the URL of remote ``name``, or None when it is not configured.
Read-only: this never contacts the remote, it only reads local config. Used
to derive a repository identity from something the owner actually chose,
instead of from whatever the clone directory happens to be called.
"""
result = _run(["remote", "get-url", name], root)
if result.returncode != 0:
return None
url = result.stdout.strip()
return url or None
def ignored(root: Path, relative_paths: list[str], *, no_index: bool = False) -> set[str]:
"""Return the subset of ``relative_paths`` that Git ignores. """Return the subset of ``relative_paths`` that Git ignores.
Used to keep the secret-shaped scan quiet about gitignored material and to Used to keep the secret-shaped scan quiet about gitignored material and to
avoid walking large ignored trees. Returns an empty set when Git is avoid walking large ignored trees. Returns an empty set when Git is
unavailable, so callers degrade to reporting everything rather than nothing. unavailable, so callers degrade to reporting everything rather than nothing.
``no_index`` evaluates the ignore rules alone. By default `check-ignore`
stays silent about a tracked path even when a rule matches it, which hides
the case worth reporting most: a file the repository's own `.gitignore`
excludes and which was nevertheless committed.
""" """
if not relative_paths: if not relative_paths:
return set() return set()
# `check-ignore` needs the candidates on stdin; `_run` does not pipe input, # `check-ignore` needs the candidates on stdin; `_run` does not pipe input,
# so issue the call directly here rather than widening the shared helper. # so issue the call directly here rather than widening the shared helper.
result = subprocess.run( result = subprocess.run(
["git", "check-ignore", "-z", "--stdin"], ["git", "check-ignore", "-z", "--stdin", *(["--no-index"] if no_index else [])],
cwd=root, cwd=root,
input="\0".join(relative_paths), input="\0".join(relative_paths),
capture_output=True, capture_output=True,
+96
View File
@@ -0,0 +1,96 @@
"""`repoctl kdb`: a repository's KnowledgeBase as a table a human can read.
Read-only. The structured form goes into the result envelope like every other
command; the Markdown table is what `--output human` renders instead of the
usual one-line outcome, because "what is in the knowledge base" is a question
whose answer is the content, not a status.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from . import io as sio
from .constants import CONTRACT_PATH
def entrypoint(root: Path) -> Path:
"""The knowledge entrypoint the contract declares, or the canonical default.
Read from the contract rather than assumed: a repository may legitimately
keep its knowledge base somewhere other than `kdb/kdb.yaml`, and guessing
would report an adopted repository as having none.
"""
contract = root / CONTRACT_PATH
if contract.exists():
loaded = sio.load_yaml(contract)
spec = (loaded or {}).get("spec") or {} if isinstance(loaded, dict) else {}
knowledge = spec.get("knowledge") if isinstance(spec.get("knowledge"), dict) else {}
rel = (knowledge or {}).get("entrypoint")
if isinstance(rel, str) and rel:
return root / rel
return root / "kdb/kdb.yaml"
def collect(root: Path) -> dict[str, Any] | None:
"""The overview as plain data, or None when the repository has no knowledge base."""
path = entrypoint(root)
if not path.exists():
return None
loaded = sio.load_yaml(path)
spec = (loaded or {}).get("spec") or {} if isinstance(loaded, dict) else {}
topics = [t for t in (spec.get("topics") or []) if isinstance(t, dict)]
documents = [d for d in (spec.get("documents") or []) if isinstance(d, dict)]
return {
"schema": "stewardship/knowledge-overview@0.1",
"entrypoint": path.relative_to(root).as_posix(),
"repository": spec.get("repository") or root.name,
"topics": [
{
"id": t.get("id"),
"priority": t.get("priority"),
"intents": list(t.get("intents") or []),
"documents": list(t.get("documents") or []),
"dataKeys": list((t.get("data") or {}) if isinstance(t.get("data"), dict) else []),
}
for t in sorted(topics, key=lambda x: -(x.get("priority") or 0))
],
"documents": [
{
"id": d.get("id"),
"path": d.get("path") or d.get("uri"),
"role": d.get("role"),
"status": d.get("status"),
}
for d in documents
],
}
def markdown(data: dict[str, Any]) -> str:
"""The overview as a compact Markdown table."""
topics, documents = data["topics"], data["documents"]
out = [
f"## {data['repository']} - {len(topics)} topics, {len(documents)} documents",
f"<!-- {data['entrypoint']} -->",
"",
"| Topic | Intents | Documents | Facts in data |",
"| --- | --- | --- | --- |",
]
for t in topics:
out.append(
f"| **{t['id']}** | {', '.join(t['intents']) or '-'} "
f"| {', '.join(t['documents']) or '-'} | {', '.join(t['dataKeys']) or '-'} |"
)
out += ["", "### Documents", "", "| Id | Path | Role | Status |", "| --- | --- | --- | --- |"]
for d in documents:
stale = " (!)" if d["status"] == "stale" else ""
out.append(f"| {d['id']} | `{d['path'] or '-'}` | {d['role']} | {d['status']}{stale} |")
return "\n".join(out)
def render(root: Path) -> str:
"""Markdown for ``root``, or a plain sentence when there is no knowledge base."""
data = collect(root)
return markdown(data) if data else f"No knowledge base at {entrypoint(root)}."
+45 -2
View File
@@ -10,11 +10,16 @@ from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from urllib.parse import unquote
from .io import ResourceError from .io import ResourceError
from .types import Finding from .types import Finding
_FENCE_RE = re.compile(r"^(```+|~~~+)(\S*)\s*$") _FENCE_RE = re.compile(r"^(```+|~~~+)(\S*)\s*$")
_LINK_RE = re.compile(r"(?<!!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)") _LINK_RE = re.compile(r"(?<!!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
# A backtick run closed by a run of the same length, per CommonMark. Non-greedy
# so `a` and `b` on one line stay two spans rather than one spanning both.
_INLINE_CODE_RE = re.compile(r"(?P<fence>`+)(?:(?!(?P=fence)).)*(?P=fence)", re.DOTALL)
_MERMAID_HEADERS = { _MERMAID_HEADERS = {
"flowchart", "flowchart",
"graph", "graph",
@@ -141,11 +146,49 @@ def _check_fences(text: str, rel_path: str) -> list[Finding]:
return findings return findings
def _blank_out(text: str) -> str:
"""Replace ``text`` with spaces, keeping newlines so line numbers do not move."""
return "".join("\n" if char == "\n" else " " for char in text)
def mask_code(text: str) -> str:
"""Blank out fenced blocks and inline code spans, preserving every offset.
Link-shaped text inside code is not a link. A PowerShell snippet such as
`[string]([IO.File]::ReadAllText($path))` parses as a Markdown link and was
reported as a missing local target, which is enough to keep `validate` red in
a repository whose documentation quotes shell at all. Masking rather than
deleting keeps reported positions aligned with the real file.
"""
lines = text.splitlines(keepends=True)
masked: list[str] = []
open_marker: str | None = None
for line in lines:
match = _FENCE_RE.match(line.rstrip("\r\n"))
if open_marker is None:
if match:
open_marker = match.group(1)
masked.append(line)
continue
# Inside a fence: the body is masked, and the fence lines themselves are
# kept so `_check_fences` still sees a balanced pair if it ever reuses this.
if match and match.group(1)[0] == open_marker[0]:
open_marker = None
masked.append(line)
else:
masked.append(_blank_out(line))
joined = "".join(masked)
return _INLINE_CODE_RE.sub(lambda m: _blank_out(m.group(0)), joined)
def _check_local_links(repo_root: Path, rel_path: str, text: str) -> list[Finding]: def _check_local_links(repo_root: Path, rel_path: str, text: str) -> list[Finding]:
findings: list[Finding] = [] findings: list[Finding] = []
base_dir = (repo_root / rel_path).parent base_dir = (repo_root / rel_path).parent
for match in _LINK_RE.finditer(text): for match in _LINK_RE.finditer(mask_code(text)):
target = match.group(1) # A link to a name with spaces or non-ASCII is percent-encoded by every
# Markdown renderer that produces one. Comparing the encoded form against
# the filesystem reports a file that is plainly there as missing.
target = unquote(match.group(1))
if target.startswith(("http://", "https://", "mailto:", "#")): if target.startswith(("http://", "https://", "mailto:", "#")):
continue continue
target_path_part = target.split("#", 1)[0] target_path_part = target.split("#", 1)[0]
+17 -4
View File
@@ -8,21 +8,34 @@ class PathViolation(ValueError):
"""A resource path escapes the repository boundary.""" """A resource path escapes the repository boundary."""
def normalize_resource_path(value: str) -> str: def normalize_resource_path(value: str, *, allow_root: bool = False) -> str:
"""Normalize a repository-relative path, rejecting anything that could escape.
``allow_root`` permits the single value ``"."``. A content root may legitimately
be the repository itself -- a repository holding one stack per directory is
declared as ``path: "."`` with a selector, per adoption-runbook 7.2 -- but that
is only ever a whole path, never a segment, and never a write target.
"""
if not value or not isinstance(value, str): if not value or not isinstance(value, str):
raise PathViolation("Path must be a non-empty string") raise PathViolation("Path must be a non-empty string")
if "\\" in value or value.startswith(("/", "\\")) or ":" in value.split("/")[0]: if "\\" in value or value.startswith(("/", "\\")) or ":" in value.split("/")[0]:
raise PathViolation("Path must be repository-relative and use '/' separators") raise PathViolation("Path must be repository-relative and use '/' separators")
if value == ".":
if allow_root:
return "."
raise PathViolation("Path must name something inside the repository")
parts = value.split("/") parts = value.split("/")
if any(part in {"", ".", ".."} for part in parts): if any(part in {"", ".", ".."} for part in parts):
raise PathViolation("Path contains an unsafe segment") raise PathViolation("Path contains an unsafe segment")
return "/".join(parts) return "/".join(parts)
def confined_path(root: Path, value: str, *, must_exist: bool = False) -> Path: def confined_path(
normalized = normalize_resource_path(value) root: Path, value: str, *, must_exist: bool = False, allow_root: bool = False
) -> Path:
normalized = normalize_resource_path(value, allow_root=allow_root)
root_resolved = root.resolve(strict=True) root_resolved = root.resolve(strict=True)
candidate = root_resolved.joinpath(*normalized.split("/")) candidate = root_resolved if normalized == "." else root_resolved.joinpath(*normalized.split("/"))
# Walk up to the nearest ancestor that actually exists before resolving # Walk up to the nearest ancestor that actually exists before resolving
# strictly: neither the candidate nor any number of its parent directories # strictly: neither the candidate nor any number of its parent directories
# are guaranteed to exist yet (e.g. a document path with a missing parent # are guaranteed to exist yet (e.g. a document path with a missing parent
@@ -17,6 +17,15 @@
"dirty": { "type": "boolean" } "dirty": { "type": "boolean" }
} }
}, },
"identity": {
"type": "object",
"required": ["name", "source"],
"additionalProperties": false,
"properties": {
"name": { "type": "string" },
"source": { "enum": ["git-remote", "directory"] }
}
},
"classification": { "classification": {
"type": "object", "type": "object",
"required": ["proposedType", "confidence", "evidence", "confirmationRequired"], "required": ["proposedType", "confidence", "evidence", "confirmationRequired"],
@@ -60,6 +69,8 @@
"id": { "type": "string" }, "id": { "type": "string" },
"path": { "type": "string" }, "path": { "type": "string" },
"role": { "type": "string" }, "role": { "type": "string" },
"kind": { "enum": ["directory", "file", "file-set", "manifest"] },
"selector": { "type": "string" },
"authority": { "enum": ["source", "generated", "observed", "mirror", "evidence"] }, "authority": { "enum": ["source", "generated", "observed", "mirror", "evidence"] },
"writePolicy": { "enum": ["managed", "read-only", "generated"] }, "writePolicy": { "enum": ["managed", "read-only", "generated"] },
"generatedFrom": { "type": "array", "items": { "type": "string" } } "generatedFrom": { "type": "array", "items": { "type": "string" } }
@@ -28,6 +28,33 @@
} }
} }
}, },
"findings": {
"type": "array",
"items": {
"type": "object",
"required": ["severity", "code"],
"additionalProperties": false,
"properties": {
"severity": { "enum": ["info", "warning", "error"] },
"code": { "type": "string" },
"path": { "type": "string" },
"message": { "type": "string" }
}
}
},
"acknowledgedFindings": {
"type": "array",
"items": {
"type": "object",
"required": ["code", "reason"],
"additionalProperties": false,
"properties": {
"code": { "type": "string" },
"path": { "type": "string" },
"reason": { "type": "string", "minLength": 1 }
}
}
},
"forbiddenChanges": { "type": "array", "items": { "type": "string" } }, "forbiddenChanges": { "type": "array", "items": { "type": "string" } },
"validations": { "type": "array", "items": { "type": "string" } }, "validations": { "type": "array", "items": { "type": "string" } },
"approval": { "approval": {
+134
View File
@@ -0,0 +1,134 @@
"""`repoctl skills`: put the stewardship agent skills where an agent looks for them.
The skills were distributed by exactly one path: `init`, which only ever runs on
a *new* repository. Adopting an existing repository needs the adoption skill,
and nothing could install it there -- so the entry point to the whole procedure
depended on the operator already having the skill from somewhere else.
This command is deliberately not plan-then-approve. That discipline exists to
protect a repository's own content, and nothing here touches it: the targets are
a fixed set of tool-owned files under a fixed subdirectory, with content
determined entirely by the installed version of repoctl. What it does keep is
the house rule that a write never destroys something it did not author -- a
skill whose content differs is reported, not overwritten.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from . import io
from .paths import PathViolation, confined_path
from .skills_content import (
KDB_TABLE_SKILL,
REPO_HANDOFF_SKILL,
REPOSITORY_ADOPTION_SKILL,
REPOSITORY_BOOTSTRAP_SKILL,
)
SKILLS_SUBPATH = ".claude/skills"
SKILLS: dict[str, str] = {
"kdb-table": KDB_TABLE_SKILL,
"repo-handoff": REPO_HANDOFF_SKILL,
"repository-adoption": REPOSITORY_ADOPTION_SKILL,
"repository-bootstrap": REPOSITORY_BOOTSTRAP_SKILL,
}
class SkillsError(ValueError):
"""`repoctl skills` refused to proceed, carrying a stable finding code."""
def __init__(self, code: str, message: str) -> None:
super().__init__(f"{code}: {message}")
self.code = code
def target_base(repo: Path | None, *, global_scope: bool) -> Path:
"""The directory the skills tree hangs under: a repository, or the user's home.
A repository-local install travels with the repository and is what a
teammate cloning it gets; a global install follows the operator across every
repository, including ones not adopted yet. Both are legitimate, and which
one is wanted cannot be guessed, so one of them must be stated.
"""
if global_scope and repo is not None:
raise SkillsError("SKILLS_SCOPE_AMBIGUOUS", "Use either --repo or --global, not both")
if global_scope:
return Path.home()
if repo is None:
raise SkillsError(
"SKILLS_SCOPE_MISSING",
"Say where the skills go: --repo PATH for one repository, or --global for every one",
)
base = repo.expanduser()
if not base.is_dir():
raise SkillsError("SKILLS_TARGET_MISSING", f"No such directory: {base}")
return base.resolve()
def skills_dir(base: Path) -> Path:
"""Where the skills live under ``base``."""
return base / SKILLS_SUBPATH
def _skill_path(base: Path, name: str) -> Path:
# Confined against the base rather than the skills directory: the latter
# routinely does not exist yet, and confinement needs a real root to
# resolve against.
try:
return confined_path(base, f"{SKILLS_SUBPATH}/{name}/SKILL.md")
except PathViolation as exc: # pragma: no cover - names are module constants
raise SkillsError("SKILLS_PATH_OUTSIDE_TARGET", f"{name}: {exc}") from exc
def status(base: Path) -> list[dict[str, str]]:
"""Report each skill as ``missing``, ``current`` or ``modified``.
``modified`` deliberately does not distinguish "the operator edited it" from
"repoctl moved on": both mean the file on disk is not the one this version
ships, and neither is safe to overwrite without being asked.
"""
report: list[dict[str, str]] = []
for name, content in SKILLS.items():
path = _skill_path(base, name)
if not path.exists():
state = "missing"
else:
on_disk = path.read_text(encoding="utf-8", errors="replace")
state = "current" if on_disk.strip() == content.strip() else "modified"
report.append({"skill": name, "state": state, "path": path.as_posix()})
return report
def install(base: Path, *, force: bool = False) -> dict[str, Any]:
"""Write every missing skill; refuse to replace one whose content differs.
Nothing is written until every target has been checked, so a refusal leaves
the directory exactly as it was rather than half-updated.
"""
current = status(base)
modified = [item["skill"] for item in current if item["state"] == "modified"]
if modified and not force:
raise SkillsError(
"SKILLS_MODIFIED",
"Already present with different content: "
+ ", ".join(sorted(modified))
+ ". Re-run with --force to replace them.",
)
written: list[str] = []
for item in current:
if item["state"] == "current":
continue
name = item["skill"]
io.write_text_atomic(_skill_path(base, name), SKILLS[name])
written.append(name)
return {
"target": skills_dir(base).as_posix(),
"installed": sorted(written),
"unchanged": sorted(i["skill"] for i in current if i["state"] == "current"),
"skills": status(base),
}
+71 -8
View File
@@ -18,10 +18,18 @@ rendering or validation here - call the CLI and explain its output.
## Procedure ## Procedure
1. Collect the missing decisions from the user: repository type 1. Run `repoctl init --answers-template > answers.yaml`. It names every key, its
(`infrastructure-config` | `service-config` | `software` | `project`), `metadata.name`, allowed values and its default; the answers keys are not the flag names
`title`, `owners`, `lifecycle`. (`--type` sets `repositoryType`). Fill it in with the user.
2. Run `repoctl init --repo <path> --answers <answers-file> --output json` to obtain a Answer `summary` and `namespace` too: they are cheap now and otherwise stay
as placeholders in the contract.
All values are refused rather than guessed -- `name` must match
`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`, `owners` must be non-empty -- and before
choosing a name, look at the sibling repositories and follow their convention.
If the target already holds `ops/contract.yaml`, this is an existing
repository: use `repository-adoption`, not `init`. Skill files left by
`repoctl skills install` are not a collision.
2. Run `repoctl init --repo <path> --answers answers.yaml --output json` to obtain a
`BootstrapPlan` (this performs no writes). `BootstrapPlan` (this performs no writes).
3. Show the user the planned files and the `planHash`. 3. Show the user the planned files and the `planHash`.
4. Only after explicit approval, run 4. Only after explicit approval, run
@@ -47,17 +55,23 @@ with machine output, and explains findings. It must not duplicate the runbook lo
1. Run `repoctl adopt --repo <path> --mode assess --output json` (read-only). 1. Run `repoctl adopt --repo <path> --mode assess --output json` (read-only).
2. Present the classification, detected content roots, and any `questions` that need 2. Present the classification, detected content roots, and any `questions` that need
owner confirmation. owner confirmation.
3. Run `repoctl adopt --repo <path> --mode plan --output json` once open questions are 3. Run `repoctl adopt --repo <path> --mode plan --owner <owner> --output json` once open
resolved. This is still read-only and returns an `AdoptionPlan` with a `planHash`. questions are resolved. This is still read-only and returns an `AdoptionPlan` with a
`planHash`. `plan` refuses without a confirmed owner, and refuses while `assess` left
an error-severity finding; an owner who accepts one lists it under
`acknowledgedFindings` (with a `reason`) in the `--answers` file.
4. Show the full plan (files created, patched managed blocks, preserved paths, 4. Show the full plan (files created, patched managed blocks, preserved paths,
forbidden changes) before asking for approval. forbidden changes) before asking for approval.
5. Only after explicit approval, run 5. Only after explicit approval, run
`repoctl adopt --repo <path> --mode apply --plan <plan-file> --approve <planHash>`. `repoctl adopt --repo <path> --mode apply --plan <plan-file> --approve <planHash>`.
`--plan` accepts the file exactly as `--output json > plan.json` wrote it: the
result envelope is unwrapped for you, so do not strip it down to `data` by hand.
6. Run `repoctl adopt --repo <path> --mode verify --output json` and report the 6. Run `repoctl adopt --repo <path> --mode verify --output json` and report the
`AdoptionReport`, including any `unresolvedFindings`. `AdoptionReport`, including any `unresolvedFindings`.
Default strategy is `overlay`. Only use `--strategy normalize --recipe The only implemented strategy is `overlay`. Normalization recipes are specified in the
documents-to-content-root` when the owner explicitly asks to reorganize root documents. runbook but not implemented, and the CLI does not offer them: do not describe
`--strategy normalize` or `--recipe` as available.
""" """
REPO_HANDOFF_SKILL = """--- REPO_HANDOFF_SKILL = """---
@@ -80,3 +94,52 @@ by hand when this skill applies - let `repoctl` perform the selection.
4. Hand the resulting `ContextBundle` (and any `warnings`) to the requester instead of 4. Hand the resulting `ContextBundle` (and any `warnings`) to the requester instead of
pasting raw repository files. pasting raw repository files.
""" """
KDB_TABLE_SKILL = """---
name: kdb-table
description: Show a repository's knowledge base (its KnowledgeBase entrypoint) to a human as a compact Markdown table of topics, intents and documents. Use when asked what is in the kdb, which topics or intents exist, where a topic routes, what can be passed to `repoctl context`, or for an overview of the knowledge base. Read-only.
---
# kdb-table
Thin wrapper. The knowledge base is machine-readable and long: reading the whole
file to answer "what is in there" is the thing this skill exists to avoid.
```bash
repoctl kdb --repo <path>
```
Like every other command it emits a result envelope; `--output human` renders
the table instead of the usual one-line outcome, and findings still go to stderr,
so piping stdout gives clean Markdown. The entrypoint is read from the
repository's own `ops/contract.yaml`
(`spec.knowledge.entrypoint`), falling back to `kdb/kdb.yaml`, so no path needs
to be guessed and the same command works on any adopted repository. A
repository with no knowledge base gets a `KNOWLEDGE_ENTRYPOINT_MISSING` warning
and exit code 3, not a traceback.
Print the Markdown it emits as-is; do not paraphrase it. Two tables:
- **topics**, by descending `priority`: id, declared intents, the documents the
topic routes to, and the top-level keys of its `data` (what facts sit inside);
- **documents**: id, path, role, status. `stale` is marked `(!)` - such a
document is out of date, and `repoctl context` warns about it when it hands
it over.
## When an overview is not what is wanted
This answers "what exists". To get only what a specific task needs, take an
intent from the Intents column and ask the tool instead:
```bash
repoctl context --repo <path> --intent <intent>
```
An unknown intent is answered with the closest known ones, so the table is
mainly for the human - an agent can afford to guess once.
## Out of scope
It neither edits nor validates the knowledge base. Schema conformance is
`repoctl validate --repo <path>`; run that after editing the entrypoint.
"""
+7 -1
View File
@@ -184,7 +184,13 @@ def _check_content_root_paths(root: Path, spec: dict[str, Any], resource_name: s
continue continue
raw_path = item.get("path") raw_path = item.get("path")
try: try:
confined = confined_path(root, raw_path) if isinstance(raw_path, str) else None # A content root may be the repository itself when the content is a
# set selected across it (runbook 7.2), unlike any other path field.
confined = (
confined_path(root, raw_path, allow_root=True)
if isinstance(raw_path, str)
else None
)
except PathViolation as exc: except PathViolation as exc:
findings.append( findings.append(
Finding( Finding(
+4 -4
View File
@@ -35,7 +35,7 @@ def test_apply_does_not_touch_working_tree_before_approval(make_repo):
repo = make_repo("adoption/lxd-legacy") repo = make_repo("adoption/lxd-legacy")
before = sorted(p.relative_to(repo).as_posix() for p in repo.rglob("*") if p.is_file()) before = sorted(p.relative_to(repo).as_posix() for p in repo.rglob("*") if p.is_file())
assessment = adoption.assess(repo) assessment = adoption.assess(repo)
adoption.build_plan(repo, assessment, confirmed_name="infra-lxd") adoption.build_plan(repo, assessment, confirmed_name="infra-lxd", confirmed_owners=["infrastructure"])
after = sorted(p.relative_to(repo).as_posix() for p in repo.rglob("*") if p.is_file()) after = sorted(p.relative_to(repo).as_posix() for p in repo.rglob("*") if p.is_file())
assert before == after assert before == after
@@ -43,7 +43,7 @@ def test_apply_does_not_touch_working_tree_before_approval(make_repo):
def test_apply_rejects_stale_baseline(make_repo): def test_apply_rejects_stale_baseline(make_repo):
repo = make_repo("adoption/lxd-legacy") repo = make_repo("adoption/lxd-legacy")
assessment = adoption.assess(repo) assessment = adoption.assess(repo)
plan = adoption.build_plan(repo, assessment, confirmed_name="infra-lxd") plan = adoption.build_plan(repo, assessment, confirmed_name="infra-lxd", confirmed_owners=["infrastructure"])
plan["baselineRevision"] = "0" * 40 plan["baselineRevision"] = "0" * 40
with pytest.raises(ValueError): with pytest.raises(ValueError):
adoption.apply_plan(repo, plan, plan["planHash"]) adoption.apply_plan(repo, plan, plan["planHash"])
@@ -77,7 +77,7 @@ def test_assess_antivirus_legacy_detects_occupied_kdb_path(make_repo):
def test_plan_antivirus_legacy_does_not_overwrite_existing_kdb(make_repo): def test_plan_antivirus_legacy_does_not_overwrite_existing_kdb(make_repo):
repo = make_repo("adoption/antivirus-legacy") repo = make_repo("adoption/antivirus-legacy")
assessment = adoption.assess(repo) assessment = adoption.assess(repo)
plan = adoption.build_plan(repo, assessment, confirmed_name="services-antivirus") plan = adoption.build_plan(repo, assessment, confirmed_name="services-antivirus", confirmed_owners=["security"])
changes_by_path = {c["path"]: c for c in plan["changes"]} changes_by_path = {c["path"]: c for c in plan["changes"]}
assert changes_by_path["kdb/kdb.yaml"]["action"] == "preserve" assert changes_by_path["kdb/kdb.yaml"]["action"] == "preserve"
@@ -86,6 +86,6 @@ def test_apply_preserves_existing_antivirus_kdb_bytes(make_repo):
repo = make_repo("adoption/antivirus-legacy") repo = make_repo("adoption/antivirus-legacy")
original = (repo / "kdb" / "kdb.yaml").read_bytes() original = (repo / "kdb" / "kdb.yaml").read_bytes()
assessment = adoption.assess(repo) assessment = adoption.assess(repo)
plan = adoption.build_plan(repo, assessment, confirmed_name="services-antivirus") plan = adoption.build_plan(repo, assessment, confirmed_name="services-antivirus", confirmed_owners=["security"])
adoption.apply_plan(repo, plan, plan["planHash"]) adoption.apply_plan(repo, plan, plan["planHash"])
assert (repo / "kdb" / "kdb.yaml").read_bytes() == original assert (repo / "kdb" / "kdb.yaml").read_bytes() == original
+344
View File
@@ -0,0 +1,344 @@
"""The gates adoption must not let through, and the evidence it must not invent.
Every case here comes from running `adopt` against two real repositories. Each
one passed before the fix and reported success on a repository that had live
credentials in git, no confirmed owner, a name taken from the clone directory,
and a contract that described almost none of its content.
"""
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
from stewardship import adoption
BASE = {"README.md": "# Sample\n"}
def _owners_plan(repo, **kwargs):
assessment = adoption.assess(repo)
return adoption.build_plan(
repo, assessment, confirmed_name="sample", confirmed_owners=["platform"], **kwargs
)
def _codes(findings, code):
return [f for f in findings if f["code"] == code]
# --- 1. secret classes ------------------------------------------------------
def test_document_about_secrets_is_a_warning_not_a_blocker(synthetic_repo) -> None:
"""A document explaining a placeholder convention carries no credential."""
repo = synthetic_repo(
{
**BASE,
"docs/SECRETS.md": (
"# Secrets convention\n\n"
"Profiles carry `<SECRET:name>` tokens instead of real credentials.\n"
"The AD-join password was removed from every profile.\n"
),
}
)
findings = adoption.assess(repo)["findings"]
assert _codes(findings, "ADOPT_SECRET_NAME_SHAPED")
assert not [f for f in findings if f["severity"] == "error"]
def test_live_credential_blocks_and_never_echoes_the_value(synthetic_repo) -> None:
repo = synthetic_repo(
{**BASE, "stack/.env": "TZ=Europe/Moscow\nPOSTGRES_PASSWORD=hunter2-live-value\n"}
)
findings = adoption.assess(repo)["findings"]
verified = _codes(findings, "ADOPT_SECRET_CONTENT_VERIFIED")
assert [f["severity"] for f in verified] == ["error"]
assert "POSTGRES_PASSWORD" in verified[0]["message"]
# Invariant: a scanner that leaks what it found is worse than none.
assert "hunter2-live-value" not in verified[0]["message"]
@pytest.mark.parametrize(
("line", "is_credential"),
[
("AIRFLOW_FERNET_KEY=Rabc123XYZ", True),
("OLLAMA_API_KEY=sk-live-1", True),
("DB_PASSPHRASE=s3kr3t", True),
# "KEY" as a bare substring cannot tell a credential from a file path.
("SSH_KEY_PATH=/home/u/.ssh/id", False),
("KEYBOARD_LAYOUT=us", False),
("BYPASS_CACHE=true", False),
("PASSENGER_ROOT=/x", False),
("TZ=Europe/Moscow", False),
# Placeholders, in the three shapes real repositories use.
("POSTGRES_PASSWORD=changeme", False),
("DB_PASSWORD=<SECRET:db>", False),
("API_TOKEN=${API_TOKEN}", False),
],
)
def test_key_pattern_precision(tmp_path: Path, line: str, is_credential: bool) -> None:
"""Which key names count, and which values read as placeholders.
Exercised against the content check directly: this is a pure decision about
a single line, and building a git repository per case bought only runtime.
"""
env = tmp_path / ".env"
env.write_text(line + "\n", encoding="utf-8")
assert bool(adoption._secret_content_evidence(env)) is is_credential
def test_pem_private_key_is_content_evidence(synthetic_repo) -> None:
repo = synthetic_repo(
{**BASE, "certs/server.key": "-----BEGIN RSA PRIVATE KEY-----\nAAAA\n-----END RSA PRIVATE KEY-----\n"}
)
findings = adoption.assess(repo)["findings"]
assert _codes(findings, "ADOPT_SECRET_CONTENT_VERIFIED")
def test_file_committed_against_its_own_ignore_rule_is_reported(synthetic_repo) -> None:
"""The fact worth reporting most, and the one the filename check missed."""
repo = synthetic_repo({**BASE, ".gitignore": "**/.env\n", "stack/.env": "TZ=Europe/Moscow\n"}, git=False)
subprocess.run(["git", "init", "-q"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.email", "t@example.com"], cwd=repo, check=True)
subprocess.run(["git", "config", "user.name", "T"], cwd=repo, check=True)
subprocess.run(["git", "add", "-A", "-f"], cwd=repo, check=True)
subprocess.run(["git", "commit", "-q", "-m", "base"], cwd=repo, check=True)
findings = adoption.assess(repo)["findings"]
contradiction = _codes(findings, "ADOPT_SECRET_IGNORED_BUT_TRACKED")
assert [f["path"] for f in contradiction] == ["stack/.env"]
assert contradiction[0]["severity"] == "warning"
# --- 2. plan inherits findings and refuses on unresolved blockers -----------
def test_plan_refuses_while_an_assess_blocker_is_unresolved(synthetic_repo) -> None:
repo = synthetic_repo({**BASE, "stack/.env": "POSTGRES_PASSWORD=hunter2-live-value\n"})
with pytest.raises(adoption.AdoptionError) as excinfo:
_owners_plan(repo)
assert excinfo.value.code == "ADOPT_ASSESS_BLOCKERS_UNRESOLVED"
def test_acknowledgement_unblocks_and_is_recorded_in_the_plan(synthetic_repo) -> None:
repo = synthetic_repo({**BASE, "stack/.env": "POSTGRES_PASSWORD=hunter2-live-value\n"})
plan = _owners_plan(
repo,
acknowledged=[
{
"code": "ADOPT_SECRET_CONTENT_VERIFIED",
"path": "stack/.env",
"reason": "rotation scheduled",
}
],
)
assert plan["acknowledgedFindings"][0]["reason"] == "rotation scheduled"
assert any(f["code"] == "ADOPT_SECRET_CONTENT_VERIFIED" for f in plan["findings"])
def test_acknowledgement_changes_the_plan_hash(synthetic_repo) -> None:
"""Approval must cover the acknowledgement, not just the file changes."""
plain = synthetic_repo({**BASE}, name="plain")
without = _owners_plan(plain)
with_ack = _owners_plan(
plain, acknowledged=[{"code": "ADOPT_WORKTREE_DIRTY", "reason": "known"}]
)
assert without["planHash"] != with_ack["planHash"]
def test_acknowledgement_without_a_reason_is_refused(synthetic_repo) -> None:
repo = synthetic_repo({**BASE})
with pytest.raises(adoption.AdoptionError) as excinfo:
_owners_plan(repo, acknowledged=[{"code": "ADOPT_SECRET_CONTENT_VERIFIED", "reason": " "}])
assert excinfo.value.code == "ADOPT_ACKNOWLEDGEMENT_INCOMPLETE"
def test_plan_carries_the_assessment_findings(synthetic_repo) -> None:
repo = synthetic_repo({**BASE, "docs/guide.md": "# G\n"})
plan = _owners_plan(repo)
assert any(f["code"] == "ADOPT_SOURCE_MIRROR_AMBIGUOUS" for f in plan["findings"])
# The plan's own answer settles this one, so it must not travel onward.
assert not any(f["code"] == "ADOPT_OWNER_UNKNOWN" for f in plan["findings"])
# --- 3. identity and owners -------------------------------------------------
def test_plan_refuses_without_confirmed_owners(synthetic_repo) -> None:
repo = synthetic_repo({**BASE})
assessment = adoption.assess(repo)
with pytest.raises(adoption.AdoptionError) as excinfo:
adoption.build_plan(repo, assessment, confirmed_name="sample", confirmed_owners=[])
assert excinfo.value.code == "ADOPT_OWNER_UNKNOWN"
def test_name_comes_from_the_remote_keeping_its_namespace(synthetic_repo) -> None:
repo = synthetic_repo({**BASE}, name="whatever-this-clone-is-called")
subprocess.run(
["git", "remote", "add", "origin", "ssh://git@example.com:9922/corsus-it/OpTools/LXD.git"],
cwd=repo,
check=True,
)
identity = adoption.assess(repo)["identity"]
assert identity == {"name": "optools-lxd", "source": "git-remote"}
def test_scp_style_remote_is_understood(synthetic_repo) -> None:
repo = synthetic_repo({**BASE}, name="clone")
subprocess.run(["git", "remote", "add", "origin", "git@example.com:group/Repo.git"], cwd=repo, check=True)
assert adoption.assess(repo)["identity"]["name"] == "group-repo"
def test_directory_fallback_says_it_was_inferred(synthetic_repo) -> None:
repo = synthetic_repo({**BASE}, name="fallback-repo")
assessment = adoption.assess(repo)
assert assessment["identity"] == {"name": "fallback-repo", "source": "directory"}
assert _codes(assessment["findings"], "ADOPT_NAME_INFERRED")
# --- 4. content roots -------------------------------------------------------
def test_docs_is_proposed_for_an_infrastructure_repository(synthetic_repo) -> None:
"""`docs` is listed as evidence for `project`, which used to hide it here."""
repo = synthetic_repo({**BASE, "profiles-source/a.yaml": "{}\n", "docs/guide.md": "# G\n"})
assessment = adoption.assess(repo)
assert assessment["classification"]["proposedType"] == "infrastructure-config"
assert "docs" in {cr["path"] for cr in assessment["proposedContentRoots"]}
def test_sibling_stacks_become_one_file_set_root(synthetic_repo) -> None:
files = {**BASE}
for stack in ("grafana", "loki", "n8n"):
files[f"{stack}/compose.yaml"] = "services: {}\n"
repo = synthetic_repo(files)
roots = adoption.assess(repo)["proposedContentRoots"]
stacks = [cr for cr in roots if cr.get("kind") == "file-set"]
assert len(stacks) == 1
assert stacks[0]["path"] == "." and stacks[0]["selector"] == "*/compose.y*ml"
def test_two_siblings_are_not_a_repeated_shape(synthetic_repo) -> None:
files = {**BASE}
for stack in ("grafana", "loki"):
files[f"{stack}/compose.yaml"] = "services: {}\n"
repo = synthetic_repo(files)
assert not [cr for cr in adoption.assess(repo)["proposedContentRoots"] if cr.get("kind") == "file-set"]
def test_file_set_root_does_not_forbid_the_whole_repository(synthetic_repo) -> None:
files = {**BASE}
for stack in ("grafana", "loki", "n8n"):
files[f"{stack}/compose.yaml"] = "services: {}\n"
repo = synthetic_repo(files)
plan = _owners_plan(repo)
assert "./**" not in plan["forbiddenChanges"]
assert "*/compose.y*ml" in plan["forbiddenChanges"]
# The plan must still be able to write what it authors.
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_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)
assert _codes(assessment["findings"], "ADOPT_SOURCE_MIRROR_AMBIGUOUS")
def test_evidenced_mirror_is_not_ambiguous(synthetic_repo) -> None:
"""`profiles` paired with `profiles-source` is derived, not defaulted."""
repo = synthetic_repo({**BASE, "profiles/a.yaml": "{}\n", "profiles-source/a.yaml": "{}\n"})
assessment = adoption.assess(repo)
mirror = next(cr for cr in assessment["proposedContentRoots"] if cr["path"] == "profiles")
assert mirror["authority"] == "mirror"
ambiguous = {f["path"] for f in _codes(assessment["findings"], "ADOPT_SOURCE_MIRROR_AMBIGUOUS")}
assert "profiles" not in ambiguous
# --- 5. markdown links are not found inside code ----------------------------
def test_link_shaped_code_is_not_a_link(tmp_path: Path) -> None:
from stewardship.markdown import check_markdown_file
(tmp_path / "CLAUDE.md").write_text(
"# Doc\n\n"
"Cast explicitly: `[string]([IO.File]::ReadAllText($path))`.\n\n"
"```powershell\n"
"see [also](nowhere/missing.md)\n"
"```\n",
encoding="utf-8",
)
assert check_markdown_file(tmp_path, "CLAUDE.md") == []
def test_a_real_broken_link_is_still_reported(tmp_path: Path) -> None:
from stewardship.markdown import check_markdown_file
(tmp_path / "CLAUDE.md").write_text("# Doc\n\nSee [x](docs/missing.md).\n", encoding="utf-8")
codes = [f.code for f in check_markdown_file(tmp_path, "CLAUDE.md")]
assert codes == ["MARKDOWN_LINK_TARGET_MISSING"]
def test_percent_encoded_link_resolves_to_the_real_file(tmp_path) -> None:
"""Renderers percent-encode spaces and non-ASCII; the file is still there."""
from stewardship.markdown import check_markdown_file
(tmp_path / "GitLab 17.10.0 Migration.md").write_text("# M" + chr(10), encoding="utf-8")
link = "See [m](GitLab%2017.10.0%20Migration.md)."
(tmp_path / "CLAUDE.md").write_text("# Doc" + chr(10) * 2 + link + chr(10), encoding="utf-8")
assert check_markdown_file(tmp_path, "CLAUDE.md") == []
# --- path confinement: "." is a whole path, never a segment ------------------
def test_repository_root_is_a_legal_content_root_path() -> None:
from stewardship.paths import normalize_resource_path
assert normalize_resource_path(".", allow_root=True) == "."
@pytest.mark.parametrize(
("value", "allow_root"),
[(".", False), ("a/./b", True), ("../escape", True), ("a/../..", True)],
)
def test_dot_segments_stay_rejected(value: str, allow_root: bool) -> None:
from stewardship.paths import PathViolation, normalize_resource_path
with pytest.raises(PathViolation):
normalize_resource_path(value, allow_root=allow_root)
+2 -2
View File
@@ -31,7 +31,7 @@ BASE = {"README.md": "# Sample\n", "policies/.gitkeep": ""}
def _plan_for(repo): def _plan_for(repo):
assessment = adoption.assess(repo) assessment = adoption.assess(repo)
return assessment, adoption.build_plan(repo, assessment, confirmed_name="sample") return assessment, adoption.build_plan(repo, assessment, confirmed_name="sample", confirmed_owners=["platform"])
def _actions(plan): def _actions(plan):
@@ -172,7 +172,7 @@ def test_both_canonical_paths_occupied_refuses_to_plan(synthetic_repo):
assessment = adoption.assess(repo) assessment = adoption.assess(repo)
with pytest.raises(adoption.AdoptionError) as excinfo: with pytest.raises(adoption.AdoptionError) as excinfo:
adoption.build_plan(repo, assessment, confirmed_name="sample") adoption.build_plan(repo, assessment, confirmed_name="sample", confirmed_owners=["platform"])
assert excinfo.value.code == "ADOPT_KNOWLEDGE_UNRESOLVED" assert excinfo.value.code == "ADOPT_KNOWLEDGE_UNRESOLVED"
+217
View File
@@ -0,0 +1,217 @@
"""What `init` must refuse before it writes a repository.
`init` is the one path where the tool controls every byte of the result, so a
repository it creates must pass `repoctl validate` by construction. Each case
here produced a `success` envelope before the fix: an invalid contract, an
unconfirmed owner, a plan that could never be applied, or a write outside the
repository from a hand-edited plan.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from stewardship import bootstrap, io
from stewardship.validate import validate_repository
VALID = {
"name": "services-mail",
"title": "Corporate mail service",
"owners": ["it-infrastructure"],
"repositoryType": "service-config",
"lifecycle": "production",
}
def _answers(**overrides):
data = dict(VALID)
data.update(overrides)
return data
# --- answers that would produce an invalid repository ------------------------
@pytest.mark.parametrize(
("overrides", "code"),
[
({"name": "Services/Mail"}, "INIT_NAME_INVALID"),
({"name": "Services Mail"}, "INIT_NAME_INVALID"),
({"name": "MAIL"}, "INIT_NAME_INVALID"),
({"name": "-leading-dash"}, "INIT_NAME_INVALID"),
({"repositoryType": "mail-server"}, "INIT_TYPE_UNKNOWN"),
({"lifecycle": "bogus"}, "INIT_LIFECYCLE_UNKNOWN"),
({"access": "semi-public"}, "INIT_ACCESS_UNKNOWN"),
({"owners": []}, "INIT_OWNER_UNKNOWN"),
({"name": ""}, "INIT_ANSWERS_INCOMPLETE"),
],
)
def test_answers_that_break_the_schema_are_refused(overrides, code) -> None:
with pytest.raises(bootstrap.BootstrapError) as excinfo:
bootstrap.BootstrapAnswers.from_mapping(_answers(**overrides))
assert excinfo.value.code == code
def test_a_rejected_name_comes_with_a_usable_suggestion() -> None:
"""An error that only says "invalid" makes the owner guess the rule."""
with pytest.raises(bootstrap.BootstrapError) as excinfo:
bootstrap.BootstrapAnswers.from_mapping(_answers(name="Services/Mail"))
assert "'services-mail'" in str(excinfo.value)
def test_owner_refusal_names_both_ways_to_answer() -> None:
"""An error that only says "refused" leaves the reader guessing the flag."""
with pytest.raises(bootstrap.BootstrapError) as excinfo:
bootstrap.BootstrapAnswers.from_mapping(_answers(owners=[]))
message = str(excinfo.value)
assert "--owner" in message and "owners:" in message
# --- the created repository must validate ------------------------------------
def test_a_freshly_created_repository_validates(tmp_path: Path) -> None:
repo = tmp_path / "mail"
repo.mkdir()
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
plan = bootstrap.build_bootstrap_plan(answers, repo)
bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
(repo / ".git").mkdir()
report = validate_repository(repo)
assert not [f for f in report.findings if f.severity == "error"]
# Content-root directories are deliberately not created (bootstrap docstring:
# no placeholder directories), so those warnings are expected, not failures.
assert {f.code for f in report.findings} <= {"CONTENT_ROOT_PATH_MISSING"}
# --- collisions belong to plan, not to apply ---------------------------------
def test_plan_refuses_a_directory_that_is_already_a_repository(tmp_path: Path) -> None:
repo = tmp_path / "existing"
(repo / "ops").mkdir(parents=True)
(repo / "ops" / "contract.yaml").write_text("existing: true\n", encoding="utf-8")
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
with pytest.raises(bootstrap.BootstrapError) as excinfo:
bootstrap.build_bootstrap_plan(answers, repo)
assert excinfo.value.code == "INIT_PATH_COLLISION"
assert "adopt" in str(excinfo.value)
def test_planning_without_a_target_still_works(tmp_path: Path) -> None:
"""`root` is optional; omitting it plans without the collision check."""
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
assert bootstrap.build_bootstrap_plan(answers)["planHash"].startswith("sha256:")
# --- a plan is an editable file, so apply confines every path ----------------
@pytest.mark.parametrize(
"escape",
["../ESCAPED.md", "../../ESCAPED.md", "ops/../../ESCAPED.md", "/etc/passwd", "C:/Windows/x"],
)
def test_apply_refuses_to_write_outside_the_repository(tmp_path: Path, escape: str) -> None:
repo = tmp_path / "inner"
repo.mkdir()
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
plan = bootstrap.build_bootstrap_plan(answers, repo)
plan["files"] = [{"path": escape, "content": "escaped\n"}]
plan.pop("planHash")
plan["planHash"] = io.sha256(plan)
with pytest.raises(bootstrap.BootstrapError) as excinfo:
bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
assert excinfo.value.code == "INIT_PATH_OUTSIDE_REPOSITORY"
assert not list(tmp_path.glob("ESCAPED.md"))
assert not list(tmp_path.parent.glob("ESCAPED.md"))
def test_a_refused_escape_writes_nothing_at_all(tmp_path: Path) -> None:
"""Confinement runs over every entry before the first byte is written."""
repo = tmp_path / "inner"
repo.mkdir()
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
plan = bootstrap.build_bootstrap_plan(answers, repo)
plan["files"].append({"path": "../ESCAPED.md", "content": "escaped\n"})
plan.pop("planHash")
plan["planHash"] = io.sha256(plan)
with pytest.raises(bootstrap.BootstrapError):
bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
assert not (repo / "ops" / "contract.yaml").exists()
# --- refusals stay machine-readable ------------------------------------------
def test_refusals_are_envelopes_not_stderr_lines(tmp_path: Path, capsys) -> None:
from stewardship.cli import main
repo = tmp_path / "mail"
repo.mkdir()
exit_code = main(
["init", "--repo", str(repo), "--name", "Services/Mail",
"--type", "service-config", "--owner", "x", "--output", "json"]
)
envelope = json.loads(capsys.readouterr().out)
assert exit_code != 0
assert envelope["outcome"] == "failure"
assert envelope["findings"][0]["code"] == "INIT_NAME_INVALID"
# --- what `repoctl skills install` leaves behind is not a collision ----------
def test_skills_already_installed_do_not_block_init(tmp_path: Path) -> None:
"""The entry point must not disable the command it exists to reach.
`repoctl skills install` is the documented way to make the bootstrap skill
reachable at all, and it writes exactly the files `init` plans to write.
Treating those as collisions sent every skill-driven bootstrap to `adopt`.
"""
from stewardship import skills
repo = tmp_path / "vault"
repo.mkdir()
skills.install(repo)
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
plan = bootstrap.build_bootstrap_plan(answers, repo)
written = bootstrap.apply_bootstrap_plan(repo, plan, plan["planHash"])
assert not [path for path in written if path.startswith(".claude/skills/")]
assert "ops/contract.yaml" in written
assert (repo / ".claude" / "skills" / "repository-adoption" / "SKILL.md").is_file()
def test_a_differing_file_is_still_a_collision(tmp_path: Path) -> None:
"""Only byte-identical content is waived; edited content still protects."""
repo = tmp_path / "vault"
(repo / ".claude" / "skills" / "repo-handoff").mkdir(parents=True)
(repo / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text(
"# locally rewritten\n", encoding="utf-8"
)
answers = bootstrap.BootstrapAnswers.from_mapping(_answers())
with pytest.raises(bootstrap.BootstrapError) as excinfo:
bootstrap.build_bootstrap_plan(answers, repo)
assert excinfo.value.code == "INIT_PATH_COLLISION"
# --- the answers template ----------------------------------------------------
def test_answers_template_is_valid_yaml_and_accepted_as_answers() -> None:
"""A template nobody can feed back to the tool is documentation, not a template."""
from stewardship.markdown import load_yaml_text
data = load_yaml_text(bootstrap.answers_template())
answers = bootstrap.BootstrapAnswers.from_mapping(data)
assert answers.name and answers.owners and answers.repository_type
def test_answers_template_names_every_vocabulary() -> None:
"""The values were previously discoverable only by sending a wrong one."""
text = bootstrap.answers_template()
for value in ("service-config", "production", "restricted"):
assert value in text
# The key that differs from its flag name, which cost a round trip to learn.
assert "repositoryType" in text
+28
View File
@@ -39,3 +39,31 @@ def test_context_strict_truncation_returns_exit_4(make_repo):
def test_init_apply_without_hash_returns_exit_2(tmp_path): def test_init_apply_without_hash_returns_exit_2(tmp_path):
code = main(["init", "--repo", str(tmp_path), "--apply", "--output", "json"]) code = main(["init", "--repo", str(tmp_path), "--apply", "--output", "json"])
assert code == 2 assert code == 2
def test_kdb_prints_the_table_on_stdout_and_findings_on_stderr(make_repo, capsys):
"""Piping stdout must give clean Markdown, so findings may not land in it."""
repo = make_repo("positive/infra-lxd")
assert main(["kdb", "--repo", str(repo)]) == 0
out = capsys.readouterr().out
assert out.startswith("## ")
assert "| Topic | Intents | Documents | Facts in data |" in out
assert "### Documents" in out
def test_kdb_json_is_an_envelope_like_every_other_command(make_repo, capsys):
import json
repo = make_repo("positive/infra-lxd")
assert main(["kdb", "--repo", str(repo), "--output", "json"]) == 0
envelope = json.loads(capsys.readouterr().out)
assert envelope["command"] == "kdb"
assert envelope["outcome"] == "success"
assert envelope["data"]["schema"] == "stewardship/knowledge-overview@0.1"
def test_kdb_without_a_knowledge_base_warns_and_returns_exit_3(make_repo, capsys):
repo = make_repo("positive/infra-lxd")
(repo / "kdb" / "kdb.yaml").unlink()
assert main(["kdb", "--repo", str(repo)]) == 3
assert "KNOWLEDGE_ENTRYPOINT_MISSING" in capsys.readouterr().err
+29
View File
@@ -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
+44
View File
@@ -0,0 +1,44 @@
"""The skills this repository ships must match the skills it uses.
`init` writes `.claude/skills/*/SKILL.md` into every new repository from the
constants in `skills_content`, so those constants are a distributed artifact
with a second copy checked in here. Editing one and not the other shipped a
stale skill into every repository created afterwards -- silently, because
neither `validate` nor any other test compared them.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from stewardship import skills_content
REPO_ROOT = Path(__file__).resolve().parents[1]
DISTRIBUTED = {
"repository-bootstrap": skills_content.REPOSITORY_BOOTSTRAP_SKILL,
"repository-adoption": skills_content.REPOSITORY_ADOPTION_SKILL,
"repo-handoff": skills_content.REPO_HANDOFF_SKILL,
}
@pytest.mark.parametrize("name", sorted(DISTRIBUTED))
def test_shipped_skill_matches_the_one_in_this_repository(name: str) -> None:
on_disk = (REPO_ROOT / ".claude" / "skills" / name / "SKILL.md").read_text(encoding="utf-8")
assert on_disk.strip() == DISTRIBUTED[name].strip(), (
f"{name}: .claude/skills/{name}/SKILL.md and skills_content.py have diverged. "
"Update both, or the next `repoctl init` ships the stale one."
)
def test_adoption_skill_does_not_offer_normalization() -> None:
"""CLAUDE.md: do not describe an operation the CLI does not offer.
The skill may name `--strategy normalize` in order to say it is unavailable;
what it must never do is instruct someone to use it.
"""
text = skills_content.REPOSITORY_ADOPTION_SKILL
assert "Only use `--strategy normalize" not in text
assert "not implemented" in text
+187
View File
@@ -0,0 +1,187 @@
"""`repoctl skills`: the entry point that made adoption reachable at all.
Before this command the stewardship skills were written by exactly one code
path -- `init`, which only runs on a *new* repository. Adopting an existing one
needs the adoption skill, and nothing could put it there, so the procedure's
entry point depended on the operator already having the skill from elsewhere.
"""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from stewardship import skills
from stewardship.cli import main
def _states(base: Path) -> dict[str, str]:
return {item["skill"]: item["state"] for item in skills.status(base)}
# --- scope has to be stated ---------------------------------------------------
def test_scope_must_be_stated() -> None:
"""Guessing between "this repository" and "every repository" is not possible."""
with pytest.raises(skills.SkillsError) as excinfo:
skills.target_base(None, global_scope=False)
assert excinfo.value.code == "SKILLS_SCOPE_MISSING"
def test_two_scopes_at_once_are_refused(tmp_path: Path) -> None:
with pytest.raises(skills.SkillsError) as excinfo:
skills.target_base(tmp_path, global_scope=True)
assert excinfo.value.code == "SKILLS_SCOPE_AMBIGUOUS"
def test_a_missing_target_directory_is_refused(tmp_path: Path) -> None:
with pytest.raises(skills.SkillsError) as excinfo:
skills.target_base(tmp_path / "nope", global_scope=False)
assert excinfo.value.code == "SKILLS_TARGET_MISSING"
# --- install ------------------------------------------------------------------
def test_install_writes_every_skill_into_a_bare_directory(tmp_path: Path) -> None:
assert set(_states(tmp_path).values()) == {"missing"}
result = skills.install(tmp_path)
assert result["installed"] == sorted(skills.SKILLS)
assert set(_states(tmp_path).values()) == {"current"}
for name in skills.SKILLS:
assert (tmp_path / ".claude" / "skills" / name / "SKILL.md").is_file()
def test_install_is_idempotent(tmp_path: Path) -> None:
skills.install(tmp_path)
second = skills.install(tmp_path)
assert second["installed"] == []
assert second["unchanged"] == sorted(skills.SKILLS)
def test_install_writes_only_what_is_missing(tmp_path: Path) -> None:
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").unlink()
result = skills.install(tmp_path)
assert result["installed"] == ["repo-handoff"]
# --- a write never destroys what it did not author ---------------------------
def test_a_modified_skill_is_reported_not_overwritten(tmp_path: Path) -> None:
skills.install(tmp_path)
edited = tmp_path / ".claude" / "skills" / "repository-adoption" / "SKILL.md"
edited.write_text("# locally rewritten\n", encoding="utf-8")
with pytest.raises(skills.SkillsError) as excinfo:
skills.install(tmp_path)
assert excinfo.value.code == "SKILLS_MODIFIED"
assert "--force" in str(excinfo.value)
assert edited.read_text(encoding="utf-8") == "# locally rewritten\n"
def test_a_refusal_writes_nothing_at_all(tmp_path: Path) -> None:
"""The check runs over every skill before the first byte is written."""
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text("edited\n", encoding="utf-8")
(tmp_path / ".claude" / "skills" / "repository-adoption" / "SKILL.md").unlink()
with pytest.raises(skills.SkillsError):
skills.install(tmp_path)
assert _states(tmp_path)["repository-adoption"] == "missing"
def test_force_replaces_only_the_divergent_skill(tmp_path: Path) -> None:
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text("edited\n", encoding="utf-8")
result = skills.install(tmp_path, force=True)
assert result["installed"] == ["repo-handoff"]
assert set(_states(tmp_path).values()) == {"current"}
# --- what lands is what this version ships -----------------------------------
def test_installed_skills_match_the_shipped_constants(tmp_path: Path) -> None:
skills.install(tmp_path)
for name, content in skills.SKILLS.items():
on_disk = (tmp_path / ".claude" / "skills" / name / "SKILL.md").read_text(encoding="utf-8")
assert on_disk.strip() == content.strip()
def test_the_adoption_skill_is_among_them() -> None:
"""The one whose absence made adopting an existing repository unreachable."""
assert "repository-adoption" in skills.SKILLS
# --- CLI ----------------------------------------------------------------------
def test_cli_install_then_status(tmp_path: Path, capsys) -> None:
assert main(["skills", "install", "--repo", str(tmp_path), "--output", "json"]) == 0
envelope = json.loads(capsys.readouterr().out)
assert envelope["outcome"] == "success"
assert envelope["data"]["installed"] == sorted(skills.SKILLS)
assert main(["skills", "status", "--repo", str(tmp_path), "--output", "json"]) == 0
envelope = json.loads(capsys.readouterr().out)
assert {item["state"] for item in envelope["data"]["skills"]} == {"current"}
def test_cli_refusal_is_an_envelope(tmp_path: Path, capsys) -> None:
skills.install(tmp_path)
(tmp_path / ".claude" / "skills" / "repo-handoff" / "SKILL.md").write_text("edited\n", encoding="utf-8")
exit_code = main(["skills", "install", "--repo", str(tmp_path), "--output", "json"])
envelope = json.loads(capsys.readouterr().out)
assert exit_code != 0
assert envelope["outcome"] == "failure"
assert envelope["findings"][0]["code"] == "SKILLS_MODIFIED"
def test_kdb_table_reads_the_entrypoint_the_contract_declares(tmp_path) -> None:
"""The path is never guessed: the contract names it, and a repo may move it."""
from stewardship.kdb_table import render
(tmp_path / "ops").mkdir()
(tmp_path / "kb").mkdir()
(tmp_path / "ops" / "contract.yaml").write_text(
"spec:" + chr(10) + " knowledge:" + chr(10) + " entrypoint: kb/index.yaml" + chr(10),
encoding="utf-8",
)
(tmp_path / "kb" / "index.yaml").write_text(
chr(10).join([
"spec:",
" repository: repo:x",
" topics:",
" - id: t-one",
" intents: [do-a-thing]",
" documents: [d-one]",
" documents:",
" - id: d-one",
" path: README.md",
" role: reference",
" status: stale",
]) + chr(10),
encoding="utf-8",
)
out = render(tmp_path)
assert "repo:x - 1 topics, 1 documents" in out
assert "<!-- kb/index.yaml -->" in out # видно, откуда взято, раз путь нестандартный
assert "**t-one**" in out and "do-a-thing" in out
assert "(!)" in out # a stale document is marked, not silently listed
def test_kdb_table_says_so_when_there_is_no_knowledge_base(tmp_path) -> None:
from stewardship.kdb_table import render
assert render(tmp_path).startswith("No knowledge base at")