dknowc-dsh 1.3.0 → 1.4.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 (41) hide show
  1. package/README.md +4 -2
  2. package/package.json +3 -3
  3. package/skills/dknowc-official-doc-writer/README.md +1 -1
  4. package/skills/dknowc-official-doc-writer/SKILL.md +26 -6
  5. package/skills/dknowc-official-doc-writer/reference/sample_trace_report.html +901 -269
  6. package/skills/dknowc-official-doc-writer/reference/search_guide.md +31 -3
  7. package/skills/dknowc-official-doc-writer/reference/search_policy.md +14 -1
  8. package/skills/dknowc-official-doc-writer/reference/task_router.md +1 -1
  9. package/skills/dknowc-official-doc-writer/scripts/adapt_mcp_result.py +52 -2
  10. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +9 -1
  11. package/skills/dknowc-official-doc-writer/scripts/initialize.py +6 -14
  12. package/skills/dknowc-official-doc-writer/scripts/mcp_direct.py +1 -1
  13. package/skills/dknowc-official-doc-writer/scripts/register.mjs +2 -2
  14. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +1317 -607
  15. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +140 -4
  16. package/skills/dknowc-ppt-assistant/SKILL.md +3 -3
  17. package/skills/dknowc-ppt-assistant/references/material_usage.md +2 -2
  18. package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +1335 -292
  19. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +1 -1
  20. package/skills/dknowc-ppt-assistant/scripts/initialize.py +7 -17
  21. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +99 -60
  22. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +1458 -653
  23. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +2 -2
  24. package/skills/dknowc-trusted-consulting/README.md +1 -1
  25. package/skills/dknowc-trusted-consulting/SKILL.md +9 -4
  26. package/skills/dknowc-trusted-consulting/reference/sample_trace_report.html +672 -307
  27. package/skills/dknowc-trusted-consulting/scripts/initialize.py +24 -34
  28. package/skills/dknowc-trusted-consulting/scripts/register_key.mjs +5 -3
  29. package/skills/dknowc-trusted-consulting/scripts/render_trace_html.py +1647 -729
  30. package/skills/dknowc-trusted-search/README.md +2 -1
  31. package/skills/dknowc-trusted-search/SKILL.md +3 -2
  32. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +1110 -251
  33. package/skills/dknowc-trusted-search/scripts/initialize.py +2 -3
  34. package/skills/dknowc-trusted-search/scripts/register_key.mjs +2 -2
  35. package/skills/dknowc-trusted-search/scripts/render_trace_html.py +1590 -692
  36. package/skills/dknowc-trusted-search/scripts/trusted_search.py +6 -3
  37. package/src/index.js +1 -1
  38. package/skills/dknowc-official-doc-writer/scripts/check_release.py +0 -93
  39. package/skills/dknowc-ppt-assistant/scripts/check_release.py +0 -106
  40. package/skills/dknowc-trusted-consulting/scripts/check_release.py +0 -66
  41. package/skills/dknowc-trusted-search/scripts/check_release.py +0 -79
@@ -1,93 +1,40 @@
1
1
  #!/usr/bin/env python3
2
- """深知可信咨询 · 可信核验报告渲染器:把统一问答 JSON 渲染为单文件可核验 HTML。
2
+ """可信核验报告渲染器:把统一问答答案/材料 JSON 渲染为单文件可核验 HTML。
3
3
 
4
4
  报告定位:不止展示"材料从哪来"(溯源),更要传达"我们查过了,可以交付"(核验)。
5
- 三个核验层次:
6
- - 报告级:核验报告单(依据溯源 / 引用对应 / 材料新旧 / 交付前检查)
7
- - 材料级:每条来源卡核验链标记(摘录可比对 + 原文可打开 + 知识专库可回溯)
8
- - 引用级:答案角标与来源卡一一绑定,未绑定角标红色警示
9
-
10
- 诚实原则:脚本真实计算的结果才打勾;政策现行效力等无法自动判定项归入
11
- "建议人工复核";self_check 未传入时显示"未记录",不假装通过。
12
- 生成前硬校验:识别到来源材料而答案无 [n] 角标时拒绝生成并报错。
13
-
14
- 布局:深色顶栏 + 左栏报告正文(分节卡片)+ 右栏核验材料面板(搜索);
15
- 打印归档模式(@media print 单栏全展开)。同时输出移除角标的干净 Markdown。
5
+ v1.3.0 架构(对齐公文写作 3.7.0 交互重构,数据口径保持咨询接口自有与真实):
6
+ - 顶栏:身份章 + 标题 + 工具组(只看正文 / 复制全文 / 打印归档)+ 阅读进度条
7
+ - Hero:大标题 + 真实统计(N 次检索 · M 条材料 · K 处引用)+ 双视图切换
8
+ - 过程回顾条:检索 → 入库 → 逐条比对 → 核验完成(静态回放,数字全部真实计算;
9
+ 无思考流数据就不展示"思考"步骤——硬造即违背核验诚实性)
10
+ - 核验报告视图(默认):核验报告单 + 正文分节卡;角标点击跳材料专库定位
11
+ - 材料专库视图(全屏):大搜索 + 热词(标题/正文高频词真实计算)+ 材料卡
12
+ (统一问答接口无检索条件分组字段,tabs 退化为 全部/未引用 引用状态筛选)
13
+ 三个核验层次:报告级(核验报告单)/材料级(来源卡核验链标记)/引用级(角标一一绑定)。
14
+ 诚实原则:脚本真实计算的结果才打勾;政策现行效力等无法自动判定项归入"建议人工复核"。
15
+ 布局为单文件静态 HTML;打印归档模式单栏全展开并附材料附录。
16
+ 咨询侧接口差异(如实退化,不虚构):无文号/快照/检索分组字段——关键性行退化为
17
+ "数据源·日期"、原文失效改用知识专库链接或如实标注(无存档快照通道)、无检索分组
18
+ tabs;另保留咨询自有的云端溯源存档(traceUrl)区与生成前硬校验。
16
19
  """
17
20
 
18
21
  from __future__ import annotations
19
22
 
20
23
  import argparse
24
+ import concurrent.futures
21
25
  import html
22
26
  import json
23
27
  import re
24
28
  import sys
29
+ import urllib.error
30
+ import urllib.request
25
31
  from datetime import datetime
26
32
  from pathlib import Path
27
33
  from typing import Any, Dict, List, Optional, Tuple
28
34
 
29
35
 
30
36
  # ============================================================
31
- # 基础工具
32
- # ============================================================
33
-
34
- def esc(value: Any) -> str:
35
- return html.escape(str(value or ""), quote=True)
36
-
37
-
38
- def load_json(path: Path) -> Dict[str, Any]:
39
- with path.open("r", encoding="utf-8") as f:
40
- data = json.load(f)
41
- if isinstance(data, dict):
42
- return data
43
- return {"data": data}
44
-
45
-
46
- def unwrap(data: Dict[str, Any]) -> Dict[str, Any]:
47
- if isinstance(data.get("data"), dict) and data.get("success") is True:
48
- return data["data"]
49
- if isinstance(data.get("content"), dict):
50
- return data["content"]
51
- return data
52
-
53
-
54
- def first_str(*values: Any) -> str:
55
- for value in values:
56
- if isinstance(value, str) and value.strip():
57
- return value.strip()
58
- if value not in (None, "", [], {}) and not isinstance(value, (dict, list)):
59
- return str(value).strip()
60
- return ""
61
-
62
-
63
- def short(text: Any, limit: int = 360) -> str:
64
- value = " ".join(str(text or "").split())
65
- if len(value) <= limit:
66
- return value
67
- return value[:limit].rstrip() + "..."
68
-
69
-
70
- def strip_tags(text: str) -> str:
71
- return re.sub(r"<[^>]+>", "", text or "")
72
-
73
-
74
- def normalize_citations(text: str) -> str:
75
- text = strip_tags(text)
76
- text = re.sub(r"【\s*(\d+)\s*】", r"[\1]", text)
77
- return re.sub(r"\[\^?(\d+)\^?\]", r"[\1]", text)
78
-
79
-
80
- def strip_citation_markers(text: str) -> str:
81
- text = strip_tags(text)
82
- text = re.sub(r"【\s*\d+\s*】", "", text)
83
- text = re.sub(r"\[\^?\d+\^?\]", "", text)
84
- text = re.sub(r"[ \t]+(\n)", r"\1", text)
85
- text = re.sub(r"\n{3,}", "\n\n", text)
86
- return text.strip() + ("\n" if text.strip() else "")
87
-
88
-
89
- # ============================================================
90
- # 工作区路径(official-docs 约定)
37
+ # 工作区路径(official-docs 约定)与咨询自有数据处理
91
38
  # ============================================================
92
39
 
93
40
  SKILL_ROOT = Path(__file__).resolve().parent.parent
@@ -107,7 +54,7 @@ OUTPUT_DIR = WS_ROOT / "official-docs" / "output"
107
54
  def _resolve_input(value: str) -> Path:
108
55
  """把待读取文件解析到本 Skill 的 official-docs/search-results/ 工作区。
109
56
 
110
- 裸文件名进 search-results/;带子路径的相对路径按当前目录解析,
57
+ 裸文件名进 search-results/;带子路径的相对路径按 SKILL_ROOT 解析,
111
58
  因此 official-docs/search-results/xxx.json 这类写法也可直接使用。
112
59
  """
113
60
  raw = Path(value).expanduser()
@@ -166,7 +113,7 @@ def _is_source_entry(line: str) -> bool:
166
113
  def strip_trailing_source_list(text: str) -> str:
167
114
  """去除答案末尾的"来源"清单块。
168
115
 
169
- 来源清单只应在对话输出中展示:核验报告由右栏核验材料面板承载来源,
116
+ 来源清单只应在对话输出中展示:核验报告由正文溯源卡与材料专库承载来源,
170
117
  clean.md 保持纯正文。仅当标题行之后全部非空行都是来源条目时才剥离,
171
118
  避免误删正文中恰好出现"来源"字样的段落。
172
119
  """
@@ -182,39 +129,154 @@ def strip_trailing_source_list(text: str) -> str:
182
129
  return "\n".join(lines[:cut]).rstrip()
183
130
 
184
131
 
132
+ def normalize_citation_punctuation(text: str) -> str:
133
+ """引文胶囊位置规范:角标与后随标点整体换位——标点紧跟文字,胶囊放标点之后。
134
+
135
+ 对齐深知晓原型"…内容。~出处"形态,避免胶囊把句号挤到下一行孤悬。
136
+ 与公文写作 3.7.0 的差异:公文只换单个角标(`[1]。`→`。[1]`),连续角标连排
137
+ (`[1][2]。`,咨询接口答案常见)时标点会悬在胶囊之间;这里整段角标连排
138
+ 整体换位(`[1][2]。`→`。[1][2]`),保证标点始终紧贴文字。
139
+ """
140
+ return re.sub(
141
+ r"(?:\[\d+\][ \t]*)+([。;,、!?:;,.])",
142
+ lambda m: m.group(1) + m.group(0)[:-len(m.group(1))],
143
+ text,
144
+ )
145
+
146
+
147
+ def resolve_citation_targets(answer: str, sources: List[Dict[str, str]]) -> Dict[str, str]:
148
+ """把答案每个角标解析到材料旧 id:{角标: 材料id}。
149
+
150
+ 现统一问答接口的真实形态:材料不返回材料级编号,但 content 每段携带
151
+ 全局唯一引文编号(id,如 101/135/201…),答案角标即段落编号——因此
152
+ 优先按"段落id→材料"解析;同一材料被多段引用时塌缩为该材料一张卡。
153
+ 旧接口形态:材料自带 explicit_id(角标即材料编号)按材料级 id 匹配。
154
+ 两种形态的未命中角标不入映射,由生成前硬校验拦截。
155
+ """
156
+ para_owner: Dict[str, str] = {}
157
+ for source in sources:
158
+ for pid in (source.get("para_ids") or []):
159
+ para_owner.setdefault(str(pid), source["id"])
160
+ source_ids = {s["id"] for s in sources}
161
+ targets: Dict[str, str] = {}
162
+ for cid in citation_ids(answer):
163
+ if cid in para_owner:
164
+ targets[cid] = para_owner[cid]
165
+ elif cid in source_ids:
166
+ targets[cid] = cid
167
+ return targets
168
+
169
+
185
170
  def renumber_citations(answer: str, sources: List[Dict[str, str]]) -> tuple:
186
- """把被引用角标按首次出现顺序重编号为 1..n,未引用材料顺延编号。
171
+ """把答案角标绑定材料并按首次出现顺序重编号为 1..n,未引用材料顺延编号。
187
172
 
188
- 统一问答接口返回的材料自带全量召回序号(如 101、601),直接透传会让
189
- 报告角标从三位数开始;交付视角应使用连续编号,同时保持角标与材料
190
- 一一对应。未绑定角标(不对应任何材料)保持原样,由生成前硬校验拦截。
173
+ 三种数据形态(resolve_citation_targets 统一解析):
174
+ ① 段落全局编号(现接口)——段落 id 即角标,绑定到所属材料卡;
175
+ ② 材料级编号(旧接口 explicit_id)——角标即材料编号,一一对应;
176
+ ③ 纯顺序兜底(如手工样例:材料 id 为 1..n、角标同为 1..n)。
177
+ 交付视角统一使用连续编号 1..n;未绑定角标保持原样,由生成前硬校验拦截。
191
178
  返回(重编号后答案, 重编号后来源列表, 旧编号→新编号映射)。
192
179
  """
193
- source_ids = {s["id"] for s in sources}
194
- cited = [cid for cid in citation_ids(answer) if cid in source_ids]
195
- mapping = {old: str(i + 1) for i, old in enumerate(cited)}
196
- next_no = len(mapping)
180
+ targets = resolve_citation_targets(answer, sources)
181
+ # 按答案角标首次出现顺序,为每个被引用材料分配连续新编号
182
+ mat_to_new: Dict[str, str] = {}
183
+ para_to_new: Dict[str, str] = {}
184
+ for cid in citation_ids(answer):
185
+ mat_id = targets.get(cid)
186
+ if mat_id is None:
187
+ continue
188
+ if mat_id not in mat_to_new:
189
+ mat_to_new[mat_id] = str(len(mat_to_new) + 1)
190
+ para_to_new[cid] = mat_to_new[mat_id]
191
+
192
+ # 未引用材料顺延编号(保持材料卡列表完整,编号不与正文冲突)
197
193
  for source in sources:
198
194
  old = source["id"]
199
- if old in mapping and mapping[old] != old:
200
- source["id"] = mapping[old]
201
- elif old not in mapping:
202
- next_no += 1
203
- mapping[old] = str(next_no)
204
- source["id"] = mapping[old]
195
+ if old not in mat_to_new:
196
+ mat_to_new[old] = str(len(mat_to_new) + 1)
197
+
198
+ for source in sources:
199
+ if source["id"] in mat_to_new:
200
+ source["id"] = mat_to_new[source["id"]]
205
201
 
206
202
  def repl(match: "re.Match[str]") -> str:
207
203
  cid = match.group(1)
208
- return f"[{mapping.get(cid, cid)}]"
204
+ if cid in para_to_new:
205
+ return f"[{para_to_new[cid]}]"
206
+ return f"[{mat_to_new.get(cid, cid)}]"
209
207
 
210
208
  answer = re.sub(r"\[(\d+)\]", repl, answer)
209
+ # 标点紧跟文字、胶囊放标点之后(含连续角标连排整体换位),
210
+ # 使对话答案、核验报告、干净 Markdown 三处标点位置一致
211
+ answer = normalize_citation_punctuation(answer)
212
+ # 合并映射:段落编号(现接口)与材料编号(旧接口)分别列出,供 Agent 输出映射表
213
+ mapping = {**mat_to_new, **para_to_new}
211
214
  return answer, sources, mapping
212
215
 
213
216
 
214
217
  # ============================================================
215
- # 素材提取(沿用原数据层)
218
+ # 基础工具
216
219
  # ============================================================
217
220
 
221
+ def esc(value: Any) -> str:
222
+ return html.escape(str(value or ""), quote=True)
223
+
224
+
225
+ def load_json(path: Path) -> Dict[str, Any]:
226
+ with path.open("r", encoding="utf-8") as f:
227
+ data = json.load(f)
228
+ if isinstance(data, dict):
229
+ return data
230
+ return {"data": data}
231
+
232
+
233
+ def unwrap(data: Dict[str, Any]) -> Dict[str, Any]:
234
+ if isinstance(data.get("data"), dict) and data.get("success") is True:
235
+ return data["data"]
236
+ if isinstance(data.get("content"), dict):
237
+ return data["content"]
238
+ return data
239
+
240
+
241
+ def first_str(*values: Any) -> str:
242
+ for value in values:
243
+ if isinstance(value, str) and value.strip():
244
+ return value.strip()
245
+ if value not in (None, "", [], {}) and not isinstance(value, (dict, list)):
246
+ return str(value).strip()
247
+ return ""
248
+
249
+
250
+ def short(text: Any, limit: int = 360) -> str:
251
+ value = " ".join(str(text or "").split())
252
+ if len(value) <= limit:
253
+ return value
254
+ return value[:limit].rstrip() + "..."
255
+
256
+
257
+ def strip_tags(text: str) -> str:
258
+ return re.sub(r"<[^>]+>", "", text or "")
259
+
260
+
261
+ def normalize_citations(text: str) -> str:
262
+ text = strip_tags(text)
263
+ text = re.sub(r"【\s*(\d+)\s*】", r"[\1]", text)
264
+ return re.sub(r"\[\^?(\d+)\^?\]", r"[\1]", text)
265
+
266
+
267
+ def strip_citation_markers(text: str) -> str:
268
+ text = strip_tags(text)
269
+ text = re.sub(r"【\s*\d+\s*】", "", text)
270
+ text = re.sub(r"\[\^?\d+\^?\]", "", text)
271
+ text = re.sub(r"[ \t]+(\n)", r"\1", text)
272
+ text = re.sub(r"\n{3,}", "\n\n", text)
273
+ return text.strip() + ("\n" if text.strip() else "")
274
+
275
+
276
+ # 注:无素材类型体系——统一问答接口不返回类型字段(类型是公文写作侧的自建概念,
277
+ # 咨询版已定稿移除),核验单为四项,来源卡不带类型徽章。
278
+
279
+
218
280
  def parse_year_month(raw: str) -> Optional[Tuple[int, int]]:
219
281
  """从日期文本提取(年, 月);识别 2025年8月 / 2025-08 / 2025.08 / 2025-08-15。"""
220
282
  text = str(raw or "").strip()
@@ -228,19 +290,42 @@ def parse_year_month(raw: str) -> Optional[Tuple[int, int]]:
228
290
  return int(m.group(1)), 1
229
291
  return None
230
292
 
293
+
294
+ # ============================================================
295
+ # 素材提取(沿用原数据层)
296
+ # ============================================================
297
+
298
+ def clean_paragraph_noise(text: str) -> str:
299
+ """清洗接口段落文本中的附件链接噪音。
300
+
301
+ 接口段落内容格式为「段落标题 https://attach.dknowc.cn/file/<正文>」——
302
+ URL 前是段落标题(已由标题链单独展示),URL 本身是附件地址(卡片有"查看原文"入口)。
303
+ 摘录只保留 URL 之后的正文;无该前缀时兜底剔除文本中的裸 URL。
304
+ """
305
+ value = str(text or "")
306
+ m = re.search(r"https?://\S*attach\.dknowc\.cn/file/", value)
307
+ if m:
308
+ return value[m.end():].strip()
309
+ value = re.sub(r"https?://\S+", " ", value)
310
+ return re.sub(r"[ \t]{2,}", " ", value).strip()
311
+
312
+
231
313
  def paragraph_text(item: Dict[str, Any]) -> str:
232
314
  paragraphs = item.get("content") or item.get("段落") or item.get("paragraphs") or item.get("paragraphList")
233
315
  if isinstance(paragraphs, list):
234
316
  chunks = []
235
317
  for para in paragraphs:
236
318
  if isinstance(para, dict):
237
- chunks.append(first_str(para.get("text"), para.get("内容"), para.get("content"), para.get("summary"), para.get("标题"), para.get("title")))
319
+ chunk = first_str(para.get("text"), para.get("内容"), para.get("content"), para.get("summary"), para.get("标题"), para.get("title"))
238
320
  else:
239
- chunks.append(str(para))
240
- text = "\n".join(chunk for chunk in chunks if chunk)
321
+ chunk = str(para)
322
+ chunk = clean_paragraph_noise(chunk)
323
+ if chunk:
324
+ chunks.append(chunk)
325
+ text = "\n".join(chunks)
241
326
  if text:
242
327
  return text
243
- return first_str(
328
+ return clean_paragraph_noise(first_str(
244
329
  item.get("摘录"),
245
330
  item.get("摘要"),
246
331
  item.get("相关段落"),
@@ -250,7 +335,7 @@ def paragraph_text(item: Dict[str, Any]) -> str:
250
335
  item.get("content"),
251
336
  item.get("text"),
252
337
  item.get("snippet"),
253
- )
338
+ ))
254
339
 
255
340
 
256
341
  def content_segments(item: Dict[str, Any]) -> List[Dict[str, str]]:
@@ -272,9 +357,11 @@ def content_segments(item: Dict[str, Any]) -> List[Dict[str, str]]:
272
357
  return segments
273
358
 
274
359
 
275
- def source_from_article(item: Dict[str, Any], index: int) -> Dict[str, str]:
360
+ def source_from_article(item: Dict[str, Any], index: int, segment: Optional[Dict[str, str]] = None) -> Dict[str, str]:
276
361
  vo = item.get("vo") if isinstance(item.get("vo"), dict) else {}
277
- # 角标号只用"材料级"编号:接口段落 id(每篇从 1 重排)不得作为角标号,否则多篇绑定冲突。
362
+ segment = segment or {}
363
+ # segment 的 id 是文章内段落序号(每篇各自从 1 起),不是材料角标号,不得用作材料 id,
364
+ # 否则多篇材料的段落 id 同为 "1" 会互相冲突,导致角标绑定错乱。
278
365
  explicit_id = first_str(
279
366
  item.get("角标"),
280
367
  item.get("编号"),
@@ -317,30 +404,48 @@ def source_from_article(item: Dict[str, Any], index: int) -> Dict[str, str]:
317
404
  "date": first_str(item.get("发布日期"), item.get("date"), item.get("发布时间"), item.get("createDate"), vo.get("dateTime"), vo.get("createDate")),
318
405
  "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")),
319
406
  "policy_url": first_str(item.get("policyUrl"), item.get("policy_url"), item.get("知识专库原文"), vo.get("policyUrl")),
320
- # 一篇材料一张卡:段落全部合并为摘录(不再按段拆卡,防止角标语义错位)
321
- "excerpt": paragraph_text(item),
407
+ "excerpt": segment.get("text") or paragraph_text(item),
322
408
  "section": first_str(item.get("正文对应"), item.get("section"), item.get("支撑")),
