mcp_audit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/env python3
  2. """Offline MCP result scaffolding and structural validation; the agent performs review."""
  3. import argparse
  4. import copy
  5. import json
  6. import math
  7. import re
  8. import sys
  9. from pathlib import Path
  10. CLEARANCE_ARRAYS = {"ys_clearance_data", "yf_clearance_data"}
  11. LEAF_KEYS = {"value", "result", "suggested_value", "reason", "reason_brief"}
  12. PAYLOAD_KEYS = {"goods_id", "claim_ref", "source_ref", "result", "summary", "summary_brief", "fields"}
  13. OVERALL_RESULTS = {"pass", "hold", "manual", "reject"}
  14. FIELD_RESULTS = {"pass", "reject", "hold", "not_checked"}
  15. # 与 fmsoperate GoodsAiPreAuditResult::HINT_FIELDS / HINT_ROW_FIELDS 一致:由审核字段计算的只读系统提示。
  16. # 只能判 pass/not_checked;提示上看出的问题记到对应审核字段(见 references/mcp-mode.md)。
  17. HINT_FIELDS = {"recommended_grade", "recommended_keyword", "sync_orders"}
  18. HINT_ROW_FIELDS = {"tax_rate", "extra_tax", "is_new_hscode", "kit_tax_rate", "is_new_kit",
  19. "adjust_rate_data", "adjust_tax_rate", "total_tax_rate", "tax_tag", "box_value"}
  20. # 与 fmsoperate GoodsAiPreAuditResult 及 Gateway Schema 一致:按字符计,单行非空。
  21. REASON_BRIEF_MAX = 20
  22. SUMMARY_BRIEF_MAX = 40
  23. ABSENT = object()
  24. PENDING = "尚未执行本字段适用规则及语义/图片/证据核查;不得据此判为通过。"
  25. PENDING_BRIEF = "尚未核查"
  26. DRAFT_SUMMARY = ("草稿:尚未完成适用的 61 项规则及语义/图片核查。页面未提供的证据须明确待核实,"
  27. "不代表客户未上传;结构校验不能证明审核完成。")
  28. DRAFT_SUMMARY_BRIEF = "草稿:尚未完成规则核查"
  29. class ContractError(ValueError):
  30. """A local payload/snapshot invariant failed; PHP owns the business schema."""
  31. def _require(condition, message):
  32. if not condition:
  33. raise ContractError(message)
  34. def _is_brief(text, limit):
  35. """One non-blank line within the character limit; the full text stays in reason/summary."""
  36. return type(text) is str and bool(text.strip()) and "\n" not in text and "\r" not in text and len(text) <= limit
  37. def _json_value(value):
  38. if value is None or type(value) in (str, bool, int):
  39. return
  40. if type(value) is float:
  41. _require(math.isfinite(value), "JSON 不允许 NaN/Infinity")
  42. elif type(value) is list:
  43. for item in value:
  44. _json_value(item)
  45. elif type(value) is dict:
  46. for key, item in value.items():
  47. _require(type(key) is str, "JSON 对象键必须是字符串")
  48. _json_value(item)
  49. else:
  50. raise ContractError("只接受 JSON 值")
  51. def loads(text):
  52. """Reject duplicate keys and non-finite numbers rather than silently losing data."""
  53. def pairs(items):
  54. result = {}
  55. for key, value in items:
  56. _require(key not in result, "JSON 含重复字段")
  57. result[key] = value
  58. return result
  59. try:
  60. value = json.loads(text, object_pairs_hook=pairs)
  61. except (ValueError, RecursionError) as exc:
  62. raise ContractError("JSON 无效或含重复字段") from exc
  63. _json_value(value)
  64. return value
  65. def _source(query):
  66. _json_value(query)
  67. _require(type(query) is dict, "读取结果必须是 JSON 对象")
  68. if "code" in query:
  69. _require(type(query["code"]) is int and query["code"] == 0, "读取 MCP 未成功")
  70. query = query.get("data")
  71. _require(type(query) is dict, "读取结果 data 必须是对象")
  72. _require(type(query.get("goods_id")) is int and query["goods_id"] > 0, "goods_id 必须是正整数")
  73. for key in ("claim_ref", "source_ref"):
  74. value = query.get(key)
  75. _require(type(value) is str and re.fullmatch(r"[0-9a-fA-F]{64}", value),
  76. key + " 必须是本次服务器返回的不透明 64hex")
  77. _require(type(query.get("context")) is dict, "context 必须是对象")
  78. labels = query["context"].get("selected_labels", {})
  79. _require(type(labels) is dict and all(
  80. type(v) is str or (type(v) is list and all(type(x) is str for x in v))
  81. for v in labels.values()), "selected_labels 只接受当前选中标签字符串或字符串数组")
  82. _require(type(query.get("page_values")) is dict, "page_values 必须是对象")
  83. return query
  84. def _keys(expected, actual, path):
  85. _require(type(actual) is dict, path + " 必须是对象")
  86. missing, extra = set(expected) - set(actual), set(actual) - set(expected)
  87. _require(not missing and not extra,
  88. path + " 字段集合不一致;缺少=" + ",".join(sorted(missing)) + "; 多出=" + ",".join(sorted(extra)))
  89. def _path(parent, key):
  90. return parent + "/" + str(key).replace("~", "~0").replace("/", "~1")
  91. def _tree(value, visit, actual=ABSENT, name=None, path="/fields"):
  92. """Traverse objects; ordinary arrays are leaves, clearance arrays contain row fields."""
  93. if name in CLEARANCE_ARRAYS:
  94. _require(type(value) is list, path + " 必须是清关行数组")
  95. if actual is not ABSENT:
  96. _require(type(actual) is list and len(actual) == len(value), path + " 清关行数不一致")
  97. rows = []
  98. for index, row in enumerate(value):
  99. row_path = _path(path, index)
  100. _require(type(row) is dict, row_path + " 必须是清关行对象")
  101. current = ABSENT if actual is ABSENT else actual[index]
  102. if current is not ABSENT:
  103. _keys(row, current, row_path)
  104. rows.append({key: visit(raw, ABSENT if current is ABSENT else current[key], _path(row_path, key))
  105. for key, raw in row.items()})
  106. return rows
  107. if type(value) is dict and (value or name is None):
  108. if actual is not ABSENT:
  109. _keys(value, actual, path)
  110. return {key: _tree(raw, visit, ABSENT if actual is ABSENT else actual[key], key, _path(path, key))
  111. for key, raw in value.items()}
  112. return visit(value, actual, path)
  113. def _gate(source, *, stop_rule=None, stop_reason=None):
  114. _require(stop_rule is None or (stop_rule == "P2" and type(stop_reason) is str and stop_reason.strip()),
  115. "手动早停只支持 P2,必须填写代理实际识别手表的证据原因")
  116. # Reuse the Excel engine's P1/P2 decisions and the current workbook's watch words.
  117. from audit import Kit, pick_workbook, precheck
  118. code = source["context"].get("country_code")
  119. country = code.strip().upper() if type(code) is str else ""
  120. if country != "US":
  121. return precheck(country, "", "", ())
  122. page = source["page_values"]
  123. cn = page.get("cn_name") if type(page.get("cn_name")) is str else ""
  124. en = page.get("en_name") if type(page.get("en_name")) is str else ""
  125. category = source["context"].get("selected_labels", {}).get("goods_category_id", "")
  126. if type(category) is list:
  127. category = " ".join(category)
  128. workbook = pick_workbook()
  129. _require(workbook is not None, "找不到当前规则工具包,不能核对 P2")
  130. kit = Kit(workbook)
  131. try:
  132. gate = precheck("美国", cn + " " + category, en, kit.watch_words())
  133. if gate is None and stop_rule == "P2":
  134. gate = ("P2", "前置·手表品类排除", stop_reason)
  135. return gate
  136. finally:
  137. kit.wb.close()
  138. def prepare(query, *, stop_rule=None, stop_reason=None):
  139. """Create a full unreviewed payload. Only shared P1/P2 gates produce manual."""
  140. source = _source(query)
  141. gate = _gate(source, stop_rule=stop_rule, stop_reason=stop_reason)
  142. reason = PENDING if gate is None else gate[0] + ":" + gate[2] + ";后续检查未执行,不给建议。"
  143. reason_brief = PENDING_BRIEF if gate is None else gate[0] + "早停,本项未执行"
  144. summary_brief = DRAFT_SUMMARY_BRIEF if gate is None else gate[0] + " " + gate[1] + ",转人工"
  145. def leaf(raw, _actual, _path):
  146. return {"value": copy.deepcopy(raw), "result": "not_checked", "suggested_value": None,
  147. "reason": reason, "reason_brief": reason_brief}
  148. return {"goods_id": source["goods_id"], "claim_ref": source["claim_ref"], "source_ref": source["source_ref"],
  149. "result": "hold" if gate is None else "manual", "summary": DRAFT_SUMMARY if gate is None else reason,
  150. "summary_brief": summary_brief, "fields": _tree(source["page_values"], leaf)}
  151. def _same_json(left, right):
  152. if type(left) is not type(right):
  153. return False
  154. if type(left) is dict:
  155. return set(left) == set(right) and all(_same_json(left[k], right[k]) for k in left)
  156. if type(left) is list:
  157. return len(left) == len(right) and all(_same_json(a, b) for a, b in zip(left, right))
  158. return left == right
  159. def _is_hint(path):
  160. """`/fields/recommended_grade` or `/fields/ys_clearance_data/0/tax_rate` style pointers."""
  161. parts = path.split("/")[2:]
  162. if len(parts) == 3 and parts[0] in CLEARANCE_ARRAYS:
  163. return parts[2] in HINT_ROW_FIELDS
  164. return len(parts) == 1 and parts[0] in HINT_FIELDS
  165. def validate(query, payload, *, stop_rule=None, stop_reason=None):
  166. """Check local structure/originals/gates, never attest review or legal suggestions."""
  167. source = _source(query)
  168. _json_value(payload)
  169. _keys(PAYLOAD_KEYS, payload, "保存请求")
  170. for key in ("goods_id", "claim_ref", "source_ref"):
  171. _require(_same_json(source[key], payload[key]), key + " 与本次读取不一致")
  172. _require(type(payload["result"]) is str and payload["result"] in OVERALL_RESULTS, "整体 result 非法")
  173. _require(type(payload["summary"]) is str and payload["summary"].strip(), "summary 必须说明完整结论/问题/缺证据原因")
  174. _require(_is_brief(payload["summary_brief"], SUMMARY_BRIEF_MAX),
  175. "summary_brief 必须是不超过 %d 字的单行整体汇总" % SUMMARY_BRIEF_MAX)
  176. _require(payload["summary_brief"] != DRAFT_SUMMARY_BRIEF and payload["summary"] != DRAFT_SUMMARY,
  177. "summary/summary_brief 仍是 prepare 草稿占位,完成核查后改写为实际结论再保存")
  178. gate = _gate(source, stop_rule=stop_rule, stop_reason=stop_reason)
  179. if gate:
  180. _require(payload["result"] == "manual", gate[0] + " 必须转人工")
  181. results, reviewed = [], []
  182. def leaf(raw, actual, path):
  183. _keys(LEAF_KEYS, actual, path)
  184. _require(_same_json(raw, actual["value"]), path + "/value 与本次页面原值/类型/顺序不一致")
  185. _require(type(actual["result"]) is str and actual["result"] in FIELD_RESULTS, path + "/result 非法")
  186. _require(type(actual["reason"]) is str and actual["reason"].strip(), path + "/reason 必须说明依据或未执行原因")
  187. _require(_is_brief(actual["reason_brief"], REASON_BRIEF_MAX),
  188. path + "/reason_brief 必须是不超过 %d 字的单行依据汇总" % REASON_BRIEF_MAX)
  189. _require(actual["reason"] != PENDING and actual["reason_brief"] != PENDING_BRIEF,
  190. path + " 仍是 prepare 草稿占位“" + PENDING_BRIEF + "”;写明实际结论,或按规则不适用/早停说明未检查原因")
  191. if gate:
  192. _require(actual["result"] == "not_checked" and actual["suggested_value"] is None,
  193. path + ":" + gate[0] + " 早停后必须 not_checked 且无建议")
  194. if _is_hint(path):
  195. _require(actual["result"] in ("pass", "not_checked"),
  196. path + " 是系统提示,只能 pass/not_checked;问题记到对应审核字段")
  197. else:
  198. reviewed.append(actual["result"])
  199. results.append(actual["result"])
  200. _tree(source["page_values"], leaf, payload["fields"])
  201. if reviewed and all(result == "not_checked" for result in reviewed):
  202. _require(payload["result"] == "manual", "客户资料和审核字段全部 not_checked 时整体只能 manual")
  203. if payload["result"] == "pass":
  204. _require("pass" in results and not ({"hold", "reject"} & set(results)),
  205. "未复核草稿或仍含 hold/reject 字段不能整体 pass;只读提示可保留 not_checked")
  206. def evidence(query, pointer, scope="page_values"):
  207. """Inspect supplied page/context evidence without fetching files or inventing field results."""
  208. source = _source(query)
  209. _require(type(pointer) is str and (pointer == "" or pointer.startswith("/")), "证据路径必须是 JSON Pointer")
  210. _require(type(scope) is str and scope in ("page_values", "context"), "证据范围只接受 page_values 或 context")
  211. current = source[scope]
  212. for token in pointer.split("/")[1:] if pointer else []:
  213. _require(re.search(r"~(?![01])", token) is None, "JSON Pointer 转义无效")
  214. token = token.replace("~1", "/").replace("~0", "~")
  215. if type(current) is dict:
  216. current = current.get(token, ABSENT)
  217. elif type(current) is list:
  218. _require(re.fullmatch(r"0|[1-9][0-9]*", token), "JSON Pointer 数组下标无效")
  219. index = int(token)
  220. current = current[index] if index < len(current) else ABSENT
  221. else:
  222. current = ABSENT
  223. if current is ABSENT:
  224. return {"status": "not_supplied"}
  225. empty = current is None or (type(current) in (str, list, dict) and not current)
  226. return {"status": "empty" if empty else "supplied", "value": copy.deepcopy(current)}
  227. def main(argv=None):
  228. parser = argparse.ArgumentParser(description=__doc__)
  229. commands = parser.add_subparsers(dest="command", required=True)
  230. prep = commands.add_parser("prepare", help="生成完整未复核草稿;P1/P2 自动早停")
  231. prep.add_argument("query", type=Path)
  232. prep.add_argument("--out", type=Path)
  233. prep.add_argument("--stop-rule", choices=["P2"])
  234. prep.add_argument("--stop-reason")
  235. check = commands.add_parser("validate", help="本地结构校验,不代表完成审核或 PHP 合法值校验")
  236. check.add_argument("query", type=Path)
  237. check.add_argument("result", type=Path)
  238. check.add_argument("--stop-rule", choices=["P2"])
  239. check.add_argument("--stop-reason")
  240. inspect = commands.add_parser("evidence", help="区分未提供、已知为空及实际已提供的页面/上下文证据")
  241. inspect.add_argument("query", type=Path)
  242. inspect.add_argument("--scope", choices=("page_values", "context"), default="page_values")
  243. inspect.add_argument("pointers", nargs="+")
  244. args = parser.parse_args(argv)
  245. try:
  246. query = loads(args.query.read_text(encoding="utf-8-sig"))
  247. if args.command == "validate":
  248. validate(query, loads(args.result.read_text(encoding="utf-8-sig")),
  249. stop_rule=args.stop_rule, stop_reason=args.stop_reason)
  250. print("本地结构校验通过;仍需代理完成适用规则/语义/图片核查,PHP 校验原值与合法建议。")
  251. return 0
  252. if args.command == "prepare":
  253. result = prepare(query, stop_rule=args.stop_rule, stop_reason=args.stop_reason)
  254. else:
  255. result = {pointer: evidence(query, pointer, scope=args.scope) for pointer in args.pointers}
  256. text = json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
  257. if args.command == "prepare" and args.out:
  258. _require(args.out.resolve() != args.query.resolve(), "输出不能覆盖本次页面原始快照")
  259. args.out.write_text(text, encoding="utf-8")
  260. else:
  261. print(text, end="")
  262. return 0
  263. except (ContractError, OSError, UnicodeError) as exc:
  264. print("[错误] " + str(exc), file=sys.stderr)
  265. return 2
  266. if __name__ == "__main__":
  267. sys.exit(main())