From c10df0e3afdbddb203fbc73e980cd9af249e934c Mon Sep 17 00:00:00 2001 From: Alexander Baranov Date: Thu, 27 Aug 2026 13:07:36 +0300 Subject: [PATCH] feat(cli): add `repoctl kdb`, the one command whose human output is content MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Обзор базы знаний жил как `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 --- .claude/skills/kdb-table/SKILL.md | 12 ++-- docs/repoctl.md | 22 +++++++ src/stewardship/cli.py | 26 ++++++++ src/stewardship/kdb_table.py | 106 ++++++++++++++++++------------ src/stewardship/skills_content.py | 12 ++-- tests/test_cli.py | 28 ++++++++ tests/test_skills.py | 1 + 7 files changed, 158 insertions(+), 49 deletions(-) diff --git a/.claude/skills/kdb-table/SKILL.md b/.claude/skills/kdb-table/SKILL.md index 897c890..d1a385e 100644 --- a/.claude/skills/kdb-table/SKILL.md +++ b/.claude/skills/kdb-table/SKILL.md @@ -9,13 +9,17 @@ 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 -python -m stewardship.kdb_table --repo +repoctl kdb --repo ``` -The entrypoint is read from the repository's own `ops/contract.yaml` +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. If the -repository has no knowledge base, it says so and exits cleanly. +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: diff --git a/docs/repoctl.md b/docs/repoctl.md index bf51da2..198c088 100644 --- a/docs/repoctl.md +++ b/docs/repoctl.md @@ -104,6 +104,28 @@ repoctl describe --repo some-repo-name --output json Возвращает нормализованный `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` — только нужные знания под задачу Главная команда для агента. Вместо чтения всей документации репозитория: diff --git a/src/stewardship/cli.py b/src/stewardship/cli.py index a93ebc9..7742b7c 100644 --- a/src/stewardship/cli.py +++ b/src/stewardship/cli.py @@ -13,6 +13,7 @@ from pathlib import Path from typing import Any from . import adoption, bootstrap, config, discovery, io, skills +from . import kdb_table from .constants import CONTRACT_PATH, LIFECYCLES, REPOSITORY_TYPES, RESULT_SCHEMA from .context import build_context from .paths import find_repository_root @@ -146,6 +147,26 @@ def cmd_describe(args: argparse.Namespace) -> int: 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: root = _resolve_repo(args.repo, args.root) result = build_context( @@ -384,6 +405,11 @@ def build_parser() -> argparse.ArgumentParser: p_describe.add_argument("--root", action="append") 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") add_common(p_context) p_context.add_argument("--repo") diff --git a/src/stewardship/kdb_table.py b/src/stewardship/kdb_table.py index f5e2943..cf8c06a 100644 --- a/src/stewardship/kdb_table.py +++ b/src/stewardship/kdb_table.py @@ -1,72 +1,96 @@ -"""Render a repository's KnowledgeBase as a compact Markdown table, for a human. +"""`repoctl kdb`: a repository's KnowledgeBase as a table a human can read. -Read-only, and deliberately outside the CLI's command surface: `repoctl`'s -contract is machine output, while this is a reading aid. Run it as -`python -m stewardship.kdb_table --repo `; the entrypoint comes from the -repository's own contract, so it works on any adopted repository. +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 -import argparse -import sys 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.""" +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(): - spec = (sio.load_yaml(contract) or {}).get("spec") or {} - rel = ((spec.get("knowledge") or {}) if isinstance(spec.get("knowledge"), dict) else {}).get("entrypoint") + 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 render(root: Path) -> str: - path = _entrypoint(root) +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 f"No knowledge base at {path}." - spec = (sio.load_yaml(path) or {}).get("spec") or {} - topics, documents = spec.get("topics") or [], spec.get("documents") or [] + 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"## {spec.get('repository', root.name)} - {len(topics)} topics, {len(documents)} documents", + f"## {data['repository']} - {len(topics)} topics, {len(documents)} documents", + f"", "", "| Topic | Intents | Documents | Facts in data |", "| --- | --- | --- | --- |", ] - for t in sorted(topics, key=lambda x: -(x.get("priority") or 0)): + for t in topics: out.append( - f"| **{t.get('id')}** | {', '.join(t.get('intents') or []) or '-'} " - f"| {', '.join(t.get('documents') or []) or '-'} " - f"| {', '.join(t.get('data') or {}) or '-'} |" + 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.get("status") == "stale" else "" - out.append( - f"| {d.get('id')} | `{d.get('path') or d.get('uri') or '-'}` " - f"| {d.get('role')} | {d.get('status')}{stale} |" - ) + stale = " (!)" if d["status"] == "stale" else "" + out.append(f"| {d['id']} | `{d['path'] or '-'}` | {d['role']} | {d['status']}{stale} |") return "\n".join(out) -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(prog="stewardship.kdb_table", description=__doc__) - parser.add_argument("--repo", default=".", help="repository root (default: current directory)") - args = parser.parse_args(argv) - # A non-ASCII knowledge base must not die on a cp1251 console; the guard is - # for stdout objects that are not a real TextIOWrapper (a captured pipe). - reconfigure = getattr(sys.stdout, "reconfigure", None) - if reconfigure is not None: - reconfigure(encoding="utf-8") - print(render(Path(args.repo).resolve())) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) +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)}." diff --git a/src/stewardship/skills_content.py b/src/stewardship/skills_content.py index c90f174..1d214dc 100644 --- a/src/stewardship/skills_content.py +++ b/src/stewardship/skills_content.py @@ -106,13 +106,17 @@ 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 -python -m stewardship.kdb_table --repo +repoctl kdb --repo ``` -The entrypoint is read from the repository's own `ops/contract.yaml` +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. If the -repository has no knowledge base, it says so and exits cleanly. +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: diff --git a/tests/test_cli.py b/tests/test_cli.py index ed36a3c..90bf38d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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): code = main(["init", "--repo", str(tmp_path), "--apply", "--output", "json"]) 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 diff --git a/tests/test_skills.py b/tests/test_skills.py index 13812d7..27b5688 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -175,6 +175,7 @@ def test_kdb_table_reads_the_entrypoint_the_contract_declares(tmp_path) -> None: ) out = render(tmp_path) assert "repo:x - 1 topics, 1 documents" in out + assert "" in out # видно, откуда взято, раз путь нестандартный assert "**t-one**" in out and "do-a-thing" in out assert "(!)" in out # a stale document is marked, not silently listed