dknowc-dsh 1.1.0 → 1.2.0

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