323
409
  "verify_note": first_str(item.get("核验"), item.get("verification"), item.get("核验说明")),
324
410
  "area": first_str(item.get("intentionArea"), item.get("area"), item.get("地域")),
325
- # 发布日期可信度("高"=模型治理入库,标题模型精抽;其余为门户抓取不标)
326
- "conf": first_str(item.get("发布日期可信度"), item.get("可信度"), item.get("confidence"), item.get("createDateReliability"), item.get("时间可靠性"), item.get("reliability")),
327
411
  }
328
- # 原文位置标题链:接口返回的段落标题即该段在原文件中的章节位置(层级以 > 分隔),统一转 ›。
329
- # 一篇材料多段时取首个非空段落标题作位置;无段落标题如实不显示。
330
- seg_title = ""
412
+ # 段落级数据(多段分块展示用):每段 {chain:[文章,章节,子节...], text}
413
+ # 段落标题自带 > 层级,拆级成面包屑;段落标题与文章标题相同或缺失时链只含文章一级。
414
+ segments = []
331
415
  for seg in content_segments(item):
332
- if first_str(seg.get("title")):
333
- seg_title = first_str(seg.get("title"))
334
- break
335
- seg_title = re.sub(r"\s*>\s*", " › ", seg_title).strip("› ").strip()
336
- if seg_title and seg_title != source["title"]:
337
- source["doc_section"] = seg_title
338
- source["chain_full"] = f"{source['title']} › {seg_title}"
339
- else:
340
- source["doc_section"] = ""
341
- source["chain_full"] = ""
342
- source["has_link"] = bool(source["url"] and source["url"] != "接口未返回") or bool(source["policy_url"])
343
- source["verified"] = bool(source["excerpt"]) and source["has_link"]
416
+ seg_title = first_str(seg.get("title"))
417
+ levels = [lvl.strip() for lvl in re.split(r"\s*>\s*", seg_title) if lvl.strip()] if seg_title else []
418
+ if levels and levels[0] == source["title"]:
419
+ levels = levels[1:]
420
+ seg_text = clean_paragraph_noise(seg.get("text"))
421
+ chain_lvls = [source["title"]] + levels
422
+ segments.append({"id": seg.get("id"), "chain": chain_lvls, "text": strip_leading_chain(seg_text, chain_lvls)})
423
+ source["segments"] = segments
424
+ # 段落全局引文编号(现统一问答接口形态:材料不返回材料级编号,content 每段
425
+ # 携带全局唯一 id,答案角标即段落编号)。保留给绑定层做"段落id→材料"解析;
426
+ # 旧接口形态段落 id 每篇从 1 重排,绑定层优先材料级编号,不受此影响。
427
+ source["para_ids"] = [str(seg["id"]) for seg in segments if str(seg.get("id") or "").strip()]
428
+ # 首段章节位置(兼容旧单行引用处)
429
+ first_chain = segments[0]["chain"][1:] if segments else []
430
+ source["doc_section"] = " › ".join(first_chain)
431
+ source["chain_full"] = " › ".join(segments[0]["chain"]) if segments else ""
432
+ # 发文字号(接口 policyFiles.writtenText,本地标题匹配)
433
+ source["doc_number"] = first_str(item.get("文号"), item.get("doc_number"))
434
+ # 所属搜索条件(多路检索分组)与引用状态(未引用=接口召回但正文未采用)
435
+ source["search_key"] = first_str(item.get("搜索条件"), item.get("search_key"))
436
+ source["used"] = item.get("已引用", item.get("used", True))
437
+ if not isinstance(source["used"], bool):
438
+ source["used"] = True
439
+ # 快照兜底:原文链接 404/410(生成时真实检测)或接口未返回源网址时,
440
+ # 改用接口提供的存档快照链接回看——快照是原文的存档副本,按钮文案如实区分。
441
+ source["snapshot"] = first_str(item.get("快照链接"), item.get("snapshot"), item.get("screenShotPath"))
442
+ source["link_dead"] = item.get("链接失效") is True or item.get("link_dead") is True
443
+ # 发布日期可信度(实测:「高」=模型治理入库、标题模型精抽;「较高」=门户抓取、标题规则提取)
444
+ source["conf"] = first_str(item.get("createDateReliability"), item.get("发布日期可信度"), item.get("时间可靠性"), item.get("可信度"), item.get("confidence"), item.get("reliability"))
445
+ live_url = bool(source["url"] and source["url"] != "接口未返回") and not source["link_dead"]
446
+ source["has_link"] = live_url or bool(source["policy_url"]) or bool(source["snapshot"])
447
+ # 核验状态只看摘录可比对;原文链接死活与快照有无是回看通道问题,不影响核验结论
448
+ source["verified"] = bool(source["excerpt"])
344
449
  return source
345
450
 
346
451
 
@@ -390,7 +495,8 @@ def extract_sources(payload: Dict[str, Any]) -> List[Dict[str, str]]:
390
495
  sources: List[Dict[str, str]] = []
391
496
  seen = set()
392
497
  for item in raw_sources:
393
- # 一篇材料一张卡:角标按"材料"粒度与正文一一对应,段落合并为摘录,不按段拆卡。
498
+ # 一篇材料一张卡:段落合并为摘录(paragraph_text 拼接全部段落),不按段落拆卡——
499
+ # 溯源 JSON 的 materials 与正文角标按"材料"粒度一一对应,拆段会使编号错位。
394
500
  source = source_from_article(item, len(sources) + 1)
395
501
  key = (source["id"], source["title"], source["url"], source["excerpt"][:80])
396
502
  if key in seen:
@@ -424,7 +530,7 @@ def extract_answer(payload: Dict[str, Any]) -> str:
424
530
  vo = item.get("vo") if isinstance(item.get("vo"), dict) else {}
425
531
  rows.append(f"[{idx}] {first_str(vo.get('showTitle'), vo.get('title'), item.get('title'), '未命名材料')}")
426
532
  return "\n".join(rows)
427
- return "接口返回中未识别到正文内容;请查看右侧来源或原始 JSON。"
533
+ return "接口返回中未识别到正文内容;请查看材料专库或原始 JSON。"
428
534
 
429
535
 
430
536
  def extract_question(payload: Dict[str, Any]) -> str:
@@ -440,37 +546,6 @@ def extract_question(payload: Dict[str, Any]) -> str:
440
546
  )
441
547
 
442
548
 
443
- def extract_knowledge_base(payload: Dict[str, Any]) -> str:
444
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
445
- data = content.get("data") if isinstance(content.get("data"), dict) else {}
446
- return first_str(
447
- content.get("knowledgeBase"),
448
- payload.get("knowledgeBase"),
449
- data.get("knowledgeBase"),
450
- payload.get("knowledgeBaseUrl"),
451
- )
452
-
453
-
454
- def extract_trace_archives(payload: Dict[str, Any]) -> List[str]:
455
- """收集"云端溯源存档"链接。
456
-
457
- 统一问答接口与公文写作的搜索接口不同:不返回可再浏览的知识专库
458
- knowledgeBase 链接,实际提供 traceUrl——云平台为本次问答生成的接口侧
459
- 可信溯源报告。两种字段都兼容,避免接口字段调整时丢链接。
460
- """
461
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
462
- values: List[str] = []
463
- for value in (payload.get("knowledgeBases"), content.get("knowledgeBases"), payload.get("knowledgeBase"), content.get("knowledgeBase")):
464
- if isinstance(value, list):
465
- values.extend(str(item).strip() for item in value if str(item).strip())
466
- elif isinstance(value, str) and value.strip():
467
- values.append(value.strip())
468
- trace = first_str(payload.get("traceUrl"), payload.get("trace_url"), content.get("traceUrl"), content.get("trace_url"))
469
- if trace:
470
- values.append(trace)
471
- return list(dict.fromkeys(values))
472
-
473
-
474
549
  def citation_ids(answer: str) -> List[str]:
475
550
  ids: List[str] = []
476
551
  for match in re.finditer(r"\[(\d+)\]", answer):
@@ -533,14 +608,18 @@ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Di
533
608
  """核验报告单数据。只计算脚本真实可得的结果,不虚构通过。"""
534
609
  generated_at = generated_at or datetime.now()
535
610
 
536
- # ① 依据溯源:只统计正文引用材料(未引用召回未进入正文核验流程,缺链不影响结论)
537
- used_ids = set(citation_ids(answer))
538
- used_sources = [s for s in sources if s["id"] in used_ids]
539
- missing_links = [s["title"] for s in used_sources if not s.get("has_link")]
540
- missing_excerpts = [s["title"] for s in used_sources if not (s.get("excerpt") or "").strip()]
541
- trace_passed = len(used_sources) - len(set(missing_links) | set(missing_excerpts))
542
-
543
- # ② 引用对应:正文角标与来源卡一一对应(按角标出现次数计,与用户在正文中数到的一致)
611
+ # ① 依据溯源:摘录可比对 + 原文链接可回看。
612
+ # 只统计被正文引用的材料——未引用召回材料未进入正文核验流程,其缺链在自身卡片上如实标注,
613
+ # 不应拖累"正文依据可交付"的报告级结论。
614
+ # 缺原文链接(接口对部分治理库文章不返回源网址,属数据源覆盖问题而非核验工作缺失)
615
+ # 不再拖垮整体结论——报告的正常结论即为"核验完成",缺链在指标行黄色提醒并在卡片标注;
616
+ # 缺摘录(正文依据无可比对的原文)仍视为核验问题计入未通过。
617
+ cited_sources = [s for s in sources if s.get("used", True)]
618
+ missing_links = [s["title"] for s in cited_sources if not s.get("has_link")]
619
+ missing_excerpts = [s["title"] for s in cited_sources if not (s.get("excerpt") or "").strip()]
620
+ trace_passed = len(cited_sources) - len(missing_excerpts)
621
+
622
+ # ② 引用绑定:正文角标与来源卡一一对应(按角标出现次数计,与用户在正文中数到的一致)
544
623
  cited = citation_ids(answer)
545
624
  all_marks = re.findall(r"\[(\d+)\]", answer)
546
625
  source_ids = {s["id"] for s in sources}
@@ -548,7 +627,7 @@ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Di
548
627
  unbound = [cid for cid in unbound_ids for _ in range(all_marks.count(cid))]
549
628
  no_citation = bool(sources) and not cited
550
629
 
551
- # ③ 材料新旧:材料日期范围与历史材料计数
630
+ # ③ 时效检查:材料日期范围与历史材料计数
552
631
  dated = [parse_year_month(s.get("date")) for s in sources]
553
632
  dated = [d for d in dated if d]
554
633
  freshness = None
@@ -560,7 +639,7 @@ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Di
560
639
  "old_count": sum(1 for y, _ in dated if y <= generated_at.year - 3),
561
640
  }
562
641
 
563
- # ⑤ 交付前检查:由 --self-check-file 或 JSON 的 self_check 传入,未传入如实显示未记录
642
+ # ⑤ 成稿自检:由溯源 JSON 的 self_check 传入,未传入如实显示未记录
564
643
  self_check_raw = None
565
644
  for holder in (payload, payload.get("content") if isinstance(payload.get("content"), dict) else {}):
566
645
  self_check_raw = self_check_raw or holder.get("selfCheck") or holder.get("self_check")
@@ -573,15 +652,12 @@ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Di
573
652
  else:
574
653
  self_check = {"items": {}, "passed": 0, "total": len(SELF_CHECK_ITEMS), "status": "missing"}
575
654
 
576
- # 政策效力:无法自动判定现行效力,列出建议人工复核
577
- policy_count = len(used_sources)
655
+ # 政策效力:无法自动判定现行效力,列出建议人工复核(咨询无类型体系,按被引用材料数计)
656
+ policy_count = len(cited_sources)
578
657
 
579
- # 交付状态约束:核验报告是交付物,交付时必须为核验通过状态。
580
- # Agent 可修正的问题(无角标/未绑定/自检未过)在生成前已被硬校验拦截;
581
- # 仅接口未返回原文链接、政策效力无法自动判定等不可抗因素以温和提示呈现,
582
- # 不作为核验失败。
658
+ trace_ok = cited_sources and not missing_excerpts
583
659
  binding_ok = (not unbound) and not no_citation
584
- overall_passed = bool(sources) and binding_ok
660
+ overall_passed = trace_ok and binding_ok
585
661
 
586
662
  reasons = []
587
663
  if not sources:
@@ -599,7 +675,7 @@ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Di
599
675
  "label": "核验完成,答案依据逐条对过原文" if overall_passed else "核验未完全通过",
600
676
  "reasons": reasons,
601
677
  },
602
- "traceability": {"total": len(sources), "passed": trace_passed,
678
+ "traceability": {"total": len(cited_sources), "passed": trace_passed,
603
679
  "missing_links": missing_links, "missing_excerpts": missing_excerpts},
604
680
  "binding": {"total": len(all_marks), "bound": len(all_marks) - len(unbound), "unbound": unbound_ids, "no_citation": no_citation},
605
681
  "freshness": freshness,
@@ -609,6 +685,94 @@ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Di
609
685
  }
610
686
 
611
687
 
688
+ # ============================================================
689
+ # 过程回顾 / 热词(真实计算,不虚构流程)
690
+ # ============================================================
691
+
692
+ def compute_process_stats(sources: List[Dict[str, str]], answer: str, question: str = "") -> Dict[str, Any]:
693
+ """过程回顾条数据:问答次数、召回/采用数、入库与引用计数。
694
+
695
+ 统一问答为单次接口召回,无检索条件分组字段——把用户问题作为唯一一路
696
+ "检索条件"如实展示(召回/采用数真实统计),不虚构分次检索流程。
697
+ """
698
+ cond_rows = []
699
+ if question.strip():
700
+ cond_rows.append({
701
+ "key": question.strip(),
702
+ "total": len(sources),
703
+ "used": sum(1 for s in sources if s.get("used", True)),
704
+ })
705
+ n_searches = len(cond_rows) or (1 if sources else 0)
706
+ used_count = sum(1 for s in sources if s.get("used", True))
707
+ unused_count = len(sources) - used_count
708
+ n_cite_marks = len(re.findall(r"\[(\d+)\]", answer))
709
+ return {
710
+ "conds": cond_rows,
711
+ "n_searches": n_searches,
712
+ "has_cond_detail": bool(cond_rows),
713
+ "n_materials": len(sources),
714
+ "used_count": used_count,
715
+ "unused_count": unused_count,
716
+ "n_cite_marks": n_cite_marks,
717
+ }
718
+
719
+
720
+ HOT_STOP = {
721
+ "关于", "通知", "工作", "意见", "方案", "实施", "有关", "问题", "情况", "报告", "总结",
722
+ "制度", "体系", "机制", "指导", "贯彻", "落实", "进一步", "以及", "其他", "相关", "以下",
723
+ "以上", "共和国", "人民", "中华", "国务院", "人民政府", "办公厅", "印发", "试行",
724
+ "办法", "条例", "若干", "的重点", "有所", "一个", "方面", "方式", "内容", "基本",
725
+ "发展", "建设", "政策", "产业", "企业", "应用", "改革", "目标", "任务", "规划",
726
+ "领域", "措施", "支持", "行动", "服务", "管理", "政府",
727
+ }
728
+
729
+
730
+ def extract_hot_terms(answer: str, sources: List[Dict[str, str]], top: int = 8) -> List[str]:
731
+ """材料专库热词:材料标题(加权)+ 检索条件 + 正文的高频 2-4 字词,真实统计。
732
+
733
+ 泛词过滤:出现在超过 60% 材料标题中的词(如库内全部材料共有的主题词)
734
+ 无法筛出子集,没有筛选价值,剔除。
735
+ """
736
+ corpus_parts: List[str] = []
737
+ for s in sources:
738
+ if s.get("title"):
739
+ corpus_parts.extend([s["title"]] * 3)
740
+ if s.get("search_key"):
741
+ corpus_parts.extend([s["search_key"]] * 2)
742
+ clean_answer = re.sub(r"\[\d+\]", "", answer or "")
743
+ corpus_parts.append(clean_answer)
744
+ corpus = "\n".join(corpus_parts)
745
+
746
+ counts: Dict[str, int] = {}
747
+ for run in re.findall(r"[一-鿿]{2,}", corpus):
748
+ for n in (2, 3, 4):
749
+ for i in range(len(run) - n + 1):
750
+ gram = run[i:i + n]
751
+ counts[gram] = counts.get(gram, 0) + 1
752
+
753
+ titles = [s.get("title") or "" for s in sources]
754
+ n_titles = max(1, len(titles))
755
+ df_limit = max(1, int(n_titles * 0.6))
756
+
757
+ cands = [(g, c) for g, c in counts.items()
758
+ if c >= 2 and g not in HOT_STOP and "的" not in g and not any(ch.isdigit() for ch in g)
759
+ and sum(1 for t in titles if g in t) <= df_limit]
760
+ cands.sort(key=lambda x: (-x[1], -len(x[0])))
761
+ kept: List[Tuple[str, int]] = []
762
+ for gram, count in cands:
763
+ redundant = False
764
+ for kgram, kcount in kept:
765
+ # 短词是已入选高频长词的子串且计数接近 → 被长词覆盖,剔除
766
+ if gram in kgram and kcount >= count * 0.6:
767
+ redundant = True
768
+ break
769
+ if not redundant:
770
+ kept.append((gram, count))
771
+ if len(kept) >= top:
772
+ break
773
+ return [g for g, _ in kept]
774
+
775
+
612
776
  # ============================================================
613
777
  # 正文解析与分节
614
778
  # ============================================================
@@ -647,12 +811,10 @@ def render_markdown_table(lines: List[str], citation_repl) -> str:
647
811
  return f'<div class="tbl-wrap"><table class="data-tbl"><thead><tr>{head_html}</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
648
812
 
649
813
 
650
- def render_excerpt_html(text: str) -> str:
651
- value = str(text or "")
652
- if "<table" not in value.lower():
653
- return f'<div class="sc-excerpt plain">{esc(value)}</div>'
654
- cleaned = re.sub(r"(?is)<script.*?</script>", "", value)
655
- cleaned = re.sub(r"(?is)<style.*?</style>", "", value)
814
+ def sanitize_table_html(text: str) -> str:
815
+ """清洗接口表格 HTML:仅保留 table/thead/tbody/tr/td/th/br,去脚本样式与属性。"""
816
+ cleaned = re.sub(r"(?is)<script.*?</script>", "", text)
817
+ cleaned = re.sub(r"(?is)<style.*?</style>", "", cleaned)
656
818
  cleaned = re.sub(r"\s+on\w+\s*=\s*(['\"]).*?\1", "", cleaned)
657
819
  cleaned = re.sub(r"\s+(href|src)\s*=\s*(['\"]).*?\2", "", cleaned)
658
820
  allowed = {"table", "thead", "tbody", "tr", "td", "th", "br"}
@@ -663,17 +825,95 @@ def render_excerpt_html(text: str) -> str:
663
825
  return ""
664
826
  return f"<{closing}{name}>"
665
827
 
666
- cleaned = re.sub(r"<\s*(/?)\s*([a-zA-Z0-9]+)(?:\s+[^>]*)?>", tag_repl, cleaned)
667
- return f'<div class="sc-excerpt rich">{cleaned}</div>'
828
+ return re.sub(r"<\s*(/?)\s*([a-zA-Z0-9]+)(?:\s+[^>]*)?>", tag_repl, cleaned)
668
829
 
669
830
 
670
- def parse_answer_blocks(answer: str, valid_ids: set) -> Tuple[List[Dict[str, Any]], set]:
671
- """把正文 Markdown 解析为结构化块;同时收集全部角标。"""
672
- def repl(match: re.Match[str]) -> str:
673
- cid = match.group(1)
674
- cls = "cite" if cid in valid_ids else "cite unresolved"
675
- label = cid if cid in valid_ids else f"{cid}未绑定"
676
- return f'<button class="{cls}" data-cite="{esc(cid)}" type="button" title="核验依据 [{esc(label)}]">[{esc(label)}]</button>'
831
+ def render_excerpt_html(text: str) -> str:
832
+ value = str(text or "")
833
+ if "<table" not in value.lower():
834
+ return f'<div class="sc-excerpt plain">{esc(value)}</div>'
835
+ return f'<div class="sc-excerpt rich">{sanitize_table_html(value)}</div>'
836
+
837
+
838
+ def parse_answer_blocks(answer: str, valid_ids: set, chip_map: Optional[Dict[str, str]] = None) -> Tuple[List[Dict[str, Any]], set]:
839
+ """把正文 Markdown 解析为结构化块;同时收集全部角标。
840
+
841
+ 角标渲染为原型式 sup.cite 上标胶囊;段落对应的溯源卡(src-card)由
842
+ render_section_cards 在段后输出。
843
+ """
844
+
845
+ def jb_html(cid: str) -> str:
846
+ jb = chip_map.get(cid)
847
+ if not jb:
848
+ return ""
849
+ if jb.get("url"):
850
+ # 咨询接口无存档快照:原文失效时回退链接是知识专库,文案如实区分
851
+ if jb.get("dead") and jb.get("snapshot"):
852
+ btn_txt = "查看存档全文"
853
+ elif jb.get("dead"):
854
+ btn_txt = "知识专库原文"
855
+ else:
856
+ btn_txt = "查看全文"
857
+ link = (f'<a class="jb-src" href="{esc(jb["url"])}" target="_blank" rel="noopener noreferrer">'
858
+ f'{ARROW_SVG}<span>{btn_txt}</span></a>')
859
+ else:
860
+ link = ""
861
+ # 原文直达区展示标题链(多段分块,各段带链——快速人工核验的核心抓手)
862
+ segs = jb.get("segments") or []
863
+ if segs:
864
+ quote = ""
865
+ seg_idx = -1
866
+ for seg in segs:
867
+ text = (seg.get("text") or "").strip()
868
+ if not text:
869
+ continue
870
+ seg_idx += 1
871
+ if "<table" in text.lower():
872
+ # 表格不能静态写进 span(解析器会拆散):此处留占位,
873
+ # 表格数据由 render_html 汇总注入页尾 JSON,展开时 JS 填充
874
+ tbl_key = f"{cid}-{seg_idx}"
875
+ jb.setdefault("_tables", {})[tbl_key] = sanitize_table_html(text)
876
+ body_txt = f'<span class="sc-excerpt rich tbl-holder" data-tbl="{esc(tbl_key)}"></span>'
877
+ else:
878
+ body_txt = f'<span class="sc-excerpt">{esc(text)}</span>'
879
+ inner = f'<i class="jb-no">{esc(cid)}</i>{body_txt}'
880
+ item = f'<span class="jb-quote" role="button" tabindex="0">{inner}</span>'
881
+ quote += render_crumb(seg.get("chain") or []) + item
882
+ elif jb["excerpt"]:
883
+ inner = f'<i class="jb-no">{esc(cid)}</i><span>{esc(jb["excerpt"])}</span>'
884
+ quote = f'<span class="jb-quote" role="button" tabindex="0">{inner}</span>'
885
+ else:
886
+ quote = ""
887
+ site_html = (f'<span class="jb-site"><span class="dot"></span>{esc(jb.get("site") or "")}</span>'
888
+ if (jb.get("site") or "").strip() else "")
889
+ return (
890
+ f'<span class="jb" data-cite="{esc(cid)}">'
891
+ f'<button class="jb-name" type="button" aria-expanded="false">{CARET_SVG}'
892
+ f'<i class="jb-id">{esc(cid)}</i>'
893
+ f'<span class="jb-txt">{esc(jb["title"])}</span></button>'
894
+ f'<span class="jb-body"><span class="jb-head"><span class="jb-label">{SRC_ICO_SVG}溯源原文:</span>{link}</span>'
895
+ f'{site_html}'
896
+ f'{quote}</span></span>'
897
+ )
898
+
899
+ def make_block_repl(block_text: str):
900
+ """按块构造角标替换器:同段同材料只保留最后一次出现的角标(前处整体删除),
901
+ 最后一处挂数字角标 + 引文胶囊——一段中同一材料只出现一次。"""
902
+ remaining: Dict[str, int] = {}
903
+ for cid in re.findall(r"\[(\d+)\]", block_text):
904
+ remaining[cid] = remaining.get(cid, 0) + 1
905
+
906
+ def repl(match: re.Match[str]) -> str:
907
+ cid = match.group(1)
908
+ remaining[cid] = max(0, remaining.get(cid, 1) - 1)
909
+ if remaining[cid] > 0:
910
+ return ""
911
+ if cid in chip_map:
912
+ return jb_html(cid)
913
+ # 未绑定角标(无对应材料):红色数字警示,绝不按位置猜测
914
+ return f'<sup class="cite unresolved" data-cite="{esc(cid)}" title="核验依据 [{esc(cid)}?]">{esc(cid)}?</sup>'
915
+
916
+ return repl
677
917
 
