Commit Graph
29 Commits
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
Alexander BaranovandClaude Opus 5 693211cee9 docs: record the open question about non-conformant knowledge bases
The adapter that adoption generates is schema-correct and inert: it is created
with empty topics on purpose, so `context` on such a repository returns an
empty bundle. That is the honest answer at apply time, but it leaves the
repository without routing indefinitely, which is the whole point of a KDB --
so whether the adapter should stay or the legacy file should be rebuilt into
one canonical index is a real open question, not a settled one.

Recorded as research rather than as a runbook change: no decision was taken and
no behaviour changed. The note argues against rebuilding, and identifies why
the adapter cannot yet grow into a replacement -- runbook 11.1 offers
`Topic.data.x-selector` as the way to index sections of a legacy source, and
build_context assembles bundles from document ids and never reads it. Until
that exists a topic can only reference a whole legacy file, so incremental
migration has nowhere to start.

Also names the question that precedes both options: whether the legacy file is
a knowledge base in a foreign format or domain data that was called kdb, which
adoption currently cannot distinguish and does not ask.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 23:26:50 +03:00
Alexander BaranovandClaude Opus 5 c483d94f36 fix(cli): report a refused plan as an envelope
Only `apply` had a handler for AdoptionError, which was true when the error
type was introduced. `plan` has since gained two ways to refuse: it validates
the managed block of an existing CLAUDE.md to test idempotence, and it now
decides the knowledge entrypoint by content. Both reached the top-level safety
net in main, which prints a bare line to stderr and exits -- so `--output json`
answered a caller with no envelope at all, breaking the machine-readable
contract precisely when something went wrong and the caller needed the code.

The mapping from finding code to exit code now lives in one place rather than
being spelled out per branch.

- add _adoption_failure and use it from both plan and apply
- cover a refused plan end to end, envelope shape and exit code included

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 22:56:58 +03:00
Alexander BaranovandClaude Opus 5 6c6dfb6fb6 fix(adopt): decide the adapter path by content too
The rule that a knowledge file's format comes from validating it, never from
the path it occupies, was applied to `kdb/kdb.yaml` and stopped there. The
first branch of _plan_knowledge declared `ops/knowledge.yaml` the entrypoint
without ever looking at its assessed action, so a repository holding a
non-conformant file at the adapter path was adopted with the contract pointing
straight at something that fails the KnowledgeBase schema -- the same defect,
one path over, with the same consequence: it surfaces only at verify and gets
repaired by hand outside the approved plan hash. assess had the answer all
along and build_plan discarded it.

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

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

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

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 22:56:50 +03:00
Alexander BaranovandClaude Opus 5 1974155281 docs: align the runbook with what adoption actually does
The tables in sections 11.1 and 11.2 were right and the code was wrong, so most
of this is recording how a row is decided rather than changing the rule: format
comes from validating content against the KnowledgeBase schema, never from the
path a file happens to occupy.

Section 13 promised thirteen verify checks and ran none of the specific ones.
Rather than let the list keep implying coverage that does not exist, it now
separates what L1 checks from what waits on normalization and L3, and states
plainly that an unscoped report proves nothing.

- document the managed-block markers, insertion point and idempotence
- mark normalization and its recipes as not implemented, matching the CLI
- record that migrate does not exist, which is why post-adoption edits to a
  contract currently fall outside plan/approve
- add the finding codes introduced with the safety and verify work, and explain
  why a tracked secret and an ignored one are no longer the same code
- PLAN.md: Antivirus is a Wave 1 pilot the owner adopts deliberately; LXD stays
  read-only. Normalization test row follows the feature into deferral

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:52:43 +03:00
Alexander BaranovandClaude Opus 5 e5a42fa446 test(adopt): bind the compatibility tables to code, and check apply's safety
Runbook 11.1 and 11.2 are decision tables, and nothing tied them to branches:
the two existing antivirus-legacy tests asserted only that kdb/kdb.yaml was
preserved, which stayed true while the surrounding behaviour was wrong. These
cases are parametrized over the table rows so prose and code cannot drift apart
again without a failure.

Writing them found two defects that no existing test could see. splice_managed_block
validated the file it patched but never the block being inserted, so a
hand-edited plan carrying unbalanced markers would have been written in and only
failed on a later run. And the adoption output schemas were validated nowhere,
which had let the richer content roots from the previous commit silently stop
conforming to AdoptionAssessment.

