dknowc-dsh 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +14 -4
  2. package/package.json +3 -3
  3. package/skills/dknowc-official-doc-writer/README.md +7 -2
  4. package/skills/dknowc-official-doc-writer/SKILL.md +38 -21
  5. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +3 -3
  6. package/skills/dknowc-official-doc-writer/reference/output_guide.md +3 -3
  7. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +18 -14
  8. package/skills/dknowc-official-doc-writer/reference/revision_workflow.md +45 -0
  9. package/skills/dknowc-official-doc-writer/reference/sample_search_result.md +1 -1
  10. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +323 -57
  11. package/skills/dknowc-official-doc-writer/reference/search_guide.md +22 -11
  12. package/skills/dknowc-official-doc-writer/reference/search_intro.md +14 -3
  13. package/skills/dknowc-official-doc-writer/reference/search_policy.md +12 -10
  14. package/skills/dknowc-official-doc-writer/reference/task_router.md +12 -8
  15. package/skills/dknowc-official-doc-writer/scripts/check_release.py +10 -0
  16. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +43 -9
  17. package/skills/dknowc-official-doc-writer/scripts/format_document.py +7 -7
  18. package/skills/dknowc-official-doc-writer/scripts/initialize.py +2 -5
  19. package/skills/dknowc-official-doc-writer/scripts/local_memory.py +3 -3
  20. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +2 -3
  21. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +12 -15
  22. package/skills/dknowc-official-doc-writer/scripts/register.mjs +3 -1
  23. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +958 -532
  24. package/skills/dknowc-official-doc-writer/scripts/review_document.py +0 -1
  25. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +19 -2
  26. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +4 -5
  27. package/skills/dknowc-ppt-assistant/README.md +7 -6
  28. package/skills/dknowc-ppt-assistant/SKILL.md +7 -5
  29. package/skills/dknowc-ppt-assistant/references/material_usage.md +20 -8
  30. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +3 -3
  31. package/skills/dknowc-ppt-assistant/scripts/preview_slide_html.py +141 -0
  32. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1037 -587
  33. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +29 -17
  34. package/skills/dknowc-ppt-assistant/workflows/routing.md +2 -2
  35. package/skills/dknowc-trusted-consulting/README.md +17 -16
  36. package/skills/dknowc-trusted-consulting/SKILL.md +58 -30
  37. package/skills/dknowc-trusted-consulting/reference/consult_intro.md +3 -3
  38. package/skills/dknowc-trusted-consulting/reference/sample_consult_answer.md +4 -4
  39. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +439 -58
  40. package/skills/dknowc-trusted-consulting/scripts/adapt_mcp_result.py +4 -0
  41. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +0 -2
  42. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +1164 -616
  43. package/skills/dknowc-trusted-search/README.md +2 -2
  44. package/skills/dknowc-trusted-search/SKILL.md +16 -11
  45. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +402 -435
  46. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1104 -562
  47. package/src/index.js +3 -3
@@ -1,5 +1,28 @@
1
1
  #!/usr/bin/env python3
2
- """Generate an interactive local HTML trace report from DKnownAI API JSON."""
2
+ """深知可信PPT 可信溯源核验报告渲染器:把检索素材 JSON + 答案文件渲染为单文件可核验 HTML。
3
+
4
+ 双版支持(--stage):
5
+ - outline 提纲版:结构方案确认门前的提纲答案文件(页面规划表 + 口径事项清单)→ 事前核验
6
+ - final 成稿版:交付时的页面级结论文本 → 事后溯源
7
+
8
+ 报告定位:不止展示"材料从哪来"(溯源),更要传达"我们查过了,可以交付"(核验)。
9
+ 三个核验层次:
10
+ - 报告级:核验报告单(依据溯源 / 引用绑定 / 时效检查 / 类型覆盖 / 自检)
11
+ - 材料级:每条来源卡核验链标记(摘录可比对 + 原文可打开 + 知识专库可回溯)
12
+ - 引用级:答案正文角标与来源卡一一绑定,未绑定角标红色警示
13
+
14
+ 诚实原则:脚本真实计算的结果才打勾;政策现行效力等无法自动判定项归入
15
+ "建议人工复核";self_check 未传入时显示"未记录",不假装通过。
16
+
17
+ 输入:trusted_search.py / 合并后的检索 JSON(检索文章,材料级「角标」编号优先,
18
+ 全库无材料级编号时按数组位置 1..N 兜底)+ --answer-file 答案文件(提纲版
19
+ <项目短名>_outline.md / 成稿版 <项目短名>_answer.txt,关键事实后标 [N] 角标)。
20
+
21
+ 布局:深色顶栏 + 左栏报告正文(分节卡片)+ 右栏核验材料面板(类型筛选/搜索);
22
+ 打印归档模式(@media print 单栏全展开);移动端适配(680px 断点:密度压缩、
23
+ 「查看核验材料」跳转与「返回核验报告单」锚点、角标/证据 chips 点击改底部弹层
24
+ 就地查看,不打断正文阅读,PC 双栏保留右栏定位高亮)。
25
+ """
3
26
 
4
27
  from __future__ import annotations
5
28
 
@@ -7,10 +30,10 @@ import argparse
7
30
  import html
8
31
  import json
9
32
  import re
33
+ import sys
10
34
  from datetime import datetime
11
35
  from pathlib import Path
12
- from typing import Any, Dict, Iterable, List, Optional
13
-
36
+ from typing import Any, Dict, List, Optional, Tuple
14
37
 
15
38
  SKILL_ROOT = Path(__file__).resolve().parent.parent
16
39
  # 产物根:dsh 会话隔离 <工作区>/dknowc-output/<DSH_SESSION_ID前8位>/;DKNWOC_WS_ROOT 显式优先;无会话回退 _default
@@ -23,6 +46,8 @@ WS_ROOT = Path(_ws).resolve()
23
46
  SEARCH_RESULTS_DIR = WS_ROOT / "official-docs" / "search-results"
24
47
  OUTPUT_DIR = WS_ROOT / "official-docs" / "output"
25
48
 
49
+ STAGE_LABELS = {"outline": "提纲版", "final": "成稿版"}
50
+
26
51
 
27
52
  def _is_within(path: Path, parent: Path) -> bool:
28
53
  try:
@@ -54,6 +79,10 @@ def _safe_output_path(value: str, allowed_suffixes: set, default_suffix: str) ->
54
79
  return resolved
55
80
 
56
81
 
82
+ # ============================================================
83
+ # 基础工具
84
+ # ============================================================
85
+
57
86
  def esc(value: Any) -> str:
58
87
  return html.escape(str(value or ""), quote=True)
59
88
 
@@ -109,6 +138,54 @@ def strip_citation_markers(text: str) -> str:
109
138
  return text.strip() + ("\n" if text.strip() else "")
110
139
 
111
140
 
141
+ # ============================================================
142
+ # 素材四分类
143
+ # ============================================================
144
+
145
+ KIND_CATALOG = {
146
+ "policy": ("政策依据", "pol"),
147
+ "data": ("数据支撑", "dat"),
148
+ "case": ("参考案例", "cas"),
149
+ "reference": ("表述参考", "ref"),
150
+ "material": ("材料", "mat"),
151
+ }
152
+
153
+
154
+ def normalize_kind(raw: str) -> Tuple[str, str, str]:
155
+ """把来源类型文本归一化为(类型键, 中文标签, css 类名)。"""
156
+ text = str(raw or "")
157
+ if "政策" in text or "法规" in text or "依据" in text or "policy" in text.lower():
158
+ key = "policy"
159
+ elif "数据" in text or "统计" in text or "指标" in text or "data" in text.lower():
160
+ key = "data"
161
+ elif "案例" in text or "经验" in text or "做法" in text or "case" in text.lower():
162
+ key = "case"
163
+ elif "表述" in text or "行文" in text or "reference" in text.lower():
164
+ key = "reference"
165
+ else:
166
+ key = "material"
167
+ label, css = KIND_CATALOG[key]
168
+ return key, label, css
169
+
170
+
171
+ def parse_year_month(raw: str) -> Optional[Tuple[int, int]]:
172
+ """从日期文本提取(年, 月);识别 2025年8月 / 2025-08 / 2025.08 / 2025-08-15。"""
173
+ text = str(raw or "").strip()
174
+ if not text:
175
+ return None
176
+ m = re.search(r"(20\d{2})\s*[年./-]\s*(\d{1,2})", text)
177
+ if m:
178
+ return int(m.group(1)), min(int(m.group(2)), 12)
179
+ m = re.search(r"(20\d{2})", text)
180
+ if m:
181
+ return int(m.group(1)), 1
182
+ return None
183
+
184
+
185
+ # ============================================================
186
+ # 素材提取(数据层:材料级编号优先 + 位置兜底)
187
+ # ============================================================
188
+
112
189
  def paragraph_text(item: Dict[str, Any]) -> str:
113
190
  paragraphs = item.get("content") or item.get("段落") or item.get("paragraphs") or item.get("paragraphList")
114
191
  if isinstance(paragraphs, list):
@@ -125,6 +202,8 @@ def paragraph_text(item: Dict[str, Any]) -> str:
125
202
  item.get("摘录"),
126
203
  item.get("摘要"),
127
204
  item.get("相关段落"),
205
+ item.get("支撑内容"),
206
+ item.get("support"),
128
207
  item.get("全文"),
129
208
  item.get("content"),
130
209
  item.get("text"),
