From 39c7da3eb12629e737fd72b0bb3c12092cdb612b Mon Sep 17 00:00:00 2001 From: Alexander Baranov Date: Thu, 27 Aug 2026 12:23:32 +0300 Subject: [PATCH] feat(kdb-table): render a knowledge base as a table a human can read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit База знаний машиночитаема и длинна: чтобы ответить «что там вообще есть», приходилось читать файл целиком. Теперь есть отдельный вывод для человека. - `stewardship.kdb_table` - модуль, а не файл рядом со скиллом: `skills install` переносит только SKILL.md, поэтому скрипт в каталоге скилла не доехал бы до репозитория, куда скилл поставили. Как модуль он доступен везде, где есть repoctl: `python -m stewardship.kdb_table --repo `. - Путь к базе знаний не угадывается: берётся `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 --- .claude/skills/kdb-table/SKILL.md | 43 ++++++++++++++++++ README.md | 2 +- src/stewardship/kdb_table.py | 72 +++++++++++++++++++++++++++++++ src/stewardship/skills.py | 2 + src/stewardship/skills_content.py | 45 +++++++++++++++++++ tests/test_skills.py | 39 +++++++++++++++++ 6 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 .claude/skills/kdb-table/SKILL.md create mode 100644 src/stewardship/kdb_table.py diff --git a/.claude/skills/kdb-table/SKILL.md b/.claude/skills/kdb-table/SKILL.md new file mode 100644 index 0000000..897c890 --- /dev/null +++ b/.claude/skills/kdb-table/SKILL.md @@ -0,0 +1,43 @@ +--- +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 +python -m stewardship.kdb_table --repo +``` + +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. + +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 --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 `; run that after editing the entrypoint. diff --git a/README.md b/README.md index 7d671f8..9411ce2 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ approval для любых записей. `ops/handlers/`, execution runner и | `src/stewardship/schemas/` | JSON Schemas (Draft 2020-12) для всех kinds | | `tests/` | unit pytest-набор (позитивные, негативные, adoption fixtures) | | `tests-universal/` | spec-driven CLI-контрактный набор, независимый от реализации | -| `.claude/skills/` | три тонких Claude skill-адаптера над `repoctl` | +| `.claude/skills/` | четыре тонких Claude skill-адаптера над `repoctl` | ### Установка и запуск diff --git a/src/stewardship/kdb_table.py b/src/stewardship/kdb_table.py new file mode 100644 index 0000000..f5e2943 --- /dev/null +++ b/src/stewardship/kdb_table.py @@ -0,0 +1,72 @@ +"""Render a repository's KnowledgeBase as a compact Markdown table, for a human. + +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. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +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.""" + 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") + if isinstance(rel, str) and rel: + return root / rel + return root / "kdb/kdb.yaml" + + +def render(root: Path) -> str: + 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 [] + out = [ + f"## {spec.get('repository', root.name)} - {len(topics)} topics, {len(documents)} documents", + "", + "| Topic | Intents | Documents | Facts in data |", + "| --- | --- | --- | --- |", + ] + for t in sorted(topics, key=lambda x: -(x.get("priority") or 0)): + 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 '-'} |" + ) + 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} |" + ) + 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()) diff --git a/src/stewardship/skills.py b/src/stewardship/skills.py index c97b5e8..6a61d7c 100644 --- a/src/stewardship/skills.py +++ b/src/stewardship/skills.py @@ -21,6 +21,7 @@ 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, @@ -29,6 +30,7 @@ from .skills_content import ( 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, diff --git a/src/stewardship/skills_content.py b/src/stewardship/skills_content.py index 33bec5e..c90f174 100644 --- a/src/stewardship/skills_content.py +++ b/src/stewardship/skills_content.py @@ -94,3 +94,48 @@ by hand when this skill applies - let `repoctl` perform the selection. 4. Hand the resulting `ContextBundle` (and any `warnings`) to the requester instead of 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 +python -m stewardship.kdb_table --repo +``` + +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. + +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 --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 `; run that after editing the entrypoint. +""" diff --git a/tests/test_skills.py b/tests/test_skills.py index f82fcc0..13812d7 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -145,3 +145,42 @@ def test_cli_refusal_is_an_envelope(tmp_path: Path, capsys) -> None: 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 "**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") +