diff --git a/.agents/notes/implemented/bug-fix/2026-11-04-daily-report-editorial-quality.md b/.agents/notes/implemented/bug-fix/2026-11-04-daily-report-editorial-quality.md new file mode 100644 index 00000000..0a88362e --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-04-daily-report-editorial-quality.md @@ -0,0 +1,29 @@ +# 日报的事实标题、素材身份与内容校验 + +Status: implemented — 内容校验实现见 #230;本篇维护生成合同,不声明真实模型效果或线上历史日报验收 + +## Problem + +标题被要求强行降低与原文的重合度,并从固定观点句式里选,容易将未填充的字母模板当成成稿。素材编号仅用于模型输入,直接出现在理由中时读者无法定位。原匹配器会保留模型声称的原文标题,甚至在显式编号无效时按其它字段重新匹配;输入整体截断后仍允许匹配完整候选池,也无法证明模型看过对应素材。 + +## Decision + +- 标题先保证具体、准确和可回查,可直接采用忠实原题;写作价值来自新变化、受影响对象和具体切入点,不强求冲突、字面差异、固定句式或凑足数量。 +- 输入预算按完整素材单元装入;匹配使用同一份实际可见素材池。显式编号无效则拒绝该项,旧格式缺编号才允许唯一标题或URL匹配;不凭不唯一的子串猜归属。同一素材只保留一次,最多9条。 +- URL、原文标题、content_id与评分由匹配到的素材注入。原文身份冲突、可识别的模板残留或无映射内部编号触发warning,并回到该素材的标题和摘要,降为速览,撤掉相应的角度/生命周期判断。不会通过只删几个字符来保留不完整推论。 +- 概览、主句、趋势、平台建议也检查同类问题。原题中真实存在的外部issue编号可保留;正常产品名X、C#版本不按占位符处理。模型无有效选题时仅从本次已提供素材构造保守摘要。 +- 离线回退同样保留原题,source_idx始终是输入位置,不能因重新按分数排序就变成另一篇素材。 + +## Alternatives considered + +只在前端替换字母或删除编号:不能恢复事实与论证,也会留下语义断裂,因此不采用。只修提示词:模型仍可能返回非法内容,不能代替确定性校验。对所有句子作关键词重合或数值匹配以宣称事实核查:相关性不等于推论成立,容易误伤正常表达,也不能作为事实正确证明。 + +## Consequences + +保守回退可能减少精讲篇数、丢弃部分模型判断,运营日志会明确记录原因。素材摘要可来自上游AI分析,仍不是独立核实的一手事实。校验只覆盖确定性的格式、引用与身份边界;无法自动证明任意事实、因果、利润比较、认证或IPO表述正确。这些仍须对照原文并通过真实模型样本评估,不因本地测试通过就声称已解决所有内容质量问题。 + +历史已生成日报不在这次代码修改中重写;生产重新生成、群推送、真实Provider费用和部署各自需要对应授权。日报公私隔离及版本身份继续由[归属与生成合同](2026-10-22-daily-report-ownership-and-generation.md)维护。 + +## Verification + +`backend/tests/test_daily_report_quality.py` 以确定性重放验证模板残留、错误身份、内部引用、重复/无效素材、完整输入预算与生成后持久化边界;使用一次性PG脚本运行,不得指向开发库。既有daily_report与digest_fallback回归一并保留。本地重放不覆盖真实Provider输出质量、完整原文事实核验或线上已发布日报。 diff --git a/backend/app/services/daily_report.py b/backend/app/services/daily_report.py index 1018cd2f..fc2c5626 100644 --- a/backend/app/services/daily_report.py +++ b/backend/app/services/daily_report.py @@ -24,6 +24,7 @@ from app.repositories.ignored_repo import IgnoredRepo from app.services.content_evidence import has_readable_content, readable_content_title from app.services.content_serialization import latest_analysis_from_item +from app.services.daily_report_editorial import review_daily_pick, review_daily_sections from app.services.digest_base import is_active_generating as _digest_is_active_generating from app.services.digest_fallback import build_daily_editorial_fallback from app.services.llm import call_llm_json @@ -239,6 +240,21 @@ def _format_items(items: list[dict], *, limit: int, selected: bool) -> str: return "\n".join(lines) +def _prepare_prompt_pool(items: list[dict], *, limit: int, max_chars: int, selected: bool) -> tuple[list[dict], str]: + """The matching pool is exactly the complete material units visible to the model.""" + pool: list[dict] = [] + rendered = "暂无" + for item in items[:limit]: + candidate = pool + [item] + text = _format_items(candidate, limit=len(candidate), selected=selected) + # Sanitise complete units before measuring; never cut the final source in half. + safe = sanitize_prompt_input(text, max_chars=len(text) * 2 + 32, escape_braces=False) + if len(safe) > max_chars: + break + pool, rendered = candidate, safe + return pool, rendered + + async def get_latest_today_report( db: AsyncSession, *, @@ -274,7 +290,7 @@ def _match_picks_to_curated( ) -> tuple[list[dict], list[int]]: """将 LLM 返回的 top_picks 匹配回精选素材,注入稳定字段并做后端兜底校验。 - 匹配优先级:source_idx(精确)→ source_title 子串兜底 → URL 末位兜底。 + 显式 source_idx 必须有效;缺编号时,才按唯一标题(精确优先)或唯一 URL 兜底。 不信任 LLM 输出的枚举/字段约束,对 tier=lifecycle/angles 做白名单过滤。 Args: @@ -286,31 +302,59 @@ def _match_picks_to_curated( """ matchable_items = curated_for_prompt curated_by_idx = {i + 1: item for i, item in enumerate(matchable_items)} - curated_by_title = {item["title"]: item for item in matchable_items} - curated_by_url = {normalize_zhihu_url(item.get("url", "")): item for item in matchable_items if item.get("url")} - curated_titles = set(curated_by_title) selected_source_ids: list[int] = [] picks: list[dict] = [] - for pick in raw_picks: + if not isinstance(raw_picks, list): + logger.warning("选题结果不是列表,转为保守摘要") + return [], [] + for raw_pick in raw_picks: + if len(picks) >= 9: + logger.warning("选题结果超过9条,保留已通过校验的前9条") + break + if not isinstance(raw_pick, dict): + logger.warning("跳过无效选题对象") + continue + pick = dict(raw_pick) matched_item: dict | None = None idx = pick.get("source_idx") - if isinstance(idx, int): - matched_item = curated_by_idx.get(idx) + if "source_idx" in pick: + if type(idx) is not int or idx not in curated_by_idx: + logger.warning("跳过未出现在本次输入中的素材编号: value_type=%s", type(idx).__name__) + continue + matched_item = curated_by_idx[idx] if not matched_item: - source_title = pick.get("source_title", "") - matched_title = next( - (t for t in curated_titles if source_title and (source_title in t or t in source_title)), - None, - ) - matched_item = curated_by_title.get(matched_title) if matched_title else None + source_title = pick.get("source_title") + candidates = [] + if isinstance(source_title, str) and source_title: + candidates = [item for item in matchable_items if item["title"] == source_title] + if not candidates: + candidates = [ + item + for item in matchable_items + if source_title in item["title"] or item["title"] in source_title + ] + matched_item = candidates[0] if len(candidates) == 1 else None if not matched_item: - pick_url_norm = normalize_zhihu_url(pick.get("source_url", "")) - matched_item = curated_by_url.get(pick_url_norm) + pick_url_norm = normalize_zhihu_url(pick["source_url"]) if isinstance(pick.get("source_url"), str) else "" + candidates = [ + item + for item in matchable_items + if pick_url_norm and normalize_zhihu_url(item.get("url", "")) == pick_url_norm + ] + matched_item = candidates[0] if len(candidates) == 1 else None if not matched_item: + logger.warning("跳过无法唯一匹配的素材") continue + if matched_item["id"] in selected_source_ids: + logger.warning("跳过重复素材: content_id=%s", matched_item["id"]) + continue + pick, issues = review_daily_pick(pick, matched_item) + if issues: + logger.warning("选题校验/保守回退: content_id=%s issues=%s", matched_item["id"], issues) # 注入稳定字段:URL/title/score 由后端按匹配结果填,模型无需也不应改写。 + pick["source_idx"] = next(i for i, item in curated_by_idx.items() if item is matched_item) pick["source_url"] = normalize_zhihu_url(matched_item.get("url", "")) - pick["source_title"] = pick.get("source_title") or matched_item["title"] + pick["source_title"] = matched_item["title"] pick["title"] = pick.get("editorial_title") or matched_item["title"] pick["score"] = round(float(matched_item.get("adjusted_score") or matched_item.get("curation_score") or 0)) # 站内阅读:注入底层 content_id(= ContentItem.id),供前端 ReaderDrawer 取正文。 @@ -325,7 +369,7 @@ def _match_picks_to_curated( else: # feature:生命周期没有足够依据时宁可不显示,也不伪造"上升期"。 lc = pick.get("lifecycle") - if lc in _VALID_LIFECYCLE: + if isinstance(lc, str) and lc in _VALID_LIFECYCLE: pick["lifecycle"] = lc else: pick.pop("lifecycle", None) @@ -670,10 +714,13 @@ async def _claim_generation() -> tuple[DailyReport, bool]: await db.commit() return report - # 截断一次:prompt 展示列表与下方匹配逻辑共用同一份,保证 source_idx 一致。 - curated_for_prompt = curated_items[:50] - curated_text = _format_items(curated_for_prompt, limit=50, selected=True) - background_text = _format_items(background_items, limit=80, selected=False) + # 按完整素材单元装入预算;展示列表与匹配逻辑共用同一份,保证 source_idx 一致。 + curated_for_prompt, curated_text = _prepare_prompt_pool(curated_items, limit=50, max_chars=6000, selected=True) + background_for_prompt, background_text = _prepare_prompt_pool( + background_items, limit=80, max_chars=8000, selected=False + ) + if len(curated_for_prompt) < min(50, len(curated_items)): + logger.warning("生成输入预算限制: visible_curated=%s available=%s", len(curated_for_prompt), len(curated_items)) prompt = REPORT_PROMPT.format( date=report_date, @@ -681,11 +728,13 @@ async def _claim_generation() -> tuple[DailyReport, bool]: edition_label=_edition_label(normalized_edition), window_start=window_start.strftime("%Y-%m-%d %H:%M"), window_end=window_end.strftime("%Y-%m-%d %H:%M"), - curated_items_text=sanitize_prompt_input(curated_text, max_chars=6000), - background_items_text=sanitize_prompt_input(background_text, max_chars=8000), + curated_items_text=curated_text, + background_items_text=background_text, ) try: + if not curated_for_prompt: + raise ValueError("精选素材超过单次输入预算,未发送模型请求") result = await call_llm_json( [ {"role": "system", "content": SYSTEM_PROMPT}, @@ -695,24 +744,30 @@ async def _claim_generation() -> tuple[DailyReport, bool]: temperature=0.4, max_tokens=4000, ) - overview = result.get("overview", "") - if not overview or "raw_response" in result: - result = build_daily_editorial_fallback( - curated_items, - label=f"{report_date} {_edition_label(normalized_edition)}", - ) - overview = result.get("overview", "") - - report.overview = overview - report.takeaway = result.get("takeaway", "") + fallback = build_daily_editorial_fallback( + curated_for_prompt, label=f"{report_date} {_edition_label(normalized_edition)}" + ) + if not isinstance(result, dict) or "raw_response" in result: + logger.warning("模型响应无效,使用素材摘要回退") + result = fallback + result, issues = review_daily_sections( + result, fallback, "\n".join(i["title"] for i in [*curated_for_prompt, *background_for_prompt]) + ) + if issues: + logger.warning("公共文案校验/回退: issues=%s", issues) + picks, selected_source_ids = _match_picks_to_curated(result.get("top_picks"), curated_for_prompt) + if not picks: + logger.warning("未留下有效选题,使用本次可见素材回退") + result = fallback + picks, selected_source_ids = _match_picks_to_curated(fallback["top_picks"], curated_for_prompt) + + report.overview = result["overview"] + report.takeaway = result["takeaway"] report.keywords = json.dumps(result.get("keywords", []), ensure_ascii=False) report.trends = json.dumps(result.get("trends", []), ensure_ascii=False) - - raw_picks = result.get("top_picks", []) - picks, selected_source_ids = _match_picks_to_curated(raw_picks, curated_for_prompt) + report.platform_tips = json.dumps(result.get("platform_tips", {}), ensure_ascii=False) report.top_picks = json.dumps(picks, ensure_ascii=False) - report.platform_tips = json.dumps(result.get("platform_tips", {}), ensure_ascii=False) report.topic_count = len(picks) report.source_item_ids = json.dumps( selected_source_ids or [item["id"] for item in curated_items], ensure_ascii=False diff --git a/backend/app/services/daily_report_editorial.py b/backend/app/services/daily_report_editorial.py new file mode 100644 index 00000000..72cf71ec --- /dev/null +++ b/backend/app/services/daily_report_editorial.py @@ -0,0 +1,138 @@ +"""Deterministic editorial checks, not a verifier of arbitrary factual claims.""" + +from __future__ import annotations + +import re +from typing import Any + +_SLOTS = re.compile(r"(? list[str]: + if not isinstance(value, str) or not value.strip(): + return ["missing_text"] + issues = [] + if len(set(_SLOTS.findall(value))) >= 2 and _TEMPLATE.search(value): + issues.append("unfilled_title_template") + # Genuine external issue numbers present in the source title remain valid. + known = set(_REFERENCES.findall(source_title)) + if set(_REFERENCES.findall(value)) - known: + issues.append("unresolved_material_reference") + return issues + + +def conservative_reason(item: dict) -> str: + title = item["title"] + for field in ("summary", "recommendation"): + value = item.get(field) + if not editorial_issues(value, title): + return f"素材摘要:{value.strip()}" + return "请阅读原文,核对具体变化和适用范围后再决定是否跟进。" + + +def review_daily_pick(pick: dict, item: dict) -> tuple[dict, list[str]]: + """Keep identity in the caller; uncertain editorial text becomes a brief.""" + result = dict(pick) + title = item["title"] + issues = [] + supplied_source = pick.get("source_title") + if ( + supplied_source is not None + and supplied_source != "" + and (not isinstance(supplied_source, str) or supplied_source.strip() != title.strip()) + ): + issues.append("source_title_mismatch") + if pick.get("editorial_title"): + issues.extend(editorial_issues(pick["editorial_title"], title)) + issues.extend(editorial_issues(pick.get("reason"), title)) + if issues: + # Do not retain lifecycle/angles derived from a rejected editorial claim. + return { + "source_idx": pick.get("source_idx"), + "source_title": title, + "editorial_title": title, + "reason": conservative_reason(item), + "category": item.get("category", "未分类"), + "tier": "brief", + "platforms": [], + }, sorted(set(issues)) + for field in ("source_title_zh", "pitfall", "time_window"): + if result.get(field) is None or result.get(field) == "": + result.pop(field, None) + continue + if editorial_issues(result[field], title): + result.pop(field) + issues.append(f"invalid_{field}") + if "angles" in result: + angles = result["angles"] + result["angles"] = [a for a in angles if not editorial_issues(a, title)] if isinstance(angles, list) else [] + if result["angles"] != angles: + issues.append("invalid_angles") + if result.get("tier", "feature") not in ("feature", "brief"): + result["tier"] = "brief" + issues.append("invalid_tier") + if not isinstance(result.get("category", ""), str): + result["category"] = item.get("category", "未分类") + issues.append("invalid_category") + platforms = result.get("platforms") + result["platforms"] = ( + list(dict.fromkeys(p for p in platforms if isinstance(p, str) and p.strip())) + if isinstance(platforms, list) + else [] + ) + return result, issues + + +def review_daily_sections(result: dict, fallback: dict, source_titles: str) -> tuple[dict, list[str]]: + """Validate public text without pretending syntactic checks prove facts.""" + cleaned = dict(result) + issues = [] + for field in ("overview", "takeaway"): + if editorial_issues(result.get(field), source_titles): + cleaned[field] = fallback[field] + issues.append(f"invalid_{field}") + trends = result.get("trends") + cleaned["trends"] = [] + if isinstance(trends, list): + for trend in trends: + if not isinstance(trend, dict) or editorial_issues(trend.get("title"), source_titles): + issues.append("invalid_trend") + continue + description = trend.get("desc") + if description is not None and ( + not isinstance(description, str) or (description and editorial_issues(description, source_titles)) + ): + issues.append("invalid_trend") + continue + cleaned_trend = {"title": trend["title"], "desc": description or ""} + momentum = trend.get("momentum", "stable") + if isinstance(momentum, str) and momentum in {"up", "down", "stable"}: + cleaned_trend["momentum"] = momentum + else: + cleaned_trend["momentum"] = "stable" + issues.append("invalid_trend_momentum") + color = trend.get("color") + if isinstance(color, str) and re.fullmatch(r"#[0-9a-fA-F]{6}", color): + cleaned_trend["color"] = color + elif color is not None: + issues.append("invalid_trend_color") + cleaned["trends"].append(cleaned_trend) + tips = result.get("platform_tips") + cleaned["platform_tips"] = {} + if isinstance(tips, dict): + for platform, texts in tips.items(): + if editorial_issues(platform) or not isinstance(texts, list): + issues.append("invalid_platform_tips") + continue + valid = [t for t in texts if not editorial_issues(t, source_titles)] + if len(valid) != len(texts): + issues.append("invalid_platform_tips") + if valid: + cleaned["platform_tips"][platform] = valid + keywords = result.get("keywords") + cleaned["keywords"] = ( + [k for k in keywords if not editorial_issues(k, source_titles)] if isinstance(keywords, list) else [] + ) + return cleaned, sorted(set(issues)) diff --git a/backend/app/services/digest_fallback.py b/backend/app/services/digest_fallback.py index 87d72441..5f07fbfc 100644 --- a/backend/app/services/digest_fallback.py +++ b/backend/app/services/digest_fallback.py @@ -3,6 +3,8 @@ from collections import Counter from typing import Any +from app.services.daily_report_editorial import editorial_issues + def _text(value: Any, default: str = "") -> str: if value is None: @@ -115,8 +117,6 @@ def build_digest_fallback( "开源项目": ["给出复现或上手路径", "与同类工具做任务对照", "标出真实适用场景"], } -_DAILY_TITLE_PREFIXES = ["先核对事实:", "值得拆开看:", "别只看标题:", "对创作者的含义:"] - def _compact_title(value: str, limit: int = 30) -> str: text = " ".join(value.split()) @@ -132,8 +132,11 @@ def _daily_platforms(category: str) -> list[str]: def _daily_reason(item: dict[str, Any]) -> str: + title = _text(item.get("title")) summary = _text(item.get("summary")) recommendation = _text(item.get("recommendation")) + summary = summary if not editorial_issues(summary, title) else "" + recommendation = recommendation if not editorial_issues(recommendation, title) else "" if summary and recommendation: return f"{summary[:120]} 创作价值在于:{recommendation[:80]}" if summary: @@ -155,6 +158,7 @@ def build_daily_editorial_fallback( JSON: it has a clear lead, a small feature set with concrete angles, and a scan-only brief list. Every claim is derived from the supplied items. """ + source_positions = {id(item): position for position, item in enumerate(items, 1)} ranked = sorted(items, key=_score, reverse=True)[:top_limit] if not ranked: return build_digest_fallback([], label=label, top_limit=top_limit) @@ -172,9 +176,9 @@ def build_daily_editorial_fallback( category = _text(item.get("category"), "未分类") feature = index <= min(3, len(ranked)) pick: dict[str, Any] = { - "source_idx": index, + "source_idx": source_positions[id(item)], "source_title": source_title, - "editorial_title": f"{_DAILY_TITLE_PREFIXES[(index - 1) % len(_DAILY_TITLE_PREFIXES)]}{_compact_title(source_title)}", + "editorial_title": source_title, "tier": "feature" if feature else "brief", "category": category, "reason": _daily_reason(item), diff --git a/backend/app/services/llm/prompts/daily_report.py b/backend/app/services/llm/prompts/daily_report.py index d0358965..df3e47ba 100644 --- a/backend/app/services/llm/prompts/daily_report.py +++ b/backend/app/services/llm/prompts/daily_report.py @@ -1,100 +1,67 @@ -""" -Daily Report LLM prompts — extracted for maintainability. +"""Daily editorial prompts: facts first, useful choices second.""" -Used by: - - app.services.daily_report.generate_daily_report -""" +SYSTEM_PROMPT = """你是 TopicEye 的内容编辑,为中文内容创作者编写每日 AI 选题日报。读者要据此判断今天值得跟进什么、能写出什么,以及还需要核实什么。 -SYSTEM_PROMPT = """你是 TopicEye 的资深内容主编,为内容创作者编写每日 AI 选题日报。读者是公众号、小红书、视频号的创作者,他们需要"今天写什么、怎么写、为什么值得写"。 +## 编辑原则 +- 标题优先讲清谁做了什么、提出什么问题或发生什么变化。保留核心实体、产品名、版本和有依据的数字;忠实准确的原文标题可以直接使用,不要求为了改写而降低字面重合度。 +- 选题判断必须有具体依据。区分已知事实、作者观点和编辑建议,不把观点写成已验证的事实。 +- 推荐理由先交代这条素材的新信息,再说明对哪类读者有用、可以从哪个具体问题切入;事实清楚时可以简短,不凑齐固定段数或强行制造冲突。 +- 跨素材对照时写出双方具体名称及可比较的维度。只有“都在谈AI”或恰好同日出现,不足以建立关联。 +- 融资金额、估值、收入和利润是不同指标。融资/估值消息不能直接推出利润高低或行业利润分配;没有财务数据时不下这类结论。 +- “银行级”“认证”“IPO”等表述必须与素材原意一致,保留传闻、计划、观点等限定,不能把比喻或作者主张改成已获认证/已确定上市。 -## 编辑立场 -- 你是"行业观察者",不是"预言家"。可以有点评和取舍,但不做"必将/彻底改变/颠覆/革命性"这类无证据的因果断言。 -- 标题要带编辑判断,必须锚定原文中的核心实体或数字,不得凭空拔高。全篇不得有 2 条 editorial_title 使用相同句式开头。 -- 任何 lifecycle 或趋势判断,必须有至少 2 条素材支撑;只有单一信号时,不要下"见顶/退潮"的强判断,在 pitfall 里注明"单一信号,待观察"。 - -## 防幻觉硬规则 -- top_picks 只能从「精选内容」中选。source_idx 必须是精选内容列表里真实存在的序号;source_title 必须逐字复制该序号对应素材的标题原文,不得改写。 -- source_title_zh:若 source_title 是英文,给出其中文翻译(产品名/技术术语保留英文原名,如"OpenAI 发布 GPT-5.6");若 source_title 本身是中文,填空字符串""。翻译要准确简洁,不加解释。 -- editorial_title 是展示用的观点化标题,可以改写,但必须包含原文中的核心实体或关键数字,让读者能对应回原文。 -- source_url 字段留空字符串即可,系统会根据 source_idx 自动填入正确链接,你不要自己写 URL。 -- overview / reason / angles 中的每个事实,必须能在精选内容或候选背景中找到依据;找不到依据的字段填 null,禁止编造。 -- 素材里没有的信息,一律不输出。所有文本用中文,不要输出英文。 - -## 输出格式 -- 只输出一个合法 JSON 对象。不要 markdown 代码围栏,不要任何解释文字。 -- 如果精选内容不足 6 条,就少输出 top_picks,不要从候选背景里硬凑。""" +## 素材与可追溯性 +- top_picks 只能从「精选内容」中选;source_idx 必须是该列表真实存在的序号,source_title 必须逐字复制该序号的标题。不要把同一素材重复选入。 +- source_title_zh:英文原文可给准确中文翻译,产品名与技术术语保留;中文原文填空字符串。不能在翻译中增加原文没有的事实。 +- source_url 填空字符串,系统按素材身份注入链接。 +- 事实只能来自本次给定素材。没有足够细节时保留为速览,明确待核实处,不补造数据、功能或因果。 +- 候选背景仅帮助归纳概览与趋势,不能冒充精选选题。趋势只是当前素材中的信号;单篇观点不能升级为行业共识,生命周期判断需要多条独立素材支持。 +- 所有读者可见文字必须独立可读:不用内部素材编号代替名称,不留未填充的字母占位符或标题公式。外部真实issue编号属于原文事实时可保留。 +只输出合法 JSON 对象,不要代码围栏或额外说明。除原文标题、专有名词与术语外用中文。""" REPORT_PROMPT = """## 日报窗口 - 日期:{date}({weekday}) - 版本:{edition_label} - 统计窗口:{window_start} ~ {window_end} -## 精选内容(top_picks 只能从这里选,序号即 source_idx) +## 精选内容(top_picks仅从此处选;序号即source_idx) {curated_items_text} -## 候选背景(仅用于判断 overview / trends / keywords 的方向,不能作为 top_picks) +## 候选背景(仅供overview / trends / keywords参考) {background_items_text} -## 输出 JSON 结构(严格按此输出,只输出 JSON) +## 输出JSON {{ - "overview": "今日主题段,150字内。第一句必须是行动指令,直接告诉创作者'今天最值得写什么'(必须含当天至少1个具体实体名或数字);第二句给论点判断——从下列句式中选一个,不要每次都用同一个:(a)'当……时,首先要解决的不是……,而是……' (b)'这些信号合在一起,指向一个反直觉的结论:……' (c)'表面上看是……,真正的机会在……' (d)'……这件事,比看上去更值得做(或更危险),原因是……';第三句用'从 X、Y 切入,分别看 A、B'把精讲选题映射到维度。禁止'今天有N篇报道'开头,禁止罗列关键词,必须兼顾机会与风险。", - "takeaway": "适合做推送标题的一句话,20字内,必须带一个冲突或一个数字,禁止'XX成新焦点''XX时代来了'这类万能句式", - "keywords": [""], - "trends": [ - {{"title": "", "desc": "趋势描述(≤30字)", "color": "#3B82F6", "momentum": "up"}} - ], - "top_picks": [ - {{ - "source_idx": 1, - "source_title": "逐字复制精选内容中对应序号的标题原文", - "source_title_zh": "英文标题的中文翻译;中文标题填空字符串", - "editorial_title": "观点化展示标题", - "tier": "feature", - "category": "模型发布", - "reason": "两段式推荐理由:先概括内容,再说明为什么值得写。feature 80字内,brief 40字内", - "angles": ["动宾短语,描述能做成什么内容,≤15字,禁问句"], - "pitfall": "避坑提示,无依据时填 null", - "lifecycle": "上升期", - "time_window": "发布时间建议,如'建议48h内发布'", - "platforms": ["公众号"], - "source_url": "" - }} - ], - "platform_tips": {{ - "公众号": [""], - "小红书": [""], - "视频号": [""] - }} + "overview": "概括今天最值得跟进的具体变化,点出有依据的主线及重要限制;主线不强时直接说明素材分散,不强行串联。150字内", + "takeaway": "今天最重要的一句具体判断或事实,不要求硬塞冲突或数字,30字内", + "keywords": ["具体主题"], + "trends": [{{"title": "有依据的信号", "desc": "依据和范围,40字内", "color": "#3B82F6", "momentum": "stable"}}], + "top_picks": [{{ + "source_idx": 1, + "source_title": "逐字复制对应精选素材标题", + "source_title_zh": "英文原标题的忠实中文翻译;中文标题为空字符串", + "editorial_title": "清楚具体的事实标题或带依据的编辑判断,可直接保留准确原题", + "tier": "feature", + "category": "产品更新", + "reason": "发生什么新变化,以及为什么值得这类创作者跟进;精讲120字内,速览80字内", + "angles": ["针对这条素材能完成的具体选题或验证任务"], + "pitfall": "发布前必须核实的具体限制,无依据则null", + "lifecycle": null, + "time_window": null, + "platforms": ["公众号"], + "source_url": "" + }}], + "platform_tips": {{"公众号": ["结合本期具体选题的建议"]}} }} -## 选题分层规则(重要) -- top_picks 共 6-9 条。按"可写性"分层(不是按 overview 主线): - - tier="feature" 2-3 条:精选分最高的、最有实操空间的选题。必须给全 reason/angles/pitfall/lifecycle/time_window/platforms。 - - tier="brief" 4-6 条:其余值得关注但不展开的。允许字段仅 source_idx/source_title/editorial_title/tier/category/reason/platforms/source_url。禁止出现 lifecycle、time_window、angles、pitfall 字段(哪怕值为空或"?"也不行)。 -- 排序:feature 在前(精选分降序),brief 在后(精选分降序)。 - -## angles 写作规范(核心) -- angles 必须是名词短语或动宾短语,描述"能做成什么内容",≤15字,禁止问句。 -- 正例:MCP实操教程 | 拆解Claude的token计费 | 测评5款开源Agent框架 | 用Coze复刻XX工作流 | 扒5个判例看巨头挖角史 -- 负例(禁止):大厂能多霸道? | AI真的能取代编辑吗? | 你会用MCP吗? -- 每条 feature 给 2-3 个 angles,切入主体要差异化(如换主角视角/换时间尺度/换输出形态各一)。 - -## editorial_title 写作规范 -- 必须含原文核心实体(让读者能对应回原文),但与 source_title 的字面重合度 < 50%。 -- 从下列结构中选一个(全篇不得 2 条用相同结构): - (a) "别再用 X 做 Y" + 立场(如:别再用BLEU评估中文模型) - (b) "X 的真正问题不是 A,是 B" - (c) "把 X 拆开看:A 比 B 更值得抄" - (d) "X 这一步,决定了 Y 的天花板" -- 反例(太接近搬运,禁止):source="Siri升级为系统核心,公测开启" → editorial="Siri升级背后:系统核心之争" -- 正例:source 同上 → editorial="Siri想当系统大脑,得先过开发者信任这一关" -- 禁止感叹号堆叠和"震惊/必看/重磅"类词。 - -## 其他写作规范 -- category 从"模型发布""产品更新""行业动态""技巧观点""科研论文""开源项目"中选最贴近的一个。 -- trends.momentum 从"up""down""stable"三选一,给出 2-3 个今日内容趋势。 -- lifecycle 仅限三选一:"上升期" | "见顶" | "退潮"。不得输出"爆发期/萌芽期/成长期/衰退期/发酵期"等同义词。仅 feature 需要此字段。 -- reason 必须是中文摘要式推荐理由:先概括这条内容讲了什么,再说明为什么值得写;不要输出英文、不要营销夸张词、不要只写"建议关注/可以写"。 -- 如果精选内容较少,就少选,不要从候选背景中硬凑。 -- 只输出 JSON,不要其他内容""" +## 取舍与分层 +- 按素材价值和可写性选择,最多9条;不足时少选,不为满足条数降低标准。 +- feature最多3条:有具体事实、可展开问题及证据时才精讲;angles给1-3个与这条素材相关的内容方案,避免泛化的“深度解析”“揭示趋势”。 +- brief为其余值得注意的速览,仅保留source_idx/source_title/source_title_zh/editorial_title/tier/category/reason/platforms/source_url,不输出生命周期、时机、角度或避坑字段。 +- feature在前,同层按精选分降序。一个source_idx只选一次。 +- category从模型发布、产品更新、行业动态、技巧观点、科研论文、开源项目中选。 +- 有足够依据时lifecycle只能为上升期、见顶、退潮;依据不足时省略或null。time_window同样需要依据,不能给所有内容机械附上48小时截止。 +- trends.momentum只能为up、down、stable;趋势可为空。平台建议只写有针对性的内容,没有就少写。 +- 标题不用预设句式,不把字母占位符、内部序号、营销话术放进成稿。理由中写具体对象与依据,禁止把两笔融资直接写成利润比较。 +- 只输出JSON。""" diff --git a/backend/tests/test_daily_report_quality.py b/backend/tests/test_daily_report_quality.py new file mode 100644 index 00000000..79c2db37 --- /dev/null +++ b/backend/tests/test_daily_report_quality.py @@ -0,0 +1,280 @@ +"""Editorial regressions use deterministic replay, never a real provider.""" + +import pytest + +from app.services.daily_report import _match_picks_to_curated +from app.services.digest_fallback import build_daily_editorial_fallback + + +def material(**changes): + return { + "id": 7, + "title": "Langfuse:不只评测模型,还要审核AI应用", + "url": "https://example.com/langfuse", + "category": "技巧观点", + "summary": "文章讨论应用级审核需要覆盖实际工作流。", + "recommendation": "可用一条实际工作流说明应用审核与模型评测的区别。", + "adjusted_score": 87, + "curation_score": 87, + "source_name": "技术观察", + "creator_score": 87, + "viral_score": 75, + "quality_score": 85, + "risk_score": 0, + **changes, + } + + +def test_daily_report_quality_replaces_leaked_title_template_and_internal_reference(caplog): + item = material() + picks, ids = _match_picks_to_curated( + [ + { + "source_idx": 1, + "editorial_title": "X的真正问题不是Y,是Z:Langfuse银行认证AI应用", + "reason": "结合#10 Siri开放,揭示模型与应用分离趋势", + "tier": "brief", + }, + ], + [item], + ) + assert ids == [7] + assert picks[0]["title"] == item["title"] + assert "#10" not in picks[0]["reason"] + assert item["summary"] in picks[0]["reason"] + assert caplog.records, "editorial fallback must not be silent" + + +def test_daily_report_quality_source_identity_is_owned_by_selected_material(): + item = material() + picks, _ = _match_picks_to_curated( + [ + { + "source_idx": 1, + "source_title": "另一家公司融资消息", + "editorial_title": "另一家公司计划IPO", + "reason": "与对应素材无关的判断", + }, + ], + [item], + ) + assert picks[0]["source_title"] == item["title"] + assert picks[0]["title"] == item["title"] + assert "IPO" not in picks[0]["reason"] + + +def test_daily_report_quality_rejects_explicit_invalid_index_instead_of_rebinding_by_title(): + item = material() + picks, ids = _match_picks_to_curated( + [ + {"source_idx": 9, "source_title": item["title"], "reason": "看似能匹配的标题"}, + ], + [item], + ) + assert picks == [] + assert ids == [] + + +def test_daily_report_quality_does_not_repeat_a_material_as_multiple_picks(): + item = material() + pick = {"source_idx": 1, "editorial_title": item["title"], "reason": "讨论应用审核的验证范围。"} + picks, ids = _match_picks_to_curated([pick, dict(pick)], [item]) + assert len(picks) == 1 + assert ids == [7] + + +def test_daily_report_quality_skips_malformed_picks_without_failing_valid_neighbors(): + item = material() + picks, ids = _match_picks_to_curated([None, "bad", {"source_idx": 1, "reason": "应用审核的验证范围。"}], [item]) + assert len(picks) == 1 + assert ids == [7] + + +def test_daily_report_quality_preserves_real_x_entity_and_external_issue_number(): + item = material(title="X发布新接口,GitHub issue #119记录迁移问题") + picks, _ = _match_picks_to_curated( + [ + { + "source_idx": 1, + "editorial_title": "X接口迁移:先处理GitHub issue #119", + "reason": "GitHub issue #119记录接口迁移问题。", + }, + ], + [item], + ) + assert picks[0]["title"].startswith("X接口迁移") + assert "#119" in picks[0]["reason"] + + +def test_daily_report_quality_fallback_uses_source_title_instead_of_a_generic_editorial_prefix(): + item = material() + result = build_daily_editorial_fallback([item], label="测试日报") + assert result["top_picks"][0]["editorial_title"] == item["title"] + + +def test_daily_report_quality_prompt_pool_contains_complete_units_and_binds_matchable_ids(): + from app.services.daily_report import _format_items, _prepare_prompt_pool + + first = material(title="支持JSON {schema}的应用评测") + second = material(id=8, title="第二条素材", summary="不能出现一半的第二条素材" * 20) + budget = len(_format_items([first], limit=1, selected=True)) + 1 + pool, text = _prepare_prompt_pool([first, second], limit=50, max_chars=budget, selected=True) + assert pool == [first] + assert "JSON {schema}" in text + assert "第二条素材" not in text + assert "truncated" not in text + assert _match_picks_to_curated([{"source_idx": 2, "reason": "输入中不存在"}], pool) == ([], []) + + +def test_daily_report_quality_fallback_source_index_is_input_position_not_new_score_rank(): + low, high = material(id=1, adjusted_score=70), material(id=2, title="高分素材", adjusted_score=90) + fallback = build_daily_editorial_fallback([low, high], label="日报") + assert [p["source_idx"] for p in fallback["top_picks"]] == [2, 1] + picks, ids = _match_picks_to_curated(fallback["top_picks"], [low, high]) + assert ids == [2, 1] + assert [p["source_title"] for p in picks] == [high["title"], low["title"]] + + +def test_daily_report_quality_cleans_public_sections_but_keeps_real_external_references(): + from app.services.daily_report_editorial import review_daily_sections + + fallback = build_daily_editorial_fallback([material()], label="日报") + result, issues = review_daily_sections( + { + "overview": "结合#10揭示趋势", + "takeaway": "X这步决定了Y天花板", + "trends": [None, {"title": "#22揭示的趋势"}, {"title": "GitHub issue #119迁移", "momentum": []}], + "platform_tips": {"公众号": ["结合#10写一篇文章", "对照应用审核的具体步骤。"]}, + }, + fallback, + "GitHub issue #119记录迁移问题", + ) + assert issues + assert result["overview"] == fallback["overview"] + assert result["takeaway"] == fallback["takeaway"] + assert len(result["trends"]) == 1 + assert result["trends"][0]["momentum"] == "stable" + assert result["platform_tips"]["公众号"] == ["对照应用审核的具体步骤。"] + + +async def _generate_replay(monkeypatch, session_factory, response, *, background=None): + from datetime import date, datetime + from unittest.mock import AsyncMock + + from app.services import daily_report + + async def inputs(*_args, **_kwargs): + return [material()], background if background is not None else [material()] + + monkeypatch.setattr(daily_report, "_fetch_report_inputs", inputs) + monkeypatch.setattr(daily_report, "_local_now", lambda: datetime(2026, 11, 4, 12)) + monkeypatch.setattr(daily_report, "call_llm_json", AsyncMock(return_value=response)) + monkeypatch.setattr(daily_report, "_push_daily_report_success", AsyncMock()) + monkeypatch.setattr(daily_report, "_push_daily_report_failure", AsyncMock()) + async with session_factory() as db: + report = await daily_report.generate_daily_report(db, target_date=date(2026, 11, 4), edition="noon") + await db.refresh(report) + return report + + +@pytest.mark.asyncio +async def test_daily_report_quality_replayed_bad_editorial_is_not_persisted(monkeypatch, test_session_factory): + import json + + report = await _generate_replay( + monkeypatch, + test_session_factory, + { + "overview": "结合#10判断整体趋势", + "takeaway": "X这步决定了Y天花板", + "top_picks": [ + { + "source_idx": 1, + "tier": "feature", + "editorial_title": "X的真正问题不是Y,是Z:Langfuse", + "reason": "结合#10 Siri开放,利润将高于应用层", + "lifecycle": "见顶", + } + ], + "trends": [{"title": "#22揭示的趋势"}], + }, + ) + assert report.status == "DONE" + for text in (report.overview, report.takeaway, report.top_picks, report.trends): + assert "#10" not in text and "#22" not in text and "X的真正问题" not in text + picks = json.loads(report.top_picks) + assert picks[0]["title"] == material()["title"] + assert picks[0]["content_id"] == 7 + assert picks[0]["tier"] == "brief" and "lifecycle" not in picks[0] + assert "利润" not in picks[0]["reason"] + + +@pytest.mark.asyncio +async def test_daily_report_quality_empty_valid_selection_uses_visible_material_fallback( + monkeypatch, test_session_factory +): + import json + + report = await _generate_replay( + monkeypatch, + test_session_factory, + { + "overview": "可以阅读今日素材。", + "takeaway": "应用审核", + "top_picks": [{"source_idx": 99}], + }, + ) + assert report.status == "DONE" + assert json.loads(report.source_item_ids) == [7] + assert json.loads(report.top_picks)[0]["source_title"] == material()["title"] + + +@pytest.mark.parametrize("index", [None, True, 1.0, "1", 0, -1]) +def test_daily_report_quality_explicit_invalid_index_cannot_use_legacy_title_fallback(index): + item = material() + assert _match_picks_to_curated([{"source_idx": index, "source_title": item["title"]}], [item]) == ([], []) + + +@pytest.mark.parametrize("field", ["source_title", "source_url"]) +def test_daily_report_quality_legacy_identity_must_be_unique_before_dictionary_deduplication(field): + first = material(id=1) + second = material(id=2, title=first["title"] if field == "source_title" else "另一条素材") + pick = {field: first["title"] if field == "source_title" else first["url"], "reason": "讨论应用审核范围。"} + assert _match_picks_to_curated([pick], [first, second]) == ([], []) + + +def test_daily_report_quality_trend_and_platform_fields_are_typed_public_text(): + from app.services.daily_report_editorial import review_daily_sections + + fallback = build_daily_editorial_fallback([material()], label="日报") + result, issues = review_daily_sections( + { + "overview": "讨论应用审核。", + "takeaway": "应用审核", + "platform_tips": {"结合#10": ["写作建议"]}, + "trends": [{"title": "观察", "desc": {}}, {"title": "应用审核", "desc": "只代表本期素材", "color": []}], + }, + fallback, + "", + ) + assert issues + assert result["platform_tips"] == {} + assert result["trends"] == [{"title": "应用审核", "desc": "只代表本期素材", "momentum": "stable"}] + + +@pytest.mark.asyncio +async def test_daily_report_quality_public_context_can_reference_real_background_issue( + monkeypatch, test_session_factory +): + report = await _generate_replay( + monkeypatch, + test_session_factory, + { + "overview": "GitHub issue #119记录了接口迁移问题。", + "takeaway": "应用审核", + "top_picks": [{"source_idx": 1, "reason": "对照应用审核的验证范围。"}], + }, + background=[material(id=8, title="GitHub issue #119记录接口迁移问题")], + ) + assert report.status == "DONE" + assert report.overview == "GitHub issue #119记录了接口迁移问题。" diff --git a/frontend/src/app/daily/_components.tsx b/frontend/src/app/daily/_components.tsx index e37df039..532e0eef 100644 --- a/frontend/src/app/daily/_components.tsx +++ b/frontend/src/app/daily/_components.tsx @@ -272,7 +272,6 @@ export function PickCard({ export interface BriefPickRowProps { pick: DailyPick; - globalIdx: number; isExpanded: boolean; onToggleExpand: () => void; markAction?: MarkAction; @@ -284,7 +283,6 @@ export interface BriefPickRowProps { export function BriefPickRow({ pick, - globalIdx, isExpanded, onToggleExpand, markAction, @@ -294,74 +292,77 @@ export function BriefPickRow({ onOpenReader, }: BriefPickRowProps) { const key = pickKey(pick); + const showSourceTitle = Boolean(pick.source_title && pick.source_title !== pick.title && isEnglishTitle(pick.source_title)); + const platforms = (pick.platforms ?? []).slice(0, 3); + const hasReadingLink = Boolean(pick.content_id || pick.source_url); return ( -