- table-driven coverage of the knowledge and agent-entrypoint rows
- path escape, forbidden path, dirty gate, rollback and preserve-tampering cases
- schema conformance for assessment, plan, report and the generated contract
- widen proposedContentRoots for writePolicy/generatedFrom, and constrain
  authority to the enum it always should have used
- add a synthetic_repo fixture instead of a fourth copy of git init

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:48:54 +03:00
Alexander BaranovandClaude Opus 5 005419a0ba fix: quiet the secret scan, narrow the CLI to what exists, name unknown intents
The secret-shaped scan walked the entire tree with rglob and filtered
afterwards, so a repository with gigabytes of gitignored vendor material paid
for statting all of it, and reported findings Git had already been told to
ignore. It also reported every hit under ADOPT_SECRET_TRACKED regardless of
whether the path was tracked, so a blocker code appeared on files that were
merely present -- including an `icon-show-password.png` inside an unpacked
vendor manual. A code named TRACKED firing on untracked files teaches people to
ignore it.

--strategy normalize and --recipe were advertised by the CLI while normalize
raised unconditionally and --recipe was never read anywhere, which is the thing
AGENTS.md asks us not to do.

An unknown intent returned an empty bundle in silence, indistinguishable from a
topic that genuinely has no content -- easy to hit by passing a topic id where
an intent belongs.

- prune ignored directories during the walk; drop ignored matches; skip formats
  that cannot carry a credential
- split ADOPT_SECRET_SHAPED_UNTRACKED from the ADOPT_SECRET_TRACKED blocker
- remove the normalize choice and the dead --recipe argument
- warn CONTEXT_INTENT_UNKNOWN with the closest declared intents

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:44:44 +03:00
Alexander BaranovandClaude Opus 5 a4b0fa5a8b fix(adopt): weigh classification evidence, and stop calling mirrors sources
Classification counted directories that merely exist, so `docs/` -- present in
nearly every repository -- carried the same weight as `policies/` and tied the
two types against each other. That tie is why the Antivirus pilot came out as
low confidence and demanded a confirmation it did not actually need; with
weights it is high confidence on the same evidence. Ties are now explicit rather
than settled by declaration order, and reported as ADOPT_TYPE_AMBIGUOUS.

Content roots were emitted with authority "source" and writePolicy "managed"
unconditionally, which meant a repository holding both profiles-source/ and
profiles/ had its generated mirror declared a source -- precisely the error
runbook section 7.2 names as the one not to make. Learned the tool has been
producing the contract its own documentation warns against.

- weighted evidence, deterministic tie-breaking, explicit ambiguity finding
- declare a known mirror as authority mirror / writePolicy generated, with
  generatedFrom, and fall back to source only when nothing generates it here
- give roots meaningful roles instead of reusing the directory name

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:40:11 +03:00
Alexander BaranovandClaude Opus 5 56a42389ab fix(adopt): make verify check something
verify re-derived baselineRevision from current HEAD instead of reading the
plan's, so drift between the planned and the actual baseline was undetectable by
construction. Called without --plan -- the obvious way to call it -- it returned
empty changedPaths and preservedPaths, which reads as "adoption touched nothing"
when it means "this verified nothing"; the pilot run reported a green pass that
was entirely vacuous. None of the specific checks runbook section 13 promises
were implemented.

Learned that a preserve promise was never actually enforced: overwriting a
preserved file after apply still produced a passing report.

- take the baseline from the plan and flag divergence from HEAD
- fail on a modified preserved path, warn on changes outside the plan
- mark an unscoped report rather than letting empty lists imply success
- express all of this through unresolvedFindings, since the report schema is
  closed and widening it would be a normative change
- expand untracked directories in dirty_paths; git collapses them to "dir/",
  which never matches the file paths a plan names

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:36:33 +03:00
Alexander BaranovandClaude Opus 5 523ef61fe3 feat(adopt): let the owner answer the type question assess asks
assess sets confirmationRequired and asks "Confirm repository type" whenever
confidence is below high, but there was no way to answer it: --answers read only
name, title, owners and lifecycle, and build_plan took the type solely from the
classifier's guess. The confirmation boundary in runbook section 9 could not be
closed through the tool, and nothing in the resulting contract distinguished a
deliberate decision from an unreviewed low-confidence default.

- accept the type via --type or a repositoryType answer, validated against the
  known set rather than written through unchecked
- record classification, confidence and evidence in metadata.annotations, which
  the schema already allows as a free-form object