678
918
  blocks: List[Dict[str, Any]] = []
679
919
  lines = answer.split("\n")
@@ -683,7 +923,10 @@ def parse_answer_blocks(answer: str, valid_ids: set) -> Tuple[List[Dict[str, Any
683
923
  if not block:
684
924
  idx += 1
685
925
  continue
926
+ # 引文胶囊位置规范:标点紧跟文字、胶囊放标点之后(含连续角标连排整体换位)
927
+ block = normalize_citation_punctuation(block)
686
928
  ids = citation_ids(block)
929
+ repl = make_block_repl(block)
687
930
  heading_match = re.match(r"^(#{1,4})\s+(.+)$", block)
688
931
  if heading_match:
689
932
  blocks.append({"kind": "heading", "level": len(heading_match.group(1)),
@@ -695,6 +938,7 @@ def parse_answer_blocks(answer: str, valid_ids: set) -> Tuple[List[Dict[str, Any
695
938
  while idx < len(lines) and "|" in lines[idx].strip() and lines[idx].strip():
696
939
  table_lines.append(lines[idx].strip())
697
940
  idx += 1
941
+ repl = make_block_repl("\n".join(table_lines))
698
942
  blocks.append({"kind": "table", "html": render_markdown_table(table_lines, repl), "cites": citation_ids("\n".join(table_lines))})
699
943
  elif block in {"---", "***"}:
700
944
  blocks.append({"kind": "hr", "html": '<hr class="doc-divider">', "cites": []})
@@ -763,38 +1007,44 @@ def group_sections(blocks: List[Dict[str, Any]]) -> Tuple[Optional[str], List[Di
763
1007
  # 各部分渲染
764
1008
  # ============================================================
765
1009
 
766
- def render_evidence_chips(ids: List[str], sources: List[Dict[str, str]]) -> str:
767
- source_map = {source["id"]: source for source in sources}
768
- chips = []
769
- for cid in ids:
770
- source = source_map.get(cid)
771
- if not source:
1010
+ def build_chip_data(sources: List[Dict[str, str]]) -> Dict[str, Dict[str, str]]:
1011
+ """行内引文胶囊数据:id → {title, site, url, excerpt}。
1012
+
1013
+ 角标后渲染原型式 jb(行内小胶囊,点击展开块级卡)。摘录展示完整
1014
+ 原文原段、不截断——段内去重后重复量可控,核对场景下就地读全文。
1015
+ """
1016
+ chip_map: Dict[str, Dict[str, str]] = {}
1017
+ for source in sources:
1018
+ cid = source["id"]
1019
+ if cid in chip_map:
772
1020
  continue
773
- meta = " | ".join(v for v in [source.get("agency"), source.get("date")] if v)
774
- excerpt = source.get("excerpt") or "接口返回中未识别到可展示的摘录。"
775
- links = render_source_links(source.get("url"), source.get("policy_url", ""))
776
- chips.append(
777
- f"""
778
- <details class="ev-chip" data-cite="{esc(cid)}">
779
- <summary><b>[{esc(cid)}]</b>{esc(short(source.get("title"), 64))}</summary>
780
- <div class="ev-panel">
781
- <div class="ev-title">{esc(source.get("title"))}</div>
782
- <div class="ev-meta">{esc(meta)}</div>
783
- <p>{esc(excerpt)}</p>
784
- {links}
785
- </div>
786
- </details>
787
- """
788
- )
789
- if not chips:
790
- return ""
791
- return f'<div class="ev-row">{"".join(chips)}</div>'
1021
+ meta_bits = [v for v in [source.get("agency"), source.get("date")] if v and v != "未知来源"]
1022
+ url = source.get("url") if (source.get("url") and source["url"] != "接口未返回") else (source.get("policy_url") or "")
1023
+ if source.get("link_dead"):
1024
+ # 咨询接口无存档快照:原文失效时改用知识专库链接回看,两者都缺则不出链接
1025
+ url = source.get("snapshot") or source.get("policy_url") or ""
1026
+ site_bits = ([source["doc_number"]] if source.get("doc_number") else []) + meta_bits
1027
+ chip_map[cid] = {
1028
+ "title": short(source.get("title") or "未命名材料", 30),
1029
+ "site": " · ".join(site_bits) or "来源站点",
1030
+ "url": url,
1031
+ "snapshot": source.get("snapshot") or "",
1032
+ "dead": bool(source.get("link_dead")),
1033
+ "excerpt": (source.get("excerpt") or "").strip(),
1034
+ "segments": source.get("segments") or [],
1035
+ }
1036
+ return chip_map
792
1037
 
793
1038
 
794
- def render_source_links(url: str, policy_url: str = "") -> str:
1039
+ def render_source_links(url: str, policy_url: str = "", snapshot: str = "", link_dead: bool = False) -> str:
1040
+ """链接区四态:原文可回看 / 原文失效改快照 / 原文失效无快照 / 无源网址有快照。
1041
+ 快照是接口对原文的存档副本,文案如实标注,不冒充原文链接。"""
795
1042
  links = []
796
- if url and url != "接口未返回":
797
- links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看原文 ↗</a>')
1043
+ if url and url != "接口未返回" and not link_dead:
1044
+ links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看全文 ↗</a>')
1045
+ if snapshot:
1046
+ # 有哪个显示哪个:快照统一展示"查看存档全文",不做原文失效的状态解释
1047
+ links.append(f'<a class="snap" href="{esc(snapshot)}" target="_blank" rel="noopener">查看存档全文 ↗</a>')
798
1048
  if policy_url:
799
1049
  links.append(f'<a href="{esc(policy_url)}" target="_blank" rel="noopener">知识专库原文 ↗</a>')
800
1050
  if not links:
@@ -803,7 +1053,7 @@ def render_source_links(url: str, policy_url: str = "") -> str:
803
1053
 
804
1054
 
805
1055
  def render_verify_panel(v: Dict[str, Any]) -> str:
806
- """核验报告单:报告级核验结论 + 五项指标。"""
1056
+ """核验报告单:报告级核验结论 + 四项指标(咨询版无素材类型项)。"""
807
1057
  manual_checks_html = "".join("<br>· " + esc(x) for x in v.get("manual_checks", []))
808
1058
  ov = v["overall"]
809
1059
  state = "ok" if ov["passed"] else "fail"
@@ -818,39 +1068,40 @@ def render_verify_panel(v: Dict[str, Any]) -> str:
818
1068
  '<span class="d">未识别到来源材料</span></div>')
819
1069
  elif tr["passed"] == tr["total"]:
820
1070
  tr_html = (f'<div class="vi"><span class="s ok">✓ 依据溯源 {tr["passed"]}/{tr["total"]}</span>'
821
- f'<span class="d">每条素材可回看原文</span></div>')
1071
+ f'<span class="d">每条材料摘录可比对,原文链接可回看</span></div>')
822
1072
  else:
823
1073
  tr_html = (f'<div class="vi"><span class="s warn">◐ 依据溯源 {tr["passed"]}/{tr["total"]}</span>'
824
- f'<span class="d">{tr["total"] - tr["passed"]} 条材料接口未返回原文链接,可经摘录与知识专库回看</span></div>')
1074
+ f'<span class="d">待补摘录 {len(tr.get("missing_excerpts") or [])} 条</span></div>')
825
1075
 
826
1076
  bd = v["binding"]
827
1077
  if bd.get("no_citation"):
828
1078
  bd_html = (f'<div class="vi"><span class="s fail">✗ 引用对应 0/0</span>'
829
- f'<span class="d">正文未包含来源角标,{v["traceability"]["total"]} 条素材无法与正文对应</span></div>')
1079
+ f'<span class="d">答案里没有来源角标,{v["traceability"]["total"]} 条材料对不上答案</span></div>')
830
1080
  elif not bd["total"]:
831
- bd_html = '<div class="vi"><span class="s none">— 引用对应 0/0</span><span class="d">正文未包含来源角标</span></div>'
1081
+ bd_html = '<div class="vi"><span class="s none">— 引用对应 0/0</span><span class="d">答案里没有来源角标</span></div>'
832
1082
  elif not bd["unbound"]:
833
1083
  bd_html = (f'<div class="vi"><span class="s ok">✓ 引用对应 {bd["bound"]}/{bd["total"]}</span>'
834
- f'<span class="d">正文引用全部对应素材</span></div>')
1084
+ f'<span class="d">答案每处 [n] 都能找到对应材料</span></div>')
835
1085
  else:
836
1086
  unbound_text = "、".join(f"[{esc(x)}]" for x in bd["unbound"][:8])
837
1087
  bd_html = (f'<div class="vi"><span class="s fail">✗ 引用对应 {bd["bound"]}/{bd["total"]}</span>'
838
- f'<span class="d">未绑定角标 {unbound_text}</span></div>')
1088
+ f'<span class="d">对不上的角标 {unbound_text}</span></div>')
839
1089
 
840
1090
  fr = v["freshness"]
841
1091
  if fr:
842
1092
  rng = f"{fr['min'][0]}-{fr['min'][1]:02d}~{fr['max'][0]}-{fr['max'][1]:02d}"
843
- old = f"({fr['old_count']} 条历史材料,已按参考口径处理)" if fr["old_count"] else ""
844
- fr_html = f'<div class="vi"><span class="s ok">✓ 材料新旧 完成</span><span class="d">材料日期 {esc(rng)}{esc(old)}</span></div>'
1093
+ old = f"({fr['old_count']} 条年头较久,按参考口径使用)" if fr["old_count"] else ""
1094
+ fr_html = f'<div class="vi"><span class="s ok">✓ 材料新旧 已核</span><span class="d">材料日期 {esc(rng)}{esc(old)}</span></div>'
845
1095
  else:
846
- fr_html = '<div class="vi"><span class="s none">— 材料新旧 未记录</span><span class="d">素材未标注发布日期</span></div>'
1096
+ fr_html = '<div class="vi"><span class="s none">— 材料新旧 未记录</span><span class="d">材料没标发布日期</span></div>'
847
1097
 
848
1098
  sc = v["self_check"]
849
1099
  if sc["status"] == "pass":
850
1100
  notes = ";".join(note for _, note in sc["items"].values() if note)
851
1101
  title_attr = f' title="{esc(notes)}"' if notes else ""
1102
+ item_names = "、".join(sc["items"].keys()) if sc["items"] else "、".join(label for _, label in SELF_CHECK_ITEMS)
852
1103
  sc_html = (f'<div class="vi"><span class="s ok"{title_attr}>✓ 交付前检查 {sc["passed"]}/{sc["total"]}</span>'
853
- f'<span class="d">角标/绑定/核验/一致/清单{esc(" · 悬停查看核验说明" if notes else "")}</span></div>')
1104
+ f'<span class="d">{esc(item_names)}{esc(" · 悬停查看说明" if notes else "")}</span></div>')
854
1105
  elif sc["status"] == "fail":
855
1106
  failed_parts = []
856
1107
  for label, (status, note) in sc["items"].items():
@@ -858,14 +1109,14 @@ def render_verify_panel(v: Dict[str, Any]) -> str:
858
1109
  suffix = f"({note[:40]}…)" if len(note) > 40 else (f"({note})" if note else "")
859
1110
  failed_parts.append(label + suffix)
860
1111
  sc_html = (f'<div class="vi"><span class="s fail">✗ 交付前检查 {sc["passed"]}/{sc["total"]}</span>'
861
- f'<span class="d">未通过:{esc("、".join(failed_parts))}</span></div>')
1112
+ f'<span class="d">没过的项:{esc("、".join(failed_parts))}</span></div>')
862
1113
  else:
863
- sc_html = '<div class="vi"><span class="s none">— 交付前检查 未记录</span><span class="d">本次未传入自检结果</span></div>'
1114
+ sc_html = '<div class="vi"><span class="s none">— 交付前检查 未记录</span><span class="d">本次未传入交付前检查结果</span></div>'
864
1115
 
865
1116
  manual = ""
866
1117
  if v["policy_count"]:
867
1118
  manual = (f'<div class="vi"><span class="s man">◐ 现行效力</span>'
868
- f'<span class="d">{v["policy_count"]} 条材料建议按官方发布复核现行效力</span></div>')
1119
+ f'<span class="d">{v["policy_count"]} 份政策文件建议按官方发布确认是否现行有效</span></div>')
869
1120
 
870
1121
  return f"""
871
1122
  <div class="verify {state}">
@@ -874,117 +1125,312 @@ def render_verify_panel(v: Dict[str, Any]) -> str:
874
1125
  <div class="v-grid">
875
1126
  {tr_html}{bd_html}{fr_html}{sc_html}{manual}
876
1127
  </div>
877
- <div class="v-note">核验方法:深知可信统一问答召回权威来源 → 逐条溯源(摘录比对 + 原文链接 + 知识专库回看)→ 答案引用对应 → 交付前检查。政策现行效力以官方发布为准。{manual_checks_html}</div>
1128
+ <div class="v-note">核验方式:先通过可信问答从权威文件库召回材料,再把答案每处依据和原文逐条比对(都能点开原文回看),最后做了交付前五项检查。政策是否现行有效,以官方发布为准。{manual_checks_html}</div>
878
1129
  </div>"""
879
1130
 
880
1131
 
1132
+ SRC_ICO_SVG = ('<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" '
1133
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'
1134
+ '<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/>'
1135
+ '<path d="M9 13h6M9 17h4"/></svg>')
1136
+ ARROW_SVG = ('<svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" stroke-width="2.2" '
1137
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 17 17 7M9 7h8v8"/></svg>')
1138
+ CARET_SVG = ('<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.4" '
1139
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>')
1140
+
1141
+
1142
+ def render_src_card(jb: Dict[str, str], cid: str, dup: bool = False) -> str:
1143
+ """句后溯源卡(原型 cardHTML 的 Python 移植):标题 + 来源 + 查看原文 + 摘录展开。"""
1144
+ src = jb.get("source") or "来源站点"
1145
+ url = jb.get("url") or ""
1146
+ title = re.sub(r"<br\s*/?>", " ", str(jb.get("title") or ""), flags=re.I)
1147
+ excerpt = (jb.get("excerpt") or "").strip()
1148
+ dup_cls = " dup-card" if dup else ""
1149
+ link_html = (f'<a class="src-link" href="{esc(url)}" target="_blank" rel="noopener noreferrer">查看全文{ARROW_SVG}</a>' if url else "")
1150
+ toggle_html = (f'<button class="src-toggle" type="button"><span class="more">展开</span>'
1151
+ f'<span class="less">收起</span>{CARET_SVG}</button>' if excerpt else "")
1152
+ body_html = f'<div class="src-body"><p>{esc(excerpt)}</p></div>' if excerpt else ""
1153
+ return (
1154
+ f'<figure class="src-card{dup_cls}" data-cite="{esc(cid)}">'
1155
+ f'<div class="src-head"><span class="src-ico" aria-hidden="true">{SRC_ICO_SVG}</span>'
1156
+ f'<figcaption class="src-title">{esc(title)}</figcaption></div>'
1157
+ f'<div class="src-meta"><span class="src-site" title="{esc(src)}"><span class="dot"></span>{esc(src)}</span>'
1158
+ f'{link_html}{toggle_html}</div>{body_html}</figure>'
1159
+ )
1160
+
1161
+
881
1162
  def render_section_cards(sections: List[Dict[str, Any]], sources: List[Dict[str, str]]) -> str:
1163
+ """正文渲染(原型复刻):chapter(h2)+ lead/para 段落 + 段后 src-card 溯源卡。
1164
+
1165
+ 溯源卡按段内角标顺序输出;同一材料在同段只出一张,跨段重复出现标记 dup-card(灰化)。
1166
+ """
1167
+ parts: List[str] = []
1168
+ first_para = True
882
1169
  source_ids = {s["id"] for s in sources}
883
- cards = []
884
- for sec in sections:
1170
+ for sec_idx, sec in enumerate(sections, 1):
1171
+ number, title_text = split_heading_number(sec["title"] or "")
1172
+ chapter_title = f"{number}、{title_text}" if (number and title_text) else (title_text or "")
885
1173
  sec_cites: List[str] = []
886
1174
  for b in sec["blocks"]:
887
1175
  for cid in b.get("cites", []):
888
1176
  if cid not in sec_cites:
889
1177
  sec_cites.append(cid)
890
- unbound_count = sum(1 for cid in sec_cites if cid not in source_ids)
891
- number, title_text = split_heading_number(sec["title"] or "")
892
- no_html = f'<span class="sec-no">{esc(number)}</span>' if number else ""
893
- title_html = f"<h3>{esc(title_text)}</h3>" if title_text else ""
894
- if sec_cites:
895
- badge_state = "bad" if unbound_count else ""
896
- badge_text = f"本章引用 {len(sec_cites)} 处" + (f" · {unbound_count} 处未绑定" if unbound_count else " · 已核验")
897
- badge_html = f'<span class="sec-badge {badge_state}">{esc(badge_text)}</span>'
898
- else:
1178
+ if chapter_title:
899
1179
  badge_html = ""
900
- head_html = f'<div class="sec-head">{no_html}{title_html}{badge_html}</div>' if (no_html or title_html or badge_html) else ""
901
-
902
- body_parts = []
1180
+ if sec_cites:
1181
+ unbound = sum(1 for cid in sec_cites if cid not in source_ids)
1182
+ state = "bad" if unbound else ""
1183
+ text = f"本章引用 {len(sec_cites)} 处" + (f" · {unbound} 处未绑定" if unbound else " · 已核验")
1184
+ badge_html = f'<span class="sec-badge {state}">{esc(text)}</span>'
1185
+ parts.append(f'<section class="chapter" id="sec-{sec_idx}">'
1186
+ f'<header class="ch-head"><h2>{esc(chapter_title)}</h2>{badge_html}</header>')
903
1187
  for b in sec["blocks"]:
904
1188
  if b["kind"] == "heading":
905
- inner_level = min(b["level"] + 1, 5)
906
- body_parts.append(f'<h{inner_level} class="doc-sub">{esc(b["text"])}</h{inner_level}>')
907
- elif b["kind"] == "list_item":
1189
+ parts.append(f'<p class="para"><b class="kw">{esc(b["text"])}</b></p>')
1190
+ first_para = False
1191
+ continue
1192
+ cls = "lead" if first_para else "para"
1193
+ first_para = False
1194
+ if b["kind"] == "list_item":
908
1195
  marker = f'{esc(b.get("number", "•"))}.' if b.get("numbered") else "•"
909
- body_parts.append(
910
- f'<div class="doc-item"><span class="doc-bullet">{marker}</span>'
911
- f'<div><p>{b["html"]}</p>{render_evidence_chips(b["cites"], sources)}</div></div>'
912
- )
1196
+ parts.append(f'<p class="{cls}"><b class="kw">{marker}</b> {b["html"]}</p>')
1197
+ elif b["kind"] == "hr":
1198
+ parts.append('<hr class="doc-divider">')
913
1199
  else:
914
- body_parts.append(f'<div class="doc-block"><p>{b["html"]}</p>{render_evidence_chips(b["cites"], sources)}</div>')
915
- cards.append(f'<section class="doc-sec">{head_html}<div class="sec-body">{"".join(body_parts)}</div></section>')
916
- return "\n".join(cards)
1200
+ parts.append(f'<p class="{cls}">{b["html"]}</p>')
1201
+ if chapter_title:
1202
+ parts.append("</section>")
1203
+ return "\n".join(parts)
1204
+
917
1205
 
1206
+ def strip_leading_chain(text: str, chain: List[str]) -> str:
1207
+ """剥掉段落文本开头与标题链各级重复的前缀。
918
1208
 
919
- def render_source_card(source: Dict[str, str], used: bool = True) -> str:
920
- if source.get("verified"):
921
- note = source.get("verify_note") or "摘录可比对,原文链接与云端存档可回看"
1209
+ 接口部分材料的"内容"字段自带段落标题前缀(个别还重复两遍),标题链已承载
1210
+ 位置信息,摘录开头再出现同级文本即冗余;逐级最长匹配剥离,无重复则原样返回。
1211
+ """
1212
+ t = (text or "").strip()
1213
+ cands = set()
1214
+ for lvl in chain:
1215
+ lvl = (lvl or "").strip()
1216
+ if lvl:
1217
+ cands.add(lvl)
1218
+ # 粘连标题(接口未给分隔符,如"建设交通强省5.民航和低空")拆出编号尾部子串
1219
+ parts = re.split(r"(?<=[\u4e00-\u9fff])(?=\d+[.、])", lvl)
1220
+ if len(parts) > 1 and parts[-1].strip():
1221
+ cands.add(parts[-1].strip())
1222
+ levels = sorted(cands, key=len, reverse=True)
1223
+ changed = True
1224
+ while changed and t:
1225
+ changed = False
1226
+ for lvl in levels:
1227
+ if t.startswith(lvl):
1228
+ t = t[len(lvl):].lstrip(" \n\r\t、。;;,,").strip()
1229
+ changed = True
1230
+ break
1231
+ return t
1232
+
1233
+
1234
+ def render_crumb(chain: List[str]) -> str:
1235
+ """面包屑标题链:文章 › 章 › 节(标题链是模型生成的结构化位置,核验核心抓手)。"""
1236
+ parts = [esc(level) for level in chain if level]
1237
+ if not parts:
1238
+ return ""
1239
+ return '<span class="crumb">' + ' <i>›</i> '.join(parts) + "</span>"
1240
+
1241
+
1242
+ def render_segments(source: Dict[str, Any]) -> str:
1243
+ """多段分块摘录:每段独立区块,各带自己的标题链——段落结构与位置直接可见。"""
1244
+ segments = source.get("segments") or []
1245
+ if not segments:
1246
+ return render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")
1247
+ blocks = []
1248
+ for seg in segments:
1249
+ text = (seg.get("text") or "").strip()
1250
+ if not text:
1251
+ continue
1252
+ blocks.append(f'<div class="seg-block">{render_crumb(seg.get("chain") or [])}'
1253
+ f'{render_excerpt_html(text)}</div>')
1254
+ return "".join(blocks) if blocks else render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")
1255
+
1256
+
1257
+ def render_source_card(source: Dict[str, str], for_print: bool = False) -> str:
1258
+ if not source.get("used", True):
1259
+ # 未引用召回材料:不标"已核验"(未进入正文核验流程),只标可否查看
1260
+ vk = ('<span class="sc-vk" style="color:var(--muted)">可查看全文</span>' if source.get("has_link")
1261
+ else '<span class="sc-vk warn">待补链接</span>')
1262
+ note_html = ""
1263
+ elif source.get("verified"):
1264
+ note = source.get("verify_note") or "摘录可比对,原文链接与知识专库可回看"
922
1265
  vk = f'<span class="sc-vk ok" title="{esc(note)}">✓ 已核验</span>'
923
1266
  note_html = f'<div class="sc-vnote">{esc(short(note, 90))}</div>' if source.get("verify_note") else ""
924
1267
  else:
925
- reason = "接口未返回原文链接" if not source.get("has_link") else "摘录待补"
926
- vk = f'<span class="sc-vk warn" title="接口未提供,非核验失败">◐ {reason}</span>'
1268
+ reason = "待补原文链接" if not source.get("has_link") else "待补摘录"
1269
+ vk = f'<span class="sc-vk warn">◐ {reason}</span>'
927
1270
  note_html = ""
928
- links = render_source_links(source.get("url"), source.get("policy_url", ""))
929
- meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area")] if v)
930
- # 标题链:段落标题即该段在原文件中的章节位置(悬停见含文章标题的完整链);无则如实不显示
931
- chain_html = ""
932
- if source.get("doc_section"):
933
- chain_html = (f'<div class="sc-chain" title="{esc("原文中的位置:" + source["chain_full"])}">'
934
- f'标题:{esc(source["doc_section"])}</div>')
935
- section_html = f'<div class="sc-section">支撑:{esc(source["section"])}</div>' if source.get("section") else ""
936
- # 高可信徽标:仅"发布日期可信度=高"(模型治理入库、标题模型精抽);其余不标
1271
+ links = render_source_links(source.get("url"), source.get("policy_url", ""), source.get("snapshot", ""), source.get("link_dead", False))
1272
+ # 关键性行:有文号(接口 policyFiles 匹配)时"文号 · 数据源 · 日期",否则"数据源 · 日期"
1273
+ meta_parts = [v for v in [source.get("doc_number"), source.get("agency"), source.get("date"), source.get("area")]
1274
+ if v and v != "未知来源"]
1275
+ meta = " | ".join(meta_parts)
1276
+ # 高可信徽标:仅"发布日期可信度=高"(模型治理入库、标题模型精抽)的材料;"较高"(门户抓取)不标。
937
1277
  conf_badge = ""
938
1278
  if source.get("conf") == "高":
939
1279
  conf_badge = ('<span class="sc-conf" title="发布日期可信度:高。内容经模型治理入库,'
940
1280
  '标题为模型从原文动态抽取,非规则提取">高可信</span>')
941
- # 摘录上方标注:内容为接口返回的原文原段,非 AI 生成
942
- excerpt_tag = '<div class="sc-extag">▍ 原文原段(非 AI 生成)</div>'
943
1281
  # 已引用材料显示角标编号;未引用召回材料显示"未引用"灰标(不占正文角标号)
944
- id_html = f'<span class="sc-id">[{esc(source["id"])}]</span>' if used else '<span class="sc-unused">未引用</span>'
945
- unused_attr = "" if used else ' data-unused="1"'
1282
+ id_html = f'<span class="sc-id">[{esc(source["id"])}]</span>' if source.get("used", True) else '<span class="sc-unused">未引用</span>'
1283
+ body_html = (f'<div class="sc-head">{id_html}'
1284
+ f'{conf_badge}{vk}</div>'
1285
+ f'<h4>{esc(source.get("title"))}</h4>'
1286
+ f'<div class="sc-meta">{esc(meta)}</div>'
1287
+ f'{note_html}'
1288
+ f'{render_segments(source)}'
1289
+ f'{links}')
1290
+ if for_print:
1291
+ # 打印附录版:无交互属性,避免与专库卡片 id 冲突
1292
+ return f'<article class="scard print-only">{body_html}</article>'
1293
+ unused_attr = "" if source.get("used", True) else ' data-unused="1"'
946
1294
  return (
947
- f'<article class="scard" id="src-{esc(source["id"])}" data-cite-id="{esc(source["id"])}"{unused_attr}>'
948
- f'<div class="sc-head">{id_html}{conf_badge}{vk}</div>'
949
- f'<h4>{esc(source.get("title"))}</h4>'
950
- f'<div class="sc-meta">{esc(meta)}</div>'
951
- f'{chain_html}{section_html}{note_html}'
952
- f'{excerpt_tag}'
953
- f'{render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")}'
954
- f'<div class="sc-more" role="button" tabindex="0"></div>'
955
- f'{links}</article>'
1295
+ f'<article class="scard" id="src-{esc(source["id"])}" '
1296
+ f'data-cite-id="{esc(source["id"])}"{unused_attr}>{body_html}</article>'
956
1297
  )
957
1298
 
958
1299
 
959
- def render_sources_panel(sources: List[Dict[str, str]], used: List[str], archive_zone: str = "") -> str:
1300
+ def render_process_bar(stats: Dict[str, Any], verification: Dict[str, Any]) -> str:
1301
+ """过程回顾条:静态回放真实流程。无思考流数据,不做"深度思考"步骤。"""
1302
+ ov = verification["overall"]
1303
+ tr = verification["traceability"]
1304
+ first_query = stats["conds"][0]["key"] if stats["conds"] else ""
1305
+ detail_rows = "".join(
1306
+ f'<div class="pd-row"><b>{esc(row["key"])}</b>'
1307
+ f'<span>召回 {row["total"]} 条 · 答案采用 {row["used"]} 条</span></div>'
1308
+ for row in stats["conds"]
1309
+ ) or '<div class="pd-row"><span>本次问答未记录用户问题</span></div>'
1310
+ detail_hint = f'{esc(short(first_query, 26))}…' if (stats["n_searches"] > 1 and first_query) else "查看召回明细"
1311
+ if stats["n_searches"] > 1:
1312
+ step1_sub = f"共 {stats['n_searches']} 路检索 · {detail_hint}"
1313
+ elif first_query:
1314
+ step1_sub = esc(short(first_query, 26))
1315
+ else:
1316
+ step1_sub = "深知可信咨询"
1317
+ step4_state = "done" if ov["passed"] else "bad"
1318
+ step4_icon = "✓" if ov["passed"] else "!"
1319
+ step4_label = "核验完成" if ov["passed"] else "核验未完全通过"
1320
+ step4_sub = "结论:答案依据逐条对过原文" if ov["passed"] else esc(short(";".join(ov["reasons"]) or "见核验报告单", 30))
1321
+ return f"""
1322
+ <section class="process" aria-label="生成过程回顾">
1323
+ <div class="p-head"><b>过程回顾</b><span>数字来自本次任务的真实记录</span></div>
1324
+ <ol class="p-steps">
1325
+ <li class="p-step expandable" id="p-step-search" role="button" tabindex="0" title="展开各路检索明细">
1326
+ <span class="p-no">1</span>
1327
+ <div class="p-txt"><b>可信问答 {stats['n_searches']} 次</b><i>{step1_sub}</i></div>
1328
+ </li>
1329
+ <li class="p-arrow" aria-hidden="true">›</li>
1330
+ <li class="p-step">
1331
+ <span class="p-no">2</span>
1332
+ <div class="p-txt"><b>材料入库 {stats['n_materials']} 条</b><i>答案采用 {stats['used_count']} · 召回未采用 {stats['unused_count']}</i></div>
1333
+ </li>
1334
+ <li class="p-arrow" aria-hidden="true">›</li>
1335
+ <li class="p-step">
1336
+ <span class="p-no">3</span>
1337
+ <div class="p-txt"><b>逐条比对原文</b><i>依据溯源 {tr['passed']}/{tr['total']} · 摘录可比对</i></div>
1338
+ </li>
1339
+ <li class="p-arrow" aria-hidden="true">›</li>
1340
+ <li class="p-step {step4_state}">
1341
+ <span class="p-no">{step4_icon}</span>
1342
+ <div class="p-txt"><b>{esc(step4_label)}</b><i>{step4_sub}</i></div>
1343
+ </li>
1344
+ </ol>
1345
+ <div class="p-detail" id="p-detail">{detail_rows}</div>
1346
+ </section>"""
1347
+
1348
+
1349
+ def render_library_view(sources: List[Dict[str, str]], hot_terms: List[str]) -> str:
1350
+ """材料专库全屏视图:大搜索 + 热词 + 引用状态筛选 tabs + 材料卡列表。
1351
+
1352
+ 统一问答接口无检索条件分组字段(search_key),tabs 只有 全部/未引用 两态——
1353
+ 这是接口能力差异的如实退化,不虚构检索分组。
1354
+ """
960
1355
  if not sources:
961
- return '<aside class="sources"><h3>核验材料</h3><p class="empty">接口返回中未识别到可展示的材料。</p></aside>'
962
- used_set = set(used)
963
- cited_sources = sorted((s for s in sources if s["id"] in used_set), key=lambda s: int(s["id"]))
964
- cited_cards = [render_source_card(s, used=True) for s in cited_sources]
965
- uncited = sorted((s for s in sources if s["id"] not in used_set), key=lambda s: int(s["id"]))
966
- uncited_html = ""
967
- if uncited:
968
- uncited_cards = "".join(render_source_card(s, used=False) for s in uncited)
969
- # 不用 <details> 折叠:部分宿主(WorkBuddy 等)的 HTML 预览服务会改写折叠区导致卡片丢失
970
- uncited_html = (
971
- '<div class="uncited-group"><div class="ug-title">未引用素材('
972
- f'{len(uncited)} 条 · 接口召回但答案未采用,供比对参考,不计入核验结论)</div>'
973
- f'<div class="uncited-list">{uncited_cards}</div></div>'
974
- )
975
- # "已核验"只统计正文引用材料:未引用召回未进入正文核验流程
976
- verified_count = sum(1 for s in cited_sources if s.get("verified"))
977
- badge = "全部已核验" if verified_count == len(cited_sources) else f"{verified_count}/{len(cited_sources)} 已核验"
978
- return (
979
- '<aside class="sources" id="sources-panel" aria-label="核验材料面板">'
980
- '<a class="back-doc" href="#doc-top">↑ 返回核验报告单</a>'
981
- f'<h3>核验材料({len(cited_sources)} 条已引用 · {esc(badge)})</h3>'
982
- '<div class="src-tip">点击正文角标 [1] 定位材料原文并核对</div>'
983
- '<input class="src-search" type="search" placeholder="搜索标题 / 来源 / 摘录…" aria-label="搜索来源">'
984
- f'<div class="src-list">{"".join(cited_cards)}{uncited_html}</div>'
985
- f'{archive_zone}'
986
- '</aside>'
987
- )
1356
+ return ('<section class="view" id="view-library" aria-label="材料专库">'
1357
+ '<div class="lib-empty">接口返回中未识别到可展示的材料。</div></section>')
1358
+ used_sources = [s for s in sources if s.get("used", True)]
1359
+ unused_sources = [s for s in sources if not s.get("used", True)]
1360
+
1361
+ # tabs = 引用状态筛选(全部 / 未引用),数字真实统计;统一问答无检索分组字段,不虚构分组
1362
+ tabs = [f'<button class="on" data-cond="" type="button">全部({len(sources)})</button>']
1363
+ if unused_sources:
1364
+ tabs.append(f'<button data-cond="__unused__" type="button">未引用({len(unused_sources)})</button>')
1365
+
1366
+ hot_html = ""
1367
+ if hot_terms:
1368
+ hot_items = "".join(f'<button class="hot-term" type="button">{esc(term)}</button>' for term in hot_terms)
1369
+ hot_html = f'<div class="hot-terms" aria-label="热门搜索词"><span class="hot-label">大家都在搜</span>{hot_items}</div>'
1370
+
1371
+ cards_html = "".join(render_source_card(s) for s in used_sources)
1372
+ cards_html += "".join(render_source_card(s) for s in unused_sources)
1373
+
1374
+ cited_verified = sum(1 for s in used_sources if s.get("verified"))
1375
+ badge = "全部已核验" if used_sources and cited_verified == len(used_sources) else f"{cited_verified}/{len(used_sources)} 已核验"
1376
+ return f"""
1377
+ <section class="view" id="view-library" aria-label="材料专库">
1378
+ <div class="lib-head">
1379
+ <div class="lib-title"><b>材料专库</b>
1380
+ <span>共 {len(sources)} 条 · 已引用 {len(used_sources)} · {esc(badge)}</span>
1381
+ </div>
1382
+ <div class="lib-searchWrap">
1383
+ <span class="lib-searchIcon" aria-hidden="true">⌕</span>
1384
+ <input class="lib-search" type="search" placeholder="搜索标题 / 来源 / 摘录…" aria-label="搜索材料">
1385
+ </div>
1386
+ {hot_html}
1387
+ <div class="lib-tabs" role="tablist" aria-label="按检索分组筛选">{"".join(tabs)}</div>
1388
+ </div>
1389
+ <div class="lib-list" id="lib-list">{cards_html}</div>
1390
+ <div class="lib-empty hide" id="lib-empty">没有符合当前筛选的材料。</div>
1391
+ <div class="lib-foot">材料来源:深知可信咨询 · 每条摘录均取自原文原段</div>
1392
+ </section>"""
1393
+
1394
+
1395
+ def render_toc(sections: List[Dict[str, Any]]) -> str:
1396
+ """章节目录(滚动 spy):长报告(≥6 节)显示,桌面端左侧浮动。"""
1397
+ if len(sections) < 6:
1398
+ return ""
1399
+ items = []
1400
+ for i, sec in enumerate(sections, 1):
1401
+ number, title_text = split_heading_number(sec["title"] or "")
1402
+ label = f"{number} {title_text}" if (number and title_text) else (title_text or f"第 {i} 节")
1403
+ items.append(f'<a href="#sec-{i}">{esc(short(label, 16))}</a>')
1404
+ return f'<nav class="toc" aria-label="章节目录">{"".join(items)}</nav>'
1405
+
1406
+
1407
+ def render_print_appendix(sources: List[Dict[str, str]]) -> str:
1408
+ """打印归档附录:全部材料卡全展开(屏幕不显示,仅打印)。"""
1409
+ if not sources:
1410
+ return ""
1411
+ cards = "".join(render_source_card(s, for_print=True) for s in sources)
1412
+ return (f'<section class="print-appendix" aria-label="核验材料附录(打印归档)">'
1413
+ f'<h3>核验材料(全 {len(sources)} 条)</h3>{cards}</section>')
1414
+
1415
+
1416
+ def extract_trace_archives(payload: Dict[str, Any]) -> List[str]:
1417
+ """收集"云端溯源存档"链接。
1418
+
1419
+ 统一问答接口不返回可再浏览的知识专库 knowledgeBase 链接,实际提供
1420
+ traceUrl——云平台为本次问答生成的接口侧可信溯源报告。两种字段都兼容,
1421
+ 避免接口字段调整时丢链接。
1422
+ """
1423
+ content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
1424
+ values: List[str] = []
1425
+ for value in (payload.get("knowledgeBases"), content.get("knowledgeBases"), payload.get("knowledgeBase"), content.get("knowledgeBase")):
1426
+ if isinstance(value, list):
1427
+ values.extend(str(item).strip() for item in value if str(item).strip())
1428
+ elif isinstance(value, str) and value.strip():
1429
+ values.append(value.strip())
1430
+ trace = first_str(payload.get("traceUrl"), payload.get("trace_url"), content.get("traceUrl"), content.get("trace_url"))
1431
+ if trace:
1432
+ values.append(trace)
1433
+ return list(dict.fromkeys(values))
988
1434
 
989
1435
 
990
1436
  def render_archive_zone(archive_urls: List[str], source_count: int) -> str:
@@ -1022,23 +1468,774 @@ def safe_output_filename(question: str, timestamp: datetime, fallback: str = "dk
1022
1468
  if not normalized:
1023
1469
  normalized = fallback
1024
1470
  suffix = timestamp.strftime("%Y%m%d_%H%M")
1025
- stem = normalized[:24].strip("._-") or fallback
1471
+ stem = normalized[:32].strip("._-") or fallback
1026
1472
  return f"{stem}_可信核验报告_{suffix}{suffix_ext}"
1027
1473
 
1028
1474
 
1475
+ # ============================================================
1476
+ # 样式与脚本(独立常量,避免模板转义)
1477
+ # ============================================================
1478
+
1479
+ PAGE_CSS = """
1480
+ :root{
1481
+ --navy:#20242c; --navy-2:#3a4152;
1482
+ --ink:#1f2328; --muted:#6b7280; --line:#e5e7eb; --line-strong:#cbd2dd;
1483
+ --brand:#6512ad; --brand-2:#8b5cf6; --brand-soft:#ede9fe;
1484
+ --grad:linear-gradient(135deg,#6512ad,#8b5cf6);
1485
+ --policy:#0f9d6e; --policy-soft:#e3f5ee;
1486
+ --case:#9a6700; --case-soft:#fdf3dc;
1487
+ --ref:#4b5563; --ref-soft:#f0f1f4;
1488
+ --warn:#9a6700; --danger:#e5484d; --ok:#0f9d6e;
1489
+ --shadow-1:0 1px 3px rgba(24,20,40,.04),0 8px 30px rgba(24,20,40,.08);
1490
+ --shadow-2:0 3px 9px rgba(101,18,173,.22),0 14px 36px rgba(24,20,40,.14);
1491
+ --primary-bright:#8b5cf6; --tint:#f3edfc; --tint-2:#faf7ff; --tint-bd:#e9dff9;
1492
+ --tint-strong:#e6d9f9; --tint-bd-strong:#d3bef0; --body-c:#3b4152; --card-bd:#e8e6f0;
1493
+ }
1494
+ *{box-sizing:border-box}
1495
+ html{scroll-behavior:smooth}
1496
+ body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI",Roboto,"PingFang SC","HarmonyOS Sans SC","Microsoft YaHei",sans-serif;
1497
+ color:var(--ink);background:#f4f5f7;line-height:1.75;font-size:14.5px}
1498
+ a{color:var(--brand)}
1499
+
1500
+ /* ===== 顶栏 ===== */
1501
+ .topbar{position:sticky;top:0;z-index:50;display:flex;justify-content:space-between;align-items:center;gap:10px;
1502
+ padding:9px 22px;background:rgba(255,255,255,.92);backdrop-filter:blur(10px);
1503
+ border-bottom:1px solid var(--line)}
1504
+ .tb-left{display:flex;align-items:center;gap:10px;min-width:0}
1505
+ .tb-stamp{flex:none;font-size:12.5px;font-weight:800;color:var(--navy);letter-spacing:4px;text-indent:4px}
1506
+ .tb-stamp::before,.tb-stamp::after{content:"";display:inline-block;width:22px;border-top:1px solid var(--line-strong);
1507
+ vertical-align:middle;margin:0 6px}
1508
+ .tb-title{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted);font-size:13px}
1509
+ .tb-right{display:flex;align-items:center;gap:8px;flex:none}
1510
+ .view-switch{display:inline-flex;border:1px solid var(--line);border-radius:999px;overflow:hidden;background:#fff}
1511
+ .view-switch button{border:0;background:transparent;color:var(--muted);font-size:12.5px;font-weight:700;
1512
+ padding:5px 14px;cursor:pointer}
1513
+ .view-switch button.on{background:var(--grad);color:#fff}
1514
+ .tb-tools{display:flex;gap:6px}
1515
+ .tb-tools button{border:1px solid var(--line);border-radius:8px;background:#fff;color:#3b3550;
1516
+ font-size:12.5px;font-weight:700;padding:5px 11px;cursor:pointer}
1517
+ .tb-tools button:hover{border-color:var(--brand-2);color:var(--brand)}
1518
+ .tb-tools button[aria-pressed="true"]{background:var(--grad);border-color:var(--brand);color:#fff}
1519
+ .print-menu{position:relative;display:inline-flex}
1520
+ .print-drop{position:absolute;top:calc(100% + 6px);right:0;z-index:70;display:flex;flex-direction:column;gap:4px;
1521
+ min-width:190px;padding:6px;background:#fff;border:1px solid var(--tint-bd);border-radius:10px;
1522
+ box-shadow:var(--shadow-2);text-align:left}
1523
+ .print-drop[hidden]{display:none}
1524
+ .print-drop button{border:0;background:none;border-radius:7px;color:var(--ink);font-size:12.5px;font-weight:600;
1525
+ padding:8px 12px;cursor:pointer;text-align:left;font-family:inherit;white-space:nowrap}
1526
+ .print-drop button:hover{background:var(--tint);color:var(--brand)}
1527
+ .progress{position:absolute;left:0;right:0;bottom:-1px;height:2px;background:transparent}
1528
+ .progress i{display:block;height:100%;width:0;background:linear-gradient(90deg,#6512ad,#8b5cf6)}
1529
+
1530
+ /* ===== Hero ===== */
1531
+ .hero{position:relative;background:linear-gradient(180deg,#fbfaff 0%,#f7f4fd 100%);
1532
+ color:var(--ink);padding:32px 22px 58px;text-align:center;border-bottom:1px solid var(--line)}
1533
+ .r-badge{display:inline-flex;align-items:center;gap:14px;margin:0 0 8px;
1534
+ background:var(--grad);color:#fff;border-radius:999px;padding:4px 22px;
1535
+ font-size:15px;font-weight:800;letter-spacing:7px;text-indent:7px;line-height:1.6;
1536
+ box-shadow:0 2px 8px rgba(101,18,173,.22)}
1537
+ .hero h1{margin:0 0 10px;font-size:24px;line-height:1.5;max-width:860px;margin-left:auto;margin-right:auto;color:var(--ink)}
1538
+ .hero .meta{color:var(--muted);font-size:13px;letter-spacing:.5px}
1539
+ .hero-switch{margin-top:16px;display:flex;justify-content:center}
1540
+ .hero-switch .view-switch{border-color:#d9c9f4;background:#fff;box-shadow:0 1px 3px rgba(24,20,40,.04)}
1541
+ .hero-switch .view-switch button{color:#70678a;padding:6px 22px;font-size:13px}
1542
+ .hero-switch .view-switch button.on{background:var(--grad);color:#fff}
1543
+
1544
+ /* ===== 容器与视图 ===== */
1545
+ .container{max-width:1080px;margin:0 auto;padding:0 18px}
1546
+ .app[data-view="library"] #view-report{display:none}
1547
+ #view-library{display:none}
1548
+ .app[data-view="library"] #view-library{display:block}
1549
+
1550
+ /* ===== 过程回顾条 ===== */
1551
+ .process{background:#fff;border:1px solid var(--line);border-radius:14px;box-shadow:var(--shadow-1);
1552
+ padding:15px 20px 13px;margin:-36px auto 16px;position:relative}
1553
+ .p-head{display:flex;align-items:baseline;gap:10px;margin-bottom:10px}
1554
+ .p-head b{font-size:14.5px;color:var(--navy);letter-spacing:1px}
1555
+ .p-head span{font-size:11.5px;color:var(--muted)}
1556
+ .p-steps{list-style:none;display:flex;align-items:stretch;gap:8px;margin:0;padding:0;flex-wrap:wrap}
1557
+ .p-step{display:flex;gap:9px;align-items:center;min-width:0;flex:1 1 150px;
1558
+ border:1px solid var(--line);border-radius:10px;padding:8px 11px;background:#fafbfc}
1559
+ .p-no{flex:none;width:24px;height:24px;border-radius:50%;background:var(--grad);color:#fff;
1560
+ display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:800}
1561
+ .p-txt{min-width:0}
1562
+ .p-txt b{display:block;font-size:12.8px;color:var(--navy);line-height:1.5}
1563
+ .p-txt i{display:block;font-style:normal;font-size:11px;color:var(--muted);line-height:1.5;
1564
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1565
+ .p-step.done{border-color:#bfe8da;background:#f2faf7}
1566
+ .p-step.done .p-no{background:var(--ok)}
1567
+ .p-step.bad{border-color:#f6c9cb;background:#fffafa}
1568
+ .p-step.bad .p-no{background:var(--danger)}
1569
+ .p-step.expandable{cursor:pointer}
1570
+ .p-step.expandable:hover{border-color:var(--brand)}
1571
+ .p-arrow{align-self:center;color:#b9c6d9;font-size:16px;font-weight:700;flex:none}
1572
+ .p-detail{display:none;margin-top:10px;border-top:1px dashed var(--line-strong);padding-top:9px}
1573
+ .p-detail.show{display:block}
1574
+ .pd-row{display:flex;justify-content:space-between;gap:14px;padding:3px 2px;font-size:12.3px;flex-wrap:wrap}
1575
+ .pd-row b{color:var(--navy);font-weight:700;min-width:0}
1576
+ .pd-row span{color:var(--muted)}
1577
+
1578
+ /* ===== 核验报告视图 ===== */
1579
+ #view-report{padding-bottom:26px}
1580
+ .warn-box{margin:0 0 16px;padding:13px 16px;border:1.5px solid var(--danger);border-radius:10px;
1581
+ background:#fdf3f3;color:#8f2626;font-size:13.5px;line-height:1.7}
1582
+ .verify{margin:0 0 16px;background:#fff;border:1px solid #bfe8da;border-left:4px solid var(--ok);
1583
+ border-radius:14px;padding:16px 20px;box-shadow:var(--shadow-1)}
1584
+ .verify.fail{border-color:#f6c9cb;border-left-color:var(--danger);background:#fffafa}
1585
+ .v-head{display:flex;align-items:center;gap:9px;font-size:15px;font-weight:800;color:var(--ok)}
1586
+ .verify.fail .v-head{color:var(--danger)}
1587
+ .v-shield{display:inline-flex;width:22px;height:22px;border-radius:50%;background:var(--ok);color:#fff;
1588
+ align-items:center;justify-content:center;font-size:12px;flex:none}
1589
+ .verify.fail .v-shield{background:var(--danger)}
1590
+ .v-stamp{margin-left:auto;font-size:11px;border:1.5px solid var(--ok);color:var(--ok);border-radius:5px;
1591
+ padding:1px 8px;letter-spacing:2px;flex:none}
1592
+ .v-stamp.bad{border-color:var(--danger);color:var(--danger)}
1593
+ .v-reasons{margin-top:6px;font-size:12.5px;color:var(--danger)}
1594
+ .v-grid{display:grid;grid-template-columns:1fr 1fr;gap:4px 20px;margin-top:10px}
1595
+ .vi{display:flex;gap:7px;align-items:baseline;font-size:12.5px;color:#3b3550;line-height:1.7;min-width:0}
1596
+ .vi .s{font-weight:800;flex:none}
1597
+ .vi .s.ok{color:var(--ok)}
1598
+ .vi .s.warn{color:var(--warn)}
1599
+ .vi .s.fail{color:var(--danger)}
1600
+ .vi .s.man{color:var(--case)}
1601
+ .vi .s.none{color:var(--muted)}
1602
+ .vi .d{color:var(--muted);min-width:0}
1603
+ .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}
1604
+
1605
+ /* 正文(原型复刻):章节 / 段落 / 角标 / 句后溯源卡 */
1606
+ .doc-paper{background:#fff;border-radius:14px;box-shadow:var(--shadow-1);padding:26px 34px 22px;margin:0 0 16px}
1607
+ .chapter{margin:40px 0 0}
1608
+ .chapter:first-child{margin-top:6px}
1609
+ .ch-head{display:flex;align-items:center;gap:14px;margin-bottom:18px;scroll-margin-top:86px}
1610
+ .ch-head h2{font-size:19.5px;font-weight:700;color:var(--ink);letter-spacing:.2px;line-height:1.4;flex:1;min-width:0}
1611
+ .ch-head::after{content:"";flex-basis:110px;height:1px;background:linear-gradient(90deg,#e9dff9,transparent);order:3;flex-grow:0;flex-shrink:0}
1612
+ .ch-head .sec-badge{order:4;flex:none;font-size:11.5px;color:var(--ok);background:var(--policy-soft);border-radius:6px;padding:2px 9px;font-weight:700}
1613
+ .ch-head .sec-badge.bad{color:var(--danger);background:#fdecec}
1614
+ @media(min-width:1000px){.ch-head::after{flex-basis:200px}}
1615
+ .lead{font-size:15.5px;line-height:1.95;color:var(--body-c);margin:14px 0;padding:0 2px;word-break:break-word}
1616
+ .para{font-size:15.5px;line-height:1.95;color:var(--body-c);margin:14px 0;padding:0 2px;word-break:break-word}
1617
+ .para b.kw,.lead b.kw{font-weight:600;color:var(--ink)}
1618
+ .doc-divider{border:0;border-top:1px solid var(--line);margin:18px 0}
1619
+ code{padding:1px 5px;border-radius:4px;background:#f3f4f6;color:#3f3d52;
1620
+ font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}
1621
+ .tbl-wrap{max-width:100%;overflow-x:auto;margin:8px 0}
1622
+ .data-tbl{width:100%;border-collapse:collapse;border:1px solid var(--line);font-size:13px}
1623
+ .data-tbl th,.data-tbl td{border:1px solid var(--line);padding:8px 10px;text-align:left;vertical-align:top;line-height:1.65}
1624
+ .data-tbl th{background:#f5f6f8;font-weight:700;color:#3f3d52}
1625
+
1626
+ /* 角标 */
1627
+ .cite{display:inline-flex;align-items:center;justify-content:center;min-width:19px;height:18px;padding:0 5px;margin:0 2px 2px 3px;font-size:10.5px;font-weight:700;font-variant-numeric:tabular-nums;color:var(--brand);background:var(--tint);border:1px solid var(--tint-bd);border-radius:5px;cursor:pointer;vertical-align:super;line-height:1;transition:.14s;position:relative;top:-1px;user-select:none;font-family:inherit}
1628
+ .cite:hover{background:var(--brand);border-color:var(--brand);color:#fff}
1629
+ .cite.flash{background:var(--primary-bright);border-color:var(--primary-bright);color:#fff}
1630
+ .cite.unresolved{color:var(--danger);border-color:#f6c9cb;background:#fdf7f7}
1631
+
1632
+ /* 段落级证据 chips(引文卡) */
1633
+ /* 行内引文 jb(原型复刻):角标后小胶囊,点击展开块级卡(溯源原文+引文摘录) */
1634
+ .jb{display:inline-block;vertical-align:top;max-width:100%;margin:2px 4px 2px 0;position:relative}
1635
+ .jb.active{display:block;margin:12px 0 2px;max-width:none}
1636
+ .jb-name{display:inline-flex;align-items:center;gap:6px;max-width:380px;min-height:26px;padding:4px 13px;border-radius:13px;border:1px solid var(--tint-bd);background:var(--tint);color:#540e8f;font-family:inherit;font-size:12px;font-weight:600;line-height:18px;cursor:pointer;transition:.16s;white-space:nowrap}
1637
+ .jb-name:hover{background:#fff;border-color:var(--brand)}
1638
+ .jb-name .jb-id{flex:none;width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-style:normal;font-size:10.5px;font-weight:800;font-variant-numeric:tabular-nums;color:#fff;background:linear-gradient(135deg,#6512ad,#8b5cf6);box-shadow:0 1px 3px rgba(101,18,173,.28)}
1639
+ .jb-name .jb-txt{overflow:hidden;text-overflow:ellipsis}
1640
+ .jb-name svg{flex:none;transition:transform .2s}
1641
+ .jb.active .jb-name{max-width:100%;white-space:normal;line-height:20px;color:var(--ink);background:#fff;font-size:13.5px;font-weight:700;text-align:left}
1642
+ .jb.active .jb-name svg{transform:rotate(180deg)}
1643
+ .jb-src{display:inline-flex;align-items:center;gap:5px;min-height:26px;padding:4px 13px;border-radius:13px;background:linear-gradient(135deg,#6512ad,#8b5cf6);color:#fff;font-size:11px;font-weight:600;text-decoration:none;box-shadow:0 2px 8px rgba(101,18,173,.22);transition:.15s;flex-shrink:0}
1644
+ .jb-src:hover{filter:brightness(1.1)}
1645
+ .jb-src span{max-width:210px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1646
+ .jb-body{display:none}
1647
+ .jb.active .jb-body{position:relative;display:block;margin-top:13px;background:#fff;border:1px solid var(--card-bd);border-radius:12px;padding:13px 15px;box-shadow:var(--shadow-1)}
1648
+ .jb-head{display:flex;align-items:center;gap:9px;flex-wrap:wrap}
1649
+ .jb-label{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;font-weight:700;color:var(--brand);letter-spacing:.5px}
1650
+ .jb-label svg{flex:none}
1651
+ .jb-site{display:inline-flex;align-items:center;gap:6px;font-size:11.5px;color:#70678a;background:#f6f4fa;
1652
+ border:1px solid var(--line);border-radius:999px;padding:3.5px 10px;max-width:100%;overflow:hidden;
1653
+ text-overflow:ellipsis;white-space:nowrap;margin:0 0 2px}
1654
+ .jb-site .dot{width:6px;height:6px;border-radius:50%;background:linear-gradient(135deg,#6512ad,#8b5cf6);flex-shrink:0}
1655
+ .jb-quote{display:flex;gap:9px;align-items:flex-start;margin-top:9px;padding:10px 12px;background:#faf9fd;border:1px solid var(--line);border-radius:9px;text-decoration:none;transition:.15s;cursor:pointer}
1656
+ .jb-quote{cursor:pointer}
1657
+ .jb-quote:hover{border-color:var(--brand);background:#f7f4fc}
1658
+ .jb-no{flex:none;width:17px;height:17px;margin-top:4px;border-radius:4px;background:var(--tint);border:1px solid var(--tint-bd);color:var(--brand);font-size:10px;font-weight:700;font-style:normal;display:flex;align-items:center;justify-content:center}
1659
+ .jb-quote span{font-size:12.5px;line-height:1.95;color:#4b4658;word-break:break-word;text-align:justify}
1660
+ .jb-quote .sc-excerpt{flex:1;min-width:0;display:block}
1661
+ a.jb-quote{text-decoration:none}
1662
+ .jb.flash{animation:cardFlash 1.6s ease}
1663
+ .ev-title{font-weight:700;font-size:13.5px;margin-bottom:4px;color:var(--ink)}
1664
+ .ev-meta{color:var(--muted);font-size:12px;margin-bottom:6px}
1665
+ .ev-chip summary{display:inline-flex;align-items:center;gap:5px;max-width:100%;min-height:26px;padding:4px 13px;
1666
+ border-radius:13px;color:#fff;background:var(--grad);cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
1667
+ list-style:none;font-size:11px;font-weight:600;box-shadow:0 2px 8px rgba(101,18,173,.22);transition:.15s}
1668
+ .ev-chip summary:hover{filter:brightness(1.12)}
1669
+ .ev-chip summary::-webkit-details-marker{display:none}
1670
+ .ev-chip summary b{color:#fff;margin-right:2px;font-weight:700}
1671
+
1672
+ .ev-title{font-weight:700;font-size:13.5px;margin-bottom:4px;color:var(--navy)}
1673
+ .ev-meta{color:var(--muted);font-size:12px;margin-bottom:6px}
1674
+ .ev-panel p{margin:0 0 8px;color:#3f3d52;font-size:12.8px;line-height:1.7}
1675
+ .sc-links{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}
1676
+ .sc-links span{display:inline-flex}
1677
+ .sc-links a{display:inline-flex;align-items:center;min-height:24px;padding:3px 9px;border-radius:6px;
1678
+ background:var(--brand-soft);color:var(--brand);font-weight:700;text-decoration:none;font-size:12px}
1679
+
1680
+ /* ===== 材料专库视图 ===== */
1681
+ #view-library{padding:26px 0 30px}
1682
+ .lib-head{max-width:860px;margin:0 auto 16px;text-align:center}
1683
+ .lib-title{margin-bottom:14px}
1684
+ .lib-title b{font-size:17px;color:var(--navy);letter-spacing:2px}
1685
+ .lib-title span{display:block;font-size:12px;color:var(--muted);margin-top:2px}
1686
+ .lib-searchWrap{position:relative;max-width:620px;margin:0 auto}
1687
+ .lib-searchIcon{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#a6adbd;font-size:16px;font-weight:700}
1688
+ .lib-search{width:100%;padding:11px 16px 11px 38px;border:1.5px solid var(--line-strong);border-radius:999px;
1689
+ font-size:14px;background:#fff;box-shadow:var(--shadow-1);outline:none}
1690
+ .lib-search:focus{border-color:var(--brand-2);box-shadow:0 0 0 3px rgba(139,92,246,.18)}
1691
+ .hot-terms{display:flex;flex-wrap:wrap;justify-content:center;gap:7px;margin-top:12px;align-items:center}
1692
+ .hot-label{font-size:12px;color:var(--muted)}
1693
+ .hot-term{border:0;border-radius:999px;background:var(--brand-soft);color:var(--brand);
1694
+ font-size:12.3px;font-weight:700;padding:3px 13px;cursor:pointer}
1695
+ .hot-term:hover{background:var(--grad);color:#fff}
1696
+ .lib-tabs{display:flex;flex-wrap:wrap;justify-content:center;gap:6px;margin-top:14px}
1697
+ .lib-tabs button{border:1px solid var(--line);border-radius:999px;background:#fff;color:var(--muted);
1698
+ padding:4px 13px;font-size:12.3px;cursor:pointer}
1699
+ .lib-tabs button.on{background:var(--grad);border-color:var(--brand);color:#fff;font-weight:700}
1700
+ .lib-list{max-width:860px;margin:0 auto;display:grid;grid-template-columns:1fr;gap:14px}
1701
+ .lib-empty{max-width:860px;margin:30px auto;text-align:center;color:var(--muted);font-size:13.5px}
1702
+ .lib-empty.hide{display:none}
1703
+ .lib-foot{text-align:center;color:var(--muted);font-size:11.5px;padding:18px 0 0;line-height:1.8}
1704
+
1705
+ /* ===== 材料卡 ===== */
1706
+ .scard{border:1px solid var(--line);border-left-width:3px;border-radius:12px;padding:14px 18px;
1707
+ background:#fff;box-shadow:var(--shadow-1);transition:box-shadow .25s}
1708
+ .scard:hover{box-shadow:var(--shadow-2)}
1709
+ .scard.pol{border-left-color:var(--policy)}
1710
+ .scard.dat{border-left-color:var(--brand-2)}
1711
+ .scard.cas{border-left-color:var(--case)}
1712
+ .scard.ref,.scard.mat{border-left-color:var(--ref)}
1713
+ .scard.hl{box-shadow:0 0 0 3px rgba(139,92,246,.35),var(--shadow-2)}
1714
+ .scard.hide{display:none}
1715
+ .sc-head{display:flex;align-items:center;gap:7px;margin-bottom:6px}
1716
+ .sc-id{font-family:monospace;font-weight:800;font-size:11px;color:#fff;background:var(--grad);
1717
+ border-radius:5px;padding:1px 8px}
1718
+ .sc-type{font-size:11px;font-weight:700;border-radius:4px;padding:1px 8px;background:var(--ref-soft);color:var(--ref)}
1719
+ .scard.pol .sc-type{background:var(--policy-soft);color:var(--policy)}
1720
+ .scard.dat .sc-type{background:var(--brand-soft);color:var(--brand)}
1721
+ .scard.cas .sc-type{background:var(--case-soft);color:var(--case)}
1722
+ .sc-vk{margin-left:auto;font-size:11px;font-weight:800;color:var(--ok)}
1723
+ .sc-vk.warn{color:var(--warn)}
1724
+ .sc-unused{font-size:10.5px;font-weight:800;color:var(--muted);background:#efedf4;border-radius:4px;
1725
+ padding:1px 7px;flex:none}
1726
+ .sc-conf{font-size:10.5px;font-weight:800;color:#8a5a00;background:var(--case-soft);border:1px solid #e6cf8f;
1727
+ border-radius:4px;padding:0 7px;flex:none}
1728
+ .scard h4{margin:0 0 5px;font-size:14.5px;color:var(--ink);line-height:1.55}
1729
+ .sc-meta{font-size:11.5px;color:var(--muted)}
1730
+ /* 标题链面包屑(模型生成的结构化位置,核验核心抓手)与多段分块 */
1731
+ .crumb{font-size:11.5px;color:var(--brand);margin:10px 0 4px;font-weight:600;line-height:1.6;
1732
+ padding:3px 9px;background:var(--tint);border-radius:7px;display:inline-block;max-width:100%;
1733
+ overflow-wrap:break-word}
1734
+ .crumb i{font-style:normal;color:#c9b3ec;margin:0 2px;font-weight:400}
1735
+ .seg-block{margin-top:8px}
1736
+ .seg-block:first-child{margin-top:2px}
1737
+ .seg-block .sc-excerpt{margin-top:5px}
1738
+ .sc-vnote{margin-top:5px;font-size:11.3px;color:var(--ok);line-height:1.6}
1739
+ .sc-excerpt{margin:8px 0 0;padding:10px 12px;border:1px solid #eceaf2;border-radius:9px;
1740
+ background:#faf9fd;color:#4a4260;font-size:12.3px;line-height:1.75}
1741
+ .sc-excerpt.rich{overflow-x:auto}
1742
+ .sc-excerpt.rich table{width:max-content;min-width:100%;border-collapse:collapse;background:#fff;font-size:12px}
1743
+ .sc-excerpt.rich td,.sc-excerpt.rich th{min-width:92px;max-width:220px;padding:7px 8px;border:1px solid var(--line);
1744
+ vertical-align:top;word-break:break-word}
1745
+ .sc-excerpt.rich thead td,.sc-excerpt.rich th{background:#f3f4f6;color:#3f3d52;font-weight:700}
1746
+ .scard .sc-links a{font-size:12px}
1747
+ .scard .sc-links{margin-top:4px}
1748
+ .no-link{font-size:11.5px;color:var(--muted)}
1749
+ .sc-links a.snap{background:#faf5ff;border-color:#d9c9f4;color:#5b21b6}
1750
+ .dead-link{font-size:11.5px;color:var(--warn)}
1751
+
1752
+ /* ===== 章节目录(spy,长报告) ===== */
1753
+ .toc{position:fixed;left:calc((100vw - 1080px)/2 - 168px);top:120px;width:140px;max-height:60vh;overflow:auto;
1754
+ display:flex;flex-direction:column;gap:2px;font-size:12px}
1755
+ .toc a{color:var(--muted);text-decoration:none;padding:4px 10px;border-left:2px solid var(--line);
1756
+ line-height:1.5;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1757
+ .toc a.on{color:var(--brand);border-left-color:var(--brand);font-weight:700}
1758
+ @media (max-width:1460px){.toc{display:none}}
1759
+
1760
+ .foot{text-align:center;color:var(--muted);font-size:11.5px;padding:16px 0 4px;line-height:1.8}
1761
+
1762
+ /* ===== 只看正文(纯净阅读态) ===== */
1763
+ body.reading .process,body.reading .verify,body.reading .jb,body.reading .sec-badge,
1764
+ body.reading .cite,body.reading .toc,body.reading .p-detail{display:none!important}
1765
+
1766
+ /* ===== 打印附录 ===== */
1767
+ .print-appendix{display:none}
1768
+
1769
+ /* ===== 移动端 ===== */
1770
+ .sheet-mask{display:none}
1771
+ .sheet{display:none}
1772
+ @media (max-width:680px){
1773
+ body{font-size:14px;line-height:1.8}
1774
+ .topbar{padding:7px 10px;gap:6px}
1775
+ .tb-stamp{font-size:11px;letter-spacing:2px;text-indent:2px}
1776
+ .tb-stamp::before,.tb-stamp::after{width:12px;margin:0 4px}
1777
+ .tb-title{display:none}
1778
+ .topbar .view-switch{display:none}
1779
+ .tb-tools button{font-size:11.5px;padding:4px 8px}
1780
+ .hero{padding:24px 14px 50px}
1781
+ .ch-head{gap:8px;margin-bottom:14px;flex-wrap:nowrap}
1782
+ .ch-head h2{font-size:17px;line-height:1.45}
1783
+ .ch-head::after{display:none}
1784
+ .ch-head .sec-badge{font-size:10.5px;padding:2px 7px;white-space:nowrap}
1785
+ .jb-name{max-width:calc(100vw - 72px)}
1786
+ .r-badge{font-size:13.5px;letter-spacing:6px;text-indent:6px;gap:10px}
1787
+ .hero h1{font-size:18.5px}
1788
+ .hero .meta{font-size:11.5px;line-height:1.7}
1789
+ .hero-switch .view-switch button{padding:6px 16px;font-size:12.5px}
1790
+ .process{margin-top:-30px;padding:12px 12px 11px}
1791
+ .p-step{flex:1 1 100%}
1792
+ .p-arrow{display:none}
1793
+ .verify{padding:13px 14px}
1794
+ .v-head{font-size:14px}
1795
+ .v-grid{grid-template-columns:1fr;gap:2px 0}
1796
+ .vi{flex-wrap:wrap;gap:4px 8px}
1797
+ .vi .d{min-width:0}
1798
+ .warn-box{font-size:12.5px;padding:11px 12px}
1799
+ .doc-paper{padding:16px 14px 10px;border-radius:10px}
1800
+ .sec-head{gap:7px;padding-bottom:8px;margin-bottom:8px}
1801
+ .sec-head h3{font-size:15px}
1802
+ .sec-badge{margin-left:0;font-size:11px}
1803
+ .doc-block p,.doc-item p{font-size:15px;line-height:1.95}
1804
+ .doc-sub{font-size:14px;margin:12px 0 6px}
1805
+ .data-tbl{font-size:12px}
1806
+ .data-tbl th,.data-tbl td{padding:6px 7px;line-height:1.55}
1807
+ .cite{font-size:11px;padding:0 4px}
1808
+ .ev-chip summary{font-size:11px}
1809
+ #view-library{padding:18px 0 24px}
1810
+ .lib-search{padding:10px 14px 10px 34px;font-size:13.5px}
1811
+ .lib-tabs{justify-content:flex-start;flex-wrap:nowrap;overflow-x:auto;padding-bottom:4px;
1812
+ -webkit-overflow-scrolling:touch;scrollbar-width:none}
1813
+ .lib-tabs::-webkit-scrollbar{display:none}
1814
+ .lib-tabs button{flex:none}
1815
+ .lib-list{grid-template-columns:1fr;gap:10px}
1816
+ .scard{padding:10px 11px}
1817
+ .crumb{font-size:11px}
1818
+ .sc-excerpt{font-size:11.5px}
1819
+ /* 移动端材料底部弹层:点角标就地弹出材料卡,不跳转打断阅读 */
1820
+ .sheet-mask{display:block;position:fixed;inset:0;background:rgba(11,31,58,.45);z-index:99;opacity:0;
1821
+ pointer-events:none;transition:opacity .2s}
1822
+ .sheet-mask.show{opacity:1;pointer-events:auto}
1823
+ .sheet{display:block;position:fixed;left:0;right:0;bottom:0;z-index:100;background:#fff;
1824
+ border-radius:14px 14px 0 0;box-shadow:0 -8px 30px rgba(11,31,58,.25);
1825
+ max-height:68vh;overflow-y:auto;-webkit-overflow-scrolling:touch;
1826
+ padding:10px 16px 22px;transform:translateY(105%);transition:transform .25s ease}
1827
+ .sheet.show{transform:translateY(0)}
1828
+ .sheet-grab{width:38px;height:4px;border-radius:2px;background:#c9d4e2;margin:2px auto 8px}
1829
+ .sheet-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
1830
+ .sheet-head b{font-size:13.5px;color:var(--navy)}
1831
+ .sheet-close{border:1px solid var(--line);background:#f5f3fa;border-radius:8px;color:#3b4a61;
1832
+ font-size:12.5px;font-weight:700;padding:5px 14px;cursor:pointer}
1833
+ .sheet .scard{box-shadow:none;margin-bottom:0}
1834
+ .sheet .sc-excerpt{display:block;-webkit-line-clamp:unset;cursor:auto}
1835
+ /* 正文表述 ↔ 原文原段 对照区(弹层顶部) */
1836
+ .cmp{margin:0 0 10px;border:1px solid var(--line);border-radius:10px;overflow:hidden}
1837
+ .cmp-tag{font-size:11px;font-weight:800;padding:3px 10px}
1838
+ .cmp-side{padding:9px 12px;font-size:12.8px;line-height:1.7}
1839
+ .cmp-side p{margin:0}
1840
+ .cmp-ai{background:#fbfaff;color:#3f3d52}
1841
+ .cmp-ai .cmp-tag{background:#eef1f6;color:var(--ref)}
1842
+ .cmp-src{background:#f4faf7;color:#2f4a3e;border-top:1px dashed var(--line-strong)}
1843
+ .cmp-src .cmp-tag{background:var(--policy-soft);color:#0b6e4f}
1844
+ .cmp-src .sc-excerpt{display:block;-webkit-line-clamp:unset;background:#fff;cursor:auto;font-size:12px;padding:8px 10px;margin:0}
1845
+ }
1846
+
1847
+ /* ===== 打印归档 ===== */
1848
+ @media print{
1849
+ .topbar,.process .p-detail,.hero-switch,.tb-tools,.view-switch,.lib-head,.toc,.sheet,.sheet-mask,
1850
+ .progress{display:none!important}
1851
+ #view-library{display:none!important}
1852
+ #view-report{display:block!important}
1853
+ .app[data-view="library"] #view-report{display:block!important}
1854
+ .hero{background:none;border:0;color:var(--ink);padding:10px 0 4px}
1855
+ .hero .meta{color:var(--muted)}
1856
+ *{-webkit-print-color-adjust:exact;print-color-adjust:exact}
1857
+ .process{box-shadow:none;margin:6px 0 12px}
1858
+ .verify{border-color:#bbb;box-shadow:none;break-inside:avoid}
1859
+ .doc-paper{box-shadow:none;border-radius:0;padding:0}
1860
+ body{background:#fff;font-size:12.5px}
1861
+ .sc-excerpt{display:block;-webkit-line-clamp:unset;cursor:auto}
1862
+ .scard{break-inside:avoid}
1863
+ .cite{background:none!important;color:#333!important;text-decoration:none!important}
1864
+ .cite::before{content:"["}.cite::after{content:"]"}
1865
+ .jb{display:inline!important}
1866
+ .jb .jb-name{border:0;background:none;padding:0;color:#333;font-weight:600}
1867
+ .jb .jb-name .jb-id{color:#333;background:none;border:1px solid #999;border-radius:3px}
1868
+ .jb .jb-body{display:none!important}
1869
+ .jb.active{break-inside:avoid}
1870
+ .jb.active .jb-body{display:block!important}
1871
+ .jb.active .jb-body .jb-quote{break-inside:avoid}
1872
+ body.reading .verify,body.reading .process,body.reading .ev-row,body.reading .sec-badge,
1873
+ body.reading .cite{display:none!important}
1874
+ .print-appendix{display:block;break-before:page}
1875
+ body.print-body-only .verify,body.print-body-only .process,body.print-body-only .print-appendix,
1876
+ body.print-body-only .jb,body.print-body-only .foot{display:none!important}
1877
+ .print-appendix h3{font-size:15px;color:var(--navy);border-bottom:1px solid #999;padding-bottom:6px;margin:0 0 12px}
1878
+ .print-appendix .scard{margin-bottom:10px}
1879
+ }
1880
+ """
1881
+
1882
+ PAGE_CSS += """
1883
+ /* ===== 咨询版新增:咨询问题行 + 云端溯源存档 ===== */
1884
+ .q-line{margin:0 auto 10px;max-width:860px;font-size:13px;color:#4b4257;background:rgba(255,255,255,.72);
1885
+ border:1px solid var(--tint-bd);border-radius:8px;padding:7px 12px;text-align:center;line-height:1.7}
1886
+ .q-line b{color:var(--brand)}
1887
+ .kb-zone{margin:16px 0 4px;border-top:1px dashed var(--line-strong);padding-top:12px}
1888
+ .kb-title{font-size:12.5px;font-weight:800;color:var(--ink)}
1889
+ .kb-desc{font-size:11.3px;color:var(--muted);line-height:1.65;margin:3px 0 8px}
1890
+ .kb-list{display:flex;flex-direction:column;gap:7px}
1891
+ .kb-chip{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid var(--line);border-radius:8px;
1892
+ background:#fbfcfe;text-decoration:none;font-size:11.5px}
1893
+ .kb-chip:hover{border-color:var(--brand);background:var(--brand-soft)}
1894
+ .kb-label{font-weight:700;color:#374151;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
1895
+ .kb-count{padding-left:8px;border-left:1px solid var(--line);color:var(--muted);white-space:nowrap}
1896
+ .kb-arrow{margin-left:auto;color:var(--brand);font-weight:700;white-space:nowrap}
1897
+ """
1898
+
1899
+ PAGE_JS = """
1900
+ (function () {
1901
+ "use strict";
1902
+ function $(sel, root) { return (root || document).querySelector(sel); }
1903
+ function $$(sel, root) { return Array.prototype.slice.call((root || document).querySelectorAll(sel)); }
1904
+
1905
+ var app = $(".app");
1906
+ var isMobile = function () { return window.matchMedia("(max-width:680px)").matches; };
1907
+
1908
+ /* ===== 1. 双视图切换(保存/恢复各自滚动位置) ===== */
1909
+ var savedScroll = { report: 0, library: 0 };
1910
+ function setView(view) {
1911
+ if (!app || app.getAttribute("data-view") === view) return;
1912
+ savedScroll[app.getAttribute("data-view") || "report"] = window.scrollY;
1913
+ app.setAttribute("data-view", view);
1914
+ $$(".view-switch button").forEach(function (b) {
1915
+ b.classList.toggle("on", b.getAttribute("data-view") === view);
1916
+ });
1917
+ window.scrollTo(0, Math.max(0, savedScroll[view] || 0));
1918
+ }
1919
+ $$(".view-switch button").forEach(function (b) {
1920
+ b.addEventListener("click", function () { setView(b.getAttribute("data-view")); });
1921
+ });
1922
+
1923
+ /* ===== 2. 阅读进度条 ===== */
1924
+ var progress = $(".progress i");
1925
+ function updateProgress() {
1926
+ if (!progress) return;
1927
+ var h = document.documentElement;
1928
+ var max = h.scrollHeight - h.clientHeight;
1929
+ progress.style.width = (max > 0 ? Math.min(100, (h.scrollTop / max) * 100) : 0) + "%";
1930
+ }
1931
+ window.addEventListener("scroll", updateProgress, { passive: true });
1932
+ updateProgress();
1933
+
1934
+ /* ===== 3. 只看正文(纯净阅读态切换) ===== */
1935
+ var readBtn = $("#btn-reading");
1936
+ if (readBtn) {
1937
+ readBtn.addEventListener("click", function () {
1938
+ var on = document.body.classList.toggle("reading");
1939
+ readBtn.setAttribute("aria-pressed", on ? "true" : "false");
1940
+ readBtn.textContent = on ? "显示核验" : "只看正文";
1941
+ /* 只看正文只作用于核验报告视图:正在材料专库时切回报告,专库不受影响 */
1942
+ if (on && app && app.getAttribute("data-view") !== "report") setView("report");
1943
+ });
1944
+ }
1945
+
1946
+ /* ===== 4. 复制全文(章节标题 + 段落 + 表格,去角标) ===== */
1947
+ var copyBtn = $("#btn-copy");
1948
+ if (copyBtn) {
1949
+ copyBtn.addEventListener("click", function () {
1950
+ var parts = [];
1951
+ /* 按文档流顺序收集章节标题/段落/表格;克隆后剔除引文胶囊与角标,
1952
+ 只复制正文本身(胶囊标题/展开摘录/编号数字均不带出) */
1953
+ var nodes = $$("#view-report .ch-head h2, #view-report .lead, #view-report .para, #view-report .tbl-wrap");
1954
+ nodes.sort(function (a, b) { return (a.compareDocumentPosition(b) & 4) ? -1 : 1; });
1955
+ nodes.forEach(function (el) {
1956
+ var clone = el.cloneNode(true);
1957
+ clone.querySelectorAll(".jb, sup.cite").forEach(function (x) { x.remove(); });
1958
+ var t = clone.textContent.replace(/[ \t]+/g, " ").trim();
1959
+ if (t) parts.push(t);
1960
+ });
1961
+ var text = parts.filter(Boolean).join("\\n\\n");
1962
+ function done(ok) {
1963
+ var old = copyBtn.textContent;
1964
+ copyBtn.textContent = ok ? "已复制 ✓" : "复制失败";
1965
+ setTimeout(function () { copyBtn.textContent = old; }, 1600);
1966
+ }
1967
+ if (navigator.clipboard && navigator.clipboard.writeText) {
1968
+ navigator.clipboard.writeText(text).then(function () { done(true); }, function () { done(fallback(text)); });
1969
+ } else {
1970
+ done(fallback(text));
1971
+ }
1972
+ function fallback(value) {
1973
+ try {
1974
+ var ta = document.createElement("textarea");
1975
+ ta.value = value;
1976
+ ta.style.position = "fixed";
1977
+ ta.style.opacity = "0";
1978
+ document.body.appendChild(ta);
1979
+ ta.select();
1980
+ var ok = document.execCommand("copy");
1981
+ document.body.removeChild(ta);
1982
+ return ok;
1983
+ } catch (e) { return false; }
1984
+ }
1985
+ });
1986
+ }
1987
+
1988
+ /* ===== 5. 打印归档(PDF):下拉双选项——只打印正文 / 完整归档 ===== */
1989
+ var printBtn = $("#btn-print");
1990
+ var printDrop = $("#print-drop");
1991
+ function printBy(mode) {
1992
+ if (mode === "body") document.body.classList.add("print-body-only");
1993
+ if (printDrop) printDrop.hidden = true;
1994
+ window.print();
1995
+ }
1996
+ if (printBtn && printDrop) {
1997
+ printBtn.addEventListener("click", function (e) {
1998
+ e.stopPropagation();
1999
+ printDrop.hidden = !printDrop.hidden;
2000
+ });
2001
+ printDrop.addEventListener("click", function (e) {
2002
+ e.stopPropagation();
2003
+ var t = e.target.closest("button");
2004
+ if (!t) return;
2005
+ printBy(t.id === "print-body" ? "body" : "full");
2006
+ });
2007
+ document.addEventListener("click", function () { printDrop.hidden = true; });
2008
+ /* 打印结束移除临时模式(浏览器打印窗口关闭后触发) */
2009
+ window.addEventListener("afterprint", function () { document.body.classList.remove("print-body-only"); });
2010
+ }
2011
+
2012
+ /* ===== 6. 材料卡索引(专库列表内,不含打印附录) ===== */
2013
+ var cards = $$("#lib-list .scard");
2014
+ var byId = {};
2015
+ cards.forEach(function (c) {
2016
+ var id = c.getAttribute("data-cite-id");
2017
+ if (id) byId[id] = c;
2018
+ });
2019
+
2020
+ /* 移动端底部弹层:正文表述 ↔ 原文原段 对照 + 材料卡 */
2021
+ var sheet = $(".sheet");
2022
+ var mask = $(".sheet-mask");
2023
+ function escHtml(s) {
2024
+ var d = document.createElement("div");
2025
+ d.textContent = s;
2026
+ return d.innerHTML;
2027
+ }
2028
+ function sentenceOf(el) {
2029
+ var para = el && el.closest ? el.closest(".doc-block,.doc-item") : null;
2030
+ return para && para.querySelector("p") ? para.querySelector("p").innerText.trim() : "";
2031
+ }
2032
+ function openSheet(card, sentence) {
2033
+ if (!sheet) return;
2034
+ var body = sheet.querySelector(".sheet-body");
2035
+ body.innerHTML = "";
2036
+ if (sentence) {
2037
+ var excerpt = card.querySelector(".sc-excerpt");
2038
+ var cmp = document.createElement("div");
2039
+ cmp.className = "cmp";
2040
+ cmp.innerHTML =
2041
+ '<div class="cmp-side cmp-ai"><div class="cmp-tag">正文表述</div><p>' + escHtml(sentence) + '</p></div>' +
2042
+ '<div class="cmp-side cmp-src"><div class="cmp-tag">原文原段</div>' +
2043
+ '<div class="sc-excerpt">' + (excerpt ? excerpt.innerHTML : "") + '</div></div>';
2044
+ body.appendChild(cmp);
2045
+ }
2046
+ var clone = card.cloneNode(true);
2047
+ clone.removeAttribute("id");
2048
+ clone.classList.remove("hide");
2049
+ clone.classList.add("open");
2050
+ body.appendChild(clone);
2051
+ sheet.classList.add("show");
2052
+ mask.classList.add("show");
2053
+ document.body.style.overflow = "hidden";
2054
+ sheet.scrollTop = 0;
2055
+ }
2056
+ function closeSheet() {
2057
+ if (!sheet) return;
2058
+ sheet.classList.remove("show");
2059
+ mask.classList.remove("show");
2060
+ document.body.style.overflow = "";
2061
+ }
2062
+ if (sheet && mask) {
2063
+ mask.addEventListener("click", closeSheet);
2064
+ var closeBtn = sheet.querySelector(".sheet-close");
2065
+ if (closeBtn) closeBtn.addEventListener("click", closeSheet);
2066
+ }
2067
+
2068
+ /* 行内引文 jb(原型行为):点小胶囊 toggle 展开卡;点角标展开对应 jb 并 flash。
2069
+ 未绑定角标红色警示,绝不按位置猜测。 */
2070
+ var JB_TABLES = {};
2071
+ try {
2072
+ var jbTablesEl = document.getElementById("jb-tables");
2073
+ if (jbTablesEl) JB_TABLES = JSON.parse(jbTablesEl.textContent || "{}");
2074
+ } catch (e) { JB_TABLES = {}; }
2075
+ function fillTableHolders(jb) {
2076
+ jb.querySelectorAll(".tbl-holder[data-tbl]").forEach(function (h) {
2077
+ if (h.getAttribute("data-filled")) return;
2078
+ var html = JB_TABLES[h.getAttribute("data-tbl")];
2079
+ if (html) h.innerHTML = html;
2080
+ h.setAttribute("data-filled", "1");
2081
+ });
2082
+ }
2083
+ function toggleJb(jb, forceOpen) {
2084
+ var open = forceOpen === true ? true : !jb.classList.contains("active");
2085
+ document.querySelectorAll(".jb.active").forEach(function (x) { if (x !== jb) x.classList.remove("active"); });
2086
+ jb.classList.toggle("active", open);
2087
+ if (open) fillTableHolders(jb);
2088
+ var name = jb.querySelector(".jb-name");
2089
+ if (name) name.setAttribute("aria-expanded", open ? "true" : "false");
2090
+ return open;
2091
+ }
2092
+ document.querySelectorAll(".jb-name").forEach(function (name) {
2093
+ name.addEventListener("click", function () { toggleJb(name.closest(".jb")); });
2094
+ });
2095
+
2096
+ /* 引文条目点击 → 材料专库定位对应卡:库内导航看完整材料;
2097
+ 外部原文跳转只保留 jb-head 的"查看全文"按钮,动线分离 */
2098
+ function jumpToLibrary(id) {
2099
+ var card = byId[id];
2100
+ if (!card) return;
2101
+ setView("library");
2102
+ card.classList.remove("hide", "open");
2103
+ card.classList.add("hl", "open");
2104
+ requestAnimationFrame(function () {
2105
+ requestAnimationFrame(function () { card.scrollIntoView({ block: "center", behavior: "smooth" }); });
2106
+ });
2107
+ setTimeout(function () { card.classList.remove("hl"); }, 2200);
2108
+ }
2109
+ document.querySelectorAll(".jb-quote").forEach(function (q) {
2110
+ function go() {
2111
+ var jbEl = q.closest(".jb");
2112
+ var id = jbEl && jbEl.getAttribute("data-cite");
2113
+ if (id) jumpToLibrary(id);
2114
+ }
2115
+ q.addEventListener("click", go);
2116
+ q.addEventListener("keydown", function (e) {
2117
+ if (e.key === "Enter" || e.key === " ") { e.preventDefault(); go(); }
2118
+ });
2119
+ });
2120
+ document.querySelectorAll("sup.cite").forEach(function (btn) {
2121
+ /* 仅剩未绑定角标(红色数字)走到这里:点击控制台留痕 */
2122
+ btn.addEventListener("click", function () {
2123
+ if (console.error) console.error("[核验] 未绑定角标:", btn.getAttribute("data-cite"));
2124
+ });
2125
+ });
2126
+
2127
+ /* 材料卡摘录直接全文展开(句后胶囊已承载即点即看,专库不再折叠) */
2128
+
2129
+ /* 胶囊点击:桌面开关对照气泡(同一气泡再点收起);手机端弹出底部材料弹层 */
2130
+ document.querySelectorAll(".ev-chip").forEach(function (chip) {
2131
+ chip.addEventListener("click", function () {
2132
+ var id = chip.getAttribute("data-cite");
2133
+ if (isMobile()) {
2134
+ var card = byId[id];
2135
+ if (card) openSheet(card, sentenceOf(chip));
2136
+ return;
2137
+ }
2138
+ togglePop(chip, id);
2139
+ });
2140
+ });
2141
+
2142
+ /* ===== 7. 材料专库:tabs + 搜索 + 热词 ===== */
2143
+ var cond = "";
2144
+ var kw = "";
2145
+ function applyFilter() {
2146
+ var visible = 0;
2147
+ cards.forEach(function (c) {
2148
+ var okCond = !cond;
2149
+ if (cond === "__unused__") okCond = c.getAttribute("data-unused") === "1";
2150
+ else if (cond) okCond = c.getAttribute("data-search") === cond;
2151
+ var okKw = !kw || (c.textContent || "").toLowerCase().indexOf(kw) !== -1;
2152
+ var show = okCond && okKw;
2153
+ c.classList.toggle("hide", !show);
2154
+ if (show) visible++;
2155
+ });
2156
+ var empty = $("#lib-empty");
2157
+ if (empty) empty.classList.toggle("hide", visible !== 0);
2158
+ }
2159
+ $$(".lib-tabs button").forEach(function (b) {
2160
+ b.addEventListener("click", function () {
2161
+ $$(".lib-tabs button").forEach(function (x) { x.classList.remove("on"); });
2162
+ b.classList.add("on");
2163
+ cond = b.getAttribute("data-cond") || "";
2164
+ applyFilter();
2165
+ });
2166
+ });
2167
+ var search = $(".lib-search");
2168
+ if (search) search.addEventListener("input", function () { kw = search.value.trim().toLowerCase(); applyFilter(); });
2169
+ $$(".hot-term").forEach(function (t) {
2170
+ t.addEventListener("click", function () {
2171
+ if (!search) return;
2172
+ search.value = t.textContent.trim();
2173
+ kw = search.value.toLowerCase();
2174
+ applyFilter();
2175
+ if (search.focus) search.focus();
2176
+ });
2177
+ });
2178
+
2179
+ /* ===== 8. 过程回顾条:检索步骤展开 ===== */
2180
+ var pStep = $("#p-step-search");
2181
+ var pDetail = $("#p-detail");
2182
+ if (pStep && pDetail) {
2183
+ function toggleDetail() { pDetail.classList.toggle("show"); }
2184
+ pStep.addEventListener("click", toggleDetail);
2185
+ pStep.addEventListener("keydown", function (e) {
2186
+ if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggleDetail(); }
2187
+ });
2188
+ }
2189
+
2190
+ /* ===== 9. 章节目录(spy) ===== */
2191
+ var toc = $(".toc");
2192
+ if (toc) {
2193
+ var links = $$("a", toc);
2194
+ var secs = links.map(function (a) { return document.querySelector(a.getAttribute("href")); });
2195
+ links.forEach(function (a) {
2196
+ a.addEventListener("click", function (e) {
2197
+ e.preventDefault();
2198
+ var target = document.querySelector(a.getAttribute("href"));
2199
+ if (target) target.scrollIntoView({ block: "start", behavior: "smooth" });
2200
+ });
2201
+ });
2202
+ function spy() {
2203
+ var pos = window.scrollY + 130;
2204
+ var current = -1;
2205
+ secs.forEach(function (s, i) { if (s && s.offsetTop <= pos) current = i; });
2206
+ links.forEach(function (a, i) { a.classList.toggle("on", i === current); });
2207
+ }
2208
+ window.addEventListener("scroll", spy, { passive: true });
2209
+ spy();
2210
+ }
2211
+ })();
2212
+ """
2213
+
2214
+
1029
2215
  def render_html(payload: Dict[str, Any], title: str, answer_override: str = "", question_override: str = "",
1030
- generated_at: Optional[datetime] = None, sources_override: Optional[List[Dict[str, str]]] = None) -> str:
2216
+ generated_at: Optional[datetime] = None,
2217
+ sources_override: Optional[List[Dict[str, str]]] = None) -> str:
1031
2218
  payload = unwrap(payload)
1032
2219
  answer = normalize_citations(answer_override) if answer_override.strip() else extract_answer(payload)
1033
- sources = sources_override if sources_override is not None else extract_sources(payload)
1034
- answer, sources, _ = renumber_citations(answer, sources)
1035
- sources = align_sources_to_answer(answer, sources)
2220
+ if sources_override is not None:
2221
+ # main 已完成重编号与硬校验,直接使用同一样本源,保证三处编号一致
2222
+ sources = sources_override
2223
+ else:
2224
+ # 直接调用渲染器(未走 main):先绑定段落/材料级编号并重编号,保证
2225
+ # 角标与来源卡一致(与 main 的 sources_override 使用同一绑定逻辑)
2226
+ sources = extract_sources(payload)
2227
+ answer, sources, _ = renumber_citations(answer, sources)
1036
2228
  used = citation_ids(answer)
1037
- kb_urls = extract_trace_archives(payload)
2229
+ # 咨询溯源 JSON 无"已引用"标记:引用状态以答案角标为准(未引用不计入核验,专库单独分组)
2230
+ for s in sources:
2231
+ s["used"] = s["id"] in used
1038
2232
  generated_at = generated_at or datetime.now()
1039
2233
  generated = generated_at.strftime("%Y-%m-%d %H:%M")
1040
2234
 
1041
2235
  verification = compute_verification(answer, sources, payload, generated_at)
2236
+ question = question_override.strip() or extract_question(payload)
2237
+ process_stats = compute_process_stats(sources, answer, question)
2238
+ hot_terms = extract_hot_terms(answer, sources)
1042
2239
  citation_warning = ""
1043
2240
  if sources and not used:
1044
2241
  citation_warning = (
@@ -1047,20 +2244,30 @@ def render_html(payload: Dict[str, Any], title: str, answer_override: str = "",
1047
2244
  '请修正最终答案文件:在关键结论后标注 [1]、[2] 等角标并逐条对应来源材料,'
1048
2245
  '然后重新运行 render_trace_html.py 生成核验报告。</div>'
1049
2246
  )
1050
- blocks, _ = parse_answer_blocks(answer, {s["id"] for s in sources})
2247
+ chip_map = build_chip_data(sources)
2248
+ blocks, _ = parse_answer_blocks(answer, {s["id"] for s in sources}, chip_map)
2249
+ # 胶囊内表格数据汇总(span 内静态表格会被解析器拆散,改为页尾 JSON + 展开时 JS 注入)
2250
+ jb_tables: Dict[str, str] = {}
2251
+ for cid, jb in chip_map.items():
2252
+ for key, html in (jb.pop("_tables", {}) or {}).items():
2253
+ jb_tables[key] = html
1051
2254
  doc_title, sections = group_sections(blocks)
1052
2255
  display_title = doc_title or title
1053
- kb_zone = render_archive_zone(kb_urls, len(sources))
2256
+
2257
+ jb_tables_json = json.dumps(jb_tables, ensure_ascii=False).replace("</", "<\\/")
2258
+ jb_tables_script = (f'<script type="application/json" id="jb-tables">{jb_tables_json}</script>\n'
2259
+ if jb_tables else "")
1054
2260
 
1055
2261
  meta_bits = []
2262
+ if process_stats["n_searches"]:
2263
+ meta_bits.append(f"可信问答 {process_stats['n_searches']} 次")
1056
2264
  if sources:
1057
- meta_bits.append(f"共 {len(sources)} 条")
1058
- meta_bits.append("点击答案角标 [1] 定位材料原文")
1059
- meta_line = " | ".join(meta_bits)
1060
- question = question_override.strip() or extract_question(payload)
1061
- question_html = (
1062
- f'<div class="q-line"><b>咨询问题:</b>{esc(question)}</div>' if question else ""
1063
- )
2265
+ meta_bits.append(f"召回材料 {len(sources)} 条")
2266
+ if process_stats["n_cite_marks"]:
2267
+ meta_bits.append(f"答案引用 {process_stats['n_cite_marks']} 处")
2268
+ meta_bits.append(f"生成于 {generated}")
2269
+ meta_line = " · ".join(meta_bits)
2270
+ question_html = (f'<div class="q-line"><b>咨询问题:</b>{esc(question)}</div>' if question else "")
1064
2271
 
1065
2272
  return f"""<!doctype html>
1066
2273
  <html lang="zh-CN">
@@ -1068,447 +2275,150 @@ def render_html(payload: Dict[str, Any], title: str, answer_override: str = "",
1068
2275
  <meta charset="utf-8">
1069
2276
  <meta name="viewport" content="width=device-width, initial-scale=1">
1070
2277
  <title>{esc(display_title)} · 可信核验报告</title>
1071
- <style>
1072
- :root{{
1073
- --navy:#0b1f3a; --ink:#172236; --muted:#667085; --line:#dce4ef; --line-strong:#b9c6d9;
1074
- --brand:#1559c7; --brand-soft:#e8f0ff;
1075
- --policy:#0c9b78; --policy-soft:#e2f6ef;
1076
- --case:#b26a00; --case-soft:#fff4e0;
1077
- --ref:#4b5563; --ref-soft:#eef1f6;
1078
- --warn:#b26a00; --danger:#b93939; --ok:#0c9b78;
1079
- }}
1080
- *{{box-sizing:border-box}}
1081
- body{{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
1082
- color:var(--ink);background:#f4f7fb;line-height:1.75;font-size:14.5px}}
1083
- a{{color:var(--brand)}}
1084
- .topbar{{position:sticky;top:0;z-index:10;display:flex;justify-content:space-between;align-items:center;gap:10px;
1085
- padding:10px 22px;background:var(--navy);color:#fff;font-size:13px}}
1086
- .topbar .tb-title{{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
1087
- .topbar .tags{{display:flex;align-items:center;gap:6px;flex:none}}
1088
- .topbar .tags span{{padding:2px 10px;border:1px solid rgba(255,255,255,.3);border-radius:999px;font-size:11.5px}}
1089
- .layout{{display:grid;grid-template-columns:minmax(0,760px) minmax(340px,420px);gap:26px;
1090
- max-width:1240px;margin:0 auto;padding:26px 18px 60px}}
1091
- /* 左栏 */
1092
- .report{{min-width:0}}
1093
- .r-head{{padding:22px 26px;background:#fff;border:1px solid var(--line);border-radius:12px;margin-bottom:16px;text-align:center}}
1094
- .r-head h1{{margin:0 0 8px;font-size:22px;color:var(--navy);line-height:1.5}}
1095
- .q-line{{margin:0 auto 10px;max-width:92%;font-size:13.5px;color:#3b4a61;background:#f5f8fc;
1096
- border:1px solid var(--line);border-radius:8px;padding:8px 12px;text-align:left;line-height:1.7}}
1097
- .r-head .sub{{color:var(--muted);font-size:12.5px}}
1098
- .warn-box{{margin:0 0 16px;padding:13px 16px;border:1.5px solid var(--danger);border-radius:10px;
1099
- background:#fdf3f3;color:#8f2626;font-size:13.5px;line-height:1.7}}
1100
- .verify{{margin:0 0 16px;background:#fff;border:1px solid #bfe5d6;border-radius:12px;padding:16px 20px}}
1101
- .verify.fail{{border-color:#f2c4c4;background:#fffafa}}
1102
- .v-head{{display:flex;align-items:center;gap:9px;font-size:15px;font-weight:800;color:var(--ok)}}
1103
- .verify.fail .v-head{{color:var(--danger)}}
1104
- .v-shield{{display:inline-flex;width:22px;height:22px;border-radius:50%;background:var(--ok);color:#fff;
1105
- align-items:center;justify-content:center;font-size:12px;flex:none}}
1106
- .verify.fail .v-shield{{background:var(--danger)}}
1107
- .v-stamp{{margin-left:auto;font-size:11px;border:1.5px solid var(--ok);color:var(--ok);border-radius:5px;
1108
- padding:1px 8px;letter-spacing:2px;flex:none}}
1109
- .v-stamp.bad{{border-color:var(--danger);color:var(--danger)}}
1110
- .v-reasons{{margin-top:6px;font-size:12.5px;color:var(--danger)}}
1111
- .v-grid{{display:grid;grid-template-columns:1fr 1fr;gap:4px 20px;margin-top:10px}}
1112
- .vi{{display:flex;gap:7px;align-items:baseline;font-size:12.5px;color:#35445c;line-height:1.7;min-width:0}}
1113
- .vi .s{{font-weight:800;flex:none}}
1114
- .vi .s.ok{{color:var(--ok)}}
1115
- .vi .s.warn{{color:var(--warn)}}
1116
- .vi .s.fail{{color:var(--danger)}}
1117
- .vi .s.man{{color:var(--case)}}
1118
- .vi .s.none{{color:var(--muted)}}
1119
- .vi .d{{color:var(--muted);min-width:0}}
1120
- .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}}
1121
- /* 正文章节卡 */
1122
- .doc-sec{{background:#fff;border:1px solid var(--line);border-radius:12px;padding:20px 24px;margin-bottom:16px}}
1123
- .sec-head{{display:flex;align-items:center;gap:9px;flex-wrap:wrap;margin-bottom:10px;
1124
- padding-bottom:10px;border-bottom:1px solid var(--line)}}
1125
- .sec-no{{display:inline-flex;width:26px;height:26px;border-radius:7px;background:var(--brand);color:#fff;
1126
- align-items:center;justify-content:center;font-size:13.5px;font-weight:700;flex:none}}
1127
- .sec-head h3{{margin:0;font-size:16.5px;color:var(--navy);line-height:1.5}}
1128
- .sec-badge{{margin-left:auto;font-size:11.5px;color:var(--ok);background:var(--policy-soft);
1129
- border-radius:6px;padding:2px 9px;font-weight:700;flex:none}}
1130
- .sec-badge.bad{{color:var(--danger);background:#fdecea}}
1131
- .doc-sub{{margin:16px 0 8px;color:var(--navy);font-size:14.5px;font-weight:700}}
1132
- h5.doc-sub{{font-size:13.5px}}
1133
- .doc-block,.doc-item{{margin:0 0 12px}}
1134
- .doc-block p,.doc-item p{{margin:0;font-size:14px;line-height:1.9}}
1135
- .doc-item{{display:grid;grid-template-columns:22px minmax(0,1fr);gap:8px}}
1136
- .doc-item.numbered{{grid-template-columns:28px minmax(0,1fr)}}
1137
- .doc-bullet{{padding-top:1px;color:#111827;font-size:15px;line-height:1.85}}
1138
- .doc-divider{{border:0;border-top:1px solid var(--line);margin:18px 0}}
1139
- code{{padding:1px 5px;border-radius:4px;background:#f3f4f6;color:#374151;
1140
- font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}}
1141
- .tbl-wrap{{max-width:100%;overflow-x:auto;margin:8px 0}}
1142
- .data-tbl{{width:100%;border-collapse:collapse;border:1px solid var(--line);font-size:13px}}
1143
- .data-tbl th,.data-tbl td{{border:1px solid var(--line);padding:8px 10px;text-align:left;vertical-align:top;line-height:1.65}}
1144
- .data-tbl th{{background:#f2f5fb;font-weight:700;color:#374151}}
1145
- /* 角标 */
1146
- .cite{{margin:0 1px;padding:0 5px;border:0;border-radius:4px;background:var(--brand-soft);color:var(--brand);
1147
- font-weight:800;font-size:10.5px;cursor:pointer;vertical-align:super;font-family:monospace}}
1148
- .cite:hover,.cite:focus-visible{{background:var(--brand);color:#fff;outline:none}}
1149
- .cite.unresolved{{background:#fdecea;color:var(--danger)}}
1150
- /* 段落级证据 chips */
1151
- .ev-row{{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 2px}}
1152
- .ev-chip{{max-width:100%}}
1153
- .ev-chip summary{{display:inline-flex;align-items:center;max-width:100%;border-radius:999px;padding:3px 10px;
1154
- color:#4b5563;background:#f3f4f6;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
1155
- list-style:none;font-size:11.5px}}
1156
- .ev-chip summary::-webkit-details-marker{{display:none}}
1157
- .ev-chip summary::after{{content:"核验";margin-left:7px;color:#9ca3af;font-size:10.5px}}
1158
- .ev-chip[open] summary::after{{content:"收起"}}
1159
- .ev-chip summary b{{color:var(--brand);margin-right:5px}}
1160
- .ev-panel{{margin:7px 0 6px;padding:12px 14px;border:1px solid var(--line);border-radius:9px;background:#fbfcfe;
1161
- box-shadow:0 8px 24px rgba(15,23,42,.06)}}
1162
- .ev-title{{font-weight:700;font-size:13.5px;margin-bottom:4px;color:var(--navy)}}
1163
- .ev-meta{{color:var(--muted);font-size:12px;margin-bottom:6px}}
1164
- .ev-panel p{{margin:0 0 8px;color:#374151;font-size:12.8px;line-height:1.7}}
1165
- .sc-links{{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}}
1166
- .sc-links span{{display:inline-flex}}
1167
- .sc-links a{{display:inline-flex;align-items:center;min-height:24px;padding:3px 9px;border-radius:6px;
1168
- background:var(--brand-soft);color:var(--brand);font-weight:700;text-decoration:none;font-size:12px}}
1169
- /* 右栏 核验材料 */
1170
- .sources{{position:sticky;top:56px;align-self:start;max-height:calc(100vh - 76px);overflow:auto;
1171
- background:#fff;border:1px solid var(--line);border-radius:12px;padding:16px 18px}}
1172
- .sources h3{{margin:0 0 3px;font-size:15px;color:var(--navy)}}
1173
- .src-tip{{font-size:11.5px;color:var(--muted);margin-bottom:10px}}
1174
- .src-search{{width:100%;padding:7px 10px;border:1px solid var(--line);border-radius:7px;font-size:12.5px;margin-bottom:12px}}
1175
- .scard{{border:1px solid var(--line);border-radius:10px;padding:11px 13px;margin-bottom:10px;
1176
- background:#fff;transition:box-shadow .25s}}
1177
- .scard.hl{{box-shadow:0 0 0 3px var(--brand)}}
1178
- .scard.hide{{display:none}}
1179
- .sc-head{{display:flex;align-items:center;gap:7px;margin-bottom:4px}}
1180
- .sc-id{{font-family:monospace;font-weight:800;font-size:11px;color:var(--brand);background:var(--brand-soft);
1181
- border-radius:4px;padding:1px 7px}}
1182
- .sc-vk{{margin-left:auto;font-size:11px;font-weight:800;color:var(--ok)}}
1183
- .sc-vk.warn{{color:var(--warn)}}
1184
- .scard h4{{margin:0 0 4px;font-size:13px;color:var(--navy);line-height:1.55}}
1185
- .sc-meta{{font-size:11.5px;color:var(--muted)}}
1186
- .sc-section{{font-size:11.5px;color:var(--brand);margin-top:3px;font-weight:600}}
1187
- .sc-vnote{{margin-top:5px;font-size:11.3px;color:var(--ok);line-height:1.6}}
1188
- .sc-unused{{font-size:10.5px;font-weight:800;color:var(--muted);background:#eef1f6;border-radius:4px;
1189
- padding:1px 7px;flex:none}}
1190
- .scard[data-unused]{{opacity:.86}}
1191
- .sc-conf{{font-size:10.5px;font-weight:800;color:#8a5a00;background:var(--case-soft);border:1px solid #e8c98a;
1192
- border-radius:4px;padding:0 7px;flex:none}}
1193
- .sc-extag{{margin-top:8px;padding-top:7px;border-top:1px dashed var(--line-strong);font-size:11px;color:#0b6e4f;font-weight:700}}
1194
- .sc-chain{{font-size:11.5px;color:var(--brand);margin-top:3px;font-weight:600;line-height:1.6;cursor:help}}
1195
- .sc-more{{display:none;margin:-3px 2px 4px;text-align:right;font-size:11px;color:var(--brand);font-weight:700;cursor:pointer;user-select:none}}
1196
- .scard.clampable .sc-more{{display:block}}
1197
- .scard.clampable .sc-more::before{{content:"展开全文 ▾"}}
1198
- .scard.clampable.open .sc-more::before{{content:"收起 ▴"}}
1199
- .cmp{{margin:0 0 10px;border:1px solid var(--line);border-radius:10px;overflow:hidden}}
1200
- .cmp-tag{{font-size:11px;font-weight:800;padding:3px 10px}}
1201
- .cmp-side{{padding:9px 12px;font-size:12.8px;line-height:1.7}}
1202
- .cmp-side p{{margin:0}}
1203
- .cmp-ai{{background:#fbfcfe;color:#374151}}
1204
- .cmp-ai .cmp-tag{{background:#eef1f6;color:var(--ref)}}
1205
- .cmp-src{{background:#f4faf7;color:#2f4a3e;border-top:1px dashed var(--line-strong)}}
1206
- .cmp-src .cmp-tag{{background:var(--policy-soft);color:#0b6e4f}}
1207
- .cmp-src .sc-excerpt{{display:block;-webkit-line-clamp:unset;background:#fff;cursor:auto;font-size:12px;padding:8px 10px;margin:0}}
1208
- .sc-excerpt{{margin:7px 0;padding:9px 10px;border-radius:7px;background:#f8fafc;color:#42566f;font-size:12px;line-height:1.7;
1209
- display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;cursor:pointer}}
1210
- .scard.open .sc-excerpt{{display:block;-webkit-line-clamp:unset}}
1211
- .sc-excerpt.rich{{overflow-x:auto}}
1212
- .sc-excerpt.rich table{{width:max-content;min-width:100%;border-collapse:collapse;background:#fff;font-size:12px}}
1213
- .sc-excerpt.rich td,.sc-excerpt.rich th{{min-width:92px;max-width:220px;padding:7px 8px;border:1px solid var(--line);
1214
- vertical-align:top;word-break:break-word}}
1215
- .sc-excerpt.rich thead td,.sc-excerpt.rich th{{background:#f3f4f6;color:#374151;font-weight:700}}
1216
- .scard .sc-links a{{font-size:12px}}
1217
- .scard .sc-links{{margin-top:4px}}
1218
- .no-link{{font-size:11.5px;color:var(--muted)}}
1219
- .uncited-group{{margin-top:12px;border-top:1px dashed var(--line-strong);padding-top:10px}}
1220
- .ug-title{{font-size:12.5px;color:var(--muted);font-weight:700;line-height:1.6}}
1221
- .uncited-group .uncited-list{{margin-top:10px}}
1222
- /* 知识专库 */
1223
- .kb-zone{{margin-top:14px;border-top:1px dashed var(--line-strong);padding-top:12px}}
1224
- .kb-title{{font-size:12.5px;font-weight:800;color:var(--navy)}}
1225
- .kb-desc{{font-size:11.3px;color:var(--muted);line-height:1.65;margin:3px 0 8px}}
1226
- .kb-list{{display:flex;flex-direction:column;gap:7px}}
1227
- .kb-chip{{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid var(--line);border-radius:8px;
1228
- background:#fbfcfe;text-decoration:none;font-size:11.5px}}
1229
- .kb-chip:hover{{border-color:var(--brand);background:var(--brand-soft)}}
1230
- .kb-label{{font-weight:700;color:#374151;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
1231
- .kb-count{{padding-left:8px;border-left:1px solid var(--line);color:var(--muted);white-space:nowrap}}
1232
- .kb-arrow{{margin-left:auto;color:var(--brand);font-weight:700;white-space:nowrap}}
1233
- .empty{{color:var(--muted)}}
1234
- .foot{{text-align:center;color:var(--muted);font-size:11.5px;padding:16px 0 4px;line-height:1.8}}
1235
- @media (max-width:1020px){{
1236
- .layout{{grid-template-columns:1fr}}
1237
- .sources{{position:static;max-height:none}}
1238
- }}
1239
- /* —— 移动端专项适配(手机阅读核验报告) —— */
1240
- .mobile-nav{{display:none}}
1241
- .back-doc{{display:none}}
1242
- /* 移动端材料底部弹层:点角标就地弹出材料卡,不跳转打断阅读 */
1243
- .sheet-mask{{display:none}}
1244
- .sheet{{display:none}}
1245
- @media (max-width:680px){{
1246
- body{{font-size:14px;line-height:1.8}}
1247
- .layout{{grid-template-columns:1fr;padding:12px 10px 40px;gap:14px}}
1248
- .topbar{{padding:8px 12px;font-size:12px;gap:4px;flex-wrap:wrap}}
1249
- .topbar .tags span{{font-size:10.5px;padding:1px 8px;margin-left:4px}}
1250
- .r-head{{padding:16px 14px;border-radius:10px}}
1251
- .r-head h1{{font-size:18px}}
1252
- .r-head .sub{{font-size:11.5px;line-height:1.6}}
1253
- .verify{{padding:13px 14px;border-radius:10px}}
1254
- .v-head{{font-size:14px}}
1255
- .v-grid{{grid-template-columns:1fr;gap:2px 0}}
1256
- .vi{{flex-wrap:wrap;gap:4px 8px}}
1257
- .vi .d{{min-width:0}}
1258
- .warn-box{{font-size:12.5px;padding:11px 12px}}
1259
- .doc-sec{{padding:14px;border-radius:10px}}
1260
- .sec-no{{width:22px;height:22px;font-size:12px;border-radius:6px}}
1261
- .sec-head{{gap:7px;padding-bottom:8px;margin-bottom:8px}}
1262
- .sec-head h3{{font-size:15px}}
1263
- .sec-badge{{margin-left:0;font-size:11px}}
1264
- .doc-block p,.doc-item p{{font-size:13.5px;line-height:1.95}}
1265
- .doc-sub{{font-size:14px;margin:12px 0 6px}}
1266
- .data-tbl{{font-size:12px}}
1267
- .data-tbl th,.data-tbl td{{padding:6px 7px;line-height:1.55}}
1268
- .cite{{font-size:11px;padding:0 4px}}
1269
- .ev-chip summary{{font-size:11px}}
1270
- .sources{{padding:12px;border-radius:10px}}
1271
- .scard{{padding:10px 11px}}
1272
- .sc-excerpt{{font-size:11.5px}}
1273
- .sc-extag{{font-size:10.5px}}
1274
- .sc-chain{{font-size:11px}}
1275
- .cmp-tag{{font-size:11px;font-weight:800;padding:3px 10px}}
1276
- .cmp-side{{padding:9px 12px;font-size:12.8px;line-height:1.7}}
1277
- .kb-chip{{flex-wrap:wrap}}
1278
- .kb-label{{white-space:normal}}
1279
- .mobile-nav{{display:block;margin:0 0 14px;padding:11px 14px;border:1.5px solid var(--brand);
1280
- border-radius:10px;background:var(--brand-soft);color:var(--brand);font-weight:800;
1281
- font-size:13.5px;text-decoration:none;text-align:center}}
1282
- .back-doc{{display:inline-block;margin:0 0 8px;font-size:12px;color:var(--brand);
1283
- font-weight:700;text-decoration:none}}
1284
- .sheet-mask{{display:block;position:fixed;inset:0;background:rgba(11,31,58,.45);z-index:99;opacity:0;
1285
- pointer-events:none;transition:opacity .2s}}
1286
- .sheet-mask.show{{opacity:1;pointer-events:auto}}
1287
- .sheet{{display:block;position:fixed;left:0;right:0;bottom:0;z-index:100;background:#fff;
1288
- border-radius:14px 14px 0 0;box-shadow:0 -8px 30px rgba(11,31,58,.25);
1289
- max-height:68vh;overflow-y:auto;-webkit-overflow-scrolling:touch;
1290
- padding:10px 16px 22px;transform:translateY(105%);transition:transform .25s ease}}
1291
- .sheet.show{{transform:translateY(0)}}
1292
- .sheet-grab{{width:38px;height:4px;border-radius:2px;background:#c9d4e2;margin:2px auto 8px}}
1293
- .sheet-head{{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}}
1294
- .sheet-head b{{font-size:13.5px;color:var(--navy)}}
1295
- .sheet-close{{border:1px solid var(--line);background:#f5f8fc;border-radius:8px;color:#3b4a61;
1296
- font-size:12.5px;font-weight:700;padding:5px 14px;cursor:pointer}}
1297
- .sheet .scard{{box-shadow:none;margin-bottom:0}}
1298
- .sheet .sc-excerpt{{display:block;-webkit-line-clamp:unset;cursor:auto}}
1299
- }}
1300
- @media print{{
1301
- .topbar,.src-search{{display:none!important}}
1302
- .layout{{grid-template-columns:1fr;max-width:none;padding:0;gap:14px}}
1303
- body{{background:#fff;font-size:12.5px}}
1304
- .sources{{position:static;max-height:none;border:0;padding:0;overflow:visible}}
1305
- .r-head,.verify,.doc-sec{{border-color:#bbb;box-shadow:none;break-inside:avoid}}
1306
- .sc-excerpt{{display:block;-webkit-line-clamp:unset;cursor:auto}}
1307
- .uncited-group[open] .uncited-list,.uncited-group{{break-inside:avoid}}
1308
- .scard{{break-inside:avoid}}
1309
- .cite{{background:#eee;color:#333}}
1310
- }}
1311
- </style>
2278
+ <style>{PAGE_CSS}</style>
1312
2279
  </head>
1313
2280
  <body>
1314
2281
 
1315
2282
  <header class="topbar">
1316
- <div class="tb-title">{esc(display_title)} · 可信核验报告</div>
1317
- <div class="tags">
1318
- <span>生成于 {esc(generated)}</span>
1319
- <span>材料来源:深知可信统一问答</span>
2283
+ <div class="tb-left">
2284
+ <span class="tb-stamp">可信核验报告</span>
2285
+ <span class="tb-title">{esc(display_title)}</span>
2286
+ </div>
2287
+ <div class="tb-right">
2288
+ <div class="view-switch" role="tablist" aria-label="视图切换">
2289
+ <button class="on" data-view="report" type="button">核验报告</button>
2290
+ <button data-view="library" type="button">材料专库</button>
2291
+ </div>
2292
+ <div class="tb-tools">
2293
+ <button id="btn-reading" type="button" aria-pressed="false" title="隐藏核验元素,纯阅读正文">只看正文</button>
2294
+ <button id="btn-copy" type="button" title="复制正文纯文本">复制全文</button>
2295
+ <span class="print-menu">
2296
+ <button id="btn-print" type="button" aria-haspopup="true" title="浏览器打印/另存为 PDF">打印归档 ▾</button>
2297
+ <span class="print-drop" id="print-drop" hidden>
2298
+ <button id="print-body" type="button">只打印正文</button>
2299
+ <button id="print-full" type="button">完整归档(含核验材料)</button>
2300
+ </span>
2301
+ </span>
2302
+ </div>
1320
2303
  </div>
2304
+ <div class="progress" aria-hidden="true"><i></i></div>
1321
2305
  </header>
1322
2306
 
1323
- <div class="layout">
1324
- <main class="report" aria-label="核验报告正文">
1325
- <div class="r-head" id="doc-top">
1326
- <h1>{esc(display_title)}</h1>
1327
- {question_html}
1328
- <div class="sub">{esc(meta_line)}</div>
2307
+ <div class="hero">
2308
+ <div class="r-badge">可信核验报告</div>
2309
+ <h1>{esc(display_title)}</h1>
2310
+ {question_html}
2311
+ <div class="meta">{esc(meta_line)} | 材料来源:深知可信咨询</div>
2312
+ <div class="hero-switch">
2313
+ <div class="view-switch" role="tablist" aria-label="视图切换">
2314
+ <button class="on" data-view="report" type="button">核验报告</button>
2315
+ <button data-view="library" type="button">材料专库({len(sources)})</button>
1329
2316
  </div>
2317
+ </div>
2318
+ </div>
2319
+
2320
+ <div class="app container" data-view="report">
2321
+ {render_process_bar(process_stats, verification)}
2322
+
2323
+ <main class="view" id="view-report" aria-label="核验报告正文">
1330
2324
  {citation_warning}
1331
2325
  {render_verify_panel(verification)}
1332
- <a class="mobile-nav" href="#sources-panel">查看核验材料({len(sources)} 条 · 点击角标可定位原文)↓</a>
2326
+ <div class="doc-paper">
1333
2327
  {render_section_cards(sections, sources)}
1334
- <div class="foot">深知可信咨询 · 可信核验报告 | 核验方法:统一问答召回 → 逐条溯源 → 引用对应 → 交付前检查 | 内容由 AI 生成,仅供参考,政策现行效力以官方发布为准</div>
2328
+ </div>
2329
+ {render_archive_zone(extract_trace_archives(payload), len(sources))}
2330
+ <div class="foot">深知可信咨询 · 可信核验报告 | 内容由 AI 生成,仅供参考,政策现行效力以官方发布为准</div>
1335
2331
  </main>
1336
- {render_sources_panel(sources, used, kb_zone)}
2332
+
2333
+ {render_library_view(sources, hot_terms)}
2334
+ {render_print_appendix(sources)}
1337
2335
  </div>
1338
2336
 
1339
- <div class="sheet-mask" aria-hidden="true"></div>
1340
- <div class="sheet" role="dialog" aria-label="依据对照">
2337
+ {render_toc(sections)}
2338
+
2339
+ <div class="ev-panel" id="ev-pop" hidden></div>
2340
+ {jb_tables_script}<div class="sheet-mask" aria-hidden="true"></div>
2341
+ <div class="sheet" role="dialog" aria-label="核验材料">
1341
2342
  <div class="sheet-grab"></div>
1342
2343
  <div class="sheet-head"><b>依据对照</b><button class="sheet-close" type="button">收起</button></div>
1343
2344
  <div class="sheet-body"></div>
1344
2345
  </div>
1345
2346
 
1346
- <script>
1347
- (function () {{
1348
- "use strict";
1349
- var cards = Array.prototype.slice.call(document.querySelectorAll(".scard"));
1350
- var byId = {{}};
1351
- cards.forEach(function (c) {{
1352
- var id = c.getAttribute("data-cite-id");
1353
- if (id) byId[id] = c;
1354
- }});
1355
-
1356
- /* 移动端底部弹层:点角标就地展示材料卡,不打断正文阅读 */
1357
- var sheet = document.querySelector(".sheet");
1358
- var mask = document.querySelector(".sheet-mask");
1359
- function isMobile() {{
1360
- return window.matchMedia("(max-width:680px)").matches;
1361
- }}
1362
- function escHtml(s) {{
1363
- var d = document.createElement("div");
1364
- d.textContent = s;
1365
- return d.innerHTML;
1366
- }}
1367
- function sentenceOf(el) {{
1368
- var para = el && el.closest ? el.closest(".doc-block,.doc-item") : null;
1369
- return para && para.querySelector("p") ? para.querySelector("p").innerText.trim() : "";
1370
- }}
1371
- function openSheet(card, sentence) {{
1372
- if (!sheet) return;
1373
- var body = sheet.querySelector(".sheet-body");
1374
- body.innerHTML = "";
1375
- if (sentence) {{
1376
- var excerpt = card.querySelector(".sc-excerpt");
1377
- var cmp = document.createElement("div");
1378
- cmp.className = "cmp";
1379
- cmp.innerHTML =
1380
- '<div class="cmp-side cmp-ai"><div class="cmp-tag">正文表述(AI 生成)</div><p>' + escHtml(sentence) + '</p></div>' +
1381
- '<div class="cmp-side cmp-src"><div class="cmp-tag">原文原段(非 AI 生成)</div>' +
1382
- '<div class="sc-excerpt">' + (excerpt ? excerpt.innerHTML : "") + '</div></div>';
1383
- body.appendChild(cmp);
1384
- }}
1385
- var clone = card.cloneNode(true);
1386
- clone.removeAttribute("id");
1387
- clone.classList.remove("hide");
1388
- clone.classList.add("open");
1389
- var sheetMore = clone.querySelector(".sc-more");
1390
- if (sheetMore) sheetMore.remove();
1391
- body.appendChild(clone);
1392
- sheet.classList.add("show");
1393
- mask.classList.add("show");
1394
- document.body.style.overflow = "hidden";
1395
- sheet.scrollTop = 0;
1396
- }}
1397
- function closeSheet() {{
1398
- if (!sheet) return;
1399
- sheet.classList.remove("show");
1400
- mask.classList.remove("show");
1401
- document.body.style.overflow = "";
1402
- }}
1403
- if (sheet && mask) {{
1404
- mask.addEventListener("click", closeSheet);
1405
- var closeBtn = sheet.querySelector(".sheet-close");
1406
- if (closeBtn) closeBtn.addEventListener("click", closeSheet);
1407
- }}
1408
-
1409
- /* 角标 → 来源卡:精确 ID 匹配,缺失即红色警示,绝不按位置猜测。
1410
- 手机单栏下不滚动定位(会跳到页面底部打断阅读),改为底部弹层就地查看。 */
1411
- document.querySelectorAll(".data-cite,[data-cite]").forEach(function (btn) {{
1412
- if (btn.classList.contains("sheet-close")) return;
1413
- btn.addEventListener("click", function () {{
1414
- var card = byId[btn.getAttribute("data-cite")];
1415
- if (!card) {{
1416
- btn.classList.add("unresolved");
1417
- if (console.error) console.error("[核验] 未绑定角标:", btn.getAttribute("data-cite"));
1418
- return;
1419
- }}
1420
- if (isMobile()) {{
1421
- openSheet(card, sentenceOf(btn));
1422
- return;
1423
- }}
1424
- card.classList.remove("hide", "open");
1425
- card.classList.add("hl", "open");
1426
- card.scrollIntoView({{ block: "center", behavior: "smooth" }});
1427
- setTimeout(function () {{ card.classList.remove("hl"); }}, 2200);
1428
- }});
1429
- }});
1430
-
1431
- /* 摘录点击展开/收起:内容被截断(超出 4 行)的卡片显示"展开全文"引导,
1432
- 未截断的短摘录不显示,避免误导 */
1433
- cards.forEach(function (c) {{
1434
- var ex = c.querySelector(".sc-excerpt");
1435
- if (!ex) return;
1436
- if (ex.scrollHeight > ex.clientHeight + 4) c.classList.add("clampable");
1437
- var more = c.querySelector(".sc-more");
1438
- function toggleExcerpt() {{ c.classList.toggle("open"); }}
1439
- ex.addEventListener("click", function (e) {{
1440
- if (e.target.closest("a")) return;
1441
- toggleExcerpt();
1442
- }});
1443
- if (more) {{
1444
- more.addEventListener("click", toggleExcerpt);
1445
- more.addEventListener("keydown", function (e) {{
1446
- if (e.key === "Enter" || e.key === " ") {{ e.preventDefault(); toggleExcerpt(); }}
1447
- }});
1448
- }}
1449
- }});
1450
-
1451
- /* 证据 chips(灰框):桌面端点击就地展开并高亮右栏来源卡;手机端不就地展开,点击直接弹出底部材料弹层 */
1452
- document.querySelectorAll(".ev-chip").forEach(function (chip) {{
1453
- var summary = chip.querySelector("summary");
1454
- if (summary) {{
1455
- summary.addEventListener("click", function (e) {{
1456
- if (!isMobile()) return;
1457
- e.preventDefault();
1458
- var card = byId[chip.getAttribute("data-cite")];
1459
- if (card) openSheet(card, sentenceOf(chip));
1460
- }});
1461
- }}
1462
- chip.addEventListener("toggle", function () {{
1463
- if (!chip.open || isMobile()) return;
1464
- var card = byId[chip.getAttribute("data-cite")];
1465
- if (!card) return;
1466
- cards.forEach(function (c) {{ c.classList.remove("hl"); }});
1467
- card.classList.add("hl");
1468
- setTimeout(function () {{ card.classList.remove("hl"); }}, 2200);
1469
- }});
1470
- }});
1471
-
1472
- /* 搜索 */
1473
- var kw = "";
1474
- function apply() {{
1475
- cards.forEach(function (c) {{
1476
- var okKw = !kw || (c.textContent || "").toLowerCase().indexOf(kw) !== -1;
1477
- c.classList.toggle("hide", !okKw);
1478
- }});
1479
- }}
1480
- var search = document.querySelector(".src-search");
1481
- if (search) search.addEventListener("input", function () {{ kw = search.value.trim().toLowerCase(); apply(); }});
1482
- }})();
1483
- </script>
2347
+ <script>{PAGE_JS}</script>
1484
2348
  </body>
1485
2349
  </html>"""
1486
2350
 
1487
2351
 
1488
- def align_sources_to_answer(answer: str, sources: List[Dict[str, str]]) -> List[Dict[str, str]]:
1489
- cited = citation_ids(answer)
1490
- if not cited or not sources:
1491
- return sources
1492
- existing = {source["id"] for source in sources}
1493
- if existing.intersection(cited):
1494
- return sources
1495
- aligned = [dict(source) for source in sources]
1496
- for idx, citation in enumerate(cited):
1497
- if idx >= len(aligned):
1498
- break
1499
- aligned[idx]["id"] = citation
1500
- return aligned
2352
+ # ============================================================
2353
+ # 链接活性检测(对齐公文写作 3.7.0:生成时真实检测,客观信号判死)
2354
+ # ============================================================
2355
+
2356
+ # 软 404 关键词:政府站常以 HTTP 200 返回"页面不存在"错误页,状态码识别不了,
2357
+ # 需读页面标题嗅探。关键词取自公文写作侧实测样例,且仅匹配 <title>
2358
+ # (政策正文不会出现在标题里),误杀风险极低。
2359
+ SOFT_404_KEYWORDS = ("页面不存在", "页面未找到", "您访问的页面", "已删除", "已下线", "无法找到", "not found", "404")
2360
+
2361
+
2362
+ def check_link_alive(url: str, timeout: int = 8) -> bool:
2363
+ """检测原文链接是否仍然可达。失效判据(客观信号,与请求方无关):
2364
+ ① HTTP 404/410;② 软件 404——HTTP 200 但页面标题为典型失效页。
2365
+ 连接失败、超时、403、5xx 等一律视为"无法确认"按有效处理——政府站
2366
+ 常对脚本请求反爬,凭这些判死会误杀可用链接。
2367
+ """
2368
+ for method in ("HEAD", "GET"):
2369
+ try:
2370
+ req = urllib.request.Request(
2371
+ url, method=method,
2372
+ headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"},
2373
+ )
2374
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
2375
+ if resp.status in (404, 410):
2376
+ return False
2377
+ if method == "GET":
2378
+ chunk = resp.read(4096).decode("utf-8", errors="replace")
2379
+ title = re.search(r"<title>(.*?)</title>", chunk, re.I | re.S)
2380
+ text = title.group(1) if title else chunk[:200]
2381
+ lowered = text.lower()
2382
+ return not any(k in text or k in lowered for k in SOFT_404_KEYWORDS)
2383
+ except urllib.error.HTTPError as e:
2384
+ if method == "GET":
2385
+ return e.code not in (404, 410)
2386
+ except Exception:
2387
+ if method == "GET":
2388
+ return True
2389
+ return True
2390
+
2391
+
2392
+ def mark_dead_links(sources: List[Dict[str, str]]) -> int:
2393
+ """并发检测全部材料的原文链接,404/410 的标记 link_dead=True。返回失效数。
2394
+
2395
+ 咨询接口无存档快照(screenShotPath)通道:失效链接如实不出"查看全文",
2396
+ 改用知识专库链接(policyUrl)回看,两者都缺则在卡片标注"待补链接"。
2397
+ """
2398
+ targets = [(i, s["url"]) for i, s in enumerate(sources)
2399
+ if (s.get("url") or "").strip() and s["url"] != "接口未返回"]
2400
+ if not targets:
2401
+ return 0
2402
+ with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
2403
+ alive = dict(zip((i for i, _ in targets), pool.map(check_link_alive, (u for _, u in targets))))
2404
+ dead = 0
2405
+ for i, _ in targets:
2406
+ if not alive.get(i, True):
2407
+ sources[i]["link_dead"] = True
2408
+ dead += 1
2409
+ return dead
1501
2410
 
1502
2411
 
1503
2412
  def main() -> None:
1504
2413
  parser = argparse.ArgumentParser(description="生成深知可信咨询可信核验报告 HTML")
1505
2414
  parser.add_argument("input_json", help="gov_chat.py 的 --json-only 输出 JSON(位于 official-docs/search-results/)")
1506
2415
  parser.add_argument("--output", help="输出 HTML 路径;不传时根据问题自动生成短文件名到 official-docs/output/")
1507
- parser.add_argument("--title", default="深知可信咨询核验报告", help="页面标题")
2416
+ parser.add_argument("--title", default="可信核验报告", help="页面标题")
1508
2417
  parser.add_argument("--answer-file", help="最终回答正文文件。整理综合后必须传入,确保 HTML 展示的答案与聊天答案一致。")
1509
2418
  parser.add_argument("--self-check-file", help="交付前检查结果 JSON(五项:角标存在/角标对应来源/结论可核验/答案一致/来源清单覆盖),值支持 通过/pass/✓ 等写法。")
1510
2419
  parser.add_argument("--clean-md-output", help="输出干净 Markdown 路径;内容来自同一份最终答案,并移除 [1]、【1】等溯源角标。")
1511
2420
  parser.add_argument("--question", default="", help="用户问题,用于生成咨询问题行与文件名。")
2421
+ parser.add_argument("--skip-link-check", action="store_true", help="跳过原文链接活性检测(默认检测:404/410 标记失效,连接失败/403 放行不误杀)")
1512
2422
  args = parser.parse_args()
1513
2423
 
1514
2424
  payload = load_json(_resolve_input(args.input_json))
@@ -1526,7 +2436,6 @@ def main() -> None:
1526
2436
  # Agent 可修正的问题在这里一律拒绝生成,倒逼先修正再交付;
1527
2437
  # 仅接口未返回原文链接、政策效力无法自动判定等不可抗因素由报告温和提示。
1528
2438
  pre_sources = extract_sources(unwrap(payload))
1529
- pre_source_ids = {s["id"] for s in pre_sources}
1530
2439
  pre_cited = citation_ids(base_answer)
1531
2440
  if pre_sources and not pre_cited:
1532
2441
  print(
@@ -1535,7 +2444,9 @@ def main() -> None:
1535
2444
  file=sys.stderr,
1536
2445
  )
1537
2446
  raise SystemExit(1)
1538
- unbound = [cid for cid in pre_cited if cid not in pre_source_ids]
2447
+ # 绑定解析与重编号共用同一逻辑:段落全局编号(现接口)/ 材料级编号(旧接口)皆可
2448
+ bound = resolve_citation_targets(base_answer, pre_sources)
2449
+ unbound = [cid for cid in pre_cited if cid not in bound]
1539
2450
  if unbound:
1540
2451
  print(
1541
2452
  f"错误:最终答案中的角标 {'、'.join('[' + c + ']' for c in unbound)} 未对应任何来源材料,已拒绝生成。\n"
@@ -1572,6 +2483,13 @@ def main() -> None:
1572
2483
  final_answer_path.parent.mkdir(parents=True, exist_ok=True)
1573
2484
  final_answer_path.write_text(final_answer, encoding="utf-8")
1574
2485
 
2486
+ # 生成时链接活性检测(对齐公文写作 3.7.0):404/410 标记失效;连接失败/403
2487
+ # 放行不误杀。咨询接口无存档快照,失效链接改用知识专库链接或如实标注。
2488
+ if not args.skip_link_check:
2489
+ dead = mark_dead_links(prepared_sources)
2490
+ if dead:
2491
+ print(f"链接检测:{dead} 条原文链接已失效(404/410),将改用知识专库链接或如实标注")
2492
+
1575
2493
  source_map = {}
1576
2494
  for source in prepared_sources:
1577
2495
  source_map.setdefault(source["id"], source)