ReMe/reme/steps/evolve/_evolve.py
yaozy2020 9c4f7621d7
Some checks failed
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / Python tests / Hermes embedded - ubuntu-latest (push) Waiting to run
CI / Python tests / Hermes embedded - windows-latest (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
fix(dream): strip YAML front matter from extraction input (#738)
* fix(dream): strip YAML front matter from extraction input

Daily notes carry YAML front matter (`name` / `description` / `tags`).
`pack_paths()` packed it verbatim into the auto-dream extraction prompt, so
the model mimicked that shape and emitted units without `bucket` / `summary`,
which then failed `DreamUnit` validation and produced 0 units (issue #730).

Move `strip_frontmatter` from `proactive/utils.py` into the shared evolve
helper module and use it in `pack_paths`, so only the body is packed. The
proactive flow already stripped front matter before feeding note content to
a model; dream did not.

The per-file `limit_per_file` budget now applies to the body as well, so a
long `description:` value can no longer consume the packing budget.

Regression tests live in their own module because `test_auto_dream.py` is
already at the pylint `too-many-lines` limit (1500).

Ref: #730

* fix(dream): 修复前置元数据剥离导致正文丢失和日期异常

仅在候选块成功解析为映射后消费内容;非映射、YAML 错误及时间戳 ValueError 均保留剩余原文。补充审查样本、畸形 Markdown 与配置化 Auto Dream 管线测试,保持空抽取的 checkpoint 语义。

验证:相关测试 176 passed;全量单测 3396 passed / 50 skipped;旧实现反向验证 7 failed / 4 passed。

* fix(dream): end the metadata run at the blank line, not at YAML parseability

`strip_frontmatter` consumed any following `---` block that happened to parse
as a mapping. Markdown body text can be valid YAML (`# heading` is a comment,
`Instruction: ...` is a mapping key), so parseability alone cannot separate
metadata from body: the body was merged into the metadata and the note was
sent to the extraction model with a heading and no content, then checkpointed
as processed.

A block is now consumed only when it is structurally part of the metadata run:
the first block may follow leading whitespace, every later block must follow
the previous closing `---` with no blank line in between. A blank line is the
metadata/body boundary, so the remaining text is kept verbatim. Consecutive
front-matter blocks (`---\n---`) still strip as before.

Adds packing- and pipeline-level regression cases for the mapping-shaped body.
2026-11-16 12:32:42 +08:00

99 lines
3.7 KiB
Python

"""Shared helpers for evolve steps."""
import datetime
import zoneinfo
import yaml
from agentscope.message import Msg
from ...schema import AgentReply, Response
def now(timezone: str | None = None) -> datetime.datetime:
"""Return current datetime in the given IANA timezone, falling back to local."""
if not timezone:
return datetime.datetime.now()
try:
return datetime.datetime.now(zoneinfo.ZoneInfo(timezone))
except Exception:
return datetime.datetime.now()
def format_history(messages: list[Msg], include_timestamp: bool = True) -> str:
"""Render a conversation slice as a human-readable transcript."""
lines: list[str] = []
for msg in messages:
text = (msg.get_text_content() or "").strip()
if not text:
continue
speaker = msg.name or msg.role or "?"
header = f"[{speaker} @ {msg.created_at}]" if include_timestamp else f"[{speaker}]"
lines.append(f"{header}\n{text}")
return "\n\n".join(lines) or "(empty)"
def agent_reply_result_text(reply_result: AgentReply) -> str:
"""Require a completed invocation and return its backend-neutral final text."""
status = reply_result["status"]
if status != "completed" or reply_result.get("error") is not None:
raise RuntimeError(reply_result.get("error") or f"Agent reply ended: {status}")
return reply_result["result"].strip()
def passthrough_response(step, skip_key: str) -> Response:
"""Return a success response when a short-circuit flag is set (INV-7).
Short-circuited rounds never write interests.yaml or checkpoint catalogs;
the job still reports success so the skipped round is not counted as a failure.
"""
assert step.context is not None
response = step.context.response
response.success = True
flag = step.context.get(skip_key)
if isinstance(flag, dict):
reason = str(flag.get("reason") or "skipped")
else:
reason = str(flag or "skipped")
response.answer = f"Skipped: {reason}"
step.logger.info(f"[{step.name}] short-circuit via {skip_key!r} reason={reason}")
return response
def strip_frontmatter(text: str) -> tuple[dict, str]:
"""Split leading ``---`` YAML frontmatter blocks from the body.
Handles files with several consecutive frontmatter blocks; returns
``(merged_meta, body)``. A block is consumed only when it parses to a
mapping **and** it is structurally part of the metadata run: the first
block may be preceded by leading whitespace, while every later block has
to follow the previous block's closing ``---`` with no blank line in
between. A blank line is the metadata/body boundary, so whatever follows
is kept verbatim as Markdown even when it would itself parse as a mapping
(a ``#`` heading is a YAML comment and ``Instruction: ...`` is a valid
mapping, so parseability alone cannot tell metadata from body). On
parse/construction errors or non-mapping YAML, stop and preserve the
remaining text rather than risk discarding Markdown.
"""
meta: dict = {}
body = (text or "").lstrip()
while body.startswith("---"):
rest = body[3:]
end = rest.find("\n---")
if end < 0:
break
block = rest[:end]
try:
data = yaml.safe_load(block)
except (yaml.YAMLError, ValueError):
break
if not isinstance(data, dict):
break
for key, value in data.items():
meta.setdefault(str(key), value)
tail = rest[end + 4 :]
nxt = tail.lstrip("\n")
if len(tail) - len(nxt) > 1 or not nxt.startswith("---"):
body = tail
break
body = nxt
return meta, body.strip()