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