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,18 @@
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
+ 布局:深色顶栏 + 左栏报告正文(分节卡片)+ 右栏核验材料面板(类型筛选/搜索);
14
+ 打印归档模式(@media print 单栏全展开)。
15
+ """
3
16
 
4
17
  from __future__ import annotations
5
18
 
@@ -9,9 +22,13 @@ import json
9
22
  import re
10
23
  from datetime import datetime
11
24
  from pathlib import Path
12
- from typing import Any, Dict, Iterable, List, Optional
25
+ from typing import Any, Dict, List, Optional, Tuple
13
26
 
14
27
 
28
+ # ============================================================
29
+ # 基础工具
30
+ # ============================================================
31
+
15
32
  def esc(value: Any) -> str:
16
33
  return html.escape(str(value or ""), quote=True)
17
34
 
@@ -67,6 +84,54 @@ def strip_citation_markers(text: str) -> str:
67
84
  return text.strip() + ("\n" if text.strip() else "")
68
85
 
69
86
 
87
+ # ============================================================
88
+ # 素材四分类
89
+ # ============================================================
90
+
91
+ KIND_CATALOG = {
92
+ "policy": ("政策依据", "pol"),
93
+ "data": ("数据支撑", "dat"),
94
+ "case": ("参考案例", "cas"),
95
+ "reference": ("表述参考", "ref"),
96
+ "material": ("材料", "mat"),
97
+ }
98
+
99
+
100
+ def normalize_kind(raw: str) -> Tuple[str, str, str]:
101
+ """把来源类型文本归一化为(类型键, 中文标签, css 类名)。"""
102
+ text = str(raw or "")
103
+ if "政策" in text or "法规" in text or "依据" in text or "policy" in text.lower():
104
+ key = "policy"
105
+ elif "数据" in text or "统计" in text or "指标" in text or "data" in text.lower():
106
+ key = "data"
107
+ elif "案例" in text or "经验" in text or "做法" in text or "case" in text.lower():
108
+ key = "case"
109
+ elif "表述" in text or "行文" in text or "reference" in text.lower():
110
+ key = "reference"
111
+ else:
112
+ key = "material"
113
+ label, css = KIND_CATALOG[key]
114
+ return key, label, css
115
+
116
+
117
+ def parse_year_month(raw: str) -> Optional[Tuple[int, int]]:
118
+ """从日期文本提取(年, 月);识别 2025年8月 / 2025-08 / 2025.08 / 2025-08-15。"""
119
+ text = str(raw or "").strip()
120
+ if not text:
121
+ return None
122
+ m = re.search(r"(20\d{2})\s*[年./-]\s*(\d{1,2})", text)
123
+ if m:
124
+ return int(m.group(1)), min(int(m.group(2)), 12)
125
+ m = re.search(r"(20\d{2})", text)
126
+ if m:
127
+ return int(m.group(1)), 1
128
+ return None
129
+
130
+
131
+ # ============================================================
132
+ # 素材提取(沿用原数据层)
133
+ # ============================================================
134
+
70
135
  def paragraph_text(item: Dict[str, Any]) -> str:
71
136
  paragraphs = item.get("content") or item.get("段落") or item.get("paragraphs") or item.get("paragraphList")
72
137
  if isinstance(paragraphs, list):
@@ -83,6 +148,8 @@ def paragraph_text(item: Dict[str, Any]) -> str:
83
148
  item.get("摘录"),
84
149
  item.get("摘要"),
85
150
  item.get("相关段落"),
151
+ item.get("支撑内容"),
152
+ item.get("support"),
86
153
  item.get("全文"),
87
154
  item.get("content"),
88
155
  item.get("text"),
@@ -133,6 +200,8 @@ def source_from_article(item: Dict[str, Any], index: int, segment: Optional[Dict
133
200
  "id": explicit_id or str(index),
134
201
  "title": first_str(
135
202
  item.get("文章标题"),
203
+ item.get("material_name"),
204
+ item.get("材料名称"),
136
205
  item.get("title"),
137
206
  item.get("标题"),
138
207
  item.get("name"),
@@ -154,11 +223,17 @@ def source_from_article(item: Dict[str, Any], index: int, segment: Optional[Dict
154
223
  "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")),
155
224
  "policy_url": first_str(item.get("policyUrl"), item.get("policy_url"), item.get("知识专库原文"), vo.get("policyUrl")),
156
225
  "excerpt": segment.get("text") or paragraph_text(item),
157
- "section": first_str(segment.get("title")),
158
- "kind": first_str(item.get("类型"), item.get("type"), vo.get("typeName"), "材料"),
226
+ "section": first_str(segment.get("title"), item.get("正文对应"), item.get("section")),
227
+ "kind": first_str(item.get("类型"), item.get("type"), item.get("素材类型"), vo.get("typeName"), "材料"),
228
+ "verify_note": first_str(item.get("核验"), item.get("verification"), item.get("核验说明")),
159
229
  "area": first_str(item.get("intentionArea"), item.get("area"), item.get("地域")),
160
- "reliability": first_str(item.get("createDateReliability"), item.get("reliability"), item.get("时间可靠性")),
161
230
  }
231
+ key, label, css = normalize_kind(source["kind"])
232
+ source["type_key"] = key
233
+ source["type_label"] = label
234
+ source["type_css"] = css
235
+ source["has_link"] = bool(source["url"] and source["url"] != "接口未返回") or bool(source["policy_url"])
236
+ source["verified"] = bool(source["excerpt"]) and source["has_link"]
162
237
  return source
163
238
 
164
239
 
@@ -247,8 +322,17 @@ def extract_answer(payload: Dict[str, Any]) -> str:
247
322
  return "接口返回中未识别到正文内容;请查看右侧来源或原始 JSON。"
248
323
 
249
324
 
250
- def extract_trace_url(payload: Dict[str, Any]) -> str:
251
- return first_str(payload.get("traceUrl"), payload.get("trace_url"), payload.get("traceReportUrl"))
325
+ def extract_question(payload: Dict[str, Any]) -> str:
326
+ content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
327
+ data = content.get("data") if isinstance(content.get("data"), dict) else {}
328
+ return first_str(
329
+ payload.get("question"),
330
+ payload.get("input"),
331
+ payload.get("query"),
332
+ data.get("用户问题"),
333
+ content.get("query"),
334
+ content.get("question"),
335
+ )
252
336
 
253
337
 
254
338
  def extract_knowledge_base(payload: Dict[str, Any]) -> str:
@@ -282,13 +366,149 @@ def citation_ids(answer: str) -> List[str]:
282
366
  return ids
283
367
 
284
368
 
369
+ # ============================================================
370
+ # 核验计算(报告级)
371
+ # ============================================================
372
+
373
+ SELF_CHECK_ITEMS = [
374
+ ("fact_basis", "事实有据"),
375
+ ("structure", "结构完整"),
376
+ ("placeholders", "无占位残留"),
377
+ ("ai_flavor", "无 AI 味"),
378
+ ("format", "格式合规"),
379
+ ]
380
+
381
+ SELF_CHECK_LABELS = dict(SELF_CHECK_ITEMS)
382
+ SELF_CHECK_LABELS.update({
383
+ "事实有据": "事实有据", "结构完整": "结构完整", "无占位残留": "无占位残留",
384
+ "无AI味": "无 AI 味", "无 AI 味": "无 AI 味", "格式合规": "格式合规",
385
+ })
386
+
387
+
388
+ def classify_check_value(raw: Any) -> Tuple[str, str]:
389
+ """把自检项的值解析为(状态, 核验说明)。
390
+
391
+ 兼容多种写法:`pass` / `true` / `通过` / `通过:说明文字` / `✓` 等;
392
+ 值后面的说明文字保留下来供核验单展示。无法识别的状态按未通过处理,
393
+ 并保留原文,不假装通过。
394
+ """
395
+ text = str(raw or "").strip()
396
+ lowered = text.lower()
397
+ for prefix in ("未通过", "不通过", "不合格", "fail", "false", "否", "✗", "no"):
398
+ if lowered.startswith(prefix):
399
+ return "fail", text[len(prefix):].lstrip("::,,、 ").strip()
400
+ for prefix in ("已通过", "通过", "合格", "pass", "ok", "true", "是", "✓", "yes"):
401
+ if lowered.startswith(prefix):
402
+ return "pass", text[len(prefix):].lstrip("::,,、 ").strip()
403
+ return "fail", text
404
+
405
+
406
+ def normalize_self_check(raw: Any) -> Optional[Dict[str, Tuple[str, str]]]:
407
+ if not isinstance(raw, dict):
408
+ return None
409
+ items: Dict[str, Tuple[str, str]] = {}
410
+ for key, value in raw.items():
411
+ status, note = classify_check_value(value)
412
+ label = SELF_CHECK_LABELS.get(key, SELF_CHECK_LABELS.get(str(key), str(key)))
413
+ items[label] = (status, note)
414
+ return items or None
415
+
416
+
417
+ def compute_verification(answer: str, sources: List[Dict[str, str]], payload: Dict[str, Any],
418
+ generated_at: Optional[datetime] = None) -> Dict[str, Any]:
419
+ """核验报告单数据。只计算脚本真实可得的结果,不虚构通过。"""
420
+ generated_at = generated_at or datetime.now()
421
+
422
+ # ① 依据溯源:摘录可比对 + 原文链接/知识专库可回看
423
+ missing_links = [s["title"] for s in sources if not s.get("has_link")]
424
+ missing_excerpts = [s["title"] for s in sources if not (s.get("excerpt") or "").strip()]
425
+ trace_passed = len(sources) - len(set(missing_links) | set(missing_excerpts))
426
+
427
+ # ② 引用绑定:正文角标与来源卡一一对应(按角标出现次数计,与用户在正文中数到的一致)
428
+ cited = citation_ids(answer)
429
+ all_marks = re.findall(r"\[(\d+)\]", answer)
430
+ source_ids = {s["id"] for s in sources}
431
+ unbound_ids = [cid for cid in cited if cid not in source_ids]
432
+ unbound = [cid for cid in unbound_ids for _ in range(all_marks.count(cid))]
433
+ no_citation = bool(sources) and not cited
434
+
435
+ # ③ 时效检查:材料日期范围与历史材料计数
436
+ dated = [parse_year_month(s.get("date")) for s in sources]
437
+ dated = [d for d in dated if d]
438
+ freshness = None
439
+ old_count = 0
440
+ if dated:
441
+ freshness = {
442
+ "min": min(dated),
443
+ "max": max(dated),
444
+ "old_count": sum(1 for y, _ in dated if y <= generated_at.year - 3),
445
+ }
446
+
447
+ # ④ 类型覆盖:素材四分类分布
448
+ coverage = {key: 0 for key in KIND_CATALOG}
449
+ for s in sources:
450
+ coverage[s.get("type_key", "material")] = coverage.get(s.get("type_key", "material"), 0) + 1
451
+
452
+ # ⑤ 成稿自检:由溯源 JSON 的 self_check 传入,未传入如实显示未记录
453
+ self_check_raw = None
454
+ for holder in (payload, payload.get("content") if isinstance(payload.get("content"), dict) else {}):
455
+ self_check_raw = self_check_raw or holder.get("selfCheck") or holder.get("self_check")
456
+ self_items = normalize_self_check(self_check_raw)
457
+ self_check = None
458
+ if self_items:
459
+ passed = sum(1 for status, _ in self_items.values() if status == "pass")
460
+ self_check = {"items": self_items, "passed": passed, "total": len(self_items),
461
+ "status": "pass" if passed == len(self_items) else "fail"}
462
+ else:
463
+ self_check = {"items": {}, "passed": 0, "total": len(SELF_CHECK_ITEMS), "status": "missing"}
464
+
465
+ # 政策效力:无法自动判定现行效力,列出建议人工复核
466
+ policy_count = coverage.get("policy", 0)
467
+
468
+ trace_ok = sources and trace_passed == len(sources)
469
+ binding_ok = (not unbound) and not no_citation
470
+ overall_passed = trace_ok and binding_ok
471
+
472
+ reasons = []
473
+ if not sources:
474
+ reasons.append("未识别到来源材料")
475
+ if no_citation:
476
+ reasons.append("正文未包含来源角标,无法建立引用-素材对应")
477
+ if missing_links:
478
+ reasons.append(f"{len(missing_links)} 条素材待补原文链接")
479
+ if unbound:
480
+ reasons.append(f"{len(unbound)} 处正文角标未绑定素材")
481
+ if self_check["status"] == "fail":
482
+ reasons.append("成稿自检存在未通过项")
483
+
484
+ return {
485
+ "overall": {
486
+ "passed": overall_passed,
487
+ "label": "核验完成,正文依据可交付" if overall_passed else "核验未完全通过",
488
+ "reasons": reasons,
489
+ },
490
+ "traceability": {"total": len(sources), "passed": trace_passed,
491
+ "missing_links": missing_links, "missing_excerpts": missing_excerpts},
492
+ "binding": {"total": len(all_marks), "bound": len(all_marks) - len(unbound), "unbound": unbound_ids, "no_citation": no_citation},
493
+ "freshness": freshness,
494
+ "coverage": coverage,
495
+ "self_check": self_check,
496
+ "policy_count": policy_count,
497
+ "manual_checks": [str(x) for x in (payload.get("verificationChecks") or payload.get("verification_checks") or []) if str(x).strip()],
498
+ }
499
+
500
+
501
+ # ============================================================
502
+ # 正文解析与分节
503
+ # ============================================================
504
+
285
505
  def render_inline_markdown(text: str, citation_repl) -> str:
286
506
  body = esc(text)
287
507
  body = re.sub(r"`([^`]+)`", r"<code>\1</code>", body)
288
508
  body = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", body)
289
509
  body = re.sub(r"__(.+?)__", r"<strong>\1</strong>", body)
290
510
  body = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<em>\1</em>", body)
291
- body = re.sub(r"(?<!_)_([^_\n]+)_(?!_)", r"<em>\1</em>", body)
511
+ body = re.sub(r"(?<!_)_([^_\n]+_)(?!_)", r"<em>\1</em>", body)
292
512
  body = re.sub(r"\[(\d+)\]", citation_repl, body)
293
513
  return body
294
514
 
@@ -313,15 +533,15 @@ def render_markdown_table(lines: List[str], citation_repl) -> str:
313
533
  for line in body_lines:
314
534
  cells = split_markdown_table_row(line)
315
535
  rows.append("<tr>" + "".join(f"<td>{render_inline_markdown(cell, citation_repl)}</td>" for cell in cells) + "</tr>")
316
- return f'<div class="answer-table-wrap"><table class="answer-table"><thead><tr>{head_html}</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
536
+ return f'<div class="tbl-wrap"><table class="data-tbl"><thead><tr>{head_html}</tr></thead><tbody>{"".join(rows)}</tbody></table></div>'
317
537
 
318
538
 
319
539
  def render_excerpt_html(text: str) -> str:
320
540
  value = str(text or "")
321
541
  if "<table" not in value.lower():
322
- return f'<div class="source-excerpt plain">{esc(value)}</div>'
542
+ return f'<div class="sc-excerpt plain">{esc(value)}</div>'
323
543
  cleaned = re.sub(r"(?is)<script.*?</script>", "", value)
324
- cleaned = re.sub(r"(?is)<style.*?</style>", "", cleaned)
544
+ cleaned = re.sub(r"(?is)<style.*?</style>", "", value)
325
545
  cleaned = re.sub(r"\s+on\w+\s*=\s*(['\"]).*?\1", "", cleaned)
326
546
  cleaned = re.sub(r"\s+(href|src)\s*=\s*(['\"]).*?\2", "", cleaned)
327
547
  allowed = {"table", "thead", "tbody", "tr", "td", "th", "br"}
@@ -333,171 +553,343 @@ def render_excerpt_html(text: str) -> str:
333
553
  return f"<{closing}{name}>"
334
554
 
335
555
  cleaned = re.sub(r"<\s*(/?)\s*([a-zA-Z0-9]+)(?:\s+[^>]*)?>", tag_repl, cleaned)
336
- return f'<div class="source-excerpt rich">{cleaned}</div>'
337
-
338
-
339
- def render_source_links(url: str, policy_url: str = "") -> str:
340
- links = []
341
- if url and url != "接口未返回":
342
- links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看原文</a>')
343
- if policy_url:
344
- links.append(f'<a href="{esc(policy_url)}" target="_blank" rel="noopener">知识专库原文</a>')
345
- if not links:
346
- return ""
347
- return '<div class="source-links">' + "".join(f"<span>{link}</span>" for link in links) + "</div>"
348
-
349
-
350
- def render_evidence_chips(ids: List[str], sources: List[Dict[str, str]]) -> str:
351
- source_map = {source["id"]: source for source in sources}
352
- chips = []
353
- for cid in ids:
354
- source = source_map.get(cid)
355
- if not source:
356
- continue
357
- title = source.get("title") or "未命名材料"
358
- section = source.get("section") or ""
359
- meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area"), source.get("kind")] if v)
360
- excerpt = source.get("excerpt") or "接口返回中未识别到可展示的摘录。"
361
- url = source.get("url")
362
- links = render_source_links(url, source.get("policy_url", ""))
363
- chips.append(
364
- f"""
365
- <details class="evidence-detail" data-source="{esc(cid)}">
366
- <summary><b>[{esc(cid)}]</b>{esc(short(title, 64))}</summary>
367
- <div class="evidence-panel">
368
- <div class="evidence-title">{esc(title)}</div>
369
- <div class="evidence-meta">{esc(meta)}</div>
370
- {f'<div class="evidence-section">{esc(section)}</div>' if section else ''}
371
- <p>{esc(excerpt)}</p>
372
- {links}
373
- </div>
374
- </details>
375
- """
376
- )
377
- if not chips:
378
- return ""
379
- return f'<div class="evidence-row">{"".join(chips)}</div>'
380
-
556
+ return f'<div class="sc-excerpt rich">{cleaned}</div>'
381
557
 
382
- def render_answer(answer: str, sources: List[Dict[str, str]]) -> str:
383
- valid_ids = {source["id"] for source in sources}
384
558
 
559
+ def parse_answer_blocks(answer: str, valid_ids: set) -> Tuple[List[Dict[str, Any]], set]:
560
+ """把正文 Markdown 解析为结构化块;同时收集全部角标。"""
385
561
  def repl(match: re.Match[str]) -> str:
386
562
  cid = match.group(1)
387
- disabled = "" if cid in valid_ids else " disabled"
388
- return f'<button class="cite{disabled}" data-source="{esc(cid)}" type="button">[{esc(cid)}]</button>'
563
+ cls = "cite" if cid in valid_ids else "cite unresolved"
564
+ label = cid if cid in valid_ids else f"{cid}未绑定"
565
+ return f'<button class="{cls}" data-cite="{esc(cid)}" type="button" title="核验依据 [{esc(label)}]">[{esc(label)}]</button>'
389
566
 
390
- paragraphs = []
567
+ blocks: List[Dict[str, Any]] = []
391
568
  lines = answer.split("\n")
392
569
  idx = 0
393
570
  while idx < len(lines):
394
- raw_block = lines[idx]
395
- block = raw_block.strip()
571
+ block = lines[idx].strip()
396
572
  if not block:
397
573
  idx += 1
398
574
  continue
399
- if "|" in block and idx + 1 < len(lines) and is_markdown_table_separator(lines[idx + 1]):
575
+ ids = citation_ids(block)
576
+ heading_match = re.match(r"^(#{1,4})\s+(.+)$", block)
577
+ if heading_match:
578
+ blocks.append({"kind": "heading", "level": len(heading_match.group(1)),
579
+ "text": heading_match.group(2).strip(), "cites": ids, "repl": repl})
580
+ idx += 1
581
+ elif "|" in block and idx + 1 < len(lines) and is_markdown_table_separator(lines[idx + 1]):
400
582
  table_lines = [block, lines[idx + 1].strip()]
401
583
  idx += 2
402
584
  while idx < len(lines) and "|" in lines[idx].strip() and lines[idx].strip():
403
585
  table_lines.append(lines[idx].strip())
404
586
  idx += 1
405
- ids = citation_ids("\n".join(table_lines))
406
- paragraphs.append(f'<div class="answer-block">{render_markdown_table(table_lines, repl)}{render_evidence_chips(ids, sources)}</div>')
407
- continue
408
- ids = citation_ids(block)
409
- evidence = render_evidence_chips(ids, sources)
410
- heading_match = re.match(r"^(#{1,4})\s+(.+)$", block)
411
- if heading_match:
412
- level = min(len(heading_match.group(1)) + 1, 4)
413
- heading = render_inline_markdown(heading_match.group(2), repl)
414
- paragraphs.append(f'<h{level} class="answer-heading">{heading}</h{level}>')
587
+ blocks.append({"kind": "table", "html": render_markdown_table(table_lines, repl), "cites": citation_ids("\n".join(table_lines))})
415
588
  elif block in {"---", "***"}:
416
- paragraphs.append('<hr class="answer-divider">')
589
+ blocks.append({"kind": "hr", "html": '<hr class="doc-divider">', "cites": []})
590
+ idx += 1
417
591
  elif re.match(r"^[-*]\s+", block):
418
592
  body = render_inline_markdown(re.sub(r"^[-*]\s+", "", block), repl)
419
- paragraphs.append(
420
- f'<div class="answer-item"><span class="bullet">•</span><div><p>{body}</p>{evidence}</div></div>'
421
- )
593
+ blocks.append({"kind": "list_item", "numbered": False, "html": body, "cites": ids})
594
+ idx += 1
422
595
  elif re.match(r"^\d+[.)]\s+", block):
423
596
  number = re.match(r"^(\d+)[.)]\s+", block).group(1)
424
597
  body = render_inline_markdown(re.sub(r"^\d+[.)]\s+", "", block), repl)
425
- paragraphs.append(
426
- f'<div class="answer-item numbered"><span class="bullet">{esc(number)}.</span><div><p>{body}</p>{evidence}</div></div>'
427
- )
598
+ blocks.append({"kind": "list_item", "numbered": True, "number": number, "html": body, "cites": ids})
599
+ idx += 1
600
+ else:
601
+ blocks.append({"kind": "para", "html": render_inline_markdown(block, repl), "cites": ids})
602
+ idx += 1
603
+ return blocks, valid_ids
604
+
605
+
606
+ def split_heading_number(text: str) -> Tuple[Optional[str], str]:
607
+ m = re.match(r"^\s*([一二三四五六七八九十]+|\d+)\s*[、..]\s*(.+)$", text)
608
+ if m:
609
+ return m.group(1), m.group(2)
610
+ return None, text
611
+
612
+
613
+ def group_sections(blocks: List[Dict[str, Any]]) -> Tuple[Optional[str], List[Dict[str, Any]]]:
614
+ """按标题层级切分章节卡。返回(报告标题, 章节列表)。
615
+
616
+ 规则:最浅层级标题若唯一且居文首,视为报告标题提出;其下一级为卡片边界。
617
+ 无标题的短公文整篇一卡。
618
+ """
619
+ if not blocks:
620
+ return None, [{"title": None, "blocks": []}]
621
+ heading_indexes = [i for i, b in enumerate(blocks) if b["kind"] == "heading"]
622
+ if not heading_indexes:
623
+ return None, [{"title": None, "blocks": blocks}]
624
+
625
+ levels = sorted({blocks[i]["level"] for i in heading_indexes})
626
+ shallow = levels[0]
627
+ shallow_indexes = [i for i in heading_indexes if blocks[i]["level"] == shallow]
628
+
629
+ doc_title = None
630
+ boundary = shallow
631
+ if len(shallow_indexes) == 1 and heading_indexes[0] == shallow_indexes[0]:
632
+ doc_title = blocks[shallow_indexes[0]]["text"]
633
+ blocks = blocks[shallow_indexes[0] + 1:]
634
+ if len(levels) > 1:
635
+ boundary = levels[1]
636
+
637
+ sections: List[Dict[str, Any]] = []
638
+ current: Dict[str, Any] = {"title": None, "blocks": []}
639
+ for b in blocks:
640
+ if b["kind"] == "heading" and b["level"] <= boundary:
641
+ if current["title"] is not None or current["blocks"]:
642
+ sections.append(current)
643
+ current = {"title": b["text"], "blocks": []}
428
644
  else:
429
- body = render_inline_markdown(block, repl)
430
- paragraphs.append(f'<div class="answer-block"><p>{body}</p>{evidence}</div>')
431
- idx += 1
432
- return "\n".join(paragraphs)
645
+ current["blocks"].append(b)
646
+ if current["title"] is not None or current["blocks"]:
647
+ sections.append(current)
648
+ return doc_title, sections
433
649
 
434
650
 
435
- def render_sources(sources: List[Dict[str, str]]) -> str:
436
- if not sources:
437
- return '<p class="empty">接口返回中未识别到可展示的材料。</p>'
438
- cards = []
439
- for source in sources:
440
- url = source.get("url")
441
- links = render_source_links(url, source.get("policy_url", ""))
442
- meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area"), source.get("kind")] if v)
443
- section = source.get("section") or ""
444
- cards.append(
651
+ # ============================================================
652
+ # 各部分渲染
653
+ # ============================================================
654
+
655
+ def render_evidence_chips(ids: List[str], sources: List[Dict[str, str]]) -> str:
656
+ source_map = {source["id"]: source for source in sources}
657
+ chips = []
658
+ for cid in ids:
659
+ source = source_map.get(cid)
660
+ if not source:
661
+ continue
662
+ meta = " | ".join(v for v in [source.get("agency"), source.get("date")] if v)
663
+ excerpt = source.get("excerpt") or "接口返回中未识别到可展示的摘录。"
664
+ links = render_source_links(source.get("url"), source.get("policy_url", ""))
665
+ chips.append(
445
666
  f"""
