Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1598-create-template-kb-schema.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `pyrite create --template -k <kb>` now builds the entry skeleton with declared fields and defaults for the KB's schema and refuses undeclared types (#1598).
48 changes: 31 additions & 17 deletions pyrite/cli/entry_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,23 +350,37 @@ def create_entry(

# Template mode: the skeleton is the result
if template:
fm: dict = {
"id": "",
"type": entry_type,
"title": title or "Your Title Here",
"tags": [],
}
# Add type-specific fields as empty values
type_info = CORE_TYPES.get(entry_type, {})
for field_name, field_type in type_info.get("fields", {}).items():
if field_name in ("tags", "links"):
continue
if "list" in field_type:
fm[field_name] = []
elif field_type == "int":
fm[field_name] = 0
else:
fm[field_name] = ""
if kb_name:
with cli_context(kbs=(kb_name,)) as (config, _db, svc):
kb_config = config.get_kb(kb_name)
try:
resolved_type, fm = svc.template_frontmatter(
entry_type,
kb_config,
title=title,
allow_undeclared=allow_undeclared,
)
except ValidationError as e:
raise _with_cli_hint(e) from None
entry_type = resolved_type
else:
fm = {
"id": "",
"type": entry_type,
"title": title or "Your Title Here",
"tags": [],
}
# Add type-specific fields as empty values
type_info = CORE_TYPES.get(entry_type, {})
for field_name, field_type in type_info.get("fields", {}).items():
if field_name in ("tags", "links"):
continue
if "list" in field_type:
fm[field_name] = []
elif field_type == "int":
fm[field_name] = 0
else:
fm[field_name] = ""
skeleton = f"---\n{dump_yaml(fm)}\n---\n\nYour content here."

def raw(console: Console, data: dict) -> None:
Expand Down
40 changes: 40 additions & 0 deletions pyrite/services/kb_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,46 @@ def _with_declared_fields(
attributes[field] = None
return {**fields, **added}, attributes

def template_frontmatter(
self,
entry_type: str,
kb_config: KBConfig,
*,
title: str | None = None,
allow_undeclared: bool = False,
) -> tuple[str, dict[str, Any]]:
"""Compute the frontmatter for an entry template in the given KB (#1598).

Refuses undeclared types unless allow_undeclared is True.
Returns (resolved_type, frontmatter_dict).
"""
from ..models.factory import build_entry

named = entry_type
resolved_type = self._resolve_entry_type(named, kb_config)
if not allow_undeclared:
if resolved_type != named:
self._refuse_undeclared_mapping_target(
named, resolved_type, kb_config.name, kb_config
)
else:
self._refuse_undeclared_type(named, kb_config.name, kb_config)
fields, attributes = self._with_declared_fields(resolved_type, kb_config, {})
entry = build_entry(
resolved_type,
entry_id="",
title=title or "Your Title Here",
body="",
**fields,
)
entry._create_fields = attributes
fm = {
**entry._frontmatter_for_file(),
"id": "",
"title": title or "Your Title Here",
}
return resolved_type, fm

def _prepare_and_save(
self,
kb_name: str,
Expand Down
115 changes: 115 additions & 0 deletions tests/test_create_template_kb_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Regression tests for create --template using KB schema (#1598).

Verifies that:
- `pyrite create -k <kb> -t <type> --template` uses the KB's declared schema fields and defaults.
- For a software KB, `backlog_item` template includes kind, status: proposed, priority: medium, effort, assignee.
- Extra fields declared in kb.yaml on core types appear in the template.
- Undeclared types in a KB that declares schema are refused with the same error as a real create.
- Without `-k`, `create -t <type> --template` keeps today's core types skeleton.
"""

from __future__ import annotations

import json
from pathlib import Path

import yaml

from pyrite.cli.init_command import BUILTIN_TEMPLATES
from pyrite.config import KBConfig
from pyrite.utils.frontmatter import split_frontmatter


def _parse_template_frontmatter(template_str: str) -> dict:
split = split_frontmatter(template_str)
return yaml.safe_load(split.text)


def test_create_template_with_software_kb_matches_create_fields(cli_world, tmp_path: Path):
"""In a software KB, backlog_item template reflects fields and defaults written by create."""
kb_path = tmp_path / "proj"
kb_path.mkdir(parents=True, exist_ok=True)
(kb_path / "kb.yaml").write_text(yaml.dump(BUILTIN_TEMPLATES["software"]))

world = cli_world(kbs=[KBConfig(name="proj", path=kb_path, kb_type="generic")])

res = world.cli("create", "-k", "proj", "-t", "backlog_item", "--template", "--format", "json")
assert res.exit_code == 0, res.output
data = json.loads(res.output)
assert data["outcome"] == "done"
assert data["entry_type"] == "backlog_item"

fm = _parse_template_frontmatter(data["template"])
assert fm["type"] == "backlog_item"
assert fm["id"] == ""
assert fm["title"] == "Your Title Here"
assert fm["status"] == "proposed"
assert fm["priority"] == "medium"
assert "kind" in fm
assert "effort" in fm
assert "assignee" in fm


def test_create_template_includes_fields_added_in_kb_yaml(cli_world, tmp_path: Path):
"""A field added to a core type in kb.yaml appears in that KB's note template."""
kb_path = tmp_path / "custom-kb"
kb_path.mkdir(parents=True, exist_ok=True)
kb_yaml_content = {
"name": "custom-kb",
"types": {
"note": {
"fields": {
"project": {"type": "text", "default": "alpha"},
"reviewed": {"type": "checkbox", "default": True},
}
}
},
}
(kb_path / "kb.yaml").write_text(yaml.dump(kb_yaml_content))

world = cli_world(kbs=[KBConfig(name="custom-kb", path=kb_path, kb_type="generic")])

res = world.cli("create", "-k", "custom-kb", "-t", "note", "--template", "--format", "json")
assert res.exit_code == 0, res.output
data = json.loads(res.output)

fm = _parse_template_frontmatter(data["template"])
assert fm["type"] == "note"
assert fm["project"] == "alpha"
assert fm["reviewed"] is True


def test_create_template_refuses_undeclared_type(cli_world, tmp_path: Path):
"""create --template refuses undeclared types with the same error code as real create."""
kb_path = tmp_path / "proj"
kb_path.mkdir(parents=True, exist_ok=True)
(kb_path / "kb.yaml").write_text(yaml.dump(BUILTIN_TEMPLATES["software"]))

world = cli_world(kbs=[KBConfig(name="proj", path=kb_path, kb_type="generic")])

# Template invocation for undeclared type
tpl_res = world.cli("create", "-k", "proj", "-t", "nosuch", "--template", "--format", "json")
assert tpl_res.exit_code == 1, tpl_res.output
tpl_data = json.loads(tpl_res.output)
assert tpl_data["error_code"] == "UNDECLARED_TYPE"
assert "type 'nosuch' is not declared in KB 'proj'" in tpl_data["error"]

# Real create invocation for undeclared type
real_res = world.cli("create", "-k", "proj", "-t", "nosuch", "--title", "x", "--format", "json")
assert real_res.exit_code == 1, real_res.output
real_data = json.loads(real_res.output)
assert real_data["error_code"] == tpl_data["error_code"]
assert "type 'nosuch' is not declared in KB 'proj'" in real_data["error"]


def test_create_template_without_kb_keeps_core_type_skeleton(cli_world):
"""Without -k, create --template prints core types skeleton with type fields."""
world = cli_world()
res = world.cli("create", "-t", "person", "--template", "--format", "json")
assert res.exit_code == 0, res.output
data = json.loads(res.output)

fm = _parse_template_frontmatter(data["template"])
assert fm["type"] == "person"
assert "role" in fm
assert "affiliations" in fm
Loading