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>
This commit is contained in:
co-authored by
Claude Opus 5
parent
c607a14f8b
commit
39c7da3eb1
@@ -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 <path>
|
||||||
|
```
|
||||||
|
|
||||||
|
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 <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.
|
||||||
@@ -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` |
|
||||||
|
|
||||||
### Установка и запуск
|
### Установка и запуск
|
||||||
|
|
||||||
|
|||||||
@@ -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 <path>`; 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())
|
||||||
@@ -21,6 +21,7 @@ from typing import Any
|
|||||||
from . import io
|
from . import io
|
||||||
from .paths import PathViolation, confined_path
|
from .paths import PathViolation, confined_path
|
||||||
from .skills_content import (
|
from .skills_content import (
|
||||||
|
KDB_TABLE_SKILL,
|
||||||
REPO_HANDOFF_SKILL,
|
REPO_HANDOFF_SKILL,
|
||||||
REPOSITORY_ADOPTION_SKILL,
|
REPOSITORY_ADOPTION_SKILL,
|
||||||
REPOSITORY_BOOTSTRAP_SKILL,
|
REPOSITORY_BOOTSTRAP_SKILL,
|
||||||
@@ -29,6 +30,7 @@ from .skills_content import (
|
|||||||
SKILLS_SUBPATH = ".claude/skills"
|
SKILLS_SUBPATH = ".claude/skills"
|
||||||
|
|
||||||
SKILLS: dict[str, str] = {
|
SKILLS: dict[str, str] = {
|
||||||
|
"kdb-table": KDB_TABLE_SKILL,
|
||||||
"repo-handoff": REPO_HANDOFF_SKILL,
|
"repo-handoff": REPO_HANDOFF_SKILL,
|
||||||
"repository-adoption": REPOSITORY_ADOPTION_SKILL,
|
"repository-adoption": REPOSITORY_ADOPTION_SKILL,
|
||||||
"repository-bootstrap": REPOSITORY_BOOTSTRAP_SKILL,
|
"repository-bootstrap": REPOSITORY_BOOTSTRAP_SKILL,
|
||||||
|
|||||||
@@ -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
|
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
|
||||||
|
python -m stewardship.kdb_table --repo <path>
|
||||||
|
```
|
||||||
|
|
||||||
|
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 <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.
|
||||||
|
"""
|
||||||
|
|||||||
@@ -145,3 +145,42 @@ def test_cli_refusal_is_an_envelope(tmp_path: Path, capsys) -> None:
|
|||||||
assert exit_code != 0
|
assert exit_code != 0
|
||||||
assert envelope["outcome"] == "failure"
|
assert envelope["outcome"] == "failure"
|
||||||
assert envelope["findings"][0]["code"] == "SKILLS_MODIFIED"
|
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")
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user