446
- <article class="source-card" id="source-{esc(source['id'])}" data-source="{esc(source['id'])}">
447
- <div class="source-top">
448
- <span class="source-index">[{esc(source['id'])}]</span>
449
- <h3>{esc(source.get("title"))}</h3>
667
+ <details class="ev-chip" data-cite="{esc(cid)}">
668
+ <summary><b>[{esc(cid)}]</b>{esc(short(source.get("title"), 64))}</summary>
669
+ <div class="ev-panel">
670
+ <div class="ev-title">{esc(source.get("title"))}</div>
671
+ <div class="ev-meta">{esc(meta)}</div>
672
+ <p>{esc(excerpt)}</p>
673
+ {links}
450
674
  </div>
451
- <p class="meta">{esc(meta)}</p>
452
- {f'<p class="section">{esc(section)}</p>' if section else ''}
453
- {render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")}
454
- {links}
455
- </article>
675
+ </details>
456
676
  """
457
677
  )
678
+ if not chips:
679
+ return ""
680
+ return f'<div class="ev-row">{"".join(chips)}</div>'
681
+
682
+
683
+ def render_source_links(url: str, policy_url: str = "") -> str:
684
+ links = []
685
+ if url and url != "接口未返回":
686
+ links.append(f'<a href="{esc(url)}" target="_blank" rel="noopener">查看原文 ↗</a>')
687
+ if policy_url:
688
+ links.append(f'<a href="{esc(policy_url)}" target="_blank" rel="noopener">知识专库原文 ↗</a>')
689
+ if not links:
690
+ return ""
691
+ return '<div class="sc-links">' + "".join(f"<span>{link}</span>" for link in links) + "</div>"
692
+
693
+
694
+ def render_verify_panel(v: Dict[str, Any]) -> str:
695
+ """核验报告单:报告级核验结论 + 五项指标。"""
696
+ manual_checks_html = "".join("<br>· " + esc(x) for x in v.get("manual_checks", []))
697
+ ov = v["overall"]
698
+ state = "ok" if ov["passed"] else "fail"
699
+ stamp = '<span class="v-stamp">已核验</span>' if ov["passed"] else '<span class="v-stamp bad">核验未通过</span>'
700
+ reasons_html = ""
701
+ if ov["reasons"]:
702
+ reasons_html = '<div class="v-reasons">' + ";".join(esc(r) for r in ov["reasons"]) + "</div>"
703
+
704
+ tr = v["traceability"]
705
+ if not tr["total"]:
706
+ tr_html = ('<div class="vi"><span class="s fail">✗ 依据溯源 0/0</span>'
707
+ '<span class="d">未识别到来源材料</span></div>')
708
+ elif tr["passed"] == tr["total"]:
709
+ tr_html = (f'<div class="vi"><span class="s ok">✓ 依据溯源 {tr["passed"]}/{tr["total"]}</span>'
710
+ f'<span class="d">每条素材可回看原文</span></div>')
711
+ else:
712
+ tr_html = (f'<div class="vi"><span class="s warn">◐ 依据溯源 {tr["passed"]}/{tr["total"]}</span>'
713
+ f'<span class="d">{tr["total"] - tr["passed"]} 条待补原文链接或摘录</span></div>')
714
+
715
+ bd = v["binding"]
716
+ if bd.get("no_citation"):
717
+ bd_html = (f'<div class="vi"><span class="s fail">✗ 引用绑定 0/0</span>'
718
+ f'<span class="d">正文未包含来源角标,{v["traceability"]["total"]} 条素材无法与正文对应</span></div>')
719
+ elif not bd["total"]:
720
+ bd_html = '<div class="vi"><span class="s none">— 引用绑定 0/0</span><span class="d">正文未包含来源角标</span></div>'
721
+ elif not bd["unbound"]:
722
+ bd_html = (f'<div class="vi"><span class="s ok">✓ 引用绑定 {bd["bound"]}/{bd["total"]}</span>'
723
+ f'<span class="d">正文引用全部对应素材</span></div>')
724
+ else:
725
+ unbound_text = "、".join(f"[{esc(x)}]" for x in bd["unbound"][:8])
726
+ bd_html = (f'<div class="vi"><span class="s fail">✗ 引用绑定 {bd["bound"]}/{bd["total"]}</span>'
727
+ f'<span class="d">未绑定角标 {unbound_text}</span></div>')
728
+
729
+ fr = v["freshness"]
730
+ if fr:
731
+ rng = f"{fr['min'][0]}-{fr['min'][1]:02d}~{fr['max'][0]}-{fr['max'][1]:02d}"
732
+ old = f"({fr['old_count']} 条历史材料,已按参考口径处理)" if fr["old_count"] else ""
733
+ fr_html = f'<div class="vi"><span class="s ok">✓ 时效检查 完成</span><span class="d">材料日期 {esc(rng)}{esc(old)}</span></div>'
734
+ else:
735
+ fr_html = '<div class="vi"><span class="s none">— 时效检查 未记录</span><span class="d">素材未标注发布日期</span></div>'
736
+
737
+ cov = v["coverage"]
738
+ parts = [f"{KIND_CATALOG[k][0]} {cov[k]}" for k in ("policy", "data", "case", "reference") if cov.get(k)]
739
+ cov_state = "ok" if cov.get("policy") or cov.get("data") or cov.get("case") else "none"
740
+ cov_html = (f'<div class="vi"><span class="s {cov_state}">{"✓" if cov_state == "ok" else "—"} 类型覆盖</span>'
741
+ f'<span class="d">{esc(" · ".join(parts)) if parts else "未标注素材类型"}</span></div>')
742
+
743
+ sc = v["self_check"]
744
+ if sc["status"] == "pass":
745
+ notes = ";".join(note for _, note in sc["items"].values() if note)
746
+ title_attr = f' title="{esc(notes)}"' if notes else ""
747
+ sc_html = (f'<div class="vi"><span class="s ok"{title_attr}>✓ 成稿自检 {sc["passed"]}/{sc["total"]}</span>'
748
+ f'<span class="d">事实/结构/占位/AI味/格式{esc(" · 悬停查看核验说明" if notes else "")}</span></div>')
749
+ elif sc["status"] == "fail":
750
+ failed_parts = []
751
+ for label, (status, note) in sc["items"].items():
752
+ if status != "pass":
753
+ suffix = f"({note[:40]}…)" if len(note) > 40 else (f"({note})" if note else "")
754
+ failed_parts.append(label + suffix)
755
+ sc_html = (f'<div class="vi"><span class="s fail">✗ 成稿自检 {sc["passed"]}/{sc["total"]}</span>'
756
+ f'<span class="d">未通过:{esc("、".join(failed_parts))}</span></div>')
757
+ else:
758
+ sc_html = '<div class="vi"><span class="s none">— 成稿自检 未记录</span><span class="d">本次溯源 JSON 未写入自检结果</span></div>'
759
+
760
+ manual = ""
761
+ if v["policy_count"]:
762
+ manual = (f'<div class="vi"><span class="s man">◐ 效力复核</span>'
763
+ f'<span class="d">{v["policy_count"]} 条政策依据建议按官方发布复核现行效力</span></div>')
764
+
765
+ return f"""
766
+ <div class="verify {state}">
767
+ <div class="v-head"><span class="v-shield">{'✓' if ov['passed'] else '!'}</span>{esc(ov['label'])}{stamp}</div>
768
+ {reasons_html}
769
+ <div class="v-grid">
770
+ {tr_html}{bd_html}{fr_html}{cov_html}{sc_html}{manual}
771
+ </div>
772
+ <div class="v-note">核验方法:深知可信搜索召回权威来源 → 逐条溯源(摘录比对 + 原文链接 + 知识专库回看)→ 正文引用绑定 → 成稿自检。政策现行效力以官方发布为准。{manual_checks_html}</div>
773
+ </div>"""
774
+
775
+
776
+ def render_section_cards(sections: List[Dict[str, Any]], sources: List[Dict[str, str]]) -> str:
777
+ source_ids = {s["id"] for s in sources}
778
+ cards = []
779
+ for sec in sections:
780
+ sec_cites: List[str] = []
781
+ for b in sec["blocks"]:
782
+ for cid in b.get("cites", []):
783
+ if cid not in sec_cites:
784
+ sec_cites.append(cid)
785
+ unbound_count = sum(1 for cid in sec_cites if cid not in source_ids)
786
+ number, title_text = split_heading_number(sec["title"] or "")
787
+ no_html = f'<span class="sec-no">{esc(number)}</span>' if number else ""
788
+ title_html = f"<h3>{esc(title_text)}</h3>" if title_text else ""
789
+ if sec_cites:
790
+ badge_state = "bad" if unbound_count else ""
791
+ badge_text = f"本章引用 {len(sec_cites)} 处" + (f" · {unbound_count} 处未绑定" if unbound_count else " · 已核验")
792
+ badge_html = f'<span class="sec-badge {badge_state}">{esc(badge_text)}</span>'
793
+ else:
794
+ badge_html = ""
795
+ head_html = f'<div class="sec-head">{no_html}{title_html}{badge_html}</div>' if (no_html or title_html or badge_html) else ""
796
+
797
+ body_parts = []
798
+ for b in sec["blocks"]:
799
+ if b["kind"] == "heading":
800
+ inner_level = min(b["level"] + 1, 5)
801
+ body_parts.append(f'<h{inner_level} class="doc-sub">{esc(b["text"])}</h{inner_level}>')
802
+ elif b["kind"] == "list_item":
803
+ marker = f'{esc(b.get("number", "•"))}.' if b.get("numbered") else "•"
804
+ body_parts.append(
805
+ f'<div class="doc-item"><span class="doc-bullet">{marker}</span>'
806
+ f'<div><p>{b["html"]}</p>{render_evidence_chips(b["cites"], sources)}</div></div>'
807
+ )
808
+ else:
809
+ body_parts.append(f'<div class="doc-block"><p>{b["html"]}</p>{render_evidence_chips(b["cites"], sources)}</div>')
810
+ cards.append(f'<section class="doc-sec">{head_html}<div class="sec-body">{"".join(body_parts)}</div></section>')
458
811
  return "\n".join(cards)
459
812
 
460
813
 
461
- def align_sources_to_answer(answer: str, sources: List[Dict[str, str]]) -> List[Dict[str, str]]:
462
- cited = citation_ids(answer)
463
- if not cited or not sources:
464
- return sources
465
- existing = {source["id"] for source in sources}
466
- if existing.intersection(cited):
467
- return sources
468
- aligned = [dict(source) for source in sources]
469
- for idx, citation in enumerate(cited):
470
- if idx >= len(aligned):
471
- break
472
- aligned[idx]["id"] = citation
473
- return aligned
814
+ def render_source_card(source: Dict[str, str]) -> str:
815
+ if source.get("verified"):
816
+ note = source.get("verify_note") or "摘录可比对,原文链接与知识专库可回看"
817
+ vk = f'<span class="sc-vk ok" title="{esc(note)}">✓ 已核验</span>'
818
+ note_html = f'<div class="sc-vnote">{esc(short(note, 90))}</div>' if source.get("verify_note") else ""
819
+ else:
820
+ reason = "待补原文链接" if not source.get("has_link") else "待补摘录"
821
+ vk = f'<span class="sc-vk warn">◐ {reason}</span>'
822
+ note_html = ""
823
+ links = render_source_links(source.get("url"), source.get("policy_url", ""))
824
+ meta = " | ".join(v for v in [source.get("agency"), source.get("date"), source.get("area")] if v)
825
+ section_html = f'<div class="sc-section">支撑:{esc(source["section"])}</div>' if source.get("section") else ""
826
+ return (
827
+ f'<article class="scard {source["type_css"]}" id="src-{esc(source["id"])}" data-type="{esc(source["type_key"])}" data-cite-id="{esc(source["id"])}">'
828
+ f'<div class="sc-head"><span class="sc-id">[{esc(source["id"])}]</span>'
829
+ f'<span class="sc-type">{esc(source["type_label"])}</span>{vk}</div>'
830
+ f'<h4>{esc(source.get("title"))}</h4>'
831
+ f'<div class="sc-meta">{esc(meta)}</div>'
832
+ f'{section_html}{note_html}'
833
+ f'{render_excerpt_html(source.get("excerpt") or "接口返回中未识别到可展示的摘录。")}'
834
+ f'{links}</article>'
835
+ )
474
836
 
475
837
 
476
- def extract_question(payload: Dict[str, Any]) -> str:
477
- content = payload.get("content") if isinstance(payload.get("content"), dict) else payload
478
- data = content.get("data") if isinstance(content.get("data"), dict) else {}
479
- return first_str(
480
- payload.get("question"),
481
- payload.get("input"),
482
- payload.get("query"),
483
- data.get("用户问题"),
484
- content.get("query"),
485
- content.get("question"),
838
+ def render_sources_panel(sources: List[Dict[str, str]], used: List[str], kb_zone: str = "") -> str:
839
+ if not sources:
840
+ return '<aside class="sources"><h3>核验材料</h3><p class="empty">接口返回中未识别到可展示的材料。</p></aside>'
841
+ used_set = set(used)
842
+ cited_cards = [render_source_card(s) for s in sources if s["id"] in used_set]
843
+ uncited = [s for s in sources if s["id"] not in used_set]
844
+ uncited_html = ""
845
+ if uncited:
846
+ uncited_cards = "".join(render_source_card(s) for s in uncited)
847
+ # 不用 <details> 折叠:部分宿主(WorkBuddy 等)的 HTML 预览服务会改写折叠区导致卡片丢失
848
+ uncited_html = (
849
+ '<div class="uncited-group"><div class="ug-title">未引用素材('
850
+ f'{len(uncited)} 条核心依据未在正文角标引用;完整召回可通过下方知识专库链接回看)</div>'
851
+ f'<div class="uncited-list">{uncited_cards}</div></div>'
852
+ )
853
+ verified_count = sum(1 for s in sources if s.get("verified"))
854
+ types_present = {s["type_key"] for s in sources}
855
+ filters_html = ""
856
+ if len(types_present) >= 2:
857
+ buttons = ['<button class="on" data-f="all" type="button">全部</button>']
858
+ for key in ("policy", "data", "case", "reference"):
859
+ if key in types_present:
860
+ buttons.append(f'<button data-f="{key}" type="button">{KIND_CATALOG[key][0]}</button>')
861
+ filters_html = f'<div class="filters" role="group" aria-label="类型筛选">{"".join(buttons)}</div>'
862
+ badge = "全部已核验" if verified_count == len(sources) else f"{verified_count}/{len(sources)} 已核验"
863
+ return (
864
+ '<aside class="sources" id="sources-panel" aria-label="核验材料面板">'
865
+ '<a class="back-doc" href="#doc-top">↑ 返回核验报告单</a>'
866
+ f'<h3>核验材料({len(sources)} 条 · {esc(badge)})</h3>'
867
+ '<div class="src-tip">点击正文角标 [1] 定位材料原文并核对</div>'
868
+ f'{filters_html}'
869
+ '<input class="src-search" type="search" placeholder="搜索标题 / 来源 / 摘录…" aria-label="搜索来源">'
870
+ f'<div class="src-list">{"".join(cited_cards)}{uncited_html}</div>'
871
+ f'{kb_zone}'
872
+ '</aside>'
486
873
  )
487
874
 
488
875
 
489
- def render_entry_chip(kb_url: str, source_count: int, kb_urls: Optional[List[str]] = None, kb_labels: Optional[List[str]] = None) -> str:
490
- urls = kb_urls or ([kb_url] if kb_url else [])
491
- if not urls:
876
+ def render_kb_zone(kb_urls: List[str], kb_labels: List[str], source_count: int) -> str:
877
+ if not kb_urls:
492
878
  return ""
493
- count_text = f"{source_count}条来源" if source_count else "来源材料"
494
- labels = kb_labels or []
495
- return "".join(
496
- f'<a class="kb-chip" href="{esc(url)}" target="_blank" rel="noopener">'
497
- f'<span class="kb-label">{esc(labels[index] if index < len(labels) else "相关搜索来源")}</span>'
498
- f'<span class="kb-count">{esc(count_text if index == 0 else "查看原始召回")}</span>'
499
- f'<span class="kb-arrow">查看</span></a>'
500
- for index, url in enumerate(urls)
879
+ chips = []
880
+ for index, url in enumerate(kb_urls):
881
+ label = kb_labels[index] if index < len(kb_labels) else "相关搜索来源"
882
+ chips.append(
883
+ f'<a class="kb-chip" href="{esc(url)}" target="_blank" rel="noopener">'
884
+ f'<span class="kb-label">{esc(label)}</span>'
885
+ f'<span class="kb-count">{"原始召回" if index else f"{source_count} 条来源"} · 可回看</span>'
886
+ '<span class="kb-arrow">打开 ↗</span></a>'
887
+ )
888
+ return (
889
+ '<div class="kb-zone"><div class="kb-title">原始召回存档(深知知识专库)</div>'
890
+ '<div class="kb-desc">以下链接可回看每次搜索的完整召回结果(含未写入正文的材料);'
891
+ '原文页面改版或下线时可回看当时召回的快照。逐条材料的核验请点击来源卡上的"查看原文"直达官方页面。</div>'
892
+ f'<div class="kb-list">{"".join(chips)}</div></div>'
501
893
  )
502
894
 
503
895
 
@@ -513,429 +905,463 @@ def safe_output_filename(question: str, timestamp: datetime, fallback: str = "dk
513
905
  return f"{stem}_{suffix}{suffix_ext}"
514
906
 
515
907
 
516
- def render_html(payload: Dict[str, Any], title: str, answer_override: str = "", question_override: str = "", generated_at: Optional[datetime] = None) -> str:
908
+ def render_html(payload: Dict[str, Any], title: str, answer_override: str = "", question_override: str = "",
909
+ generated_at: Optional[datetime] = None) -> str:
517
910
  payload = unwrap(payload)
518
911
  answer = normalize_citations(answer_override) if answer_override.strip() else extract_answer(payload)
519
912
  sources = align_sources_to_answer(answer, extract_sources(payload))
520
913
  used = citation_ids(answer)
521
914
  kb_urls = extract_knowledge_bases(payload)
522
915
  kb_labels = payload.get("knowledgeBaseLabels") if isinstance(payload.get("knowledgeBaseLabels"), list) else []
523
- kb_url = kb_urls[0] if kb_urls else ""
524
- question = question_override.strip() or extract_question(payload)
525
916
  generated_at = generated_at or datetime.now()
526
917
  generated = generated_at.strftime("%Y-%m-%d %H:%M")
527
- tools_html = f'<div class="tools">{render_entry_chip(kb_url, len(sources), kb_urls, kb_labels)}</div>' if kb_url else ""
528
- question_html = f'<div class="question-bubble">{esc(question)}</div>' if question else ""
918
+
919
+ verification = compute_verification(answer, sources, payload, generated_at)
529
920
  citation_warning = ""
530
921
  if sources and not used:
531
922
  citation_warning = (
532
- '<div class="warning-box">'
533
- '<b>生成检查提示:</b>本轮最终答案没有包含来源角标,因此无法在答案段落下做“结论-来源”一一对应。'
534
- '请重新生成最终答案,并在关键结论后标注接口材料编号,例如 [1]、[2]。'
535
- '</div>'
923
+ '<div class="warn-box"><b>生成检查未通过:正文没有来源角标。</b>'
924
+ '本报告无法建立"结论-素材"核验对应,仅作素材清单参考。'
925
+ '请修正溯源 JSON:在 document_content 的关键结论后标注 [1]、[2] 等角标并逐条对应 materials,'
926
+ '然后重新运行 source_note_html.py 生成核验报告。</div>'
536
927
  )
537
- note_text = "AI综合所有相关权威材料后,参考性解读如下,建议点击角标查看所依据的材料原文。"
538
- compact_answer_start = re.sub(r"\s+", "", answer.lstrip()[:120])
539
- compact_note_start = re.sub(r"\s+", "", note_text[:36])
540
- note_html = "" if compact_answer_start.startswith(compact_note_start) else f'<p class="ai-note">{esc(note_text)}</p>'
928
+ blocks, _ = parse_answer_blocks(answer, {s["id"] for s in sources})
929
+ doc_title, sections = group_sections(blocks)
930
+ display_title = doc_title or title
931
+ kb_zone = render_kb_zone(kb_urls, kb_labels, len(sources))
932
+
933
+ cov = verification["coverage"]
934
+ meta_bits = []
935
+ cov_bits = [f"{KIND_CATALOG[k][0]} {cov[k]}" for k in ("policy", "data", "case", "reference") if cov.get(k)]
936
+ if cov_bits:
937
+ meta_bits.append("素材:" + " · ".join(cov_bits))
938
+ if sources:
939
+ meta_bits.append(f"共 {len(sources)} 条")
940
+ meta_bits.append("点击正文角标 [1] 定位材料原文")
941
+ meta_line = " | ".join(meta_bits)
541
942
 
542
943
  return f"""<!doctype html>
543
944
  <html lang="zh-CN">
544
945
  <head>
545
- <meta charset="utf-8">
546
- <meta name="viewport" content="width=device-width, initial-scale=1">
547
- <title>{esc(title)}</title>
548
- <style>
549
- :root {{
550
- --purple: #6b18c9;
551
- --purple-soft: #f4ebff;
552
- --ink: #2f3033;
553
- --muted: #6b7280;
554
- --line: #e5e7eb;
555
- --panel: #ffffff;
556
- --page: #ffffff;
557
- --soft: #f7f7f8;
558
- }}
559
- * {{ box-sizing: border-box; }}
560
- body {{
561
- margin: 0;
562
- font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
563
- color: var(--ink);
564
- background: var(--page);
565
- }}
566
- header {{
567
- padding: 12px 28px;
568
- background: #fff;
569
- border-bottom: 1px solid var(--line);
570
- position: sticky;
571
- top: 0;
572
- z-index: 2;
573
- text-align: center;
574
- }}
575
- h1 {{ margin: 0 0 3px; font-size: 16px; letter-spacing: 0; font-weight: 700; }}
576
- header p {{ margin: 0; color: #9ca3af; font-size: 12px; }}
577
- .layout {{
578
- display: grid;
579
- grid-template-columns: minmax(0, 700px) minmax(390px, 460px);
580
- gap: 30px;
581
- justify-content: center;
582
- max-width: 1220px;
583
- margin: 0 auto;
584
- padding: 30px 18px 40px;
585
- }}
586
- .conversation {{
587
- min-width: 0;
588
- }}
589
- .question-bubble {{
590
- max-width: 560px;
591
- margin: 0 0 26px auto;
592
- padding: 12px 16px;
593
- border-radius: 9px;
594
- background: var(--purple);
595
- color: #fff;
596
- line-height: 1.55;
597
- font-weight: 700;
598
- font-size: 14px;
599
- }}
600
- .answer {{
601
- background: transparent;
602
- padding: 0;
603
- }}
604
- .kb-chip {{
605
- display: inline-flex;
606
- align-items: center;
607
- gap: 10px;
608
- max-width: 100%;
609
- margin: 0 0 16px;
610
- padding: 7px 10px;
611
- border: 1px solid var(--line);
612
- border-radius: 7px;
613
- color: #4b5563;
614
- background: #fafafa;
615
- text-decoration: none;
616
- box-shadow: none;
617
- font-size: 12px;
618
- }}
619
- .kb-chip:hover {{ border-color: #d1d5db; background: #f7f7f8; }}
620
- .kb-label {{ font-weight: 700; color: #374151; }}
621
- .kb-count {{
622
- padding-left: 10px;
623
- border-left: 1px solid var(--line);
624
- color: #6b7280;
625
- }}
626
- .kb-arrow {{
627
- color: var(--purple);
628
- font-weight: 700;
629
- }}
630
- .ai-note {{ margin: 0 0 10px; color: #52525b; line-height: 1.75; font-size: 14px; }}
631
- .answer-body {{
632
- padding: 0;
633
- background: transparent;
634
- }}
635
- .answer-block, .answer-item {{ margin: 0 0 12px; }}
636
- .answer-item {{ display: grid; grid-template-columns: 20px minmax(0, 1fr); gap: 8px; }}
637
- .answer-item .bullet {{ padding-top: 2px; color: #111827; font-size: 16px; line-height: 1.75; }}
638
- .answer-item.numbered {{ grid-template-columns: 28px minmax(0, 1fr); }}
639
- .answer p {{ margin: 0; font-size: 14px; line-height: 1.85; }}
640
- .answer strong {{ font-weight: 700; color: #202124; }}
641
- .answer em {{ font-style: normal; color: #4b5563; }}
642
- .answer code {{
643
- padding: 1px 5px;
644
- border-radius: 4px;
645
- background: #f3f4f6;
646
- color: #374151;
647
- font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
648
- font-size: 12px;
649
- }}
650
- .answer-table-wrap {{ max-width: 100%; overflow-x: auto; margin: 6px 0 8px; }}
651
- .answer-table {{
652
- width: 100%;
653
- border-collapse: collapse;
654
- border: 1px solid var(--line);
655
- border-radius: 8px;
656
- overflow: hidden;
657
- font-size: 13px;
658
- }}
659
- .answer-table th, .answer-table td {{
660
- padding: 9px 10px;
661
- border: 1px solid var(--line);
662
- text-align: left;
663
- vertical-align: top;
664
- line-height: 1.65;
665
- }}
666
- .answer-table th {{ background: #f8fafc; font-weight: 700; color: #374151; }}
667
- .answer-heading {{ margin: 20px 0 9px; color: #111827; line-height: 1.45; letter-spacing: 0; }}
668
- h2.answer-heading {{ font-size: 18px; }}
669
- h3.answer-heading {{ font-size: 16px; }}
670
- h4.answer-heading {{ font-size: 15px; }}
671
- .answer-divider {{ border: 0; border-top: 1px solid var(--line); margin: 22px 0; }}
672
- .warning-box {{
673
- margin: 0 0 16px;
674
- padding: 12px 14px;
675
- border: 1px solid #f59e0b;
676
- border-radius: 8px;
677
- background: #fffbeb;
678
- color: #92400e;
679
- line-height: 1.7;
680
- font-size: 14px;
681
- }}
682
- .cite {{
683
- margin: 0 2px;
684
- padding: 0 5px;
685
- border: 0;
686
- border-radius: 4px;
687
- color: var(--purple);
688
- background: var(--purple-soft);
689
- font-weight: 700;
690
- cursor: pointer;
691
- vertical-align: super;
692
- font-size: 10px;
693
- line-height: 1.4;
694
- }}
695
- .cite.disabled {{ color: #9ca3af; background: #f3f4f6; cursor: default; }}
696
- .evidence-row {{
697
- display: flex;
698
- flex-wrap: wrap;
699
- gap: 6px;
700
- margin: 5px 0 0;
701
- }}
702
- .evidence-detail {{
703
- max-width: 100%;
704
- }}
705
- .evidence-detail summary {{
706
- display: inline-flex;
707
- align-items: center;
708
- max-width: 100%;
709
- border-radius: 999px;
710
- padding: 4px 9px;
711
- color: #6b7280;
712
- background: #f3f4f6;
713
- cursor: pointer;
714
- overflow: hidden;
715
- text-overflow: ellipsis;
716
- white-space: nowrap;
717
- list-style: none;
718
- font-size: 12px;
719
- }}
720
- .evidence-detail summary::-webkit-details-marker {{ display: none; }}
721
- .evidence-detail summary::after {{
722
- content: "展开";
723
- margin-left: 7px;
724
- color: #9ca3af;
725
- font-size: 11px;
726
- }}
727
- .evidence-detail[open] summary::after {{ content: "收起"; }}
728
- .evidence-detail summary b {{ color: var(--purple); margin-right: 5px; }}
729
- .evidence-panel {{
730
- margin: 7px 0 4px;
731
- padding: 12px 14px;
732
- border: 1px solid var(--line);
733
- border-radius: 8px;
734
- background: #fff;
735
- box-shadow: 0 8px 24px rgba(15, 23, 42, 0.06);
736
- }}
737
- .evidence-title {{ font-weight: 700; font-size: 14px; margin-bottom: 5px; color: #111827; }}
738
- .evidence-meta {{ color: var(--muted); font-size: 12px; margin-bottom: 6px; }}
739
- .evidence-section {{ color: var(--purple); font-size: 12px; margin-bottom: 6px; font-weight: 700; }}
740
- .evidence-panel p {{ margin: 0 0 8px; color: #374151; font-size: 13px; line-height: 1.7; }}
741
- .evidence-panel a {{ color: var(--purple); font-weight: 700; text-decoration: none; }}
742
- .source-links {{
743
- display: flex;
744
- flex-wrap: wrap;
745
- gap: 8px;
746
- margin-top: 8px;
747
- }}
748
- .source-links span {{
749
- display: inline-flex;
750
- }}
751
- .source-links a {{
752
- display: inline-flex;
753
- align-items: center;
754
- min-height: 24px;
755
- padding: 3px 8px;
756
- border-radius: 6px;
757
- background: var(--purple-soft);
758
- color: var(--purple);
759
- font-weight: 700;
760
- text-decoration: none;
761
- font-size: 12px;
762
- }}
763
- .tools {{
764
- display: flex;
765
- flex-wrap: wrap;
766
- gap: 8px;
767
- margin-top: 20px;
768
- padding-top: 16px;
769
- border-top: 1px solid var(--line);
770
- }}
771
- .tools a {{
772
- color: var(--purple);
773
- background: var(--purple-soft);
774
- border-radius: 999px;
775
- padding: 7px 12px;
776
- text-decoration: none;
777
- font-weight: 600;
778
- }}
779
- .sources {{
780
- align-self: start;
781
- position: sticky;
782
- top: 70px;
783
- max-height: calc(100vh - 92px);
784
- overflow: auto;
785
- background: #fff;
786
- border-left: 1px solid var(--line);
787
- padding: 16px 0 16px 24px;
788
- }}
789
- .sources h2 {{ margin: 0 0 12px; font-size: 15px; }}
790
- .searchbox {{
791
- width: 100%;
792
- margin: 0 0 14px;
793
- padding: 9px 12px;
794
- border: 1px solid var(--line);
795
- border-radius: 8px;
796
- color: #6b7280;
797
- background: #fff;
798
- }}
799
- .source-card {{
800
- padding: 14px 0 15px;
801
- border: 0;
802
- border-bottom: 1px solid #f1f1f2;
803
- border-radius: 0;
804
- margin-bottom: 0;
805
- background: #fff;
806
- }}
807
- .source-card.active {{
808
- margin-left: -10px;
809
- padding-left: 10px;
810
- border-left: 3px solid var(--purple);
811
- background: #fbf8ff;
812
- box-shadow: none;
813
- }}
814
- .source-top {{
815
- display: grid;
816
- grid-template-columns: auto minmax(0, 1fr);
817
- gap: 7px;
818
- align-items: start;
819
- margin-bottom: 6px;
820
- }}
821
- .source-index {{
822
- color: var(--purple);
823
- background: var(--purple-soft);
824
- border-radius: 5px;
825
- padding: 1px 5px;
826
- font-weight: 800;
827
- font-size: 12px;
828
- line-height: 1.5;
829
- }}
830
- .source-card h3 {{ margin: 0; font-size: 13px; line-height: 1.55; letter-spacing: 0; }}
831
- .source-card p {{ margin: 0 0 7px; color: #374151; line-height: 1.72; font-size: 12px; }}
832
- .source-card .meta {{ color: var(--muted); font-size: 12px; line-height: 1.55; }}
833
- .source-card .section {{ color: var(--purple); font-size: 12px; font-weight: 700; }}
834
- .source-card a {{ color: var(--purple); font-weight: 700; text-decoration: none; font-size: 12px; }}
835
- .source-card .source-excerpt {{
836
- margin: 8px 0 8px;
837
- padding: 9px 10px;
838
- border-radius: 7px;
839
- background: #f8fafc;
840
- color: #374151;
841
- font-size: 12px;
842
- line-height: 1.75;
843
- }}
844
- .source-excerpt.rich {{
845
- overflow-x: auto;
846
- max-width: 100%;
847
- }}
848
- .source-excerpt.rich table {{
849
- width: max-content;
850
- min-width: 100%;
851
- border-collapse: collapse;
852
- background: #fff;
853
- font-size: 12px;
854
- line-height: 1.55;
855
- }}
856
- .source-excerpt.rich td, .source-excerpt.rich th {{
857
- min-width: 92px;
858
- max-width: 220px;
859
- padding: 7px 8px;
860
- border: 1px solid #e5e7eb;
861
- vertical-align: top;
862
- word-break: break-word;
863
- }}
864
- .source-excerpt.rich thead td, .source-excerpt.rich th {{
865
- background: #f3f4f6;
866
- color: #374151;
867
- font-weight: 700;
868
- }}
869
- .empty {{ color: var(--muted); }}
870
- @media (max-width: 900px) {{
871
- .layout {{ grid-template-columns: 1fr; padding: 14px; }}
872
- .sources {{ position: static; max-height: none; }}
873
- .question-bubble {{ margin-left: 0; }}
874
- }}
875
- </style>
946
+ <meta charset="utf-8">
947
+ <meta name="viewport" content="width=device-width, initial-scale=1">
948
+ <title>{esc(display_title)} · 可信溯源核验报告</title>
949
+ <style>
950
+ :root{{
951
+ --navy:#0b1f3a; --ink:#172236; --muted:#667085; --line:#dce4ef; --line-strong:#b9c6d9;
952
+ --brand:#1559c7; --brand-soft:#e8f0ff;
953
+ --policy:#0c9b78; --policy-soft:#e2f6ef;
954
+ --case:#b26a00; --case-soft:#fff4e0;
955
+ --ref:#4b5563; --ref-soft:#eef1f6;
956
+ --warn:#b26a00; --danger:#b93939; --ok:#0c9b78;
957
+ }}
958
+ *{{box-sizing:border-box}}
959
+ body{{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;
960
+ color:var(--ink);background:#f4f7fb;line-height:1.75;font-size:14.5px}}
961
+ a{{color:var(--brand)}}
962
+ .topbar{{position:sticky;top:0;z-index:10;display:flex;justify-content:space-between;align-items:center;gap:10px;
963
+ padding:10px 22px;background:var(--navy);color:#fff;font-size:13px}}
964
+ .topbar .tb-title{{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
965
+ .topbar .tags{{display:flex;align-items:center;gap:6px;flex:none}}
966
+ .topbar .tags span{{padding:2px 10px;border:1px solid rgba(255,255,255,.3);border-radius:999px;font-size:11.5px}}
967
+ .layout{{display:grid;grid-template-columns:minmax(0,760px) minmax(340px,420px);gap:26px;
968
+ max-width:1240px;margin:0 auto;padding:26px 18px 60px}}
969
+ /* 左栏 */
970
+ .report{{min-width:0}}
971
+ .r-head{{padding:22px 26px;background:#fff;border:1px solid var(--line);border-radius:12px;margin-bottom:16px;text-align:center}}
972
+ .r-head h1{{margin:0 0 8px;font-size:22px;color:var(--navy);line-height:1.5}}
973
+ .r-head .sub{{color:var(--muted);font-size:12.5px}}
974
+ .warn-box{{margin:0 0 16px;padding:13px 16px;border:1.5px solid var(--danger);border-radius:10px;
975
+ background:#fdf3f3;color:#8f2626;font-size:13.5px;line-height:1.7}}
976
+ .verify{{margin:0 0 16px;background:#fff;border:1px solid #bfe5d6;border-radius:12px;padding:16px 20px}}
977
+ .verify.fail{{border-color:#f2c4c4;background:#fffafa}}
978
+ .v-head{{display:flex;align-items:center;gap:9px;font-size:15px;font-weight:800;color:var(--ok)}}
979
+ .verify.fail .v-head{{color:var(--danger)}}
980
+ .v-shield{{display:inline-flex;width:22px;height:22px;border-radius:50%;background:var(--ok);color:#fff;
981
+ align-items:center;justify-content:center;font-size:12px;flex:none}}
982
+ .verify.fail .v-shield{{background:var(--danger)}}
983
+ .v-stamp{{margin-left:auto;font-size:11px;border:1.5px solid var(--ok);color:var(--ok);border-radius:5px;
984
+ padding:1px 8px;letter-spacing:2px;flex:none}}
985
+ .v-stamp.bad{{border-color:var(--danger);color:var(--danger)}}
986
+ .v-reasons{{margin-top:6px;font-size:12.5px;color:var(--danger)}}
987
+ .v-grid{{display:grid;grid-template-columns:1fr 1fr;gap:4px 20px;margin-top:10px}}
988
+ .vi{{display:flex;gap:7px;align-items:baseline;font-size:12.5px;color:#35445c;line-height:1.7;min-width:0}}
989
+ .vi .s{{font-weight:800;flex:none}}
990
+ .vi .s.ok{{color:var(--ok)}}
991
+ .vi .s.warn{{color:var(--warn)}}
992
+ .vi .s.fail{{color:var(--danger)}}
993
+ .vi .s.man{{color:var(--case)}}
994
+ .vi .s.none{{color:var(--muted)}}
995
+ .vi .d{{color:var(--muted);min-width:0}}
996
+ .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}}
997
+ /* 正文章节卡 */
998
+ .doc-sec{{background:#fff;border:1px solid var(--line);border-radius:12px;padding:20px 24px;margin-bottom:16px}}
999
+ .sec-head{{display:flex;align-items:center;gap:9px;flex-wrap:wrap;margin-bottom:10px;
1000
+ padding-bottom:10px;border-bottom:1px solid var(--line)}}
1001
+ .sec-no{{display:inline-flex;width:26px;height:26px;border-radius:7px;background:var(--brand);color:#fff;
1002
+ align-items:center;justify-content:center;font-size:13.5px;font-weight:700;flex:none}}
1003
+ .sec-head h3{{margin:0;font-size:16.5px;color:var(--navy);line-height:1.5}}
1004
+ .sec-badge{{margin-left:auto;font-size:11.5px;color:var(--ok);background:var(--policy-soft);
1005
+ border-radius:6px;padding:2px 9px;font-weight:700;flex:none}}
1006
+ .sec-badge.bad{{color:var(--danger);background:#fdecea}}
1007
+ .doc-sub{{margin:16px 0 8px;color:var(--navy);font-size:14.5px;font-weight:700}}
1008
+ h5.doc-sub{{font-size:13.5px}}
1009
+ .doc-block,.doc-item{{margin:0 0 12px}}
1010
+ .doc-block p,.doc-item p{{margin:0;font-size:14px;line-height:1.9}}
1011
+ .doc-item{{display:grid;grid-template-columns:22px minmax(0,1fr);gap:8px}}
1012
+ .doc-item.numbered{{grid-template-columns:28px minmax(0,1fr)}}
1013
+ .doc-bullet{{padding-top:1px;color:#111827;font-size:15px;line-height:1.85}}
1014
+ .doc-divider{{border:0;border-top:1px solid var(--line);margin:18px 0}}
1015
+ code{{padding:1px 5px;border-radius:4px;background:#f3f4f6;color:#374151;
1016
+ font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px}}
1017
+ .tbl-wrap{{max-width:100%;overflow-x:auto;margin:8px 0}}
1018
+ .data-tbl{{width:100%;border-collapse:collapse;border:1px solid var(--line);font-size:13px}}
1019
+ .data-tbl th,.data-tbl td{{border:1px solid var(--line);padding:8px 10px;text-align:left;vertical-align:top;line-height:1.65}}
1020
+ .data-tbl th{{background:#f2f5fb;font-weight:700;color:#374151}}
1021
+ /* 角标 */
1022
+ .cite{{margin:0 1px;padding:0 5px;border:0;border-radius:4px;background:var(--brand-soft);color:var(--brand);
1023
+ font-weight:800;font-size:10.5px;cursor:pointer;vertical-align:super;font-family:monospace}}
1024
+ .cite:hover,.cite:focus-visible{{background:var(--brand);color:#fff;outline:none}}
1025
+ .cite.unresolved{{background:#fdecea;color:var(--danger)}}
1026
+ /* 段落级证据 chips */
1027
+ .ev-row{{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0 2px}}
1028
+ .ev-chip{{max-width:100%}}
1029
+ .ev-chip summary{{display:inline-flex;align-items:center;max-width:100%;border-radius:999px;padding:3px 10px;
1030
+ color:#4b5563;background:#f3f4f6;cursor:pointer;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
1031
+ list-style:none;font-size:11.5px}}
1032
+ .ev-chip summary::-webkit-details-marker{{display:none}}
1033
+ .ev-chip summary::after{{content:"核验";margin-left:7px;color:#9ca3af;font-size:10.5px}}
1034
+ .ev-chip[open] summary::after{{content:"收起"}}
1035
+ .ev-chip summary b{{color:var(--brand);margin-right:5px}}
1036
+ .ev-panel{{margin:7px 0 6px;padding:12px 14px;border:1px solid var(--line);border-radius:9px;background:#fbfcfe;
1037
+ box-shadow:0 8px 24px rgba(15,23,42,.06)}}
1038
+ .ev-title{{font-weight:700;font-size:13.5px;margin-bottom:4px;color:var(--navy)}}
1039
+ .ev-meta{{color:var(--muted);font-size:12px;margin-bottom:6px}}
1040
+ .ev-panel p{{margin:0 0 8px;color:#374151;font-size:12.8px;line-height:1.7}}
1041
+ .sc-links{{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}}
1042
+ .sc-links span{{display:inline-flex}}
1043
+ .sc-links a{{display:inline-flex;align-items:center;min-height:24px;padding:3px 9px;border-radius:6px;
1044
+ background:var(--brand-soft);color:var(--brand);font-weight:700;text-decoration:none;font-size:12px}}
1045
+ /* 右栏 核验材料 */
1046
+ .sources{{position:sticky;top:56px;align-self:start;max-height:calc(100vh - 76px);overflow:auto;
1047
+ background:#fff;border:1px solid var(--line);border-radius:12px;padding:16px 18px}}
1048
+ .sources h3{{margin:0 0 3px;font-size:15px;color:var(--navy)}}
1049
+ .src-tip{{font-size:11.5px;color:var(--muted);margin-bottom:10px}}
1050
+ .filters{{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:8px}}
1051
+ .filters button{{border:1px solid var(--line);border-radius:999px;background:#fff;color:var(--muted);
1052
+ padding:3px 11px;font-size:12px;cursor:pointer}}
1053
+ .filters button.on{{background:var(--brand);border-color:var(--brand);color:#fff;font-weight:700}}
1054
+ .src-search{{width:100%;padding:7px 10px;border:1px solid var(--line);border-radius:7px;font-size:12.5px;margin-bottom:12px}}
1055
+ .scard{{border:1px solid var(--line);border-left-width:3px;border-radius:10px;padding:11px 13px;margin-bottom:10px;
1056
+ background:#fff;transition:box-shadow .25s}}
1057
+ .scard.pol{{border-left-color:var(--policy)}}
1058
+ .scard.dat{{border-left-color:var(--brand)}}
1059
+ .scard.cas{{border-left-color:var(--case)}}
1060
+ .scard.ref,.scard.mat{{border-left-color:var(--ref)}}
1061
+ .scard.hl{{box-shadow:0 0 0 3px var(--brand)}}
1062
+ .scard.hide{{display:none}}
1063
+ .sc-head{{display:flex;align-items:center;gap:7px;margin-bottom:4px}}
1064
+ .sc-id{{font-family:monospace;font-weight:800;font-size:11px;color:var(--brand);background:var(--brand-soft);
1065
+ border-radius:4px;padding:1px 7px}}
1066
+ .sc-type{{font-size:11px;font-weight:700;border-radius:4px;padding:1px 8px;background:var(--ref-soft);color:var(--ref)}}
1067
+ .scard.pol .sc-type{{background:var(--policy-soft);color:var(--policy)}}
1068
+ .scard.dat .sc-type{{background:var(--brand-soft);color:var(--brand)}}
1069
+ .scard.cas .sc-type{{background:var(--case-soft);color:var(--case)}}
1070
+ .sc-vk{{margin-left:auto;font-size:11px;font-weight:800;color:var(--ok)}}
1071
+ .sc-vk.warn{{color:var(--warn)}}
1072
+ .scard h4{{margin:0 0 4px;font-size:13px;color:var(--navy);line-height:1.55}}
1073
+ .sc-meta{{font-size:11.5px;color:var(--muted)}}
1074
+ .sc-section{{font-size:11.5px;color:var(--brand);margin-top:3px;font-weight:600}}
1075
+ .sc-vnote{{margin-top:5px;font-size:11.3px;color:var(--ok);line-height:1.6}}
1076
+ .sc-excerpt{{margin:7px 0;padding:9px 10px;border-radius:7px;background:#f8fafc;color:#42566f;font-size:12px;line-height:1.7;
1077
+ display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;cursor:pointer}}
1078
+ .scard.open .sc-excerpt{{display:block;-webkit-line-clamp:unset}}
1079
+ .sc-excerpt.rich{{overflow-x:auto}}
1080
+ .sc-excerpt.rich table{{width:max-content;min-width:100%;border-collapse:collapse;background:#fff;font-size:12px}}
1081
+ .sc-excerpt.rich td,.sc-excerpt.rich th{{min-width:92px;max-width:220px;padding:7px 8px;border:1px solid var(--line);
1082
+ vertical-align:top;word-break:break-word}}
1083
+ .sc-excerpt.rich thead td,.sc-excerpt.rich th{{background:#f3f4f6;color:#374151;font-weight:700}}
1084
+ .scard .sc-links a{{font-size:12px}}
1085
+ .scard .sc-links{{margin-top:4px}}
1086
+ .no-link{{font-size:11.5px;color:var(--muted)}}
1087
+ .uncited-group{{margin-top:12px;border-top:1px dashed var(--line-strong);padding-top:10px}}
1088
+ .ug-title{{font-size:12.5px;color:var(--muted);font-weight:700;line-height:1.6}}
1089
+ .uncited-group .uncited-list{{margin-top:10px}}
1090
+ /* 知识专库 */
1091
+ .kb-zone{{margin-top:14px;border-top:1px dashed var(--line-strong);padding-top:12px}}
1092
+ .kb-title{{font-size:12.5px;font-weight:800;color:var(--navy)}}
1093
+ .kb-desc{{font-size:11.3px;color:var(--muted);line-height:1.65;margin:3px 0 8px}}
1094
+ .kb-list{{display:flex;flex-direction:column;gap:7px}}
1095
+ .kb-chip{{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid var(--line);border-radius:8px;
1096
+ background:#fbfcfe;text-decoration:none;font-size:11.5px}}
1097
+ .kb-chip:hover{{border-color:var(--brand);background:var(--brand-soft)}}
1098
+ .kb-label{{font-weight:700;color:#374151;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}}
1099
+ .kb-count{{padding-left:8px;border-left:1px solid var(--line);color:var(--muted);white-space:nowrap}}
1100
+ .kb-arrow{{margin-left:auto;color:var(--brand);font-weight:700;white-space:nowrap}}
1101
+ .empty{{color:var(--muted)}}
1102
+ .foot{{text-align:center;color:var(--muted);font-size:11.5px;padding:16px 0 4px;line-height:1.8}}
1103
+ @media (max-width:1020px){{
1104
+ .layout{{grid-template-columns:1fr}}
1105
+ .sources{{position:static;max-height:none}}
1106
+ }}
1107
+ /* —— 移动端专项适配(手机阅读核验报告) —— */
1108
+ .mobile-nav{{display:none}}
1109
+ .back-doc{{display:none}}
1110
+ /* 移动端材料底部弹层:点角标就地弹出材料卡,不跳转打断阅读 */
1111
+ .sheet-mask{{display:none}}
1112
+ .sheet{{display:none}}
1113
+ @media (max-width:680px){{
1114
+ body{{font-size:14px;line-height:1.8}}
1115
+ .layout{{grid-template-columns:1fr;padding:12px 10px 40px;gap:14px}}
1116
+ .topbar{{padding:8px 12px;font-size:12px;gap:4px;flex-wrap:wrap}}
1117
+ .topbar .tags span{{font-size:10.5px;padding:1px 8px;margin-left:4px}}
1118
+ .r-head{{padding:16px 14px;border-radius:10px}}
1119
+ .r-head h1{{font-size:18px}}
1120
+ .r-head .sub{{font-size:11.5px;line-height:1.6}}
1121
+ .verify{{padding:13px 14px;border-radius:10px}}
1122
+ .v-head{{font-size:14px}}
1123
+ .v-grid{{grid-template-columns:1fr;gap:2px 0}}
1124
+ .vi{{flex-wrap:wrap;gap:4px 8px}}
1125
+ .vi .d{{min-width:0}}
1126
+ .warn-box{{font-size:12.5px;padding:11px 12px}}
1127
+ .doc-sec{{padding:14px;border-radius:10px}}
1128
+ .sec-no{{width:22px;height:22px;font-size:12px;border-radius:6px}}
1129
+ .sec-head{{gap:7px;padding-bottom:8px;margin-bottom:8px}}
1130
+ .sec-head h3{{font-size:15px}}
1131
+ .sec-badge{{margin-left:0;font-size:11px}}
1132
+ .doc-block p,.doc-item p{{font-size:13.5px;line-height:1.95}}
1133
+ .doc-sub{{font-size:14px;margin:12px 0 6px}}
1134
+ .data-tbl{{font-size:12px}}
1135
+ .data-tbl th,.data-tbl td{{padding:6px 7px;line-height:1.55}}
1136
+ .cite{{font-size:11px;padding:0 4px}}
1137
+ .ev-chip summary{{font-size:11px}}
1138
+ .sources{{padding:12px;border-radius:10px}}
1139
+ .scard{{padding:10px 11px}}
1140
+ .sc-excerpt{{font-size:11.5px}}
1141
+ .kb-chip{{flex-wrap:wrap}}
1142
+ .kb-label{{white-space:normal}}
1143
+ .mobile-nav{{display:block;margin:0 0 14px;padding:11px 14px;border:1.5px solid var(--brand);
1144
+ border-radius:10px;background:var(--brand-soft);color:var(--brand);font-weight:800;
1145
+ font-size:13.5px;text-decoration:none;text-align:center}}
1146
+ .back-doc{{display:inline-block;margin:0 0 8px;font-size:12px;color:var(--brand);
1147
+ font-weight:700;text-decoration:none}}
1148
+ .sheet-mask{{display:block;position:fixed;inset:0;background:rgba(11,31,58,.45);z-index:99;opacity:0;
1149
+ pointer-events:none;transition:opacity .2s}}
1150
+ .sheet-mask.show{{opacity:1;pointer-events:auto}}
1151
+ .sheet{{display:block;position:fixed;left:0;right:0;bottom:0;z-index:100;background:#fff;
1152
+ border-radius:14px 14px 0 0;box-shadow:0 -8px 30px rgba(11,31,58,.25);
1153
+ max-height:68vh;overflow-y:auto;-webkit-overflow-scrolling:touch;
1154
+ padding:10px 16px 22px;transform:translateY(105%);transition:transform .25s ease}}
1155
+ .sheet.show{{transform:translateY(0)}}
1156
+ .sheet-grab{{width:38px;height:4px;border-radius:2px;background:#c9d4e2;margin:2px auto 8px}}
1157
+ .sheet-head{{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}}
1158
+ .sheet-head b{{font-size:13.5px;color:var(--navy)}}
1159
+ .sheet-close{{border:1px solid var(--line);background:#f5f8fc;border-radius:8px;color:#3b4a61;
1160
+ font-size:12.5px;font-weight:700;padding:5px 14px;cursor:pointer}}
1161
+ .sheet .scard{{box-shadow:none;margin-bottom:0}}
1162
+ .sheet .sc-excerpt{{display:block;-webkit-line-clamp:unset;cursor:auto}}
1163
+ }}
1164
+ @media print{{
1165
+ .topbar,.filters,.src-search{{display:none!important}}
1166
+ .layout{{grid-template-columns:1fr;max-width:none;padding:0;gap:14px}}
1167
+ body{{background:#fff;font-size:12.5px}}
1168
+ .sources{{position:static;max-height:none;border:0;padding:0;overflow:visible}}
1169
+ .r-head,.verify,.doc-sec{{border-color:#bbb;box-shadow:none;break-inside:avoid}}
1170
+ .sc-excerpt{{display:block;-webkit-line-clamp:unset;cursor:auto}}
1171
+ .uncited-group[open] .uncited-list,.uncited-group{{break-inside:avoid}}
1172
+ .scard{{break-inside:avoid}}
1173
+ .cite{{background:#eee;color:#333}}
1174
+ }}
1175
+ </style>
876
1176
  </head>
877
1177
  <body>
878
- <header>
879
- <h1>{esc(title)}</h1>
880
- <p>内容为 AI 生成,仅供参考|生成时间:{esc(generated)}</p>
881
- </header>
882
- <main class="layout">
883
- <section class="conversation" aria-label="回答正文">
884
- {question_html}
885
- <div class="answer">
886
- {note_html}
887
- {citation_warning}
888
- <div class="answer-body">{render_answer(answer, sources)}</div>
889
- {tools_html}
890
- </div>
891
- </section>
892
- <aside class="sources" aria-label="可信来源">
893
- <h2>可信来源</h2>
894
- <input class="searchbox" type="search" placeholder="搜索来源标题或摘录">
895
- {render_sources(sources)}
896
- </aside>
1178
+
1179
+ <header class="topbar">
1180
+ <div class="tb-title">{esc(display_title)} · 可信溯源核验报告</div>
1181
+ <div class="tags">
1182
+ <span>生成于 {esc(generated)}</span>
1183
+ <span>素材来源:深知可信搜索</span>
1184
+ </div>
1185
+ </header>
1186
+
1187
+ <div class="layout">
1188
+ <main class="report" aria-label="核验报告正文">
1189
+ <div class="r-head" id="doc-top">
1190
+ <h1>{esc(display_title)}</h1>
1191
+ <div class="sub">{esc(meta_line)}</div>
1192
+ </div>
1193
+ {citation_warning}
1194
+ {render_verify_panel(verification)}
1195
+ <a class="mobile-nav" href="#sources-panel">查看核验材料({len(sources)} 条 · 点击角标可定位原文)↓</a>
1196
+ {render_section_cards(sections, sources)}
1197
+ <div class="foot">深知公文写作 · 可信溯源核验报告 | 核验方法:可信搜索召回 → 逐条溯源 → 正文绑定 → 成稿自检 | 内容由 AI 生成,仅供参考,政策现行效力以官方发布为准</div>
897
1198
  </main>
898
- <script>
899
- const cards = Array.from(document.querySelectorAll(".source-card"));
900
- function activate(id) {{
901
- cards.forEach(card => card.classList.toggle("active", card.dataset.source === id));
902
- const target = document.querySelector(`#source-${{CSS.escape(id)}}`);
903
- if (target) target.scrollIntoView({{ block: "nearest", behavior: "smooth" }});
904
- }}
905
- document.querySelectorAll(".cite").forEach(button => {{
906
- if (button.classList.contains("disabled")) return;
907
- button.addEventListener("click", () => activate(button.dataset.source));
1199
+ {render_sources_panel(sources, used, kb_zone)}
1200
+ </div>
1201
+
1202
+ <div class="sheet-mask" aria-hidden="true"></div>
1203
+ <div class="sheet" role="dialog" aria-label="核验材料">
1204
+ <div class="sheet-grab"></div>
1205
+ <div class="sheet-head"><b>核验材料</b><button class="sheet-close" type="button">收起</button></div>
1206
+ <div class="sheet-body"></div>
1207
+ </div>
1208
+
1209
+ <script>
1210
+ (function () {{
1211
+ "use strict";
1212
+ var cards = Array.prototype.slice.call(document.querySelectorAll(".scard"));
1213
+ var byId = {{}};
1214
+ cards.forEach(function (c) {{
1215
+ var id = c.getAttribute("data-cite-id");
1216
+ if (id) byId[id] = c;
1217
+ }});
1218
+
1219
+ /* 移动端底部弹层:点角标就地展示材料卡,不打断正文阅读 */
1220
+ var sheet = document.querySelector(".sheet");
1221
+ var mask = document.querySelector(".sheet-mask");
1222
+ function isMobile() {{
1223
+ return window.matchMedia("(max-width:680px)").matches;
1224
+ }}
1225
+ function openSheet(card) {{
1226
+ if (!sheet) return;
1227
+ var body = sheet.querySelector(".sheet-body");
1228
+ var clone = card.cloneNode(true);
1229
+ clone.removeAttribute("id");
1230
+ clone.classList.remove("hide");
1231
+ clone.classList.add("open");
1232
+ body.innerHTML = "";
1233
+ body.appendChild(clone);
1234
+ sheet.classList.add("show");
1235
+ mask.classList.add("show");
1236
+ document.body.style.overflow = "hidden";
1237
+ sheet.scrollTop = 0;
1238
+ }}
1239
+ function closeSheet() {{
1240
+ if (!sheet) return;
1241
+ sheet.classList.remove("show");
1242
+ mask.classList.remove("show");
1243
+ document.body.style.overflow = "";
1244
+ }}
1245
+ if (sheet && mask) {{
1246
+ mask.addEventListener("click", closeSheet);
1247
+ var closeBtn = sheet.querySelector(".sheet-close");
1248
+ if (closeBtn) closeBtn.addEventListener("click", closeSheet);
1249
+ }}
1250
+
1251
+ /* 角标 → 来源卡:精确 ID 匹配,缺失即红色警示,绝不按位置猜测。
1252
+ 手机单栏下不滚动定位(会跳到页面底部打断阅读),改为底部弹层就地查看。 */
1253
+ document.querySelectorAll(".data-cite,[data-cite]").forEach(function (btn) {{
1254
+ if (btn.classList.contains("sheet-close")) return;
1255
+ btn.addEventListener("click", function () {{
1256
+ var card = byId[btn.getAttribute("data-cite")];
1257
+ if (!card) {{
1258
+ btn.classList.add("unresolved");
1259
+ if (console.error) console.error("[核验] 未绑定角标:", btn.getAttribute("data-cite"));
1260
+ return;
1261
+ }}
1262
+ if (isMobile()) {{
1263
+ openSheet(card);
1264
+ return;
1265
+ }}
1266
+ card.classList.remove("hide", "open");
1267
+ card.classList.add("hl", "open");
1268
+ card.scrollIntoView({{ block: "center", behavior: "smooth" }});
1269
+ setTimeout(function () {{ card.classList.remove("hl"); }}, 2200);
908
1270
  }});
909
- document.querySelectorAll(".evidence-detail").forEach(detail => {{
910
- detail.addEventListener("toggle", () => {{
911
- if (!detail.open) return;
912
- cards.forEach(card => card.classList.toggle("active", card.dataset.source === detail.dataset.source));
913
- }});
1271
+ }});
1272
+
1273
+ /* 摘录点击展开/收起 */
1274
+ cards.forEach(function (c) {{
1275
+ var ex = c.querySelector(".sc-excerpt");
1276
+ if (!ex) return;
1277
+ ex.addEventListener("click", function (e) {{
1278
+ if (e.target.closest("a")) return;
1279
+ c.classList.toggle("open");
914
1280
  }});
915
- const searchbox = document.querySelector(".searchbox");
916
- if (searchbox) {{
917
- searchbox.addEventListener("input", () => {{
918
- const value = searchbox.value.trim().toLowerCase();
919
- cards.forEach(card => {{
920
- card.style.display = !value || card.innerText.toLowerCase().includes(value) ? "" : "none";
921
- }});
1281
+ }});
1282
+
1283
+ /* 证据 chips(灰框):桌面端点击就地展开并高亮右栏来源卡;手机端不就地展开,点击直接弹出底部材料弹层 */
1284
+ document.querySelectorAll(".ev-chip").forEach(function (chip) {{
1285
+ var summary = chip.querySelector("summary");
1286
+ if (summary) {{
1287
+ summary.addEventListener("click", function (e) {{
1288
+ if (!isMobile()) return;
1289
+ e.preventDefault();
1290
+ var card = byId[chip.getAttribute("data-cite")];
1291
+ if (card) openSheet(card);
922
1292
  }});
923
1293
  }}
924
- </script>
1294
+ chip.addEventListener("toggle", function () {{
1295
+ if (!chip.open || isMobile()) return;
1296
+ var card = byId[chip.getAttribute("data-cite")];
1297
+ if (!card) return;
1298
+ cards.forEach(function (c) {{ c.classList.remove("hl"); }});
1299
+ card.classList.add("hl");
1300
+ setTimeout(function () {{ card.classList.remove("hl"); }}, 2200);
1301
+ }});
1302
+ }});
1303
+
1304
+ /* 类型筛选 + 搜索 */
1305
+ var filter = "all";
1306
+ var kw = "";
1307
+ function apply() {{
1308
+ cards.forEach(function (c) {{
1309
+ var okType = filter === "all" || c.getAttribute("data-type") === filter;
1310
+ var okKw = !kw || (c.textContent || "").toLowerCase().indexOf(kw) !== -1;
1311
+ c.classList.toggle("hide", !(okType && okKw));
1312
+ }});
1313
+ }}
1314
+ document.querySelectorAll(".filters button").forEach(function (b) {{
1315
+ b.addEventListener("click", function () {{
1316
+ document.querySelectorAll(".filters button").forEach(function (x) {{ x.classList.remove("on"); }});
1317
+ b.classList.add("on");
1318
+ filter = b.getAttribute("data-f");
1319
+ apply();
1320
+ }});
1321
+ }});
1322
+ var search = document.querySelector(".src-search");
1323
+ if (search) search.addEventListener("input", function () {{ kw = search.value.trim().toLowerCase(); apply(); }});
1324
+ }})();
1325
+ </script>
925
1326
  </body>
926
- </html>
927
- """
1327
+ </html>"""
1328
+
1329
+
1330
+ def align_sources_to_answer(answer: str, sources: List[Dict[str, str]]) -> List[Dict[str, str]]:
1331
+ cited = citation_ids(answer)
1332
+ if not cited or not sources:
1333
+ return sources
1334
+ existing = {source["id"] for source in sources}
1335
+ if existing.intersection(cited):
1336
+ return sources
1337
+ aligned = [dict(source) for source in sources]
1338
+ for idx, citation in enumerate(cited):
1339
+ if idx >= len(aligned):
1340
+ break
1341
+ aligned[idx]["id"] = citation
1342
+ aligned[idx]["type_key"] = aligned[idx].get("type_key", "material")
1343
+ aligned[idx]["type_label"] = aligned[idx].get("type_label", "材料")
1344
+ aligned[idx]["type_css"] = aligned[idx].get("type_css", "mat")
1345
+ return aligned
928
1346
 
929
1347
 
930
1348
  def main() -> None:
931
- parser = argparse.ArgumentParser(description="生成深知可信搜索可交互可信溯源 HTML")
932
- parser.add_argument("input_json", help="trusted_search.py 或 deep_query.py 的 --json-only 输出 JSON")
1349
+ # dsh:未显式传 --output 时,默认输出到会话产物目录 official-docs/output/
1350
+ import os as _os
1351
+ _ws = _os.environ.get("DKNWOC_WS_ROOT")
1352
+ if not _ws:
1353
+ _sid = _os.environ.get("DSH_SESSION_ID", "")
1354
+ _ws = str(Path.cwd() / "dknowc-output" / (_sid[:8] if _sid else "_default"))
1355
+ default_output_dir = str(Path(_ws).resolve() / "official-docs" / "output")
1356
+
1357
+ parser = argparse.ArgumentParser(description="生成可信溯源核验报告 HTML")
1358
+ parser.add_argument("input_json", help="结构化溯源 JSON 或搜索结果 JSON")
933
1359
  parser.add_argument("--output", help="输出 HTML 路径;不传时根据问题自动生成短文件名")
934
- parser.add_argument("--output-dir", default="./outputs", help="未传 --output 时的输出目录")
935
- parser.add_argument("--title", default="深知可信搜索可信溯源", help="页面标题")
936
- parser.add_argument("--answer-file", help="最终回答正文文件。复杂任务综合后必须传入,确保 HTML 展示的答案与聊天答案一致。")
1360
+ parser.add_argument("--output-dir", default=default_output_dir, help="未传 --output 时的输出目录")
1361
+ parser.add_argument("--title", default="可信溯源核验报告", help="页面标题")
1362
+ parser.add_argument("--answer-file", help="最终正文文件。复杂任务综合后必须传入,确保 HTML 展示的正文与交付一致。")
937
1363
  parser.add_argument("--clean-md-output", help="输出干净 Markdown 路径;内容来自同一份最终答案,并移除 [1]、【1】等溯源角标。")
938
- parser.add_argument("--question", default="", help="用户问题,用于生成顶部对话气泡。")
1364
+ parser.add_argument("--question", default="", help="任务主题,用于自动生成文件名。")
939
1365
  args = parser.parse_args()
940
1366
 
941
1367
  payload = load_json(Path(args.input_json))