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>
This commit is contained in:
co-authored by
Claude Opus 5
parent
39c7da3eb1
commit
c10df0e3af
@@ -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.
|
file to answer "what is in there" is the thing this skill exists to avoid.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python -m stewardship.kdb_table --repo <path>
|
repoctl kdb --repo <path>
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
(`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
|
to be guessed and the same command works on any adopted repository. A
|
||||||
repository has no knowledge base, it says so and exits cleanly.
|
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:
|
Print the Markdown it emits as-is; do not paraphrase it. Two tables:
|
||||||
|
|
||||||
|
|||||||
@@ -104,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` — только нужные знания под задачу
|
||||||
|
|
||||||
Главная команда для агента. Вместо чтения всей документации репозитория:
|
Главная команда для агента. Вместо чтения всей документации репозитория:
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ from pathlib import Path
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from . import adoption, bootstrap, config, discovery, io, skills
|
from . import adoption, bootstrap, config, discovery, io, skills
|
||||||
|
from . import kdb_table
|
||||||
from .constants import CONTRACT_PATH, LIFECYCLES, REPOSITORY_TYPES, RESULT_SCHEMA
|
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
|
||||||
@@ -146,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(
|
||||||
@@ -384,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")
|
||||||
|
|||||||
@@ -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
|
Read-only. The structured form goes into the result envelope like every other
|
||||||
contract is machine output, while this is a reading aid. Run it as
|
command; the Markdown table is what `--output human` renders instead of the
|
||||||
`python -m stewardship.kdb_table --repo <path>`; the entrypoint comes from the
|
usual one-line outcome, because "what is in the knowledge base" is a question
|
||||||
repository's own contract, so it works on any adopted repository.
|
whose answer is the content, not a status.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
from . import io as sio
|
from . import io as sio
|
||||||
from .constants import CONTRACT_PATH
|
from .constants import CONTRACT_PATH
|
||||||
|
|
||||||
|
|
||||||
def _entrypoint(root: Path) -> Path:
|
def entrypoint(root: Path) -> Path:
|
||||||
"""The knowledge entrypoint the contract declares, or the canonical default."""
|
"""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
|
contract = root / CONTRACT_PATH
|
||||||
if contract.exists():
|
if contract.exists():
|
||||||
spec = (sio.load_yaml(contract) or {}).get("spec") or {}
|
loaded = sio.load_yaml(contract)
|
||||||
rel = ((spec.get("knowledge") or {}) if isinstance(spec.get("knowledge"), dict) else {}).get("entrypoint")
|
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:
|
if isinstance(rel, str) and rel:
|
||||||
return root / rel
|
return root / rel
|
||||||
return root / "kdb/kdb.yaml"
|
return root / "kdb/kdb.yaml"
|
||||||
|
|
||||||
|
|
||||||
def render(root: Path) -> str:
|
def collect(root: Path) -> dict[str, Any] | None:
|
||||||
path = _entrypoint(root)
|
"""The overview as plain data, or None when the repository has no knowledge base."""
|
||||||
|
path = entrypoint(root)
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
return f"No knowledge base at {path}."
|
return None
|
||||||
spec = (sio.load_yaml(path) or {}).get("spec") or {}
|
loaded = sio.load_yaml(path)
|
||||||
topics, documents = spec.get("topics") or [], spec.get("documents") or []
|
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 = [
|
out = [
|
||||||
f"## {spec.get('repository', root.name)} - {len(topics)} topics, {len(documents)} documents",
|
f"## {data['repository']} - {len(topics)} topics, {len(documents)} documents",
|
||||||
|
f"<!-- {data['entrypoint']} -->",
|
||||||
"",
|
"",
|
||||||
"| Topic | Intents | Documents | Facts in data |",
|
"| 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(
|
out.append(
|
||||||
f"| **{t.get('id')}** | {', '.join(t.get('intents') or []) or '-'} "
|
f"| **{t['id']}** | {', '.join(t['intents']) or '-'} "
|
||||||
f"| {', '.join(t.get('documents') or []) or '-'} "
|
f"| {', '.join(t['documents']) or '-'} | {', '.join(t['dataKeys']) or '-'} |"
|
||||||
f"| {', '.join(t.get('data') or {}) or '-'} |"
|
|
||||||
)
|
)
|
||||||
out += ["", "### Documents", "", "| Id | Path | Role | Status |", "| --- | --- | --- | --- |"]
|
out += ["", "### Documents", "", "| Id | Path | Role | Status |", "| --- | --- | --- | --- |"]
|
||||||
for d in documents:
|
for d in documents:
|
||||||
stale = " (!)" if d.get("status") == "stale" else ""
|
stale = " (!)" if d["status"] == "stale" else ""
|
||||||
out.append(
|
out.append(f"| {d['id']} | `{d['path'] or '-'}` | {d['role']} | {d['status']}{stale} |")
|
||||||
f"| {d.get('id')} | `{d.get('path') or d.get('uri') or '-'}` "
|
|
||||||
f"| {d.get('role')} | {d.get('status')}{stale} |"
|
|
||||||
)
|
|
||||||
return "\n".join(out)
|
return "\n".join(out)
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
def render(root: Path) -> str:
|
||||||
parser = argparse.ArgumentParser(prog="stewardship.kdb_table", description=__doc__)
|
"""Markdown for ``root``, or a plain sentence when there is no knowledge base."""
|
||||||
parser.add_argument("--repo", default=".", help="repository root (default: current directory)")
|
data = collect(root)
|
||||||
args = parser.parse_args(argv)
|
return markdown(data) if data else f"No knowledge base at {entrypoint(root)}."
|
||||||
# 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())
|
|
||||||
|
|||||||
@@ -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.
|
file to answer "what is in there" is the thing this skill exists to avoid.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python -m stewardship.kdb_table --repo <path>
|
repoctl kdb --repo <path>
|
||||||
```
|
```
|
||||||
|
|
||||||
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
|
(`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
|
to be guessed and the same command works on any adopted repository. A
|
||||||
repository has no knowledge base, it says so and exits cleanly.
|
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:
|
Print the Markdown it emits as-is; do not paraphrase it. Two tables:
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -175,6 +175,7 @@ def test_kdb_table_reads_the_entrypoint_the_contract_declares(tmp_path) -> None:
|
|||||||
)
|
)
|
||||||
out = render(tmp_path)
|
out = render(tmp_path)
|
||||||
assert "repo:x - 1 topics, 1 documents" in out
|
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 "**t-one**" in out and "do-a-thing" in out
|
||||||
assert "(!)" in out # a stale document is marked, not silently listed
|
assert "(!)" in out # a stale document is marked, not silently listed
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user