- omit any timestamp so re-planning stays deterministic and planHash stable

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:33:42 +03:00
Alexander BaranovandClaude Opus 5 90bf25c49d feat(adopt): point an existing CLAUDE.md at the contract, and derive managedPaths
Runbook 11.2 says an existing shared entrypoint should gain a narrow managed
block rather than be replaced, but build_plan only ever chose between "create"
and "preserve", so a repository that already had CLAUDE.md was adopted without
any pointer to its own contract -- an agent kept reading the large legacy
document first, which is the cost adoption was supposed to remove. The
patch-managed-block action existed in the schema and in apply_plan with nothing
producing it.

managedPaths was hardcoded to ops/contract.yaml even though the plan already
knows every file it authors, so the contract understated what adoption owns and
the missing entries had to be added by hand afterwards.

- emit patch-managed-block for an existing CLAUDE.md, and preserve when the
  block is already current, which makes re-planning idempotent
- assemble the contract last so managedPaths is derived from the actual changes
- keep the pointer block ASCII, matching the earlier em-dash cleanup

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:31:53 +03:00
Alexander BaranovandClaude Opus 5 5bb8914d72 fix(adopt): decide KDB treatment by content, and implement runbook 11.1
assess declared kdb/kdb.yaml conformant on the strength of its path alone and
never parsed it, so a legacy custom knowledge base was reported as
stewardship-yaml and the contract was pointed straight at a file that fails the
KnowledgeBase schema. The row of runbook 11.1 covering exactly that case -- a
legacy KDB already occupying the canonical path -- had no branch in the code at
all, and _knowledge_entrypoint could not have helped: both of its branches
returned the same literal, so the loop was dead and the answer was always
kdb/kdb.yaml.

Learned that this is what made the pilot adoption of Services/Antivirus produce
an invalid contract that only surfaced at verify, and had to be repaired by
hand outside the approved plan hash.

- classify a knowledge file by validating it against the KnowledgeBase schema
- when a legacy KDB occupies kdb/kdb.yaml, index it from a new ops/knowledge.yaml,
  preserve the original and forbid writes to it
- generate empty topics deliberately: which sections matter is not inferable
- delete _knowledge_entrypoint and derive the entrypoint from the same decision

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:29:07 +03:00
Alexander BaranovandClaude Opus 5 c918bd8373 fix(adopt): confine, gate and splice writes instead of overwriting blindly
apply_plan was the only path in the package that writes to disk and the only one
that skipped confined_path, so an absolute path in a hand-edited plan file
replaced the repository root outright (pathlib join semantics) and wrote
anywhere. It also treated patch-managed-block as a full-file write, meaning the
first plan to emit that action would have destroyed the target CLAUDE.md rather
than patching it -- two bugs that only stayed harmless because build_plan never
emitted the action. Learned that forbiddenChanges and the plan's own
"path-confinement" validation entry were decorative: nothing ever checked them.

- confine every change path via the existing confined_path helper
- implement real managed-block splicing between markers; refuse malformed or
  duplicated markers rather than guessing
- enforce forbiddenChanges at apply time
- re-check the worktree at apply time and refuse only when a dirty path is one
  the plan writes, leaving unrelated user edits alone
- restore rollback by what was on disk, not by what we think we finished
- add gitutil.dirty_paths/ignored; is_dirty threw the path list away
- replace the CLI's guess-the-code-from-the-message mapping with AdoptionError

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-24 18:25:45 +03:00
Alexander Baranov 36d5d01d43 fix: accept saved result envelopes as plan files; fix docs CLI examples
apply_plan/apply_bootstrap_plan required the raw plan object, but the
natural capture workflow (repoctl ... --output json > plan.json) saves
the full result envelope, so following the documented workflow verbatim
failed the hash check. repoctl now unwraps a stored envelope's `data`
automatically (an idea worth keeping from codex/repoctl-l1's cli.py,
which had the same fallback).

