dknowc-dsh 2.3.1 → 2.4.1

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 (193) hide show
  1. package/README.md +11 -3
  2. package/cordis.patch.yml +1 -1
  3. package/package.json +7 -4
  4. package/skills/dk-trace-report/SKILL.md +288 -0
  5. package/skills/dk-trace-report/config/examples/doc.json +56 -0
  6. package/skills/dk-trace-report/config/examples/legal.json +51 -0
  7. package/skills/dk-trace-report/config/examples/ppt.json +47 -0
  8. package/skills/dk-trace-report/config/examples/tax.json +46 -0
  9. package/skills/dk-trace-report/config/examples/trusted.json +122 -0
  10. package/skills/dk-trace-report/reference/sample_input.json +60 -0
  11. package/skills/dk-trace-report/resources/ECHARTS-NOTICE.txt +10 -0
  12. package/skills/dk-trace-report/resources/echarts.custom.min.js +48 -0
  13. package/skills/dk-trace-report/scripts/build_report_input.py +333 -0
  14. package/skills/{dknowc-trusted-search → dk-trace-report}/scripts/chart_embed.py +4 -1
  15. package/skills/{dknowc-trusted-search → dk-trace-report}/scripts/render_trace_html.py +1071 -536
  16. package/skills/dk-trace-report/scripts/run_paths.py +95 -0
  17. package/skills/dk-trace-report/scripts/trust_digest.py +77 -0
  18. package/skills/dknowc-legal-assistant/README.md +95 -0
  19. package/skills/dknowc-legal-assistant/SKILL.md +122 -0
  20. package/skills/dknowc-legal-assistant/attribution.json +5 -0
  21. package/skills/dknowc-legal-assistant/reference/answer-and-report.md +221 -0
  22. package/skills/dknowc-legal-assistant/reference/capability-layer.md +143 -0
  23. package/skills/dknowc-legal-assistant/reference/legal_claims.example.json +96 -0
  24. package/skills/dknowc-legal-assistant/reference/onboarding_scripts.md +198 -0
  25. package/skills/dknowc-legal-assistant/reference/policy_tags.json +2002 -0
  26. package/skills/dknowc-legal-assistant/reference/retrieval-statute.md +81 -0
  27. package/skills/dknowc-legal-assistant/reference/retrieval-v2.md +133 -0
  28. package/skills/dknowc-legal-assistant/reference/sample_search_result.md +33 -0
  29. package/skills/dknowc-legal-assistant/reference/sample_trace_report.html +940 -0
  30. package/skills/dknowc-legal-assistant/reference/tags.md +53 -0
  31. package/skills/dknowc-legal-assistant/reference/troubleshooting.md +50 -0
  32. package/skills/dknowc-legal-assistant/reference/verification-pass.md +59 -0
  33. package/skills/dknowc-legal-assistant/resources/echarts.custom.min.js +48 -0
  34. package/skills/dknowc-legal-assistant/scripts/api_key.py +68 -0
  35. package/skills/dknowc-legal-assistant/scripts/attribution.py +61 -0
  36. package/skills/dknowc-legal-assistant/scripts/calc_legal.py +375 -0
  37. package/skills/dknowc-legal-assistant/scripts/calc_period.py +155 -0
  38. package/skills/dknowc-legal-assistant/scripts/check_answer.py +664 -0
  39. package/skills/dknowc-legal-assistant/scripts/initialize.py +188 -0
  40. package/skills/dknowc-legal-assistant/scripts/legal_client.py +208 -0
  41. package/skills/dknowc-legal-assistant/scripts/legal_search.py +1059 -0
  42. package/skills/dknowc-legal-assistant/scripts/merge_search_results.py +630 -0
  43. package/skills/dknowc-legal-assistant/scripts/path_guard.py +92 -0
  44. package/skills/dknowc-legal-assistant/scripts/question_profile.py +215 -0
  45. package/skills/dknowc-legal-assistant/scripts/register_key.mjs +1152 -0
  46. package/skills/dknowc-legal-assistant/scripts/run_eval.py +109 -0
  47. package/skills/dknowc-legal-assistant/scripts/source_cards.py +321 -0
  48. package/skills/dknowc-legal-assistant/scripts/tag_catalog.py +162 -0
  49. package/skills/dknowc-legal-assistant/scripts/trace_report.config.json +66 -0
  50. package/skills/dknowc-legal-assistant/scripts/verify_claims.py +448 -0
  51. package/skills/dknowc-legal-assistant/scripts/websearch_convert.py +396 -0
  52. package/skills/dknowc-official-doc-writer/README.md +32 -21
  53. package/skills/dknowc-official-doc-writer/SKILL.md +28 -15
  54. package/skills/dknowc-official-doc-writer/config/trace_report.config.json +56 -0
  55. package/skills/dknowc-official-doc-writer/reference/anti_ai_patterns.md +14 -2
  56. package/skills/dknowc-official-doc-writer/reference/fact_discipline.md +4 -0
  57. package/skills/dknowc-official-doc-writer/reference/genre_writing_notes.md +4 -0
  58. package/skills/dknowc-official-doc-writer/reference/initialization.md +13 -8
  59. package/skills/dknowc-official-doc-writer/reference/local_memory_guide.md +7 -7
  60. package/skills/dknowc-official-doc-writer/reference/material_usage_guidance.md +21 -0
  61. package/skills/dknowc-official-doc-writer/reference/materials_pipeline.md +64 -7
  62. package/skills/dknowc-official-doc-writer/reference/onboarding_scripts.md +1 -1
  63. package/skills/dknowc-official-doc-writer/reference/outline_rules.md +1 -1
  64. package/skills/dknowc-official-doc-writer/reference/output_guide.md +13 -13
  65. package/skills/dknowc-official-doc-writer/reference/research_notes.md +5 -3
  66. package/skills/dknowc-official-doc-writer/reference/review_checklist.md +6 -2
  67. package/skills/dknowc-official-doc-writer/reference/search_guide.md +44 -32
  68. package/skills/dknowc-official-doc-writer/reference/search_policy.md +63 -36
  69. package/skills/dknowc-official-doc-writer/reference/standards/01_report.md +3 -3
  70. package/skills/dknowc-official-doc-writer/reference/standards/02_qingshi.md +6 -3
  71. package/skills/dknowc-official-doc-writer/reference/standards/03_pifu.md +2 -2
  72. package/skills/dknowc-official-doc-writer/reference/standards/04_tongzhi.md +12 -3
  73. package/skills/dknowc-official-doc-writer/reference/standards/05_yijian.md +8 -2
  74. package/skills/dknowc-official-doc-writer/reference/standards/06_han.md +2 -2
  75. package/skills/dknowc-official-doc-writer/reference/standards/08_tongbao.md +2 -2
  76. package/skills/dknowc-official-doc-writer/reference/standards/09_tonggao.md +2 -2
  77. package/skills/dknowc-official-doc-writer/reference/standards/10_gonggao.md +2 -2
  78. package/skills/dknowc-official-doc-writer/reference/standards/11_fuhan_approve.md +2 -2
  79. package/skills/dknowc-official-doc-writer/reference/standards/12_fuhan_objection.md +2 -2
  80. package/skills/dknowc-official-doc-writer/reference/standards/13_reminder.md +3 -3
  81. package/skills/dknowc-official-doc-writer/reference/standards/14_generic.md +1 -1
  82. package/skills/dknowc-official-doc-writer/reference/standards/16_decision.md +2 -2
  83. package/skills/dknowc-official-doc-writer/reference/standards/18_order.md +1 -1
  84. package/skills/dknowc-official-doc-writer/reference/standards/19_gazette.md +1 -1
  85. package/skills/dknowc-official-doc-writer/reference/standards/20_motion.md +2 -2
  86. package/skills/dknowc-official-doc-writer/reference/standards/22_application.md +2 -2
  87. package/skills/dknowc-official-doc-writer/reference/standards/23_publicity.md +1 -1
  88. package/skills/dknowc-official-doc-writer/reference/standards/25_plan.md +2 -1
  89. package/skills/dknowc-official-doc-writer/reference/standards/26_summary.md +7 -1
  90. package/skills/dknowc-official-doc-writer/reference/standards/27_speech.md +4 -1
  91. package/skills/dknowc-official-doc-writer/reference/standards/99_expressions.md +1 -1
  92. package/skills/dknowc-official-doc-writer/reference/task_router.md +4 -4
  93. package/skills/dknowc-official-doc-writer/reference/working_principles.md +4 -4
  94. package/skills/dknowc-official-doc-writer/reference/writing_method.md +166 -0
  95. package/skills/dknowc-official-doc-writer/reference/writing_rules.md +10 -4
  96. package/skills/dknowc-official-doc-writer/scripts/api_key.py +24 -25
  97. package/skills/dknowc-official-doc-writer/scripts/attribution.py +1 -1
  98. package/skills/dknowc-official-doc-writer/scripts/build_trace_json.py +205 -13
  99. package/skills/dknowc-official-doc-writer/scripts/check_materials.py +367 -22
  100. package/skills/dknowc-official-doc-writer/scripts/deep_convert.py +5 -0
  101. package/skills/dknowc-official-doc-writer/scripts/deep_query.py +2 -1
  102. package/skills/dknowc-official-doc-writer/scripts/dkag_search.py +20 -7
  103. package/skills/dknowc-official-doc-writer/scripts/extract_reference.py +1 -0
  104. package/skills/dknowc-official-doc-writer/scripts/format_document.py +88 -30
  105. package/skills/dknowc-official-doc-writer/scripts/initialize.py +232 -6
  106. package/skills/dknowc-official-doc-writer/scripts/local_memory.py +2 -6
  107. package/skills/dknowc-official-doc-writer/scripts/merge_search_results.py +100 -7
  108. package/skills/dknowc-official-doc-writer/scripts/outline_reference.py +2 -1
  109. package/skills/dknowc-official-doc-writer/scripts/register.mjs +265 -32
  110. package/skills/dknowc-official-doc-writer/scripts/review_document.py +1 -0
  111. package/skills/dknowc-official-doc-writer/scripts/source_note_html.py +117 -10
  112. package/skills/dknowc-official-doc-writer/scripts/template_generator.py +1 -0
  113. package/skills/dknowc-official-doc-writer/scripts/update_skill.py +339 -0
  114. package/skills/dknowc-official-doc-writer/scripts/websearch_convert.py +326 -0
  115. package/skills/dknowc-ppt-assistant/README.md +7 -9
  116. package/skills/dknowc-ppt-assistant/SKILL.md +28 -19
  117. package/skills/dknowc-ppt-assistant/config/trace_report.config.json +65 -0
  118. package/skills/dknowc-ppt-assistant/references/initialization.md +20 -8
  119. package/skills/dknowc-ppt-assistant/references/material_usage.md +46 -9
  120. package/skills/dknowc-ppt-assistant/references/onboarding_scripts.md +7 -5
  121. package/skills/dknowc-ppt-assistant/references/sample_trace_report.html +372 -920
  122. package/skills/dknowc-ppt-assistant/references/search_intro.md +2 -2
  123. package/skills/dknowc-ppt-assistant/references/svg-authoring.md +2 -2
  124. package/skills/dknowc-ppt-assistant/scripts/api_key.py +5 -28
  125. package/skills/dknowc-ppt-assistant/scripts/build_trace_input.py +188 -0
  126. package/skills/dknowc-ppt-assistant/scripts/initialize.py +238 -3
  127. package/skills/dknowc-ppt-assistant/scripts/mcp_convert.py +1 -10
  128. package/skills/dknowc-ppt-assistant/scripts/merge_search_results.py +604 -0
  129. package/skills/dknowc-ppt-assistant/scripts/preview_slide_html.py +4 -11
  130. package/skills/dknowc-ppt-assistant/scripts/register_key.mjs +224 -63
  131. package/skills/dknowc-ppt-assistant/scripts/trusted_search.py +29 -12
  132. package/skills/dknowc-ppt-assistant/scripts/update_skill.py +314 -0
  133. package/skills/dknowc-ppt-assistant/scripts/websearch_convert.py +326 -0
  134. package/skills/dknowc-ppt-assistant/workflows/generate-pptx.md +92 -29
  135. package/skills/dknowc-ppt-assistant/workflows/routing.md +1 -1
  136. package/skills/dknowc-tax-assistant/README.md +54 -0
  137. package/skills/dknowc-tax-assistant/SKILL.md +99 -0
  138. package/skills/dknowc-tax-assistant/attribution.json +5 -0
  139. package/skills/dknowc-tax-assistant/reference/answer-and-report.md +100 -0
  140. package/skills/dknowc-tax-assistant/reference/capability-layer.md +205 -0
  141. package/skills/dknowc-tax-assistant/reference/onboarding_scripts.md +68 -0
  142. package/skills/dknowc-tax-assistant/reference/policy_tags.json +2002 -0
  143. package/skills/dknowc-tax-assistant/reference/retrieval-policy.md +43 -0
  144. package/skills/dknowc-tax-assistant/reference/retrieval-v2.md +58 -0
  145. package/skills/dknowc-tax-assistant/reference/tags.md +53 -0
  146. package/skills/dknowc-tax-assistant/reference/tax_claims.example.json +76 -0
  147. package/skills/dknowc-tax-assistant/reference/trace_report.config.json +46 -0
  148. package/skills/dknowc-tax-assistant/reference/troubleshooting.md +70 -0
  149. package/skills/dknowc-tax-assistant/reference/websearch-fallback.md +59 -0
  150. package/skills/dknowc-tax-assistant/resources/THIRD_PARTY_NOTICES.md +9 -0
  151. package/skills/dknowc-tax-assistant/resources/echarts.custom.min.js +48 -0
  152. package/skills/dknowc-tax-assistant/scripts/api_key.py +60 -0
  153. package/skills/dknowc-tax-assistant/scripts/attribution.py +61 -0
  154. package/skills/dknowc-tax-assistant/scripts/calc_period.py +156 -0
  155. package/skills/dknowc-tax-assistant/scripts/calc_tax.py +179 -0
  156. package/skills/dknowc-tax-assistant/scripts/check_answer.py +210 -0
  157. package/skills/dknowc-tax-assistant/scripts/initialize.py +208 -0
  158. package/skills/dknowc-tax-assistant/scripts/merge_search_results.py +631 -0
  159. package/skills/dknowc-tax-assistant/scripts/path_guard.py +23 -0
  160. package/skills/dknowc-tax-assistant/scripts/question_profile.py +444 -0
  161. package/skills/dknowc-tax-assistant/scripts/register_key.mjs +1173 -0
  162. package/skills/dknowc-tax-assistant/scripts/run_dir.py +149 -0
  163. package/skills/dknowc-tax-assistant/scripts/source_cards.py +372 -0
  164. package/skills/dknowc-tax-assistant/scripts/tag_catalog.py +164 -0
  165. package/skills/dknowc-tax-assistant/scripts/tax_client.py +218 -0
  166. package/skills/dknowc-tax-assistant/scripts/tax_search.py +403 -0
  167. package/skills/dknowc-tax-assistant/scripts/verify_claims.py +587 -0
  168. package/skills/dknowc-tax-assistant/scripts/websearch_convert.py +352 -0
  169. package/skills/dknowc-trusted-search/README.md +25 -19
  170. package/skills/dknowc-trusted-search/SKILL.md +205 -73
  171. package/skills/dknowc-trusted-search/config/trace_report.config.json +119 -0
  172. package/skills/dknowc-trusted-search/reference/onboarding_scripts.md +3 -3
  173. package/skills/dknowc-trusted-search/reference/sample_trace_report.html +286 -191
  174. package/skills/dknowc-trusted-search/resources/ECHARTS-NOTICE.txt +10 -0
  175. package/skills/dknowc-trusted-search/scripts/api_key.py +0 -1
  176. package/skills/dknowc-trusted-search/scripts/attribution.py +1 -1
  177. package/skills/dknowc-trusted-search/scripts/build_trace_input.py +173 -0
  178. package/skills/dknowc-trusted-search/scripts/deep_convert.py +79 -30
  179. package/skills/dknowc-trusted-search/scripts/deep_query.py +22 -33
  180. package/skills/dknowc-trusted-search/scripts/initialize.py +343 -2
  181. package/skills/dknowc-trusted-search/scripts/merge_search_results.py +222 -35
  182. package/skills/dknowc-trusted-search/scripts/register_key.mjs +241 -29
  183. package/skills/dknowc-trusted-search/scripts/source_display.py +59 -0
  184. package/skills/dknowc-trusted-search/scripts/trusted_search.py +67 -34
  185. package/skills/dknowc-trusted-search/scripts/update_skill.py +300 -0
  186. package/skills/dknowc-trusted-search/scripts/websearch_convert.py +328 -0
  187. package/src/index.js +18 -2
  188. package/skills/dknowc-official-doc-writer/scripts/render_trace_html.py +0 -2574
  189. package/skills/dknowc-ppt-assistant/official-docs/output/.gitkeep +0 -0
  190. package/skills/dknowc-ppt-assistant/official-docs/search-results/.gitkeep +0 -0
  191. package/skills/dknowc-ppt-assistant/scripts/render_trace_html.py +0 -2642
  192. package/skills/dknowc-trusted-search/official-docs/output/.gitkeep +0 -0
  193. package/skills/dknowc-trusted-search/official-docs/search-results/.gitkeep +0 -0
