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