@@ -177,6 +256,8 @@ def source_from_article(item: Dict[str, Any], index: int, segment: Optional[Dict
177
256
  "id": explicit_id or str(index),
178
257
  "title": first_str(
179
258
  item.get("文章标题"),
259
+ item.get("material_name"),
260
+ item.get("材料名称"),
180
261
  item.get("title"),
181
262
  item.get("标题"),
182
263
  item.get("name"),
@@ -195,23 +276,35 @@ def source_from_article(item: Dict[str, Any], index: int, segment: Optional[Dict
195
276
  vo.get("sourceName"),
196
277
  ),
197
278
  "date": first_str(item.get("发布日期"), item.get("date"), item.get("发布时间"), item.get("createDate"), vo.get("dateTime"), vo.get("createDate")),
198
- "url": first_str(item.get("sourceUrl"), item.get("source_url"), item.get("源网址"), item.get("url"), item.get("原文"), vo.get("sourceUrl"), vo.get("url")),
279
+ "url": first_str(item.get("sourceUrl"), item.get("source_url"), item.get("源网址"), item.get("原文链接"), item.get("url"), item.get("原文"), vo.get("sourceUrl"), vo.get("url")),
199
280
  "policy_url": first_str(item.get("policyUrl"), item.get("policy_url"), item.get("知识专库原文"), vo.get("policyUrl")),
200
281
  "excerpt": segment.get("text") or paragraph_text(item),
201
- "section": first_str(segment.get("title")),
202
- "kind": first_str(item.get("类型"), item.get("type"), vo.get("typeName"), "材料"),
282
+ "section": first_str(segment.get("title"), item.get("正文对应"), item.get("section")),
283
+ "kind": first_str(item.get("类型"), item.get("type"), item.get("素材类型"), vo.get("typeName"), "材料"),
284
+ "verify_note": first_str(item.get("核验"), item.get("verification"), item.get("核验说明")),
203
285
  "area": first_str(item.get("intentionArea"), item.get("area"), item.get("地域")),
204
- "reliability": first_str(item.get("createDateReliability"), item.get("reliability"), item.get("时间可靠性")),
205
286
  }
287
+ key, label, css = normalize_kind(source["kind"])
288
+ source["type_key"] = key
289
+ source["type_label"] = label
290
+ source["type_css"] = css
291
+ source["has_link"] = bool(source["url"] and source["url"] != "接口未返回") or bool(source["policy_url"])
292
+ # 数据缺口(无原文链接)不改变核验状态,仅在来源卡与核验单上温和提醒
293
+ source["verified"] = bool(source["excerpt"])
206
294
  return source
207
295
 
208
296
 
209
297
  def extract_articles_from_search(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
298
+ # 兼容两种形态:原始接口的 content.data.检索文章(嵌套)与手工合并 JSON 的
299
+ # 顶层 检索文章(Agent 合并时常剥掉接口包装,与 knowledgeBase/self_check 平级)。
210
300
  content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
211
301
  data = content.get("data") if isinstance(content.get("data"), dict) else content.get("data")
302
+ articles: List[Dict[str, Any]] = []
212
303
  if isinstance(data, dict) and isinstance(data.get("检索文章"), list):
213
- return [x for x in data["检索文章"] if isinstance(x, dict)]
214
- return []
304
+ articles.extend(x for x in data["检索文章"] if isinstance(x, dict))
305
+ if isinstance(payload.get("检索文章"), list):
306
+ articles.extend(x for x in payload["检索文章"] if isinstance(x, dict))
307
+ return articles
215
308
 
216
309
 
217
310
  def extract_articles_from_deep(payload: Dict[str, Any]) -> List[Dict[str, Any]]:
@@ -243,6 +336,17 @@ def extract_reference_materials(payload: Dict[str, Any]) -> List[Dict[str, Any]]
243
336
  return []
244
337
 
245
338
 
339
+ def material_level_id(item: Dict[str, Any]) -> str:
340
+ return first_str(
341
+ item.get("角标"),
342
+ item.get("编号"),
343
+ item.get("materialIndex"),
344
+ item.get("referenceIndex"),
345
+ item.get("serialNo"),
346
+ item.get("引用编号"),
347
+ )
348
+
349
+
246
350
  def extract_sources(payload: Dict[str, Any]) -> List[Dict[str, str]]:
247
351
  raw_sources: List[Dict[str, Any]] = []
248
352
  raw_sources.extend(extract_reference_materials(payload))
@@ -254,30 +358,12 @@ def extract_sources(payload: Dict[str, Any]) -> List[Dict[str, str]]:
254
358
  # 任一材料带材料级编号(角标等)即视为「已按素材清单编号」;
255
359
  # 全库都没有时按合并数组位置 1..N 自动编号(一条材料一张卡),
256
360
  # 与答案文件按合并顺序书写 [N] 角标的约定对齐。
257
- has_material_ids = any(
258
- first_str(
259
- item.get("角标"),
260
- item.get("编号"),
261
- item.get("materialIndex"),
262
- item.get("referenceIndex"),
263
- item.get("serialNo"),
264
- item.get("引用编号"),
265
- )
266
- for item in raw_sources
267
- )
361
+ has_material_ids = any(material_level_id(item) for item in raw_sources)
268
362
  for item in raw_sources:
269
363
  segments = content_segments(item)
270
364
  # 有材料级编号(角标等)时整条材料只出一张来源卡(摘录为全文段落拼接),
271
- # 与素材清单「一条材料一个编号」对齐;无材料级编号时按段落拆分(原行为)。
272
- item_level_id = first_str(
273
- item.get("角标"),
274
- item.get("编号"),
275
- item.get("materialIndex"),
276
- item.get("referenceIndex"),
277
- item.get("serialNo"),
278
- item.get("引用编号"),
279
- )
280
- single_card = bool(item_level_id) or not has_material_ids
365
+ # 与素材清单「一条材料一个编号」对齐;无材料级编号时按段落拆分。
366
+ single_card = bool(material_level_id(item)) or not has_material_ids
281
367
  candidates = [None] if single_card else (segments or [None])
282
368
  for segment in candidates:
283
369
  source = source_from_article(item, len(sources) + 1, segment=segment)
@@ -316,21 +402,32 @@ def extract_answer(payload: Dict[str, Any]) -> str:
316
402
  return "接口返回中未识别到正文内容;请查看右侧来源或原始 JSON。"
317
403
 
318
404
 
319
- def extract_trace_url(payload: Dict[str, Any]) -> str:
320
- return first_str(payload.get("traceUrl"), payload.get("trace_url"), payload.get("traceReportUrl"))
321
-
322
-
323
- def extract_knowledge_base(payload: Dict[str, Any]) -> str:
405
+ def extract_question(payload: Dict[str, Any]) -> str:
324
406
  content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
325
407
  data = content.get("data") if isinstance(content.get("data"), dict) else {}
326
408
  return first_str(
327
- content.get("knowledgeBase"),
328
- payload.get("knowledgeBase"),
329
- data.get("knowledgeBase"),
330
- payload.get("knowledgeBaseUrl"),
409
+ payload.get("question"),
410
+ payload.get("input"),
411
+ payload.get("query"),
412
+ data.get("用户问题"),
413
+ content.get("query"),
414
+ content.get("question"),
331
415
  )
332
416
 
333
417
 
418
+ def extract_knowledge_bases(payload: Dict[str, Any]) -> List[str]:
419
+ content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
420
+ data = content.get("data") if isinstance(content.get("data"), dict) else {}
421
+ values: List[str] = []
422
+ for value in (payload.get("knowledgeBases"), content.get("knowledgeBases"),
423
+ payload.get("knowledgeBase"), content.get("knowledgeBase"), data.get("knowledgeBase")):
424
+ if isinstance(value, list):
425
+ values.extend(str(item).strip() for item in value if str(item).strip())
426
+ elif isinstance(value, str) and value.strip():
427
+ values.append(value.strip())
428
+ return list(dict.fromkeys(values))
429
+
430
+
334
431
  def citation_ids(answer: str) -> List[str]:
335
432
  ids: List[str] = []
336
433
  for match in re.finditer(r"\[(\d+)\]", answer):
@@ -340,13 +437,148 @@ def citation_ids(answer: str) -> List[str]:
340
437
  return ids
341
438
 
342
439
 
440
+ # ============================================================
441
+ # 核验计算(报告级)
442
+ # ============================================================
443
+
444
+ SELF_CHECK_ITEMS = [
445
+ ("fact_basis", "事实有据"),
446
+ ("quality", "质检通过"),
447
+ ("placeholders", "无占位残留"),
448
+ ("chart_sources", "图表有来源注"),
449
+ ("caliber", "口径一致"),
450
+ ]
451
+
452
+ SELF_CHECK_LABELS = dict(SELF_CHECK_ITEMS)
453
+ SELF_CHECK_LABELS.update({
454
+ "事实有据": "事实有据", "质检通过": "质检通过", "无占位残留": "无占位残留",
455
+ "图表有来源注": "图表有来源注", "口径一致": "口径一致",
456
+ })
457
+
458
+
459
+ def classify_check_value(raw: Any) -> Tuple[str, str]:
460
+ """把自检项的值解析为(状态, 核验说明)。
461
+
462
+ 兼容多种写法:`pass` / `true` / `通过` / `通过:说明文字` / `✓` 等;
463
+ 值后面的说明文字保留下来供核验单展示。无法识别的状态按未通过处理,
464
+ 并保留原文,不假装通过。
465
+ """
466
+ text = str(raw or "").strip()
467
+ lowered = text.lower()
468
+ for prefix in ("未通过", "不通过", "不合格", "fail", "false", "否", "✗", "no"):
469
+ if lowered.startswith(prefix):
470
+ return "fail", text[len(prefix):].lstrip("::,,、 ").strip()
471
+ for prefix in ("已通过", "通过", "合格", "pass", "ok", "true", "是", "✓", "yes"):
472
+ if lowered.startswith(prefix):
473
+ return "pass", text[len(prefix):].lstrip("::,,、 ").strip()
474
+ return "fail", text
475
+
476
+
477
+ def normalize_self_check(raw: Any) -> Optional[Dict[str, Tuple[str, str]]]:
478
+ if not isinstance(raw, dict):
479
+ return None
480
+ items: Dict[str, Tuple[str, str]] = {}
481
+ for key, value in raw.items():
482
+ status, note = classify_check_value(value)
483
+ label = SELF_CHECK_LABELS.get(key, SELF_CHECK_LABELS.get(str(key), str(key)))
484
+ items[label] = (status, note)
485
+ return items or None
486
+
487
+
488
+ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Dict[str, Any],
489
+ generated_at: Optional[datetime] = None) -> Dict[str, Any]:
490
+ """核验报告单数据。只计算脚本真实可得的结果,不虚构通过。"""
491
+ generated_at = generated_at or datetime.now()
492
+
493
+ # ① 依据溯源:摘录可比对 + 原文链接/知识专库可回看。
494
+ # 数据缺口(接口偶发不返回链接/摘录)降级为提醒,不参与核验判定。
495
+ missing_links = [s["title"] for s in sources if not s.get("has_link")]
496
+ missing_excerpts = [s["title"] for s in sources if not (s.get("excerpt") or "").strip()]
497
+
498
+ # ② 引用绑定:正文角标与来源卡一一对应(按角标出现次数计,与用户在正文中数到的一致)
499
+ cited = citation_ids(answer)
500
+ all_marks = re.findall(r"\[(\d+)\]", answer)
501
+ source_ids = {s["id"] for s in sources}
502
+ unbound_ids = [cid for cid in cited if cid not in source_ids]
503
+ unbound = [cid for cid in unbound_ids for _ in range(all_marks.count(cid))]
504
+ no_citation = bool(sources) and not cited
505
+
506
+ # ③ 时效检查:材料日期范围与历史材料计数
507
+ dated = [parse_year_month(s.get("date")) for s in sources]
508
+ dated = [d for d in dated if d]
509
+ freshness = None
510
+ old_count = 0
511
+ if dated:
512
+ freshness = {
513
+ "min": min(dated),
514
+ "max": max(dated),
515
+ "old_count": sum(1 for y, _ in dated if y <= generated_at.year - 3),
516
+ }
517
+
518
+ # ④ 类型覆盖:素材四分类分布
519
+ coverage = {key: 0 for key in KIND_CATALOG}
520
+ for s in sources:
521
+ coverage[s.get("type_key", "material")] = coverage.get(s.get("type_key", "material"), 0) + 1
522
+
523
+ # ⑤ 自检:由检索/溯源 JSON 的 self_check 传入,未传入如实显示未记录
524
+ self_check_raw = None
525
+ for holder in (payload, payload.get("content") if isinstance(payload.get("content"), dict) else {}):
526
+ self_check_raw = self_check_raw or holder.get("selfCheck") or holder.get("self_check")
527
+ self_items = normalize_self_check(self_check_raw)
528
+ self_check = None
529
+ if self_items:
530
+ passed = sum(1 for status, _ in self_items.values() if status == "pass")
531
+ self_check = {"items": self_items, "passed": passed, "total": len(self_items),
532
+ "status": "pass" if passed == len(self_items) else "fail"}
533
+ else:
534
+ self_check = {"items": {}, "passed": 0, "total": len(SELF_CHECK_ITEMS), "status": "missing"}
535
+
536
+ # 政策效力:无法自动判定现行效力,列出建议人工复核
537
+ policy_count = coverage.get("policy", 0)
538
+
539
+ # 核验判定:只有真实错误才判不通过(无素材 / 正文无角标 / 角标未绑定);
540
+ # 数据缺口(缺链/缺摘录)只提醒不影响判定
541
+ trace_ok = bool(sources)
542
+ binding_ok = (not unbound) and not no_citation
543
+ overall_passed = trace_ok and binding_ok
544
+
545
+ reasons = []
546
+ if not sources:
547
+ reasons.append("未识别到来源材料")
548
+ if no_citation:
549
+ reasons.append("正文未包含来源角标,无法建立引用-素材对应")
550
+ if unbound:
551
+ reasons.append(f"{len(unbound)} 处正文角标未绑定素材")
552
+ if self_check["status"] == "fail":
553
+ reasons.append("自检存在未通过项")
554
+
555
+ return {
556
+ "overall": {
557
+ "passed": overall_passed,
558
+ "label": "核验完成,正文依据可交付" if overall_passed else "核验未完全通过",
559
+ "reasons": reasons,
560
+ },
561
+ "traceability": {"total": len(sources), "passed": len(sources),
562
+ "missing_links": missing_links, "missing_excerpts": missing_excerpts},
563
+ "binding": {"total": len(all_marks), "bound": len(all_marks) - len(unbound), "unbound": unbound_ids, "no_citation": no_citation},
564
+ "freshness": freshness,
565
+ "coverage": coverage,
566
+ "self_check": self_check,
567
+ "policy_count": policy_count,
568
+ "manual_checks": [str(x) for x in (payload.get("verificationChecks") or payload.get("verification_checks") or []) if str(x).strip()],
569
+ }
570
+
571
+
572
+ # ============================================================
573
+ # 正文解析与分节
574
+ # ============================================================
575
+
343
576
  def render_inline_markdown(text: str, citation_repl) -> str:
344
577
  body = esc(text)
345
578
  body = re.sub(r"`([^`]+)`", r"<code>\1</code>", body)
346
579
  body = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", body)
347
580
  body = re.sub(r"__(.+?)__", r"<strong>\1</strong>", body)
348
581
  body = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<em>\1</em>", body)
349
- body = re.sub(r"(?<!_)_([^_\n]+)_(?!_)", r"<em>\1</em>", body)
350
582
  body = re.sub(r"\[(\d+)\]", citation_repl, body)
351
583
  return body
352
584
 
@@ -376,15 +608,15 @@ def render_markdown_table(lines: List[str], citation_repl) -> str:
376
608
  cells = cells + [""] * (len(header) - len(cells))
377
609
  rows.append("<tr>" + "".join(f"<td>{render_inline_markdown(cell, citation_repl)}</td>" for cell in cells) + "</tr>")
378
610
  wide_cls = " wide" if len(header) >= 4 else ""
379
- return f'<div class="answer-table-wrap"><table class="answer-table{wide_cls}"><thead><tr>{head_html}</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
611
+ return f'<div class="tbl-wrap"><table class="data-tbl{wide_cls}"><thead><tr>{head_html}</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
380
612
 
381
613
 
382
614
  def render_excerpt_html(text: str) -> str:
383
615
  value = str(text or "")
384
616
  if "<table" not in value.lower():
385
- return f'<div class="source-excerpt plain">{esc(value)}</div>'
617
+ return f'<div class="sc-excerpt plain">{esc(value)}</div>'
386
618
  cleaned = re.sub(r"(?is)<script.*?</script>", "", value)
387
- cleaned = re.sub(r"(?is)<style.*?</style>", "", cleaned)
619
+ cleaned = re.sub(r"(?is)<style.*?</style>", "", value)
388
620
  cleaned = re.sub(r"\s+on\w+\s*=\s*(['\"]).*?\1", "", cleaned)
389
621
  cleaned = re.sub(r"\s+(href|src)\s*=\s*(['\"]).*?\2", "", cleaned)
390
622
  allowed = {"table", "thead", "tbody", "tr", "td", "th", "br"}
@@ -396,169 +628,354 @@ def render_excerpt_html(text: str) -> str:
396
628
  return f"<{closing}{name}>"
397
629
 
398
630
  cleaned = re.sub(r"<\s*(/?)\s*([a-zA-Z0-9]+)(?:\s+[^>]*)?>", tag_repl, cleaned)
399
- return f'<div class="source-excerpt rich">{cleaned}</div>'
400
-
401
-
402
- def render_source_links(url: str, policy_url: str = "") -> str:
403
- links = []
404
- if url and url != "接口未返回":
405
- links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看原文</a>')
406
- if policy_url:
407
- links.append(f'<a href="{esc(policy_url)}" target="_blank" rel="noopener">知识专库原文</a>')
408
- if not links:
409
- return ""
410
- return '<div class="source-links">' + "".join(f"<span>{link}</span>" for link in links) + "</div>"
631
+ return f'<div class="sc-excerpt rich">{cleaned}</div>'
411
632
 
412
633
 
413
- def render_evidence_chips(ids: List[str], sources: List[Dict[str, str]]) -> str:
414
- source_map = {source["id"]: source for source in sources}
415
- chips = []
416
- for cid in ids:
417
- source = source_map.get(cid)
418
- if not source:
419
- continue
420
- title = source.get("title") or "未命名材料"
421
- section = source.get("section") or ""
422
- meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area"), source.get("kind")] if v)
423
- excerpt = source.get("excerpt") or "接口返回中未识别到可展示的摘录。"
424
- url = source.get("url")
425
- links = render_source_links(url, source.get("policy_url", ""))
426
- chips.append(
427
- f"""
428
- <details class="evidence-detail" data-source="{esc(cid)}">
429
- <summary><b>[{esc(cid)}]</b>{esc(short(title, 64))}</summary>
430
- <div class="evidence-panel">
431
- <div class="evidence-title">{esc(title)}</div>
432
- <div class="evidence-meta">{esc(meta)}</div>
433
- {f'<div class="evidence-section">{esc(section)}</div>' if section else ''}
434
- <p>{esc(excerpt)}</p>
435
- {links}
436
- </div>
437
- </details>
438
- """
439
- )
440
- if not chips:
441
- return ""
442
- return f'<div class="evidence-row">{"".join(chips)}</div>'
443
-
444
-
445
- def render_answer(answer: str, sources: List[Dict[str, str]]) -> str:
446
- valid_ids = {source["id"] for source in sources}
447
-
634
+ def parse_answer_blocks(answer: str, valid_ids: set) -> Tuple[List[Dict[str, Any]], set]:
635
+ """把正文 Markdown 解析为结构化块;同时收集全部角标。"""
448
636
  def repl(match: re.Match[str]) -> str:
449
637
  cid = match.group(1)
450
- disabled = "" if cid in valid_ids else " disabled"
451
- return f'<button class="cite{disabled}" data-source="{esc(cid)}" type="button">[{esc(cid)}]</button>'
638
+ cls = "cite" if cid in valid_ids else "cite unresolved"
639
+ label = cid if cid in valid_ids else f"{cid}未绑定"
640
+ return f'<button class="{cls}" data-cite="{esc(cid)}" type="button" title="核验依据 [{esc(label)}]">[{esc(label)}]</button>'
452
641
 
453
- paragraphs = []
642
+ blocks: List[Dict[str, Any]] = []
454
643
  lines = answer.split("\n")
455
644
  idx = 0
456
645
  while idx < len(lines):
457
- raw_block = lines[idx]
458
- block = raw_block.strip()
646
+ block = lines[idx].strip()
459
647
  if not block:
460
648
  idx += 1
461
649
  continue
462
- if "|" in block and idx + 1 < len(lines) and is_markdown_table_separator(lines[idx + 1]):
650
+ ids = citation_ids(block)
651
+ heading_match = re.match(r"^(#{1,4})\s+(.+)$", block)
652
+ if heading_match:
653
+ blocks.append({"kind": "heading", "level": len(heading_match.group(1)),
654
+ "text": heading_match.group(2).strip(), "cites": ids})
655
+ idx += 1
656
+ elif "|" in block and idx + 1 < len(lines) and is_markdown_table_separator(lines[idx + 1]):
463
657
  table_lines = [block, lines[idx + 1].strip()]
464
658
  idx += 2
465
659
  while idx < len(lines) and "|" in lines[idx].strip() and lines[idx].strip():
466
660
  table_lines.append(lines[idx].strip())
467
661
  idx += 1
468
- ids = citation_ids("\n".join(table_lines))
469
- paragraphs.append(f'<div class="answer-block">{render_markdown_table(table_lines, repl)}{render_evidence_chips(ids, sources)}</div>')
470
- continue
471
- ids = citation_ids(block)
472
- evidence = render_evidence_chips(ids, sources)
473
- heading_match = re.match(r"^(#{1,4})\s+(.+)$", block)
474
- if heading_match:
475
- level = min(len(heading_match.group(1)) + 1, 4)
476
- heading = render_inline_markdown(heading_match.group(2), repl)
477
- paragraphs.append(f'<h{level} class="answer-heading">{heading}</h{level}>')
662
+ blocks.append({"kind": "table", "html": render_markdown_table(table_lines, repl), "cites": citation_ids("\n".join(table_lines))})
478
663
  elif block in {"---", "***"}:
479
- paragraphs.append('<hr class="answer-divider">')
664
+ blocks.append({"kind": "hr", "html": '<hr class="doc-divider">', "cites": []})
665
+ idx += 1
480
666
  elif re.match(r"^[-*]\s+", block):
481
667
  body = render_inline_markdown(re.sub(r"^[-*]\s+", "", block), repl)
482
- paragraphs.append(
483
- f'<div class="answer-item"><span class="bullet">•</span><div><p>{body}</p>{evidence}</div></div>'
484
- )
668
+ blocks.append({"kind": "list_item", "numbered": False, "html": body, "cites": ids})
669
+ idx += 1
485
670
  elif re.match(r"^\d+[.)]\s+", block):
486
671
  number = re.match(r"^(\d+)[.)]\s+", block).group(1)
487
672
  body = render_inline_markdown(re.sub(r"^\d+[.)]\s+", "", block), repl)
488
- paragraphs.append(
489
- f'<div class="answer-item numbered"><span class="bullet">{esc(number)}.</span><div><p>{body}</p>{evidence}</div></div>'
490
- )
673
+ blocks.append({"kind": "list_item", "numbered": True, "number": number, "html": body, "cites": ids})
674
+ idx += 1
491
675
  else:
492
- body = render_inline_markdown(block, repl)
493
- paragraphs.append(f'<div class="answer-block"><p>{body}</p>{evidence}</div>')
494
- idx += 1
495
- return "\n".join(paragraphs)
676
+ blocks.append({"kind": "para", "html": render_inline_markdown(block, repl), "cites": ids})
677
+ idx += 1
678
+ return blocks, valid_ids
679
+
680
+
681
+ def split_heading_number(text: str) -> Tuple[Optional[str], str]:
682
+ m = re.match(r"^\s*([一二三四五六七八九十]+|\d+)\s*[、..]\s*(.+)$", text)
683
+ if m:
684
+ return m.group(1), m.group(2)
685
+ return None, text
686
+
687
+
688
+ def group_sections(blocks: List[Dict[str, Any]]) -> Tuple[Optional[str], List[Dict[str, Any]]]:
689
+ """按标题层级切分章节卡。返回(报告标题, 章节列表)。
690
+
691
+ 规则:最浅层级标题若唯一且居文首,视为报告标题提出;其下一级为卡片边界。
692
+ 无标题的短正文整篇一卡。
693
+ """
694
+ if not blocks:
695
+ return None, [{"title": None, "blocks": []}]
696
+ heading_indexes = [i for i, b in enumerate(blocks) if b["kind"] == "heading"]
697
+ if not heading_indexes:
698
+ return None, [{"title": None, "blocks": blocks}]
699
+
700
+ levels = sorted({blocks[i]["level"] for i in heading_indexes})
701
+ shallow = levels[0]
702
+ shallow_indexes = [i for i in heading_indexes if blocks[i]["level"] == shallow]
703
+
704
+ doc_title = None
705
+ boundary = shallow
706
+ if len(shallow_indexes) == 1 and heading_indexes[0] == shallow_indexes[0]:
707
+ doc_title = blocks[shallow_indexes[0]]["text"]
708
+ blocks = blocks[shallow_indexes[0] + 1:]
709
+ if len(levels) > 1:
710
+ boundary = levels[1]
711
+
712
+ sections: List[Dict[str, Any]] = []
713
+ current: Dict[str, Any] = {"title": None, "blocks": []}
714
+ for b in blocks:
715
+ if b["kind"] == "heading" and b["level"] <= boundary:
716
+ if current["title"] is not None or current["blocks"]:
717
+ sections.append(current)
718
+ current = {"title": b["text"], "blocks": []}
719
+ else:
720
+ current["blocks"].append(b)
721
+ if current["title"] is not None or current["blocks"]:
722
+ sections.append(current)
723
+ return doc_title, sections
496
724
 
497
725
 
498
- def render_sources(sources: List[Dict[str, str]]) -> str:
499
- if not sources:
500
- return '<p class="empty">接口返回中未识别到可展示的材料。</p>'
501
- cards = []
502
- for source in sources:
503
- url = source.get("url")
504
- links = render_source_links(url, source.get("policy_url", ""))
505
- meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area"), source.get("kind")] if v)
506
- section = source.get("section") or ""
507
- cards.append(
726
+ # ============================================================
727
+ # 各部分渲染
728
+ # ============================================================
729
+
730
+ def render_evidence_chips(ids: List[str], sources: List[Dict[str, str]]) -> str:
731
+ source_map = {source["id"]: source for source in sources}
732
+ chips = []
733
+ for cid in ids:
734
+ source = source_map.get(cid)
735
+ if not source:
736
+ continue
737
+ meta = " | ".join(v for v in [source.get("agency"), source.get("date")] if v)
738
+ excerpt = source.get("excerpt") or "接口返回中未识别到可展示的摘录。"
739
+ links = render_source_links(source.get("url"), source.get("policy_url", ""))
740
+ chips.append(
508
741
  f"""
509
- <article class="source-card" id="source-{esc(source['id'])}" data-source="{esc(source['id'])}">
510
- <div class="source-top">
511
- <span class="source-index">[{esc(source['id'])}]</span>
512
- <h3>{esc(source.get("title"))}</h3>
742
+ <details class="ev-chip" data-cite="{esc(cid)}">
743
+ <summary><b>[{esc(cid)}]</b>{esc(short(source.get("title"), 64))}</summary>
744
+ <div class="ev-panel">
745
+ <div class="ev-title">{esc(source.get("title"))}</div>
746
+ <div class="ev-meta">{esc(meta)}</div>
747
+ <p>{esc(excerpt)}</p>
748
+ {links}
513
749
  </div>
514
- <p class="meta">{esc(meta)}</p>
515
- {f'<p class="section">{esc(section)}</p>' if section else ''}
516
- {render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")}
517
- {links}
518
- </article>
750
+ </details>
519
751
  """
520
752
  )
753
+ if not chips:
754
+ return ""
755
+ return f'<div class="ev-row">{"".join(chips)}</div>'
756
+
757
+
758
+ def render_source_links(url: str, policy_url: str = "") -> str:
759
+ links = []
760
+ if url and url != "接口未返回":
761
+ links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看原文 ↗</a>')
762
+ if policy_url:
763
+ links.append(f'<a href="{esc(policy_url)}" target="_blank" rel="noopener">知识专库原文 ↗</a>')
764
+ if not links:
765
+ return ""
766
+ return '<div class="sc-links">' + "".join(f"<span>{link}</span>" for link in links) + "</div>"
767
+
768
+
769
+ def render_verify_panel(v: Dict[str, Any], stage: str = "final") -> str:
770
+ """核验报告单:报告级核验结论 + 五项指标。"""
771
+ stage_label = STAGE_LABELS.get(stage, "成稿版")
772
+ check_name = "提纲自检" if stage == "outline" else "成稿自检"
773
+ check_hint = "事实/口径/占位/素材清单/类型标注" if stage == "outline" else "事实/质检/占位/来源注/口径"
774
+ manual_checks_html = "".join("<br>· " + esc(x) for x in v.get("manual_checks", []))
775
+ ov = v["overall"]
776
+ state = "ok" if ov["passed"] else "fail"
777
+ stamp = '<span class="v-stamp">已核验</span>' if ov["passed"] else '<span class="v-stamp bad">核验未通过</span>'
778
+ reasons_html = ""
779
+ if ov["reasons"]:
780
+ reasons_html = '<div class="v-reasons">' + ";".join(esc(r) for r in ov["reasons"]) + "</div>"
781
+
782
+ tr = v["traceability"]
783
+ if not tr["total"]:
784
+ tr_html = ('<div class="vi"><span class="s fail">✗ 依据溯源 0/0</span>'
785
+ '<span class="d">未识别到来源材料</span></div>')
786
+ elif tr["missing_links"] or tr["missing_excerpts"]:
787
+ gap_n = len(set(tr["missing_links"]) | set(tr["missing_excerpts"]))
788
+ tr_html = (f'<div class="vi"><span class="s ok">✓ 依据溯源 {tr["total"]}/{tr["total"]}</span>'
789
+ f'<span class="d">素材摘录可比对;{gap_n} 条无原文链接,汇报前请注意核对</span></div>')
790
+ else:
791
+ tr_html = (f'<div class="vi"><span class="s ok">✓ 依据溯源 {tr["passed"]}/{tr["total"]}</span>'
792
+ f'<span class="d">每条素材可回看原文</span></div>')
793
+
794
+ bd = v["binding"]
795
+ if bd.get("no_citation"):
796
+ bd_html = (f'<div class="vi"><span class="s fail">✗ 引用绑定 0/0</span>'
797
+ f'<span class="d">正文未包含来源角标,{v["traceability"]["total"]} 条素材无法与正文对应</span></div>')
798
+ elif not bd["total"]:
799
+ bd_html = '<div class="vi"><span class="s none">— 引用绑定 0/0</span><span class="d">正文未包含来源角标</span></div>'
800
+ elif not bd["unbound"]:
801
+ bd_html = (f'<div class="vi"><span class="s ok">✓ 引用绑定 {bd["bound"]}/{bd["total"]}</span>'
802
+ f'<span class="d">正文引用全部对应素材</span></div>')
803
+ else:
804
+ unbound_text = "、".join(f"[{esc(x)}]" for x in bd["unbound"][:8])
805
+ bd_html = (f'<div class="vi"><span class="s fail">✗ 引用绑定 {bd["bound"]}/{bd["total"]}</span>'
806
+ f'<span class="d">未绑定角标 {unbound_text}</span></div>')
807
+
808
+ fr = v["freshness"]
809
+ if fr:
810
+ rng = f"{fr['min'][0]}-{fr['min'][1]:02d}~{fr['max'][0]}-{fr['max'][1]:02d}"
811
+ old = f"({fr['old_count']} 条历史材料,已按参考口径处理)" if fr["old_count"] else ""
812
+ fr_html = f'<div class="vi"><span class="s ok">✓ 时效检查 完成</span><span class="d">材料日期 {esc(rng)}{esc(old)}</span></div>'
813
+ else:
814
+ fr_html = '<div class="vi"><span class="s none">— 时效检查 未记录</span><span class="d">素材未标注发布日期</span></div>'
815
+
816
+ cov = v["coverage"]
817
+ parts = [f"{KIND_CATALOG[k][0]} {cov[k]}" for k in ("policy", "data", "case", "reference") if cov.get(k)]
818
+ cov_state = "ok" if cov.get("policy") or cov.get("data") or cov.get("case") else "none"
819
+ cov_html = (f'<div class="vi"><span class="s {cov_state}">{"✓" if cov_state == "ok" else "—"} 类型覆盖</span>'
820
+ f'<span class="d">{esc(" · ".join(parts)) if parts else "未标注素材类型(合并 JSON 可加「类型」字段)"}</span></div>')
821
+
822
+ sc = v["self_check"]
823
+ if sc["status"] == "pass":
824
+ notes = ";".join(note for _, note in sc["items"].values() if note)
825
+ title_attr = f' title="{esc(notes)}"' if notes else ""
826
+ sc_html = (f'<div class="vi"><span class="s ok"{title_attr}>✓ {esc(check_name)} {sc["passed"]}/{sc["total"]}</span>'
827
+ f'<span class="d">{esc(check_hint)}{esc(" · 悬停查看核验说明" if notes else "")}</span></div>')
828
+ elif sc["status"] == "fail":
829
+ failed_parts = []
830
+ for label, (status, note) in sc["items"].items():
831
+ if status != "pass":
832
+ suffix = f"({note[:40]}…)" if len(note) > 40 else (f"({note})" if note else "")
833
+ failed_parts.append(label + suffix)
834
+ sc_html = (f'<div class="vi"><span class="s fail">✗ {esc(check_name)} {sc["passed"]}/{sc["total"]}</span>'
835
+ f'<span class="d">未通过:{esc("、".join(failed_parts))}</span></div>')
836
+ else:
837
+ sc_html = (f'<div class="vi"><span class="s none">— {esc(check_name)} 未记录</span>'
838
+ f'<span class="d">检索 JSON 未写入 self_check 字段</span></div>')
839
+
840
+ manual = ""
841
+ if v["policy_count"]:
842
+ manual = (f'<div class="vi"><span class="s man">◐ 效力复核</span>'
843
+ f'<span class="d">{v["policy_count"]} 条政策依据建议按官方发布复核现行效力</span></div>')
844
+
845
+ return f"""
846
+ <div class="verify {state}">
847
+ <div class="v-head"><span class="v-shield">{'✓' if ov['passed'] else '!'}</span>{esc(ov['label'])}({esc(stage_label)}){stamp}</div>
848
+ {reasons_html}
849
+ <div class="v-grid">
850
+ {tr_html}{bd_html}{fr_html}{cov_html}{sc_html}{manual}
851
+ </div>
852
+ <div class="v-note">核验方法:深知可信搜索召回权威来源 → 逐条溯源(摘录比对 + 原文链接 + 知识专库回看)→ {'提纲/页面结论' if stage == 'outline' else '页面级结论'}引用绑定 → {esc(check_name)}。政策现行效力以官方发布为准。{manual_checks_html}</div>
853
+ </div>"""
854
+
855
+
856
+ def render_section_cards(sections: List[Dict[str, Any]], sources: List[Dict[str, str]]) -> str:
857
+ source_ids = {s["id"] for s in sources}
858
+ cards = []
859
+ for sec in sections:
860
+ sec_cites: List[str] = []
861
+ for b in sec["blocks"]:
862
+ for cid in b.get("cites", []):
863
+ if cid not in sec_cites:
864
+ sec_cites.append(cid)
865
+ unbound_count = sum(1 for cid in sec_cites if cid not in source_ids)
866
+ number, title_text = split_heading_number(sec["title"] or "")
867
+ no_html = f'<span class="sec-no">{esc(number)}</span>' if number else ""
868
+ title_html = f"<h3>{esc(title_text)}</h3>" if title_text else ""
869
+ if sec_cites:
870
+ badge_state = "bad" if unbound_count else ""
871
+ badge_text = f"本节引用 {len(sec_cites)} 处" + (f" · {unbound_count} 处未绑定" if unbound_count else " · 已核验")
872
+ badge_html = f'<span class="sec-badge {badge_state}">{esc(badge_text)}</span>'
873
+ else:
874
+ badge_html = ""
875
+ head_html = f'<div class="sec-head">{no_html}{title_html}{badge_html}</div>' if (no_html or title_html or badge_html) else ""
876
+
877
+ body_parts = []
878
+ for b in sec["blocks"]:
879
+ if b["kind"] == "heading":
880
+ inner_level = min(b["level"] + 1, 5)
881
+ body_parts.append(f'<h{inner_level} class="doc-sub">{esc(b["text"])}</h{inner_level}>')
882
+ elif b["kind"] == "list_item":
883
+ marker = f'{esc(b.get("number", "•"))}.' if b.get("numbered") else "•"
884
+ body_parts.append(
885
+ f'<div class="doc-item"><span class="doc-bullet">{marker}</span>'
886
+ f'<div><p>{b["html"]}</p>{render_evidence_chips(b["cites"], sources)}</div></div>'
887
+ )
888
+ else:
889
+ body_parts.append(f'<div class="doc-block"><p>{b["html"]}</p>{render_evidence_chips(b["cites"], sources)}</div>')
890
+ cards.append(f'<section class="doc-sec">{head_html}<div class="sec-body">{"".join(body_parts)}</div></section>')
521
891
  return "\n".join(cards)
522
892
 
523
893
 
524
- def align_sources_to_answer(answer: str, sources: List[Dict[str, str]]) -> List[Dict[str, str]]:
525
- cited = citation_ids(answer)
526
- if not cited or not sources:
527
- return sources
528
- existing = {source["id"] for source in sources}
529
- if existing.intersection(cited):
530
- return sources
531
- aligned = [dict(source) for source in sources]
532
- for idx, citation in enumerate(cited):
533
- if idx >= len(aligned):
534
- break
535
- aligned[idx]["id"] = citation
536
- return aligned
894
+ def render_source_card(source: Dict[str, str]) -> str:
895
+ vk_parts = []
896
+ if source.get("verified"):
897
+ fallback = "摘录可比对,原文链接与知识专库可回看" if source.get("has_link") else "摘录可比对;本条无原文链接,请留意核对"
898
+ note = source.get("verify_note") or fallback
899
+ vk_parts.append(f'<span class="sc-vk ok" title="{esc(note)}">✓ 已核验</span>')
900
+ note_html = f'<div class="sc-vnote">{esc(short(note, 90))}</div>' if source.get("verify_note") else ""
901
+ else:
902
+ note_html = ""
903
+ # 数据缺口(缺链/缺摘录)以温和提醒并列展示,不改变核验状态
904
+ if not source.get("has_link"):
905
+ vk_parts.append('<span class="sc-vk warn">◐ 无原文链接</span>')
906
+ if not (source.get("excerpt") or "").strip():
907
+ vk_parts.append('<span class="sc-vk warn">◐ 无摘录</span>')
908
+ vk = "".join(vk_parts)
909
+ links = render_source_links(source.get("url"), source.get("policy_url", ""))
910
+ meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area")] if v)
911
+ section_html = f'<div class="sc-section">支撑:{esc(source["section"])}</div>' if source.get("section") else ""
912
+ return (
913
+ f'<article class="scard {source["type_css"]}" id="src-{esc(source["id"])}" data-type="{esc(source["type_key"])}" data-cite-id="{esc(source["id"])}">'
914
+ f'<div class="sc-head"><span class="sc-id">[{esc(source["id"])}]</span>'
915
+ f'<span class="sc-type">{esc(source["type_label"])}</span>{vk}</div>'
916
+ f'<h4>{esc(source.get("title"))}</h4>'
917
+ f'<div class="sc-meta">{esc(meta)}</div>'
918
+ f'{section_html}{note_html}'
919
+ f'{render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")}'
920
+ f'{links}</article>'
921
+ )
537
922
 
538
923
 
539
- def extract_question(payload: Dict[str, Any]) -> str:
540
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
541
- data = content.get("data") if isinstance(content.get("data"), dict) else {}
542
- return first_str(
543
- payload.get("question"),
544
- payload.get("input"),
545
- payload.get("query"),
546
- data.get("用户问题"),
547
- content.get("query"),
548
- content.get("question"),
924
+ def render_sources_panel(sources: List[Dict[str, str]], used: List[str], kb_zone: str = "") -> str:
925
+ if not sources:
926
+ return '<aside class="sources"><h3>核验材料</h3><p class="empty">接口返回中未识别到可展示的材料。</p></aside>'
927
+ used_set = set(used)
928
+ cited_cards = [render_source_card(s) for s in sources if s["id"] in used_set]
929
+ uncited = [s for s in sources if s["id"] not in used_set]
930
+ uncited_html = ""
931
+ if uncited:
932
+ uncited_cards = "".join(render_source_card(s) for s in uncited)
933
+ # 不用 <details> 折叠:部分宿主(WorkBuddy 等)的 HTML 预览服务会改写折叠区导致卡片丢失
934
+ uncited_html = (
935
+ '<div class="uncited-group"><div class="ug-title">未引用素材('
936
+ f'{len(uncited)} 条核心依据未在正文角标引用;完整召回可通过下方知识专库链接回看)</div>'
937
+ f'<div class="uncited-list">{uncited_cards}</div></div>'
938
+ )
939
+ verified_count = sum(1 for s in sources if s.get("verified"))
940
+ types_present = {s["type_key"] for s in sources}
941
+ filters_html = ""
942
+ if len(types_present) >= 2:
943
+ buttons = ['<button class="on" data-f="all" type="button">全部</button>']
944
+ for key in ("policy", "data", "case", "reference"):
945
+ if key in types_present:
946
+ buttons.append(f'<button data-f="{key}" type="button">{KIND_CATALOG[key][0]}</button>')
947
+ filters_html = f'<div class="filters" role="group" aria-label="类型筛选">{"".join(buttons)}</div>'
948
+ badge = "全部已核验" if verified_count == len(sources) else f"{verified_count}/{len(sources)} 已核验"
949
+ return (
950
+ '<aside class="sources" id="sources-panel" aria-label="核验材料面板">'
951
+ '<a class="back-doc" href="#doc-top">↑ 返回核验报告单</a>'
952
+ f'<h3>核验材料({len(sources)} 条 · {esc(badge)})</h3>'
953
+ '<div class="src-tip">点击正文角标 [1] 定位材料原文并核对</div>'
954
+ f'{filters_html}'
955
+ '<input class="src-search" type="search" placeholder="搜索标题 / 来源 / 摘录…" aria-label="搜索来源">'
956
+ f'<div class="src-list">{"".join(cited_cards)}{uncited_html}</div>'
957
+ f'{kb_zone}'
958
+ '</aside>'
549
959
  )
550
960
 
551
961
 
552
- def render_entry_chip(kb_url: str, source_count: int) -> str:
553
- if not kb_url:
962
+ def render_kb_zone(kb_urls: List[str], kb_labels: List[str], source_count: int) -> str:
963
+ if not kb_urls:
554
964
  return ""
555
- count_text = f"{source_count}条来源" if source_count else "来源材料"
965
+ chips = []
966
+ for index, url in enumerate(kb_urls):
967
+ label = kb_labels[index] if index < len(kb_labels) else "相关搜索来源"
968
+ chips.append(
969
+ f'<a class="kb-chip" href="{esc(url)}" target="_blank" rel="noopener">'
970
+ f'<span class="kb-label">{esc(label)}</span>'
971
+ f'<span class="kb-count">{"原始召回" if index else f"{source_count} 条来源"} · 可回看</span>'
972
+ '<span class="kb-arrow">打开 ↗</span></a>'
973
+ )
556
974
  return (
557
- f'<a class="kb-chip" href="{esc(kb_url)}" target="_blank" rel="noopener">'
558
- f'<span class="kb-label">知识专库</span>'
559
- f'<span class="kb-count">{esc(count_text)}</span>'
560
- f'<span class="kb-arrow">查看</span>'
561
- f'</a>'
975
+ '<div class="kb-zone"><div class="kb-title">原始召回存档(深知知识专库)</div>'
976
+ '<div class="kb-desc">以下链接可回看每次搜索的完整召回结果(含未写入正文的材料);'
977
+ '原文页面改版或下线时可回看当时召回的快照。逐条材料的核验请点击来源卡上的"查看原文"直达官方页面。</div>'
978
+ f'<div class="kb-list">{"".join(chips)}</div></div>'
562
979
  )
563
980
 
564
981
 
@@ -574,451 +991,466 @@ def safe_output_filename(question: str, timestamp: datetime, fallback: str = "dk
574
991
  return f"{stem}_{suffix}{suffix_ext}"
575
992
 
576
993
 
577
- def render_html(payload: Dict[str, Any], title: str, answer_override: str = "", question_override: str = "", generated_at: Optional[datetime] = None) -> str:
994
+ def render_html(payload: Dict[str, Any], title: str, answer_override: str = "", question_override: str = "",
995
+ generated_at: Optional[datetime] = None, stage: str = "final") -> str:
996
+ # unwrap 会取出 content 包装;self_check / verification_checks / knowledgeBase 等
997
+ # 控制字段可能写在原始 JSON 顶层(结构化写法)或 content 内(搜索返回),两边合并查。
998
+ raw_payload = payload
578
999
  payload = unwrap(payload)
1000
+ for key in ("selfCheck", "self_check", "verificationChecks", "verification_checks",
1001
+ "knowledgeBases", "knowledgeBase", "knowledgeBaseLabels"):
1002
+ if key in raw_payload and key not in payload:
1003
+ payload[key] = raw_payload[key]
579
1004
  answer = normalize_citations(answer_override) if answer_override.strip() else extract_answer(payload)
580
1005
  sources = align_sources_to_answer(answer, extract_sources(payload))
581
1006
  used = citation_ids(answer)
582
- kb_url = extract_knowledge_base(payload)
583
- question = question_override.strip() or extract_question(payload)
1007
+ kb_urls = extract_knowledge_bases(payload)
1008
+ kb_labels = payload.get("knowledgeBaseLabels") if isinstance(payload.get("knowledgeBaseLabels"), list) else []
584
1009
  generated_at = generated_at or datetime.now()
585
1010
  generated = generated_at.strftime("%Y-%m-%d %H:%M")
586
- kb_link = f'<a href="{esc(kb_url)}" target="_blank" rel="noopener">知识专库</a>' if kb_url else ""
587
- links = kb_link
588
- tools_html = f'<div class="tools">{links}</div>' if links else ""
589
- question_html = f'<div class="question-bubble">{esc(question)}</div>' if question else ""
1011
+ stage_label = STAGE_LABELS.get(stage, "成稿版")
1012
+
1013
+ verification = compute_verification(answer, sources, payload, generated_at)
590
1014
  citation_warning = ""
591
1015
  if sources and not used:
592
1016
  citation_warning = (
593
- '<div class="warning-box">'
594
- '<b>生成检查提示:</b>本轮最终答案没有包含来源角标,因此无法在答案段落下做“结论-来源”一一对应。'
595
- '请重新生成最终答案,并在关键结论后标注接口材料编号,例如 [1]、[2]。'
596
- '</div>'
1017
+ '<div class="warn-box"><b>生成检查未通过:正文没有来源角标。</b>'
1018
+ '本报告无法建立"结论-素材"核验对应,仅作素材清单参考。'
1019
+ '请修正答案文件(提纲版 _outline.md / 成稿版 _answer.txt):在关键事实后标注 [1]、[2] 等角标'
1020
+ '并逐条对应素材清单,然后重新运行 render_trace_html.py 生成核验报告。</div>'
597
1021
  )
598
- note_text = "AI综合所有相关权威材料后,参考性解读如下,建议点击角标查看所依据的材料原文。"
599
- compact_answer_start = re.sub(r"\s+", "", answer.lstrip()[:120])
600
- compact_note_start = re.sub(r"\s+", "", note_text[:36])
601
- note_html = "" if compact_answer_start.startswith(compact_note_start) else f'<p class="ai-note">{esc(note_text)}</p>'
602
- product_links_html = (
603
- '<nav class="product-links" aria-label="产品链接">'
604
- '<a href="https://yun.dknowc.cn/wlcb/dknowc-chat/#/" target="_blank" rel="noopener">深知晓内测</a>'
605
- '<a href="https://www.dknowc.cn/" target="_blank" rel="noopener">深知可信智能官网</a>'
606
- '</nav>'
607
- )
1022
+ blocks, _ = parse_answer_blocks(answer, {s["id"] for s in sources})
1023
+ doc_title, sections = group_sections(blocks)
1024
+ display_title = doc_title or title
1025
+ report_label = f"可信溯源核验报告({stage_label})"
1026
+ kb_zone = render_kb_zone(kb_urls, kb_labels, len(sources))
1027
+
1028
+ cov = verification["coverage"]
1029
+ meta_bits = []
1030
+ cov_bits = [f"{KIND_CATALOG[k][0]} {cov[k]}" for k in ("policy", "data", "case", "reference") if cov.get(k)]
1031
+ if cov_bits:
1032
+ meta_bits.append("素材:" + " · ".join(cov_bits))
1033
+ if sources:
1034
+ meta_bits.append(f"共 {len(sources)} 条")
1035
+ meta_bits.append("点击正文角标 [1] 定位材料原文")
1036
+ meta_line = " | ".join(meta_bits)
608
1037
 
609
1038
  return f"""<!doctype html>
610
1039
  <html lang="zh-CN">
611
1040
  <head>
612
- <meta charset="utf-8">
613
- <meta name="viewport" content="width=device-width, initial-scale=1">
614
- <title>{esc(title)}</title>
615
- <style>
616
- :root {{
617
- --purple: #6b18c9;
618
- --purple-soft: #f4ebff;
619
- --ink: #2f3033;
620
- --muted: #6b7280;
621
- --line: #e5e7eb;
622
- --panel: #ffffff;
623
- --page: #ffffff;
624
- --soft: #f7f7f8;
625
- }}
626
- * {{ box-sizing: border-box; }}
627
- body {{
628
- margin: 0;
629
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
630
- color: var(--ink);
631
- background: var(--page);
632
- }}
633
- header {{
634
- padding: 12px 28px;
635
- background: #fff;
636
- border-bottom: 1px solid var(--line);
637
- position: sticky;
638
- top: 0;
639
- z-index: 2;
640
- text-align: center;
641
- }}
642
- h1 {{ margin: 0 0 3px; font-size: 16px; letter-spacing: 0; font-weight: 700; }}
643
- header p {{ margin: 0; color: #9ca3af; font-size: 12px; }}
644
- .product-links {{
645
- display: flex;
646
- justify-content: center;
647
- gap: 14px;
648
- margin-top: 8px;
649
- font-size: 12px;
650
- }}
651
- .product-links a {{
652
- color: var(--purple);
653
- text-decoration: none;
654
- font-weight: 600;
655
- }}
656
- .product-links a:hover {{ text-decoration: underline; }}
657
- .layout {{
658
- display: grid;
659
- grid-template-columns: minmax(0, 700px) minmax(390px, 460px);
660
- gap: 30px;
661
- justify-content: center;
662
- max-width: 1220px;
663
- margin: 0 auto;
664
- padding: 30px 18px 40px;
665
- }}
666
- .conversation {{
667
- min-width: 0;
668
- }}
669
- .question-bubble {{
670
- max-width: 560px;
671
- margin: 0 0 26px auto;
672
- padding: 12px 16px;
673
- border-radius: 9px;
674
- background: var(--purple);
675
- color: #fff;
676
- line-height: 1.55;
677
- font-weight: 700;
678
- font-size: 14px;
679
- }}
680
- .answer {{
681
- background: transparent;
682
- padding: 0;
683
- }}
684
- .kb-chip {{
685
- display: inline-flex;
686
- align-items: center;
687
- gap: 10px;
688
- max-width: 100%;
689
- margin: 0 0 16px;
690
- padding: 7px 10px;
691
- border: 1px solid var(--line);
692
- border-radius: 7px;
693
- color: #4b5563;
694
- background: #fafafa;
695
- text-decoration: none;
696
- box-shadow: none;
697
- font-size: 12px;
698
- }}
699
- .kb-chip:hover {{ border-color: #d1d5db; background: #f7f7f8; }}
700
- .kb-label {{ font-weight: 700; color: #374151; }}
701
- .kb-count {{
702
- padding-left: 10px;
703
- border-left: 1px solid var(--line);
704
- color: #6b7280;
705
- }}
706
- .kb-arrow {{
707
- color: var(--purple);
708
- font-weight: 700;
709
- }}
710
- .ai-note {{ margin: 0 0 10px; color: #52525b; line-height: 1.75; font-size: 14px; }}
711
- .answer-body {{
712
- padding: 0;
713
- background: transparent;
714
- }}
715
- .answer-block, .answer-item {{ margin: 0 0 12px; }}
716
- .answer-item {{ display: grid; grid-template-columns: 20px minmax(0, 1fr); gap: 8px; }}
717
- .answer-item .bullet {{ padding-top: 2px; color: #111827; font-size: 16px; line-height: 1.75; }}
718
- .answer-item.numbered {{ grid-template-columns: 28px minmax(0, 1fr); }}
719
- .answer p {{ margin: 0; font-size: 14px; line-height: 1.85; }}
720
- .answer strong {{ font-weight: 700; color: #202124; }}
721
- .answer em {{ font-style: normal; color: #4b5563; }}
722
- .answer code {{
723
- padding: 1px 5px;
724
- border-radius: 4px;
725
- background: #f3f4f6;
726
- color: #374151;
727
- font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
728
- font-size: 12px;
729
- }}
730
- .answer-table-wrap {{ max-width: 100%; overflow-x: auto; margin: 6px 0 8px; }}
731
- .answer-table {{
732
- width: 100%;
733
- border-collapse: collapse;
734
- border: 1px solid var(--line);
735
- border-radius: 8px;
736
- overflow: hidden;
737
- font-size: 13px;
738
- }}
739
- .answer-table th, .answer-table td {{
740
- padding: 9px 10px;
741
- border: 1px solid var(--line);
742
- text-align: left;
743
- vertical-align: top;
744
- line-height: 1.65;
745
- }}
746
- .answer-table th {{ background: #f8fafc; font-weight: 700; color: #374151; white-space: nowrap; }}
747
- .answer-table tbody tr:nth-child(even) td {{ background: #fafbfc; }}
748
- .answer-table.wide {{ min-width: 560px; }}
749
- .answer-heading {{ margin: 20px 0 9px; color: #111827; line-height: 1.45; letter-spacing: 0; }}
750
- h2.answer-heading {{ font-size: 18px; }}
751
- h3.answer-heading {{ font-size: 16px; }}
752
- h4.answer-heading {{ font-size: 15px; }}
753
- .answer-divider {{ border: 0; border-top: 1px solid var(--line); margin: 22px 0; }}
754
- .warning-box {{
755
- margin: 0 0 16px;
756
- padding: 12px 14px;
757
- border: 1px solid #f59e0b;
758
- border-radius: 8px;
759
- background: #fffbeb;
760
- color: #92400e;
761
- line-height: 1.7;
762
- font-size: 14px;
763
- }}
764
- .cite {{
765
- margin: 0 2px;
766
- padding: 0 5px;
767
- border: 0;
768
- border-radius: 4px;
769
- color: var(--purple);
770
- background: var(--purple-soft);
771
- font-weight: 700;
772
- cursor: pointer;
773
- vertical-align: super;
774
- font-size: 10px;
775
- line-height: 1.4;
776
- }}
777
- .cite.disabled {{ color: #9ca3af; background: #f3f4f6; cursor: default; }}
778
- .evidence-row {{
779
- display: flex;
780
- flex-wrap: wrap;
781
- gap: 6px;
782
- margin: 5px 0 0;
783
- }}
784
- .evidence-detail {{
785
- max-width: 100%;
786
- }}
787
- .evidence-detail summary {{
788
- display: inline-flex;
789
- align-items: center;
790
- max-width: 100%;
791
- border-radius: 999px;
792
- padding: 4px 9px;
793
- color: #6b7280;
794
- background: #f3f4f6;
795
- cursor: pointer;
796
- overflow: hidden;
797
- text-overflow: ellipsis;
798
- white-space: nowrap;
799
- list-style: none;
800
- font-size: 12px;
801
- }}
802
- .evidence-detail summary::-webkit-details-marker {{ display: none; }}
803
- .evidence-detail summary::after {{
804
- content: "展开";
805
- margin-left: 7px;
806
- color: #9ca3af;
807
- font-size: 11px;
808
- }}
809
- .evidence-detail[open] summary::after {{ content: "收起"; }}
810
- .evidence-detail summary b {{ color: var(--purple); margin-right: 5px; }}
811
- .evidence-panel {{
812
- margin: 7px 0 4px;
813
- padding: 12px 14px;
814
- border: 1px solid var(--line);
815
- border-radius: 8px;
816
- background: #fff;
817
- box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
818
- }}
819
- .evidence-title {{ font-weight: 700; font-size: 14px; margin-bottom: 5px; color: #111827; }}
820
- .evidence-meta {{ color: var(--muted); font-size: 12px; margin-bottom: 6px; }}
821
- .evidence-section {{ color: var(--purple); font-size: 12px; margin-bottom: 6px; font-weight: 700; }}
822
- .evidence-panel p {{ margin: 0 0 8px; color: #374151; font-size: 13px; line-height: 1.7; }}
823
- .evidence-panel a {{ color: var(--purple); font-weight: 700; text-decoration: none; }}
824
- .source-links {{
825
- display: flex;
826
- flex-wrap: wrap;
827
- gap: 8px;
828
- margin-top: 8px;
829
- }}
830
- .source-links span {{
831
- display: inline-flex;
832
- }}
833
- .source-links a {{
834
- display: inline-flex;
835
- align-items: center;
836
- min-height: 24px;
837
- padding: 3px 8px;
838
- border-radius: 6px;
839
- background: var(--purple-soft);
840
- color: var(--purple);
841
- font-weight: 700;
842
- text-decoration: none;
843
- font-size: 12px;
844
- }}
845
- .tools {{
846
- display: flex;
847
- flex-wrap: wrap;
848
- gap: 8px;
849
- margin-top: 20px;
850
- padding-top: 16px;
851
- border-top: 1px solid var(--line);
852
- }}
853
- .tools a {{
854
- color: var(--purple);
855
- background: var(--purple-soft);
856
- border-radius: 999px;
857
- padding: 7px 12px;
858
- text-decoration: none;
859
- font-weight: 600;
860
- }}
861
- .sources {{
862
- align-self: start;
863
- position: sticky;
864
- top: 70px;
865
- max-height: calc(100vh - 92px);
866
- overflow: auto;
867
- background: #fff;
868
- border-left: 1px solid var(--line);
869
- padding: 16px 0 16px 24px;
870
- }}
871
- .sources h2 {{ margin: 0 0 12px; font-size: 15px; }}
872
- .searchbox {{
873
- width: 100%;
874
- margin: 0 0 14px;
875
- padding: 9px 12px;
876
- border: 1px solid var(--line);
877
- border-radius: 8px;
878
- color: #6b7280;
879
- background: #fff;
880
- }}
881
- .source-card {{
882
- padding: 14px 0 15px;
883
- border: 0;
884
- border-bottom: 1px solid #f1f1f2;
885
- border-radius: 0;
886
- margin-bottom: 0;
887
- background: #fff;
888
- }}
889
- .source-card.active {{
890
- margin-left: -10px;
891
- padding-left: 10px;
892
- border-left: 3px solid var(--purple);
893
- background: #fbf8ff;
894
- box-shadow: none;
895
- }}
896
- .source-top {{
897
- display: grid;
898
- grid-template-columns: auto minmax(0, 1fr);
899
- gap: 7px;
900
- align-items: start;
901
- margin-bottom: 6px;
902
- }}
903
- .source-index {{
904
- color: var(--purple);
905
- background: var(--purple-soft);
906
- border-radius: 5px;
907
- padding: 1px 5px;
908
- font-weight: 800;
909
- font-size: 12px;
910
- line-height: 1.5;
911
- }}
912
- .source-card h3 {{ margin: 0; font-size: 13px; line-height: 1.55; letter-spacing: 0; }}
913
- .source-card p {{ margin: 0 0 7px; color: #374151; line-height: 1.72; font-size: 12px; }}
914
- .source-card .meta {{ color: var(--muted); font-size: 12px; line-height: 1.55; }}
915
- .source-card .section {{ color: var(--purple); font-size: 12px; font-weight: 700; }}
916
- .source-card a {{ color: var(--purple); font-weight: 700; text-decoration: none; font-size: 12px; }}
917
- .source-card .source-excerpt {{
918
- margin: 8px 0 8px;
919
- padding: 9px 10px;
920
- border-radius: 7px;
921
- background: #f8fafc;
922
- color: #374151;
923
- font-size: 12px;
924
- line-height: 1.75;
925
- }}
926
- .source-excerpt.rich {{
927
- overflow-x: auto;
928
- max-width: 100%;
929
- }}
930
- .source-excerpt.rich table {{
931
- width: max-content;
932
- min-width: 100%;
933
- border-collapse: collapse;
934
- background: #fff;
935
- font-size: 12px;
936
- line-height: 1.55;
937
- }}
938
- .source-excerpt.rich td, .source-excerpt.rich th {{
939
- min-width: 92px;
940
- max-width: 220px;
941
- padding: 7px 8px;
942
- border: 1px solid #e5e7eb;
943
- vertical-align: top;
944
- word-break: break-word;
945
- }}
946
- .source-excerpt.rich thead td, .source-excerpt.rich th {{
947
- background: #f3f4f6;
948
- color: #374151;
949
- font-weight: 700;
950
- }}
951
- .empty {{ color: var(--muted); }}
952
- @media (max-width: 900px) {{
953
- .layout {{ grid-template-columns: 1fr; padding: 14px; }}
954
- .sources {{ position: static; max-height: none; }}
955
- .question-bubble {{ margin-left: 0; }}
956
- }}
957
- </style>
1041
+ <meta charset="utf-8">
1042
+ <meta name="viewport" content="width=device-width, initial-scale=1">
1043
+ <title>{esc(display_title)} · {esc(report_label)}</title>
1044
+ <style>
1045
+ :root{{
1046
+ --navy:#0b1f3a; --ink:#172236; --muted:#667085; --line:#dce4ef; --line-strong:#b9c6d9;
1047
+ --brand:#1559c7; --brand-soft:#e8f0ff;
1048
+ --policy:#0c9b78; --policy-soft:#e2f6ef;
1049
+ --case:#b26a00; --case-soft:#fff4e0;
1050
+ --ref:#4b5563; --ref-soft:#eef1f6;
1051
+ --warn:#b26a00; --danger:#b93939; --ok:#0c9b78;
1052
+ }}
1053
+ *{{box-sizing:border-box}}
1054
+ body{{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
1055
+ color:var(--ink);background:#f4f7fb;line-height:1.75;font-size:14.5px}}
1056
+ a{{color:var(--brand)}}
1057
+ .topbar{{position:sticky;top:0;z-index:10;display:flex;justify-content:space-between;align-items:center;gap:10px;
1058
+ padding:10px 22px;background:var(--navy);color:#fff;font-size:13px}}
1059
+ .topbar .tb-title{{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
1060
+ .topbar .tags{{display:flex;align-items:center;gap:6px;flex:none}}
1061
+ .topbar .tags span{{padding:2px 10px;border:1px solid rgba(255,255,255,.3);border-radius:999px;font-size:11.5px}}
1062
+ .layout{{display:grid;grid-template-columns:minmax(0,760px) minmax(340px,420px);gap:26px;
1063
+ max-width:1240px;margin:0 auto;padding:26px 18px 60px}}
1064
+ /* 左栏 */
1065
+ .report{{min-width:0}}
1066
+ .r-head{{padding:22px 26px;background:#fff;border:1px solid var(--line);border-radius:12px;margin-bottom:16px;text-align:center}}
1067
+ .r-head h1{{margin:0 0 8px;font-size:22px;color:var(--navy);line-height:1.5}}
1068
+ .r-head .sub{{color:var(--muted);font-size:12.5px}}
1069
+ .warn-box{{margin:0 0 16px;padding:13px 16px;border:1.5px solid var(--danger);border-radius:10px;
1070
+ background:#fdf3f3;color:#8f2626;font-size:13.5px;line-height:1.7}}
1071
+ .verify{{margin:0 0 16px;background:#fff;border:1px solid #bfe5d6;border-radius:12px;padding:16px 20px}}
1072
+ .verify.fail{{border-color:#f2c4c4;background:#fffafa}}
1073
+ .v-head{{display:flex;align-items:center;gap:9px;font-size:15px;font-weight:800;color:var(--ok)}}
1074
+ .verify.fail .v-head{{color:var(--danger)}}
1075
+ .v-shield{{display:inline-flex;width:22px;height:22px;border-radius:50%;background:var(--ok);color:#fff;
1076
+ align-items:center;justify-content:center;font-size:12px;flex:none}}
1077
+ .verify.fail .v-shield{{background:var(--danger)}}
1078
+ .v-stamp{{margin-left:auto;font-size:11px;border:1.5px solid var(--ok);color:var(--ok);border-radius:5px;
1079
+ padding:1px 8px;letter-spacing:2px;flex:none}}
1080
+ .v-stamp.bad{{border-color:var(--danger);color:var(--danger)}}
1081
+ .v-reasons{{margin-top:6px;font-size:12.5px;color:var(--danger)}}
1082
+ .v-grid{{display:grid;grid-template-columns:1fr 1fr;gap:4px 20px;margin-top:10px}}
1083
+ .vi{{display:flex;gap:7px;align-items:baseline;font-size:12.5px;color:#35445c;line-height:1.7;min-width:0}}
1084
+ .vi .s{{font-weight:800;flex:none}}
1085
+ .vi .s.ok{{color:var(--ok)}}
1086
+ .vi .s.warn{{color:var(--warn)}}
1087
+ .vi .s.fail{{color:var(--danger)}}
1088
+ .vi .s.man{{color:var(--case)}}
1089
+ .vi .s.none{{color:var(--muted)}}
1090
+ .vi .d{{color:var(--muted);min-width:0}}
1091
+ .v-note{{margin-top:11px;padding-top:9px;border-top:1px dashed var(--line);font-size:11.5px;color:var(--muted);line-height:1.7}}
1092
+ /* 正文章节卡 */
1093
+ .doc-sec{{background:#fff;border:1px solid var(--line);border-radius:12px;padding:20px 24px;margin-bottom:16px}}
1094
+ .sec-head{{display:flex;align-items:center;gap:9px;flex-wrap:wrap;margin-bottom:10px;
1095
+ padding-bottom:10px;border-bottom:1px solid var(--line)}}
1096
+ .sec-no{{display:inline-flex;width:26px;height:26px;border-radius:7px;background:var(--brand);color:#fff;
1097
+ align-items:center;justify-content:center;font-size:13.5px;font-weight:700;flex:none}}
1098
+ .sec-head h3{{margin:0;font-size:16.5px;color:var(--navy);line-height:1.5}}
1099
+ .sec-badge{{margin-left:auto;font-size:11.5px;color:var(--ok);background:var(--policy-soft);
1100
+ border-radius:6px;padding:2px 9px;font-weight:700;flex:none}}
1101
+ .sec-badge.bad{{color:var(--danger);background:#fdecea}}
1102
+ .doc-sub{{margin:16px 0 8px;color:var(--navy);font-size:14.5px;font-weight:700}}
1103
+ h5.doc-sub{{font-size:13.5px}}
1104
+ .doc-block,.doc-item{{margin:0 0 12px}}
1105
+ .doc-block p,.doc-item p{{margin:0;font-size:14px;line-height:1.9}}
1106
+ .doc-item{{display:grid;grid-template-columns:22px minmax(0,1fr);gap:8px}}
1107
+ .doc-item.numbered{{grid-template-columns:28px minmax(0,1fr)}}
1108
+ .doc-bullet{{padding-top:1px;color:#111827;font-size:15px;line-height:1.85}}
1109
+ .doc-divider{{border:0;border-top:1px solid var(--line);margin:18px 0}}
1110
+ code{{padding:1px 5px;border-radius:4px;background:#f3f4f6;color:#374151;
1111
+ font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}}
1112
+ .tbl-wrap{{max-width:100%;overflow-x:auto;margin:8px 0}}
1113
+ .data-tbl{{width:100%;border-collapse:collapse;border:1px solid var(--line);font-size:13px}}
1114
+ .data-tbl th,.data-tbl td{{border:1px solid var(--line);padding:8px 10px;text-align:left;vertical-align:top;line-height:1.65}}
1115
+ .data-tbl th{{background:#f2f5fb;font-weight:700;color:#374151;white-space:nowrap}}
1116
+ .data-tbl tbody tr:nth-child(even) td{{background:#fafbfd}}
1117
+ .data-tbl.wide{{min-width:560px}}
1118
+ /* 角标 */
1119
+ .cite{{margin:0 1px;padding:0 5px;border:0;border-radius:4px;background:var(--brand-soft);color:var(--brand);
1120
+ font-weight:800;font-size:10.5px;cursor:pointer;vertical-align:super;font-family:monospace}}
1121
+ .cite:hover,.cite:focus-visible{{background:var(--brand);color:#fff;outline:none}}
1122
+ .cite.unresolved{{background:#fdecea;color:var(--danger)}}
1123
+ /* 段落级证据 chips */
1124
+ .ev-row{{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 2px}}
1125
+ .ev-chip{{max-width:100%}}
1126
+ .ev-chip summary{{display:inline-flex;align-items:center;max-width:100%;border-radius:999px;padding:3px 10px;
1127
+ color:#4b5563;background:#f3f4f6;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
1128
+ list-style:none;font-size:11.5px}}
1129
+ .ev-chip summary::-webkit-details-marker{{display:none}}
1130
+ .ev-chip summary::after{{content:"核验";margin-left:7px;color:#9ca3af;font-size:10.5px}}
1131
+ .ev-chip[open] summary::after{{content:"收起"}}
1132
+ .ev-chip summary b{{color:var(--brand);margin-right:5px}}
1133
+ .ev-panel{{margin:7px 0 6px;padding:12px 14px;border:1px solid var(--line);border-radius:9px;background:#fbfcfe;
1134
+ box-shadow:0 8px 24px rgba(15,23,42,.06)}}
1135
+ .ev-title{{font-weight:700;font-size:13.5px;margin-bottom:4px;color:var(--navy)}}
1136
+ .ev-meta{{color:var(--muted);font-size:12px;margin-bottom:6px}}
1137
+ .ev-panel p{{margin:0 0 8px;color:#374151;font-size:12.8px;line-height:1.7}}
1138
+ .sc-links{{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}}
1139
+ .sc-links span{{display:inline-flex}}
1140
+ .sc-links a{{display:inline-flex;align-items:center;min-height:24px;padding:3px 9px;border-radius:6px;
1141
+ background:var(--brand-soft);color:var(--brand);font-weight:700;text-decoration:none;font-size:12px}}
1142
+ /* 右栏 核验材料 */
1143
+ .sources{{position:sticky;top:56px;align-self:start;max-height:calc(100vh - 76px);overflow:auto;
1144
+ background:#fff;border:1px solid var(--line);border-radius:12px;padding:16px 18px}}
1145
+ .sources h3{{margin:0 0 3px;font-size:15px;color:var(--navy)}}
1146
+ .src-tip{{font-size:11.5px;color:var(--muted);margin-bottom:10px}}
1147
+ .filters{{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:8px}}
1148
+ .filters button{{border:1px solid var(--line);border-radius:999px;background:#fff;color:var(--muted);
1149
+ padding:3px 11px;font-size:12px;cursor:pointer}}
1150
+ .filters button.on{{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:700}}
1151
+ .src-search{{width:100%;padding:7px 10px;border:1px solid var(--line);border-radius:7px;font-size:12.5px;margin-bottom:12px}}
1152
+ .scard{{border:1px solid var(--line);border-left-width:3px;border-radius:10px;padding:11px 13px;margin-bottom:10px;
1153
+ background:#fff;transition:box-shadow .25s}}
1154
+ .scard.pol{{border-left-color:var(--policy)}}
1155
+ .scard.dat{{border-left-color:var(--brand)}}
1156
+ .scard.cas{{border-left-color:var(--case)}}
1157
+ .scard.ref,.scard.mat{{border-left-color:var(--ref)}}
1158
+ .scard.hl{{box-shadow:0 0 0 3px var(--brand)}}
1159
+ .scard.hide{{display:none}}
1160
+ .sc-head{{display:flex;align-items:center;gap:7px;margin-bottom:4px}}
1161
+ .sc-id{{font-family:monospace;font-weight:800;font-size:11px;color:var(--brand);background:var(--brand-soft);
1162
+ border-radius:4px;padding:1px 7px}}
1163
+ .sc-type{{font-size:11px;font-weight:700;border-radius:4px;padding:1px 8px;background:var(--ref-soft);color:var(--ref)}}
1164
+ .scard.pol .sc-type{{background:var(--policy-soft);color:var(--policy)}}
1165
+ .scard.dat .sc-type{{background:var(--brand-soft);color:var(--brand)}}
1166
+ .scard.cas .sc-type{{background:var(--case-soft);color:var(--case)}}
1167
+ .sc-vk{{margin-left:auto;font-size:11px;font-weight:800;color:var(--ok)}}
1168
+ .sc-vk.warn{{color:var(--warn)}}
1169
+ .scard h4{{margin:0 0 4px;font-size:13px;color:var(--navy);line-height:1.55}}
1170
+ .sc-meta{{font-size:11.5px;color:var(--muted)}}
1171
+ .sc-section{{font-size:11.5px;color:var(--brand);margin-top:3px;font-weight:600}}
1172
+ .sc-vnote{{margin-top:5px;font-size:11.3px;color:var(--ok);line-height:1.6}}
1173
+ .sc-excerpt{{margin:7px 0;padding:9px 10px;border-radius:7px;background:#f8fafc;color:#42566f;font-size:12px;line-height:1.7;
1174
+ display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;cursor:pointer}}
1175
+ .scard.open .sc-excerpt{{display:block;-webkit-line-clamp:unset}}
1176
+ .sc-excerpt.rich{{overflow-x:auto}}
1177
+ .sc-excerpt.rich table{{width:max-content;min-width:100%;border-collapse:collapse;background:#fff;font-size:12px}}
1178
+ .sc-excerpt.rich td,.sc-excerpt.rich th{{min-width:92px;max-width:220px;padding:7px 8px;border:1px solid var(--line);
1179
+ vertical-align:top;word-break:break-word}}
1180
+ .sc-excerpt.rich thead td,.sc-excerpt.rich th{{background:#f3f4f6;color:#374151;font-weight:700}}
1181
+ .scard .sc-links a{{font-size:12px}}
1182
+ .scard .sc-links{{margin-top:4px}}
1183
+ .no-link{{font-size:11.5px;color:var(--muted)}}
1184
+ .uncited-group{{margin-top:12px;border-top:1px dashed var(--line-strong);padding-top:10px}}
1185
+ .ug-title{{font-size:12.5px;color:var(--muted);font-weight:700;line-height:1.6}}
1186
+ .uncited-group .uncited-list{{margin-top:10px}}
1187
+ /* 知识专库 */
1188
+ .kb-zone{{margin-top:14px;border-top:1px dashed var(--line-strong);padding-top:12px}}
1189
+ .kb-title{{font-size:12.5px;font-weight:800;color:var(--navy)}}
1190
+ .kb-desc{{font-size:11.3px;color:var(--muted);line-height:1.65;margin:3px 0 8px}}
1191
+ .kb-list{{display:flex;flex-direction:column;gap:7px}}
1192
+ .kb-chip{{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid var(--line);border-radius:8px;
1193
+ background:#fbfcfe;text-decoration:none;font-size:11.5px}}
1194
+ .kb-chip:hover{{border-color:var(--brand);background:var(--brand-soft)}}
1195
+ .kb-label{{font-weight:700;color:#374151;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
1196
+ .kb-count{{padding-left:8px;border-left:1px solid var(--line);color:var(--muted);white-space:nowrap}}
1197
+ .kb-arrow{{margin-left:auto;color:var(--brand);font-weight:700;white-space:nowrap}}
1198
+ .empty{{color:var(--muted)}}
1199
+ .foot{{text-align:center;color:var(--muted);font-size:11.5px;padding:16px 0 4px;line-height:1.8}}
1200
+ .mobile-nav{{display:none}}
1201
+ .back-doc{{display:none}}
1202
+ /* 移动端材料底部弹层:点角标就地弹出材料卡,不跳转打断阅读 */
1203
+ .sheet-mask{{display:none}}
1204
+ .sheet{{display:none}}
1205
+ @media (max-width:680px){{
1206
+ body{{font-size:14px;line-height:1.8}}
1207
+ .layout{{grid-template-columns:1fr;padding:12px 10px 40px;gap:14px}}
1208
+ .topbar{{padding:8px 12px;font-size:12px;gap:4px;flex-wrap:wrap}}
1209
+ .topbar .tags span{{font-size:10.5px;padding:1px 8px;margin-left:4px}}
1210
+ .r-head{{padding:16px 14px;border-radius:10px}}
1211
+ .r-head h1{{font-size:18px}}
1212
+ .r-head .sub{{font-size:11.5px;line-height:1.6}}
1213
+ .verify{{padding:13px 14px;border-radius:10px}}
1214
+ .v-head{{font-size:14px}}
1215
+ .v-grid{{grid-template-columns:1fr;gap:2px 0}}
1216
+ .vi{{flex-wrap:wrap;gap:4px 8px}}
1217
+ .vi .d{{min-width:0}}
1218
+ .warn-box{{font-size:12.5px;padding:11px 12px}}
1219
+ .doc-sec{{padding:14px;border-radius:10px}}
1220
+ .sec-no{{width:22px;height:22px;font-size:12px;border-radius:6px}}
1221
+ .sec-head{{gap:7px;padding-bottom:8px;margin-bottom:8px}}
1222
+ .sec-head h3{{font-size:15px}}
1223
+ .sec-badge{{margin-left:0;font-size:11px}}
1224
+ .doc-block p,.doc-item p{{font-size:13.5px;line-height:1.95}}
1225
+ .doc-sub{{font-size:14px;margin:12px 0 6px}}
1226
+ .data-tbl{{font-size:12px}}
1227
+ .data-tbl th,.data-tbl td{{padding:6px 7px;line-height:1.55}}
1228
+ .cite{{font-size:11px;padding:0 4px}}
1229
+ .ev-chip summary{{font-size:11px}}
1230
+ .sources{{padding:12px;border-radius:10px}}
1231
+ .scard{{padding:10px 11px}}
1232
+ .sc-excerpt{{font-size:11.5px}}
1233
+ .kb-chip{{flex-wrap:wrap}}
1234
+ .kb-label{{white-space:normal}}
1235
+ .mobile-nav{{display:block;margin:0 0 14px;padding:11px 14px;border:1.5px solid var(--brand);
1236
+ border-radius:10px;background:var(--brand-soft);color:var(--brand);font-weight:800;
1237
+ font-size:13.5px;text-decoration:none;text-align:center}}
1238
+ .back-doc{{display:inline-block;margin:0 0 8px;font-size:12px;color:var(--brand);
1239
+ font-weight:700;text-decoration:none}}
1240
+ .sheet-mask{{display:block;position:fixed;inset:0;background:rgba(11,31,58,.45);z-index:99;opacity:0;
1241
+ pointer-events:none;transition:opacity .2s}}
1242
+ .sheet-mask.show{{opacity:1;pointer-events:auto}}
1243
+ .sheet{{display:block;position:fixed;left:0;right:0;bottom:0;z-index:100;background:#fff;
1244
+ border-radius:14px 14px 0 0;box-shadow:0 -8px 30px rgba(11,31,58,.25);
1245
+ max-height:68vh;overflow-y:auto;-webkit-overflow-scrolling:touch;
1246
+ padding:10px 16px 22px;transform:translateY(105%);transition:transform .25s ease}}
1247
+ .sheet.show{{transform:translateY(0)}}
1248
+ .sheet-grab{{width:38px;height:4px;border-radius:2px;background:#c9d4e2;margin:2px auto 8px}}
1249
+ .sheet-head{{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}}
1250
+ .sheet-head b{{font-size:13.5px;color:var(--navy)}}
1251
+ .sheet-close{{border:1px solid var(--line);background:#f5f8fc;border-radius:8px;color:#3b4a61;
1252
+ font-size:12.5px;font-weight:700;padding:5px 14px;cursor:pointer}}
1253
+ .sheet .scard{{box-shadow:none;margin-bottom:0}}
1254
+ .sheet .sc-excerpt{{display:block;-webkit-line-clamp:unset;cursor:auto}}
1255
+ }}
1256
+ @media (max-width:1020px){{
1257
+ .layout{{grid-template-columns:1fr}}
1258
+ .sources{{position:static;max-height:none}}
1259
+ }}
1260
+ @media print{{
1261
+ .topbar,.filters,.src-search{{display:none!important}}
1262
+ .layout{{grid-template-columns:1fr;max-width:none;padding:0;gap:14px}}
1263
+ body{{background:#fff;font-size:12.5px}}
1264
+ .sources{{position:static;max-height:none;border:0;padding:0;overflow:visible}}
1265
+ .r-head,.verify,.doc-sec{{border-color:#bbb;box-shadow:none;break-inside:avoid}}
1266
+ .sc-excerpt{{display:block;-webkit-line-clamp:unset;cursor:auto}}
1267
+ .uncited-group[open] .uncited-list,.uncited-group{{break-inside:avoid}}
1268
+ .scard{{break-inside:avoid}}
1269
+ .cite{{background:#eee;color:#333}}
1270
+ }}
1271
+ </style>
958
1272
  </head>
959
1273
  <body>
960
- <header>
961
- <h1>{esc(title)}</h1>
962
- <p>内容为 AI 生成,仅供参考|生成时间:{esc(generated)}</p>
963
- {product_links_html}
964
- </header>
965
- <main class="layout">
966
- <section class="conversation" aria-label="回答正文">
967
- {question_html}
968
- <div class="answer">
969
- {render_entry_chip(kb_url, len(sources))}
970
- {note_html}
971
- {citation_warning}
972
- <div class="answer-body">{render_answer(answer, sources)}</div>
973
- {tools_html}
974
- </div>
975
- </section>
976
- <aside class="sources" aria-label="可信来源">
977
- <h2>可信来源</h2>
978
- <input class="searchbox" type="search" placeholder="搜索来源标题或摘录">
979
- {render_sources(sources)}
980
- </aside>
1274
+
1275
+ <header class="topbar">
1276
+ <div class="tb-title">{esc(display_title)} · {esc(report_label)}</div>
1277
+ <div class="tags">
1278
+ <span>生成于 {esc(generated)}</span>
1279
+ <span>素材来源:深知可信搜索</span>
1280
+ </div>
1281
+ </header>
1282
+
1283
+ <div class="layout">
1284
+ <main class="report" aria-label="核验报告正文">
1285
+ <div class="r-head" id="doc-top">
1286
+ <h1>{esc(display_title)}</h1>
1287
+ <div class="sub">{esc(report_label)} | {esc(meta_line)}</div>
1288
+ </div>
1289
+ {citation_warning}
1290
+ {render_verify_panel(verification, stage)}
1291
+ <a class="mobile-nav" href="#sources-panel">查看核验材料({len(sources)} 条 · 点击角标可定位原文)↓</a>
1292
+ {render_section_cards(sections, sources)}
1293
+ <div class="foot">深知可信PPT · {esc(report_label)} | 核验方法:可信搜索召回 → 逐条溯源 → 正文绑定 → {'提纲自检' if stage == 'outline' else '成稿自检'} | 内容由 AI 生成,仅供参考,政策现行效力以官方发布为准</div>
981
1294
  </main>
982
- <script>
983
- const cards = Array.from(document.querySelectorAll(".source-card"));
984
- function activate(id) {{
985
- cards.forEach(card => card.classList.toggle("active", card.dataset.source === id));
986
- const target = document.querySelector(`#source-${{CSS.escape(id)}}`);
987
- if (target) target.scrollIntoView({{ block: "nearest", behavior: "smooth" }});
988
- }}
989
- document.querySelectorAll(".cite").forEach(button => {{
990
- if (button.classList.contains("disabled")) return;
991
- button.addEventListener("click", () => activate(button.dataset.source));
1295
+ {render_sources_panel(sources, used, kb_zone)}
1296
+ </div>
1297
+
1298
+ <div class="sheet-mask" aria-hidden="true"></div>
1299
+ <div class="sheet" role="dialog" aria-label="核验材料">
1300
+ <div class="sheet-grab"></div>
1301
+ <div class="sheet-head"><b>核验材料</b><button class="sheet-close" type="button">收起</button></div>
1302
+ <div class="sheet-body"></div>
1303
+ </div>
1304
+
1305
+ <script>
1306
+ (function () {{
1307
+ "use strict";
1308
+ var cards = Array.prototype.slice.call(document.querySelectorAll(".scard"));
1309
+ var byId = {{}};
1310
+ cards.forEach(function (c) {{
1311
+ var id = c.getAttribute("data-cite-id");
1312
+ if (id) byId[id] = c;
1313
+ }});
1314
+
1315
+ /* 移动端底部弹层:点角标就地展示材料卡,不打断正文阅读 */
1316
+ var sheet = document.querySelector(".sheet");
1317
+ var mask = document.querySelector(".sheet-mask");
1318
+ function isMobile() {{
1319
+ return window.matchMedia("(max-width:680px)").matches;
1320
+ }}
1321
+ function openSheet(card) {{
1322
+ if (!sheet) return;
1323
+ var body = sheet.querySelector(".sheet-body");
1324
+ var clone = card.cloneNode(true);
1325
+ clone.removeAttribute("id");
1326
+ clone.classList.remove("hide");
1327
+ clone.classList.add("open");
1328
+ body.innerHTML = "";
1329
+ body.appendChild(clone);
1330
+ sheet.classList.add("show");
1331
+ mask.classList.add("show");
1332
+ document.body.style.overflow = "hidden";
1333
+ sheet.scrollTop = 0;
1334
+ }}
1335
+ function closeSheet() {{
1336
+ if (!sheet) return;
1337
+ sheet.classList.remove("show");
1338
+ mask.classList.remove("show");
1339
+ document.body.style.overflow = "";
1340
+ }}
1341
+ if (sheet && mask) {{
1342
+ mask.addEventListener("click", closeSheet);
1343
+ var closeBtn = sheet.querySelector(".sheet-close");
1344
+ if (closeBtn) closeBtn.addEventListener("click", closeSheet);
1345
+ }}
1346
+
1347
+ /* 角标 → 来源卡:精确 ID 匹配,缺失即红色警示,绝不按位置猜测。
1348
+ 手机单栏下不滚动定位(会跳到页面底部打断阅读),改为底部弹层就地查看。 */
1349
+ document.querySelectorAll(".data-cite,[data-cite]").forEach(function (btn) {{
1350
+ if (btn.classList.contains("sheet-close")) return;
1351
+ btn.addEventListener("click", function () {{
1352
+ var card = byId[btn.getAttribute("data-cite")];
1353
+ if (!card) {{
1354
+ btn.classList.add("unresolved");
1355
+ if (console.error) console.error("[核验] 未绑定角标:", btn.getAttribute("data-cite"));
1356
+ return;
1357
+ }}
1358
+ if (isMobile()) {{
1359
+ openSheet(card);
1360
+ return;
1361
+ }}
1362
+ card.classList.remove("hide", "open");
1363
+ card.classList.add("hl", "open");
1364
+ card.scrollIntoView({{ block: "center", behavior: "smooth" }});
1365
+ setTimeout(function () {{ card.classList.remove("hl"); }}, 2200);
992
1366
  }});
993
- document.querySelectorAll(".evidence-detail").forEach(detail => {{
994
- detail.addEventListener("toggle", () => {{
995
- if (!detail.open) return;
996
- cards.forEach(card => card.classList.toggle("active", card.dataset.source === detail.dataset.source));
997
- }});
1367
+ }});
1368
+
1369
+ /* 摘录点击展开/收起 */
1370
+ cards.forEach(function (c) {{
1371
+ var ex = c.querySelector(".sc-excerpt");
1372
+ if (!ex) return;
1373
+ ex.addEventListener("click", function (e) {{
1374
+ if (e.target.closest("a")) return;
1375
+ c.classList.toggle("open");
998
1376
  }});
999
- const searchbox = document.querySelector(".searchbox");
1000
- if (searchbox) {{
1001
- searchbox.addEventListener("input", () => {{
1002
- const value = searchbox.value.trim().toLowerCase();
1003
- cards.forEach(card => {{
1004
- card.style.display = !value || card.innerText.toLowerCase().includes(value) ? "" : "none";
1005
- }});
1377
+ }});
1378
+
1379
+ /* 证据 chips(灰框):桌面端点击就地展开并高亮右栏来源卡;手机端不就地展开,点击直接弹出底部材料弹层 */
1380
+ document.querySelectorAll(".ev-chip").forEach(function (chip) {{
1381
+ var summary = chip.querySelector("summary");
1382
+ if (summary) {{
1383
+ summary.addEventListener("click", function (e) {{
1384
+ if (!isMobile()) return;
1385
+ e.preventDefault();
1386
+ var card = byId[chip.getAttribute("data-cite")];
1387
+ if (card) openSheet(card);
1006
1388
  }});
1007
1389
  }}
1008
- </script>
1390
+ chip.addEventListener("toggle", function () {{
1391
+ if (!chip.open || isMobile()) return;
1392
+ var card = byId[chip.getAttribute("data-cite")];
1393
+ if (!card) return;
1394
+ cards.forEach(function (c) {{ c.classList.remove("hl"); }});
1395
+ card.classList.add("hl");
1396
+ setTimeout(function () {{ card.classList.remove("hl"); }}, 2200);
1397
+ }});
1398
+ }});
1399
+
1400
+ /* 类型筛选 + 搜索 */
1401
+ var filter = "all";
1402
+ var kw = "";
1403
+ function apply() {{
1404
+ cards.forEach(function (c) {{
1405
+ var okType = filter === "all" || c.getAttribute("data-type") === filter;
1406
+ var okKw = !kw || (c.textContent || "").toLowerCase().indexOf(kw) !== -1;
1407
+ c.classList.toggle("hide", !(okType && okKw));
1408
+ }});
1409
+ }}
1410
+ document.querySelectorAll(".filters button").forEach(function (b) {{
1411
+ b.addEventListener("click", function () {{
1412
+ document.querySelectorAll(".filters button").forEach(function (x) {{ x.classList.remove("on"); }});
1413
+ b.classList.add("on");
1414
+ filter = b.getAttribute("data-f");
1415
+ apply();
1416
+ }});
1417
+ }});
1418
+ var search = document.querySelector(".src-search");
1419
+ if (search) search.addEventListener("input", function () {{ kw = search.value.trim().toLowerCase(); apply(); }});
1420
+ }})();
1421
+ </script>
1009
1422
  </body>
1010
- </html>
1011
- """
1423
+ </html>"""
1424
+
1425
+
1426
+ def align_sources_to_answer(answer: str, sources: List[Dict[str, str]]) -> List[Dict[str, str]]:
1427
+ cited = citation_ids(answer)
1428
+ if not cited or not sources:
1429
+ return sources
1430
+ existing = {source["id"] for source in sources}
1431
+ if existing.intersection(cited):
1432
+ return sources
1433
+ aligned = [dict(source) for source in sources]
1434
+ for idx, citation in enumerate(cited):
1435
+ if idx >= len(aligned):
1436
+ break
1437
+ aligned[idx]["id"] = citation
1438
+ aligned[idx]["type_key"] = aligned[idx].get("type_key", "material")
1439
+ aligned[idx]["type_label"] = aligned[idx].get("type_label", "材料")
1440
+ aligned[idx]["type_css"] = aligned[idx].get("type_css", "mat")
1441
+ return aligned
1012
1442
 
1013
1443
 
1014
1444
  def main() -> None:
1015
- parser = argparse.ArgumentParser(description="生成深知可信搜索可交互可信溯源核验报告")
1016
- parser.add_argument("input_json", help="trusted_search.py 或 deep_query.py 的 --json-only 输出 JSON")
1445
+ parser = argparse.ArgumentParser(description="生成深知可信PPT 可信溯源核验报告 HTML(提纲版/成稿版)")
1446
+ parser.add_argument("input_json", help="trusted_search.py 或合并后的检索 JSON")
1017
1447
  parser.add_argument("--output", help="输出 HTML 路径;不传时根据问题自动生成短文件名到 official-docs/output/")
1018
- parser.add_argument("--title", default="深知可信搜索可信溯源核验报告", help="页面标题")
1019
- parser.add_argument("--answer-file", help="最终回答正文文件。复杂任务综合后必须传入,确保 HTML 展示的答案与聊天答案一致。")
1020
- parser.add_argument("--clean-md-output", help="输出干净 Markdown 路径;内容来自同一份最终答案,并移除 [1]、【1】等溯源角标。")
1021
- parser.add_argument("--question", default="", help="用户问题,用于生成顶部对话气泡。")
1448
+ parser.add_argument("--title", default="可信溯源核验报告", help="演示标题;正文首行有标题时以正文为准")
1449
+ parser.add_argument("--answer-file", help="答案文件(提纲版 <项目短名>_outline.md / 成稿版 <项目短名>_answer.txt),关键事实后标 [N] 角标。")
1450
+ parser.add_argument("--clean-md-output", help="输出干净 Markdown 路径;内容来自同一份答案,并移除 [1]、【1】等溯源角标。")
1451
+ parser.add_argument("--question", default="", help="用户需求,用于自动生成文件名。")
1452
+ parser.add_argument("--stage", choices=["outline", "final"], default="final",
1453
+ help="报告版本:outline 提纲版(确认门前事前核验)/ final 成稿版(交付时事后溯源),默认 final。")
1022
1454
  args = parser.parse_args()
1023
1455
 
1024
1456
  payload = load_json(_safe_input_path(args.input_json, {".json"}))
@@ -1026,13 +1458,31 @@ def main() -> None:
1026
1458
  if args.answer_file:
1027
1459
  answer_override = _safe_input_path(args.answer_file, {".txt", ".md"}).read_text(encoding="utf-8")
1028
1460
  question = args.question.strip() or extract_question(unwrap(payload))
1461
+
1462
+ # 生成前硬校验:有素材而正文无角标时拒绝生成,杜绝产出无核验对应的报告
1463
+ pre_answer = normalize_citations(answer_override) if answer_override.strip() else extract_answer(unwrap(payload))
1464
+ pre_sources = extract_sources(unwrap(payload))
1465
+ if pre_sources and not citation_ids(pre_answer):
1466
+ print("生成检查未通过:答案正文没有任何 [N] 来源角标,无法建立\"结论-素材\"核验对应。", file=sys.stderr)
1467
+ print(f"请修正答案文件({'提纲版 _outline.md:页面规划表事实要点' if args.stage == 'outline' else '成稿版 _answer.txt:页面级结论文本'}"
1468
+ "的关键事实后标注 [1]、[2] 等角标并逐条对应素材清单),然后重新运行本脚本。", file=sys.stderr)
1469
+ raise SystemExit(2)
1470
+ # 生成前硬校验(反向):正文有角标却识别不到任何素材,多为合并 JSON 结构不符
1471
+ # (渲染器识别 检索文章 的路径:顶层 或 content.data 嵌套),当场报错而非产出 0 卡报告
1472
+ if citation_ids(pre_answer) and not pre_sources:
1473
+ print("生成检查未通过:输入 JSON 未识别到任何素材,但正文包含 [N] 角标。", file=sys.stderr)
1474
+ print("请检查合并 JSON 结构:素材数组须为顶层 {\"检索文章\": [...]} 或原始接口的 content.data.检索文章 形态;"
1475
+ "knowledgeBase/self_check/verification_checks 放顶层。修正后重新运行本脚本。", file=sys.stderr)
1476
+ raise SystemExit(2)
1477
+
1029
1478
  generated_at = datetime.now()
1030
1479
  if args.output:
1031
1480
  output = _safe_output_path(args.output, {".html", ".htm"}, ".html")
1032
1481
  else:
1033
1482
  output = _safe_output_path(safe_output_filename(question, generated_at), {".html", ".htm"}, ".html")
1034
1483
  output.parent.mkdir(parents=True, exist_ok=True)
1035
- output.write_text(render_html(payload, args.title, answer_override=answer_override, question_override=args.question, generated_at=generated_at), encoding="utf-8")
1484
+ output.write_text(render_html(payload, args.title, answer_override=answer_override,
1485
+ question_override=args.question, generated_at=generated_at, stage=args.stage), encoding="utf-8")
1036
1486
  print(f"已生成:{output}")
1037
1487
  if args.clean_md_output:
1038
1488
  clean_output = _safe_output_path(args.clean_md_output, {".md"}, ".md")