@@ -0,0 +1,587 @@
1
+ #!/usr/bin/env python3
2
+ """结论图校验:用问题画像 + 材料画像 + claim 做通用对齐。
3
+
4
+ 替代"针对某个错题写一条正则"的做法。核心检查维度:
5
+ - 地域:claim / 来源 / 问题是否一致(全国口径除外)
6
+ - 税种:claim 标注的税种是否与问题画像相交
7
+ - 时点:claim 的 as_of 是否明确;否定结论是否写截止日期与检索覆盖
8
+ - 来源:抓取失败不能当依据;次级媒体不能直接当政策条文结论
9
+ - 引文:direct 的 quote 是否在来源 span 里,数量是否等于枚举项数
10
+ - 计算:calculation 是否用 calc_tax.py / calc_period.py,口径是否写明,结果能否重算
11
+ - 否定:negative 是否有 as_of / coverage / wording,答案是否写成"截至……未见"
12
+ - 推断:inference 是否有"通常/一般/以属地……认定为准"
13
+ - 解释争议:interpretation 是否同时给出 primary / alternative
14
+ - 答案:强断言是否有 answer_anchor 或引用角标
15
+
16
+ 用法:
17
+ python3 scripts/verify_claims.py \
18
+ --claims tax_claims.json \
19
+ --sources tax_source_cards.json \
20
+ --profile tax_question_profile.json \
21
+ --answer tax_answer.txt \
22
+ --output tax_verify.json
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import re
30
+ import sys
31
+ from decimal import Decimal
32
+ from typing import Any, Dict, List, Optional, Tuple
33
+
34
+ import calc_tax
35
+ import run_dir
36
+ # dsh:内核抽离到插件内兄弟 skill「溯源核验报告生成器」(dk-trace-report),
37
+ # 此处注入其 scripts 目录到 sys.path;母版同目录形态下目录不存在、行为不变。
38
+ import sys as _sys
39
+ from pathlib import Path as _Path
40
+ _KERNEL_DIR = _Path(__file__).resolve().parent.parent.parent / "dk-trace-report" / "scripts"
41
+ if _KERNEL_DIR.is_dir():
42
+ _sys.path.insert(0, str(_KERNEL_DIR))
43
+
44
+ import trust_digest
45
+ from calc_period import build_result as calc_period_build_result
46
+ from calc_period import parse_date, parse_decimal, parse_rate
47
+ from question_profile import CITY_PROVINCE
48
+
49
+ TYPES = {"direct", "calculation", "negative", "inference", "external", "interpretation"}
50
+ NATIONAL = {"全国", "国家", "中国", ""}
51
+ SECONDARY = {"次级媒体", "未知"}
52
+ SOURCE_NATURES = {"政府网站", "官方媒体", "次级媒体", "未知"}
53
+ QUALIFIERS = ("通常", "一般", "原则上", "以属地", "以当地", "以主管", "以认定为准", "视", "可能")
54
+ STRONG_TERMS = (
55
+ "确有", "已经", "属于", "不存在", "全部", "一律", "一定", "已上调", "已执行",
56
+ "已补发", "免征", "免税", "减半征收", "可以享受", "不得享受", "无需缴纳",
57
+ )
58
+ CALC_TOOLS = ("calc_tax.py", "calc_period.py")
59
+ _ENUM_CN = re.compile(r"[((]\s*([一二三四五六七八九十]+)\s*[))]")
60
+ _ENUM_NUM = re.compile(r"(?m)^\s*(\d{1,2})[.、]\s*")
61
+
62
+
63
+ def _items(data: Any) -> List[Dict[str, Any]]:
64
+ if isinstance(data, dict):
65
+ data = data.get("claims") or data.get("sources") or []
66
+ return [x for x in data if isinstance(x, dict)] if isinstance(data, list) else []
67
+
68
+
69
+ def _source_text(source: Dict[str, Any]) -> str:
70
+ spans = source.get("spans") or []
71
+ if isinstance(spans, list):
72
+ return "\n".join(str(x) for x in spans if x)
73
+ return str(spans or "")
74
+
75
+
76
+ def _same_jurisdiction(left: str, right: str) -> bool:
77
+ left = (left or "").strip()
78
+ right = (right or "").strip()
79
+ if left in NATIONAL or right in NATIONAL:
80
+ return True
81
+ if left == right or left in right or right in left:
82
+ return True
83
+ # 省级来源 vs 市级问题:河北省 vs 石家庄市 → 同一辖区。
84
+ for a, b in ((left, right), (right, left)):
85
+ if a.endswith(("省", "自治区")) and b.endswith("市"):
86
+ province = CITY_PROVINCE.get(b.rstrip("市"), "")
87
+ if province == a:
88
+ return True
89
+ if a.endswith("市") and b.endswith("区"):
90
+ if b.startswith(a) or a.startswith(b):
91
+ return True
92
+ return False
93
+
94
+
95
+ def _norm_ws(value: str) -> str:
96
+ return re.sub(r"\s+", "", value or "")
97
+
98
+
99
+ def quote_in_text(quote: str, text: str) -> bool:
100
+ """引文比对:允许省略号,但省略号分隔的每一段都要能在材料里找到。"""
101
+ q = _norm_ws(quote)
102
+ t = _norm_ws(text)
103
+ if not q:
104
+ return True
105
+ if not t:
106
+ return False
107
+ parts = [p for p in re.split(r"(?:……|\.{3,}|…+)", q) if len(p) >= 4]
108
+ if len(parts) > 1:
109
+ return all(p in t for p in parts)
110
+ return q in t
111
+
112
+
113
+ def count_enumerations(quote: str) -> int:
114
+ """数引文里的"(一)(二)……"或行首"1. 2."枚举项。"""
115
+ text = quote or ""
116
+ cn = len({m.group(1) for m in _ENUM_CN.finditer(text)})
117
+ nums = [int(m.group(1)) for m in _ENUM_NUM.finditer(text)]
118
+ return max(cn, max(nums, default=0))
119
+
120
+
121
+ def _opt_decimal(value: Any) -> Optional[Decimal]:
122
+ return None if value is None or str(value).strip() == "" else parse_decimal(str(value))
123
+
124
+
125
+ def _opt_rate(value: Any) -> Optional[Decimal]:
126
+ return None if value is None or str(value).strip() == "" else parse_rate(str(value))
127
+
128
+
129
+ def _opt_date(value: Any) -> Optional[Any]:
130
+ return None if value is None or str(value).strip() == "" else parse_date(str(value))
131
+
132
+
133
+ def _claim_mode(claim: Dict[str, Any]) -> str:
134
+ mode = str(claim.get("mode") or "").strip()
135
+ if mode:
136
+ return mode
137
+ if claim.get("principal") is not None and claim.get("start") and claim.get("end"):
138
+ return "late-fee"
139
+ if claim.get("amount") is not None:
140
+ return "tax-inclusive"
141
+ if claim.get("base") is not None:
142
+ return "tax-exclusive"
143
+ if claim.get("tax") is not None and (claim.get("reduction_rate") or claim.get("reduction")):
144
+ return "reduction"
145
+ return ""
146
+
147
+
148
+ def _calc_tax_matches(claim: Dict[str, Any]) -> Tuple[bool, str]:
149
+ mode = str(claim.get("mode") or "").strip()
150
+ try:
151
+ args = argparse.Namespace(
152
+ mode=mode or None,
153
+ start=_opt_date(claim.get("start")),
154
+ end=_opt_date(claim.get("end")),
155
+ day_count=str(claim.get("convention") or claim.get("day_count") or "") or None,
156
+ principal=_opt_decimal(claim.get("principal")),
157
+ daily_rate=_opt_rate(claim.get("daily_rate")),
158
+ base=_opt_decimal(claim.get("base")),
159
+ amount=_opt_decimal(claim.get("amount")),
160
+ rate=_opt_rate(claim.get("rate")),
161
+ tax=_opt_decimal(claim.get("tax")),
162
+ reduction=_opt_rate(claim.get("reduction_rate") or claim.get("reduction")),
163
+ )
164
+ result = calc_tax.build_result(args)
165
+ except Exception as exc: # noqa: BLE001
166
+ return False, f"无法重算:{exc}"
167
+ if not mode:
168
+ mode = str(result.get("mode") or "")
169
+ if mode != result.get("mode"):
170
+ return False, f"mode 台账={mode},工具={result.get('mode')}"
171
+ for key in ("days", "amount", "tax", "base", "relief", "payable"):
172
+ if claim.get(key) is not None and str(claim.get(key)) != str(result.get(key)):
173
+ return False, f"{key} 台账={claim.get(key)},工具={result.get(key)}"
174
+ return True, ""
175
+
176
+
177
+ def _calc_period_matches(claim: Dict[str, Any], claim_map: Dict[str, Dict[str, Any]]) -> Tuple[bool, str]:
178
+ required = ("start", "end", "principal", "annual_rate")
179
+ if not all(claim.get(k) for k in required):
180
+ aggregate = claim.get("aggregate_of")
181
+ if isinstance(aggregate, list) and aggregate:
182
+ total = Decimal("0")
183
+ for ref in aggregate:
184
+ other = claim_map.get(str(ref))
185
+ if not other or other.get("type") != "calculation":
186
+ return False, f"aggregate_of 引用无效:{ref}"
187
+ try:
188
+ total += Decimal(str(other.get("interest") or "0"))
189
+ except Exception: # noqa: BLE001
190
+ return False, f"aggregate_of 引用缺少 interest:{ref}"
191
+ if claim.get("interest") is not None:
192
+ try:
193
+ if Decimal(str(claim["interest"])) != total:
194
+ return False, f"aggregate_of 合计={total},claim.interest={claim['interest']}"
195
+ except Exception: # noqa: BLE001
196
+ return False, "aggregate_of 的 interest 不是有效金额"
197
+ return True, ""
198
+ return False, "calculation 缺少 start/end/principal/annual_rate,或 aggregate_of"
199
+ try:
200
+ args = type("Args", (), {
201
+ "start": parse_date(str(claim["start"])),
202
+ "end": parse_date(str(claim["end"])),
203
+ "day_count": str(claim.get("convention") or "include-end"),
204
+ "principal": parse_decimal(str(claim["principal"])),
205
+ "rate": parse_rate(str(claim["annual_rate"])),
206
+ "basis_days": int(claim.get("basis_days") or 365),
207
+ })()
208
+ result = calc_period_build_result(args)
209
+ except Exception as exc: # noqa: BLE001
210
+ return False, f"无法重算:{exc}"
211
+ for key in ("days", "interest"):
212
+ if claim.get(key) is not None and str(claim.get(key)) != str(result.get(key)):
213
+ return False, f"{key} 台账={claim.get(key)},工具={result.get(key)}"
214
+ return True, ""
215
+
216
+
217
+ def _norm_text(value: str) -> str:
218
+ return re.sub(r"[\s*_`#]+", "", value or "")
219
+
220
+
221
+ def _anchors(claim: Dict[str, Any]) -> List[str]:
222
+ value = claim.get("answer_anchor") or claim.get("answer_anchors") or []
223
+ if isinstance(value, str):
224
+ value = [value]
225
+ return [str(x) for x in value if str(x).strip()] if isinstance(value, list) else []
226
+
227
+
228
+ def _answer_sentences(answer: str) -> List[str]:
229
+ out: List[str] = []
230
+ for raw in answer.splitlines():
231
+ line = raw.strip()
232
+ if not line or line.startswith(">") or line.startswith("#") or line.startswith("```"):
233
+ continue
234
+ for sent in re.split(r"(?<=[。!?;!?;])", line):
235
+ sent = sent.strip()
236
+ if sent:
237
+ out.append(sent)
238
+ return out
239
+
240
+
241
+ def _as_list(value: Any) -> List[str]:
242
+ if isinstance(value, str):
243
+ return [value] if value.strip() else []
244
+ if isinstance(value, list):
245
+ return [str(x) for x in value if str(x).strip()]
246
+ return []
247
+
248
+
249
+ def verify(claims: List[Dict[str, Any]], sources: List[Dict[str, Any]],
250
+ profile: Dict[str, Any], answer: str = "") -> Dict[str, Any]:
251
+ source_map = {str(s.get("id")): s for s in sources}
252
+ claim_map = {str(c.get("id")): c for c in claims if c.get("id")}
253
+ question_jurisdiction = str(profile.get("jurisdiction") or "").strip()
254
+ question_tax_types = set(_as_list(profile.get("tax_types")))
255
+ issues: List[str] = []
256
+ item_results: List[Dict[str, Any]] = []
257
+
258
+ if not question_jurisdiction:
259
+ issues.append("问题画像缺少 jurisdiction")
260
+ if not str(profile.get("as_of") or "").strip():
261
+ issues.append("问题画像缺少 as_of")
262
+ if not claims:
263
+ issues.append("没有结论台账(claims 为空)")
264
+
265
+ for idx, claim in enumerate(claims, start=1):
266
+ cid = str(claim.get("id") or f"c{idx}")
267
+ ctype = str(claim.get("type") or "").strip()
268
+ text = str(claim.get("text") or claim.get("claim") or "").strip()
269
+ local: List[str] = []
270
+
271
+ if ctype not in TYPES:
272
+ local.append(f"type 非法:{ctype or '空'}")
273
+ if not text:
274
+ local.append("缺少 text/claim")
275
+ anchors = _anchors(claim)
276
+ if anchors and answer:
277
+ if not any(_norm_text(a) in _norm_text(answer) for a in anchors):
278
+ local.append("answer_anchor 未在答案中出现,答案没有落到这条 claim")
279
+
280
+ claim_tax_types = set(_as_list(claim.get("tax_types")))
281
+ if claim_tax_types and question_tax_types and not (claim_tax_types & question_tax_types):
282
+ local.append(
283
+ f"claim 税种({'、'.join(sorted(claim_tax_types))})与问题税种"
284
+ f"({'、'.join(sorted(question_tax_types))})不一致"
285
+ )
286
+
287
+ source_ids = _as_list(claim.get("source_ids"))
288
+ cited = [source_map[str(sid)] for sid in source_ids if str(sid) in source_map]
289
+ if source_ids and not cited:
290
+ local.append("source_ids 在材料画像中都不存在")
291
+ for source in cited:
292
+ if source.get("fetch_status") == "failed":
293
+ local.append(f"来源 {source.get('id')} 抓取失败,不能作为依据")
294
+
295
+ claim_jurisdiction = str(claim.get("jurisdiction") or "").strip()
296
+ if not claim_jurisdiction and cited:
297
+ claim_jurisdiction = str(cited[0].get("jurisdiction") or "")
298
+ if ctype in ("direct", "external") and not claim_jurisdiction:
299
+ local.append("缺少 jurisdiction,无法判断地域是否匹配")
300
+ if claim_jurisdiction and not _same_jurisdiction(claim_jurisdiction, question_jurisdiction):
301
+ local.append(f"claim 地域({claim_jurisdiction})与问题地域({question_jurisdiction})不一致")
302
+
303
+ if ctype == "external":
304
+ nature = str(claim.get("source_nature") or "").strip()
305
+ source_jurisdiction = str(
306
+ claim.get("jurisdiction") or (cited[0].get("jurisdiction") if cited else "")
307
+ ).strip()
308
+ question_j = str(claim.get("question_jurisdiction") or question_jurisdiction).strip()
309
+ if not nature:
310
+ local.append("external 缺少 source_nature")
311
+ elif nature not in SOURCE_NATURES:
312
+ local.append(f"external source_nature 非法:{nature}")
313
+ if not str(claim.get("as_of") or "").strip():
314
+ local.append("external 缺少 as_of")
315
+ if not source_ids and not claim.get("url") and not claim.get("source_ref") and not claim.get("official_value"):
316
+ local.append("external 缺少来源引用(source_ids/url/source_ref)")
317
+ if nature == "政府网站" and not source_ids and not claim.get("url"):
318
+ local.append("政府网站来源缺少 source_ids/url,无法回查")
319
+ if not source_jurisdiction or not question_j:
320
+ local.append("external 缺少 jurisdiction / question_jurisdiction")
321
+ elif not _same_jurisdiction(source_jurisdiction, question_j):
322
+ local.append(f"来源地域({source_jurisdiction})与问题地域({question_j})不一致")
323
+ if nature in SECONDARY and not (claim.get("official_value") or claim.get("wording")):
324
+ local.append("次级媒体 external 缺少 official_value 或「待核验」措辞")
325
+ value = str(claim.get("value") or "").strip()
326
+ official_value = str(claim.get("official_value") or "").strip()
327
+ wording = str(claim.get("wording") or "")
328
+ if value and official_value and value not in official_value and official_value not in value:
329
+ if not re.search(r"待核验|未见正式|以官方|官方口径", wording):
330
+ local.append("外部数值与官方口径不一致,但措辞未写「待核验/未见正式文件/官方口径」")
331
+ mixed = claim.get("mixed_sources")
332
+ if mixed:
333
+ if isinstance(mixed, dict):
334
+ mixed_grades = set()
335
+ for sid, grade in mixed.items():
336
+ if str(sid) not in {str(x) for x in source_ids}:
337
+ local.append(f"mixed_sources 引用了未引用的来源:{sid}")
338
+ grade = str(grade or "")
339
+ if grade not in SOURCE_NATURES:
340
+ local.append(f"mixed_sources 的来源等级非法:{grade or '空'}")
341
+ mixed_grades.add(grade)
342
+ if nature not in SECONDARY and not any(g in SECONDARY for g in mixed_grades):
343
+ local.append("mixed_sources 没有任何次级媒体/未知来源,不能解释 claim 的来源等级")
344
+ elif isinstance(mixed, str):
345
+ if not (re.search(r"次级媒体|未知|转引|转载", mixed) and re.search(r"政府网站|官方媒体", mixed)):
346
+ local.append("mixed_sources 必须同时说明政府网站/官方媒体与次级媒体/转引")
347
+ else:
348
+ local.append("mixed_sources 必须是对象或说明字符串")
349
+
350
+ for source in cited:
351
+ if (
352
+ source.get("jurisdiction")
353
+ and question_jurisdiction
354
+ and not _same_jurisdiction(str(source["jurisdiction"]), question_jurisdiction)
355
+ ):
356
+ local.append(f"来源 {source.get('id')} 地域({source.get('jurisdiction')})与问题不一致")
357
+ if (
358
+ not source.get("jurisdiction")
359
+ and question_j not in NATIONAL
360
+ and claim_jurisdiction not in NATIONAL
361
+ ):
362
+ local.append(f"来源 {source.get('id')} 地域未知,不能用于省级/地方问题")
363
+ grade = str(source.get("source_grade") or "").strip()
364
+ if grade in SECONDARY and nature not in SECONDARY and not claim.get("mixed_sources"):
365
+ local.append(
366
+ f"claim 标为「{nature}」,但来源 {source.get('id')} 是「{grade}」;请拆分或写 mixed_sources"
367
+ )
368
+
369
+ if ctype == "direct":
370
+ if not source_ids:
371
+ local.append("direct 缺少 source_ids")
372
+ # 直接依据必须能支撑 claim 的地域:全国结论不能拿地方文件当地基,
373
+ # 地方结论也不能用其他辖区来源。
374
+ if cited and claim_jurisdiction:
375
+ for source in cited:
376
+ source_j = str(source.get("jurisdiction") or "").strip()
377
+ if not source_j or source_j in NATIONAL:
378
+ continue
379
+ if claim_jurisdiction in NATIONAL:
380
+ local.append(
381
+ f"全国结论引用了地方来源 {source.get('id')}({source_j}),不能支撑全国口径"
382
+ )
383
+ elif not _same_jurisdiction(source_j, claim_jurisdiction):
384
+ local.append(
385
+ f"direct 来源 {source.get('id')} 地域({source_j})与 claim 地域"
386
+ f"({claim_jurisdiction})不一致"
387
+ )
388
+ quote = str(claim.get("quote") or "")
389
+ if not quote:
390
+ local.append("direct 缺少 quote")
391
+ elif cited:
392
+ if not any(quote_in_text(quote, _source_text(s)) for s in cited):
393
+ local.append("direct.quote 在来源 span 中找不到")
394
+ count = claim.get("count")
395
+ if count is not None:
396
+ try:
397
+ expected = int(count)
398
+ except (TypeError, ValueError):
399
+ local.append("count 不是整数")
400
+ else:
401
+ actual = count_enumerations(quote)
402
+ if actual != expected:
403
+ local.append(f"count 声称 {expected} 项,引文数出 {actual} 项")
404
+ if cited and not all(
405
+ s.get("official") or s.get("source_grade") in ("官方库", "政府网站", "官方原文")
406
+ for s in cited
407
+ ):
408
+ local.append("direct 依据含次级媒体/未知来源,不能作为政策条文结论")
409
+
410
+ elif ctype == "calculation":
411
+ tool = str(claim.get("tool") or "")
412
+ if tool not in CALC_TOOLS:
413
+ local.append("calculation 必须写 tool=calc_tax.py 或 calc_period.py")
414
+ if tool == "calc_tax.py":
415
+ mode = _claim_mode(claim)
416
+ if mode == "late-fee":
417
+ if str(claim.get("convention") or claim.get("day_count") or "") not in ("include-end", "exclude-end"):
418
+ local.append("滞纳金 calculation 必须写 convention=include-end/exclude-end")
419
+ required_outputs = {
420
+ "late-fee": ("days", "amount"),
421
+ "tax-exclusive": ("tax",),
422
+ "tax-inclusive": ("base", "tax"),
423
+ "reduction": ("relief",),
424
+ }
425
+ if mode not in required_outputs:
426
+ local.append("calculation 无法判断 mode,或 mode 非法")
427
+ else:
428
+ missing = [k for k in required_outputs[mode] if claim.get(k) is None]
429
+ if missing:
430
+ local.append(
431
+ f"calculation 缺少写回的工具结果:{'/'.join(missing)};"
432
+ "不能只写输入,必须落 calc_tax.py 的输出"
433
+ )
434
+ ok, msg = _calc_tax_matches(claim)
435
+ else:
436
+ if str(claim.get("convention") or "").strip() not in ("include-end", "exclude-end"):
437
+ local.append("calculation 必须写 convention=include-end/exclude-end")
438
+ ok, msg = _calc_period_matches(claim, claim_map)
439
+ if not ok:
440
+ local.append(msg)
441
+
442
+ elif ctype == "negative":
443
+ as_of = str(claim.get("as_of") or "").strip()
444
+ coverage = str(claim.get("coverage") or "").strip()
445
+ wording = str(claim.get("wording") or "").strip()
446
+ if not as_of:
447
+ local.append("negative 缺少 as_of")
448
+ if not coverage:
449
+ local.append("negative 缺少 coverage")
450
+ if not wording:
451
+ local.append("negative 缺少 wording")
452
+ elif not re.search(r"截至|本次检索|公开渠道|未检索|未见", wording):
453
+ local.append("negative wording 必须写「截至……/本次检索未见……」")
454
+
455
+ elif ctype == "inference":
456
+ if not str(claim.get("wording") or "").strip():
457
+ local.append("inference 缺少限定 wording")
458
+ if answer and text in answer and not any(q in answer for q in QUALIFIERS):
459
+ local.append("答案里的 inference 结论没有限定词")
460
+
461
+ elif ctype == "interpretation":
462
+ if not str(claim.get("primary") or "").strip() or not str(claim.get("alternative") or "").strip():
463
+ local.append("interpretation 必须同时写 primary 和 alternative")
464
+ if not str(claim.get("selected_reason") or "").strip():
465
+ local.append("interpretation 缺少 selected_reason")
466
+
467
+ item_results.append({"id": cid, "type": ctype, "verdict": "fail" if local else "pass", "issues": local})
468
+ issues.extend(f"{cid}:{x}" for x in local)
469
+
470
+ # 答案层通用措辞:否定结论必须有截止日期和检索覆盖。
471
+ if answer:
472
+ for lineno, line in enumerate(answer.splitlines(), 1):
473
+ if line.strip().startswith(">") or not line.strip():
474
+ continue
475
+ if re.search(r"未上调|未再上调|未发生|不存在|没有出台|未出台|未见调整", line):
476
+ if not (re.search(r"截至\s*\d{4}-\d{2}-\d{2}", line) and re.search(r"公开渠道未见|未检索到|未见", line)):
477
+ issues.append(f"答案第 {lineno} 行:否定结论缺少「截至YYYY-MM-DD,公开渠道未见」")
478
+
479
+ # 句子 -> claim:强断言必须有 answer_anchor 或引用角标。
480
+ anchors_all: List[str] = []
481
+ claim_texts: List[str] = []
482
+ for claim in claims:
483
+ anchors_all.extend(_norm_text(a) for a in _anchors(claim))
484
+ claim_texts.append(_norm_text(str(claim.get("text") or claim.get("claim") or "")))
485
+ for sent in _answer_sentences(answer):
486
+ if not any(term in sent for term in STRONG_TERMS):
487
+ continue
488
+ if re.search(r"\[\d+\]", sent):
489
+ continue
490
+ norm = _norm_text(sent)
491
+ if any(a and a in norm for a in anchors_all):
492
+ continue
493
+ if any(t and t in norm for t in claim_texts if len(t) >= 8):
494
+ continue
495
+ issues.append(f"答案强断言没有 claim 锚点/引用:{sent[:80]}")
496
+
497
+ return {"verdict": "pass" if not issues else "fail", "issues": issues, "items": item_results}
498
+
499
+
500
+ def _renderer_evidence_items(sources: List[Dict[str, Any]], answer: str) -> List[Dict[str, str]]:
501
+ """复刻渲染器 renumber_citations 之后的 (id, url) 集合(trust_digest 口径)。
502
+
503
+ 渲染器:材料 id = 合并产物「编号」;被引编号按答案首现顺序重排为 1..N,
504
+ 未引用材料按原顺序顺延。两侧顺序都来自同一份合并产物,天然对齐。
505
+ """
506
+ cited: List[str] = []
507
+ for m in re.finditer(r"\[(\d+)\]", answer or ""):
508
+ if m.group(1) not in cited:
509
+ cited.append(m.group(1))
510
+ mapping = {old: str(i + 1) for i, old in enumerate(cited)}
511
+ next_id = len(mapping)
512
+ items: List[Dict[str, str]] = []
513
+ for idx, s in enumerate(sources, start=1):
514
+ no = str(s.get("article_no") or "").strip() or str(idx)
515
+ if no in mapping:
516
+ key = mapping[no]
517
+ else:
518
+ next_id += 1
519
+ key = str(next_id)
520
+ items.append({"id": key, "url": s.get("url") or ""})
521
+ return items
522
+
523
+
524
+ def main() -> int:
525
+ parser = argparse.ArgumentParser(description="问题画像 + 材料画像 + claim 通用校验")
526
+ parser.add_argument("--claims", required=True)
527
+ parser.add_argument("--sources", required=True)
528
+ parser.add_argument("--profile", required=True)
529
+ parser.add_argument("--answer", default="")
530
+ parser.add_argument("--out", help="运行目录(会话工作区);与 --output 文件名一起用")
531
+ parser.add_argument("--output", default="tax_verify.json",
532
+ help="输出文件名(配合 --out)或显式输出路径(不得指向 Skill 安装目录)")
533
+ args = parser.parse_args()
534
+
535
+ def _load_in(value: str) -> Any:
536
+ return json.loads(
537
+ run_dir.resolve_run_input(value, args.out).read_text(encoding="utf-8")
538
+ )
539
+
540
+ try:
541
+ claims = _items(_load_in(args.claims))
542
+ sources = _items(_load_in(args.sources))
543
+ profile = _load_in(args.profile)
544
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
545
+ print(f"输入不可读:{exc}", file=sys.stderr)
546
+ return 1
547
+ try:
548
+ answer = (
549
+ run_dir.resolve_run_input(args.answer, args.out).read_text(encoding="utf-8")
550
+ if args.answer else ""
551
+ )
552
+ except (OSError, ValueError) as exc:
553
+ print(f"答案不可读:{exc}", file=sys.stderr)
554
+ return 1
555
+ result = verify(claims, sources, profile, answer)
556
+ # 摘要绑定(上游 trust_digest 口径,1.0.2 内核继承):渲染端按同一算法复算,
557
+ # 不一致即“核验记录已失效”。证据侧复刻渲染器 renumber 后的 (id, url)——
558
+ # 渲染器把被引材料按角标首现重排为 1..N、未引用顺延编号,这里必须同构,
559
+ # 否则会“永远 stale”。
560
+ result["record"] = {
561
+ # dsh:与 legal 版口径对齐——指纹前 strip 尾部空白;内核渲染侧 extract_answer
562
+ # 会去掉答案尾换行,不去 strip 会因一个尾换行恒判「核验后答案被修改」。
563
+ "answer_digest": trust_digest.answer_digest(answer.strip()) if answer else "",
564
+ "evidence_digest": trust_digest.evidence_digest(
565
+ _renderer_evidence_items(sources, answer)
566
+ ),
567
+ "verdict": result["verdict"],
568
+ }
569
+ # 顶层摘要保留(旧消费者/排查用),权威字段是 record.*
570
+ result["answer_digest"] = result["record"]["answer_digest"]
571
+ result["evidence_digest"] = result["record"]["evidence_digest"]
572
+ result["profile_digest"] = trust_digest.answer_digest(
573
+ json.dumps(profile, ensure_ascii=False, sort_keys=True)
574
+ )
575
+
576
+ try:
577
+ out = run_dir.resolve_write_target(args.output, args.out)
578
+ except ValueError as exc:
579
+ parser.error(str(exc))
580
+ out.parent.mkdir(parents=True, exist_ok=True)
581
+ out.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
582
+ print(json.dumps(result, ensure_ascii=False, indent=2))
583
+ return 0 if result["verdict"] == "pass" else 1
584
+
585
+
586
+ if __name__ == "__main__":
587
+ raise SystemExit(main())