Found while walking docs/repoctl.md's adopt and cross-repo examples
live end to end: two more invocation bugs in the doc itself
(`config add-root` takes a positional path, not `--path`; `--output`
must follow `config` itself, not the add-root/remove-root subaction) --
fixed and clarified in place.
2026-08-24 16:02:24 +03:00
Alexander Baranov 4fbe56d81f docs: add human-facing repoctl guide in Russian, route it via KDB
docs/repoctl.md walks a human through what repoctl is, the install-once
/ invoke-from-other-repositories model (folding in the framing already
present on the sibling codex/repoctl-l1 branch's docs/repoctl.md), each
command with real sample output, the exit-code table, and troubleshooting.
docs/specification.md stays the normative machine reference.

kdb/kdb.yaml routes the new document into the tooling-implementation
topic; README.md links it and documents running tests-universal.
2026-08-24 15:42:48 +03:00
Alexander Baranov 86dd79c8ae test: add spec-driven universal CLI suite; fix context strict + path confinement bugs
- tests-universal/ drives repoctl only as a subprocess CLI, asserting
  directly against docs/specification.md (envelope, exit codes 0-5,
  validation rules MVP, security invariants) so the same suite can judge
  any conforming implementation, including the sibling codex/repoctl-l1
  branch built independently from the same baseline.
- Running it surfaced two real bugs, both fixed:
  - `context --strict` only checked budget truncation, never stale or
    missing referenced documents, despite specification.md 19.2 defining
    exit 4 as "stale or incomplete context" (not just truncation).
  - `paths.confined_path` crashed with an unhandled WinError2 when a
    referenced path's parent directory also didn't exist, because it
    resolved a single non-existent parent with strict=True instead of
    walking up to the nearest existing ancestor.
2026-08-24 15:38:49 +03:00
Alexander BaranovandClaude Sonnet 5 64e6c2f5f5 fix: force UTF-8 stdout/stderr in repoctl and drop non-ASCII em dashes
End-to-end smoke testing of `init` and `adopt` (plan -> approve -> apply -> verify)
via subprocess surfaced a real portability bug: on Windows, sys.stdout defaults to
the console codepage rather than UTF-8 when not attached to a UTF-8 terminal, so
machine YAML/JSON output containing non-ASCII characters (an em dash in generated
skill/docstring text) could fail to decode for downstream consumers. repoctl now
reconfigures stdout/stderr to UTF-8 unconditionally in main(), and the offending
em dashes are replaced with ASCII hyphens so generated file content is unaffected
either way.

Verified via manual CLI smoke tests: full init and adopt flows (including baseline
re-check, plan-hash approval, collision rejection on re-apply, and preservation of
profiles-source/, profiles/ and legacy kdb.yaml) work end to end.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 15:04:11 +03:00
Alexander BaranovandClaude Sonnet 5 7286322c83 docs: self-host at L1 and ship the three Claude skill adapters
- Move ops/contract.yaml annotation from specification-only to l1-implemented and
  declare real content roots for repoctl source, schemas, tests and Claude adapters.
- Add repoctl-cli capability to provides[].
- Route repository.tooling.use and repository.handoff intents to the existing
  tooling-implementation KDB topic.
- Update README, AGENTS.md and CLAUDE.md to describe the implemented repoctl surface
  instead of a planned one, without claiming L2/L3/MCP capabilities that don't exist.
- Add .claude/skills/{repository-bootstrap,repository-adoption,repo-handoff}/SKILL.md,
  generated from the same stewardship.skills_content strings that ship inside every
  repoctl init bootstrap (no duplicated logic).

`repoctl validate --repo .` passes with zero findings after this change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 15:00:34 +03:00
Alexander BaranovandClaude Sonnet 5 96d4d08230 feat: implement repoctl L1 core (models, schemas, validate, discover, context, init, adopt)
Adds the repository-stewardship Python package (src/stewardship) with:
- JSON Schemas (Draft 2020-12) for RepositoryContract, KnowledgeBase, CatalogIndex,
  ContextBundle, BootstrapPlan, AdoptionAssessment/Plan/Report, user config and the
  repoctl-result envelope.
- Safe YAML I/O, path confinement, deterministic clock and canonical-JSON hashing.
- validate: schema, ID uniqueness, path safety, KDB references, freshness, secret-shaped
  fields, shell-string detection, and Markdown frontmatter/fence/link checks.
- discover/CatalogIndex with deterministic sorting and duplicate-name detection.
- describe (contract-only) and context (intent-scoped ContextBundle with budgeted
  materialization and --strict truncation).
- init: plan-then-apply bootstrap with SHA-256 plan-hash approval, no fake domain
  artifacts, bundled Claude skills.
- adopt: assess/plan/apply/verify overlay workflow per docs/adoption-runbook.md,
  preserving legacy content roots and KDB, with baseline-hash re-check and rollback.
- argparse-based `repoctl` CLI with human/yaml/json output and spec exit codes.
- pytest suite (39 tests) covering positive/negative fixtures, discovery, context,
  bootstrap and adoption (including LXD- and Antivirus-shaped legacy layouts).

Managed with uv (.venv), ruff clean, mypy --strict clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 14:57:34 +03:00
Alexander Baranov 9a39b8a941 docs: baseline specification-only repository stewardship 2026-08-24 14:39:09 +03:00