refactor(frontmatter-read): simplify answer rendering

This commit is contained in:
jinli.yl 2026-10-28 16:11:19 +08:00
parent 50bfb0f971
commit 4e8b6ef2ee

View file

@ -2,10 +2,8 @@
Cheap structured read — frontmatter only, no body. Use ``body:read``
for the post-frontmatter content slice, or whole-file ``read`` when
you want both at once. The answer is textual — one JSON-encoded
``- "key": value`` entry per line, so every key and value stays on a
single line — because MCP callers only ever see ``answer``; the parsed
mapping itself is returned in ``metadata["frontmatter"]`` (and
you want both at once. The answer has one ``- "key": value`` entry per
line; the parsed mapping is returned in ``metadata["frontmatter"]`` (and
``exists: false`` in metadata when the target doesn't exist).
``path`` is a path relative to the workspace.
@ -23,19 +21,11 @@ from ...components import R
def _render_value(value) -> str:
"""Render one frontmatter key or value on a single answer line.
"""Render a key or value on one line using JSON with a ``repr`` fallback.
``frontmatter_read`` is served straight to the LLM, so the answer
has to carry the frontmatter itself, one ``- "key": value`` entry
per line. ``json.dumps`` (with ``default=str`` for YAML-only types
such as dates, and ``ensure_ascii=False`` for non-ASCII) keeps each
entry on one line and preserves the distinction between a literal
``"\\n"`` two-character sequence and an actual newline, and between
the string ``"null"`` and YAML ``null``. Presentation limitation:
JSON stringifies mapping keys, so an int ``1`` and a string ``"1"``
both render as ``"1"`` (only the structured metadata keeps them
apart, and re-parsing the fragment keeps the last value). The
fallback covers values JSON refuses, recursive aliases included.
YAML-only values such as dates use ``str``. Unsupported mapping keys
and recursive aliases fall back to ``repr``. JSON stringifies nested
mapping keys; only metadata preserves their original types.
"""
try:
return json.dumps(value, ensure_ascii=False, default=str)
@ -97,7 +87,7 @@ class FrontmatterReadStep(BaseStep):
return
self.context.response.success = True
header = f"Read frontmatter from {probed} ({len(meta)} key(s))"
rendered = [f"- {_render_value(key)}: {_render_value(value)}" for key, value in meta.items()]
self.context.response.answer = f"{header}:\n" + "\n".join(rendered) if rendered else f"{header}: (no keys)"
body = "\n".join(f"- {_render_value(key)}: {_render_value(value)}" for key, value in meta.items())
self.context.response.answer = f"{header}:\n{body}" if body else f"{header}: (no keys)"
self.context.response.metadata.update({"path": path, "exists": True, "frontmatter": meta, **resolved})
self.logger.info(f"[{self.name}] path={path} keys={len(meta)}")