#!/usr/bin/env python3 """Offline MCP result scaffolding and structural validation; the agent performs review.""" import argparse import copy import json import math import re import sys from pathlib import Path CLEARANCE_ARRAYS = {"ys_clearance_data", "yf_clearance_data"} LEAF_KEYS = {"value", "result", "suggested_value", "reason", "reason_brief"} PAYLOAD_KEYS = {"goods_id", "claim_ref", "source_ref", "result", "summary", "summary_brief", "fields"} OVERALL_RESULTS = {"pass", "hold", "manual", "reject"} FIELD_RESULTS = {"pass", "reject", "hold", "not_checked"} # 与 fmsoperate GoodsAiPreAuditResult::HINT_FIELDS / HINT_ROW_FIELDS 一致:由审核字段计算的只读系统提示。 # 只能判 pass/not_checked;提示上看出的问题记到对应审核字段(见 references/mcp-mode.md)。 HINT_FIELDS = {"recommended_grade", "recommended_keyword", "sync_orders"} HINT_ROW_FIELDS = {"tax_rate", "extra_tax", "is_new_hscode", "kit_tax_rate", "is_new_kit", "adjust_rate_data", "adjust_tax_rate", "total_tax_rate", "tax_tag", "box_value"} # 与 fmsoperate GoodsAiPreAuditResult 及 Gateway Schema 一致:按字符计,单行非空。 REASON_BRIEF_MAX = 20 SUMMARY_BRIEF_MAX = 40 ABSENT = object() PENDING = "尚未执行本字段适用规则及语义/图片/证据核查;不得据此判为通过。" PENDING_BRIEF = "尚未核查" DRAFT_SUMMARY = ("草稿:尚未完成适用的 61 项规则及语义/图片核查。页面未提供的证据须明确待核实," "不代表客户未上传;结构校验不能证明审核完成。") DRAFT_SUMMARY_BRIEF = "草稿:尚未完成规则核查" class ContractError(ValueError): """A local payload/snapshot invariant failed; PHP owns the business schema.""" def _require(condition, message): if not condition: raise ContractError(message) def _is_brief(text, limit): """One non-blank line within the character limit; the full text stays in reason/summary.""" return type(text) is str and bool(text.strip()) and "\n" not in text and "\r" not in text and len(text) <= limit def _json_value(value): if value is None or type(value) in (str, bool, int): return if type(value) is float: _require(math.isfinite(value), "JSON 不允许 NaN/Infinity") elif type(value) is list: for item in value: _json_value(item) elif type(value) is dict: for key, item in value.items(): _require(type(key) is str, "JSON 对象键必须是字符串") _json_value(item) else: raise ContractError("只接受 JSON 值") def loads(text): """Reject duplicate keys and non-finite numbers rather than silently losing data.""" def pairs(items): result = {} for key, value in items: _require(key not in result, "JSON 含重复字段") result[key] = value return result try: value = json.loads(text, object_pairs_hook=pairs) except (ValueError, RecursionError) as exc: raise ContractError("JSON 无效或含重复字段") from exc _json_value(value) return value def _source(query): _json_value(query) _require(type(query) is dict, "读取结果必须是 JSON 对象") if "code" in query: _require(type(query["code"]) is int and query["code"] == 0, "读取 MCP 未成功") query = query.get("data") _require(type(query) is dict, "读取结果 data 必须是对象") _require(type(query.get("goods_id")) is int and query["goods_id"] > 0, "goods_id 必须是正整数") for key in ("claim_ref", "source_ref"): value = query.get(key) _require(type(value) is str and re.fullmatch(r"[0-9a-fA-F]{64}", value), key + " 必须是本次服务器返回的不透明 64hex") _require(type(query.get("context")) is dict, "context 必须是对象") labels = query["context"].get("selected_labels", {}) _require(type(labels) is dict and all( type(v) is str or (type(v) is list and all(type(x) is str for x in v)) for v in labels.values()), "selected_labels 只接受当前选中标签字符串或字符串数组") _require(type(query.get("page_values")) is dict, "page_values 必须是对象") return query def _keys(expected, actual, path): _require(type(actual) is dict, path + " 必须是对象") missing, extra = set(expected) - set(actual), set(actual) - set(expected) _require(not missing and not extra, path + " 字段集合不一致;缺少=" + ",".join(sorted(missing)) + "; 多出=" + ",".join(sorted(extra))) def _path(parent, key): return parent + "/" + str(key).replace("~", "~0").replace("/", "~1") def _tree(value, visit, actual=ABSENT, name=None, path="/fields"): """Traverse objects; ordinary arrays are leaves, clearance arrays contain row fields.""" if name in CLEARANCE_ARRAYS: _require(type(value) is list, path + " 必须是清关行数组") if actual is not ABSENT: _require(type(actual) is list and len(actual) == len(value), path + " 清关行数不一致") rows = [] for index, row in enumerate(value): row_path = _path(path, index) _require(type(row) is dict, row_path + " 必须是清关行对象") current = ABSENT if actual is ABSENT else actual[index] if current is not ABSENT: _keys(row, current, row_path) rows.append({key: visit(raw, ABSENT if current is ABSENT else current[key], _path(row_path, key)) for key, raw in row.items()}) return rows if type(value) is dict and (value or name is None): if actual is not ABSENT: _keys(value, actual, path) return {key: _tree(raw, visit, ABSENT if actual is ABSENT else actual[key], key, _path(path, key)) for key, raw in value.items()} return visit(value, actual, path) def _gate(source, *, stop_rule=None, stop_reason=None): _require(stop_rule is None or (stop_rule == "P2" and type(stop_reason) is str and stop_reason.strip()), "手动早停只支持 P2,必须填写代理实际识别手表的证据原因") # Reuse the Excel engine's P1/P2 decisions and the current workbook's watch words. from audit import Kit, pick_workbook, precheck code = source["context"].get("country_code") country = code.strip().upper() if type(code) is str else "" if country != "US": return precheck(country, "", "", ()) page = source["page_values"] cn = page.get("cn_name") if type(page.get("cn_name")) is str else "" en = page.get("en_name") if type(page.get("en_name")) is str else "" category = source["context"].get("selected_labels", {}).get("goods_category_id", "") if type(category) is list: category = " ".join(category) workbook = pick_workbook() _require(workbook is not None, "找不到当前规则工具包,不能核对 P2") kit = Kit(workbook) try: gate = precheck("美国", cn + " " + category, en, kit.watch_words()) if gate is None and stop_rule == "P2": gate = ("P2", "前置·手表品类排除", stop_reason) return gate finally: kit.wb.close() def prepare(query, *, stop_rule=None, stop_reason=None): """Create a full unreviewed payload. Only shared P1/P2 gates produce manual.""" source = _source(query) gate = _gate(source, stop_rule=stop_rule, stop_reason=stop_reason) reason = PENDING if gate is None else gate[0] + ":" + gate[2] + ";后续检查未执行,不给建议。" reason_brief = PENDING_BRIEF if gate is None else gate[0] + "早停,本项未执行" summary_brief = DRAFT_SUMMARY_BRIEF if gate is None else gate[0] + " " + gate[1] + ",转人工" def leaf(raw, _actual, _path): return {"value": copy.deepcopy(raw), "result": "not_checked", "suggested_value": None, "reason": reason, "reason_brief": reason_brief} return {"goods_id": source["goods_id"], "claim_ref": source["claim_ref"], "source_ref": source["source_ref"], "result": "hold" if gate is None else "manual", "summary": DRAFT_SUMMARY if gate is None else reason, "summary_brief": summary_brief, "fields": _tree(source["page_values"], leaf)} def _same_json(left, right): if type(left) is not type(right): return False if type(left) is dict: return set(left) == set(right) and all(_same_json(left[k], right[k]) for k in left) if type(left) is list: return len(left) == len(right) and all(_same_json(a, b) for a, b in zip(left, right)) return left == right def _is_hint(path): """`/fields/recommended_grade` or `/fields/ys_clearance_data/0/tax_rate` style pointers.""" parts = path.split("/")[2:] if len(parts) == 3 and parts[0] in CLEARANCE_ARRAYS: return parts[2] in HINT_ROW_FIELDS return len(parts) == 1 and parts[0] in HINT_FIELDS def validate(query, payload, *, stop_rule=None, stop_reason=None): """Check local structure/originals/gates, never attest review or legal suggestions.""" source = _source(query) _json_value(payload) _keys(PAYLOAD_KEYS, payload, "保存请求") for key in ("goods_id", "claim_ref", "source_ref"): _require(_same_json(source[key], payload[key]), key + " 与本次读取不一致") _require(type(payload["result"]) is str and payload["result"] in OVERALL_RESULTS, "整体 result 非法") _require(type(payload["summary"]) is str and payload["summary"].strip(), "summary 必须说明完整结论/问题/缺证据原因") _require(_is_brief(payload["summary_brief"], SUMMARY_BRIEF_MAX), "summary_brief 必须是不超过 %d 字的单行整体汇总" % SUMMARY_BRIEF_MAX) _require(payload["summary_brief"] != DRAFT_SUMMARY_BRIEF and payload["summary"] != DRAFT_SUMMARY, "summary/summary_brief 仍是 prepare 草稿占位,完成核查后改写为实际结论再保存") gate = _gate(source, stop_rule=stop_rule, stop_reason=stop_reason) if gate: _require(payload["result"] == "manual", gate[0] + " 必须转人工") results, reviewed = [], [] def leaf(raw, actual, path): _keys(LEAF_KEYS, actual, path) _require(_same_json(raw, actual["value"]), path + "/value 与本次页面原值/类型/顺序不一致") _require(type(actual["result"]) is str and actual["result"] in FIELD_RESULTS, path + "/result 非法") _require(type(actual["reason"]) is str and actual["reason"].strip(), path + "/reason 必须说明依据或未执行原因") _require(_is_brief(actual["reason_brief"], REASON_BRIEF_MAX), path + "/reason_brief 必须是不超过 %d 字的单行依据汇总" % REASON_BRIEF_MAX) _require(actual["reason"] != PENDING and actual["reason_brief"] != PENDING_BRIEF, path + " 仍是 prepare 草稿占位“" + PENDING_BRIEF + "”;写明实际结论,或按规则不适用/早停说明未检查原因") if gate: _require(actual["result"] == "not_checked" and actual["suggested_value"] is None, path + ":" + gate[0] + " 早停后必须 not_checked 且无建议") if _is_hint(path): _require(actual["result"] in ("pass", "not_checked"), path + " 是系统提示,只能 pass/not_checked;问题记到对应审核字段") else: reviewed.append(actual["result"]) results.append(actual["result"]) _tree(source["page_values"], leaf, payload["fields"]) if reviewed and all(result == "not_checked" for result in reviewed): _require(payload["result"] == "manual", "客户资料和审核字段全部 not_checked 时整体只能 manual") if payload["result"] == "pass": _require("pass" in results and not ({"hold", "reject"} & set(results)), "未复核草稿或仍含 hold/reject 字段不能整体 pass;只读提示可保留 not_checked") def evidence(query, pointer, scope="page_values"): """Inspect supplied page/context evidence without fetching files or inventing field results.""" source = _source(query) _require(type(pointer) is str and (pointer == "" or pointer.startswith("/")), "证据路径必须是 JSON Pointer") _require(type(scope) is str and scope in ("page_values", "context"), "证据范围只接受 page_values 或 context") current = source[scope] for token in pointer.split("/")[1:] if pointer else []: _require(re.search(r"~(?![01])", token) is None, "JSON Pointer 转义无效") token = token.replace("~1", "/").replace("~0", "~") if type(current) is dict: current = current.get(token, ABSENT) elif type(current) is list: _require(re.fullmatch(r"0|[1-9][0-9]*", token), "JSON Pointer 数组下标无效") index = int(token) current = current[index] if index < len(current) else ABSENT else: current = ABSENT if current is ABSENT: return {"status": "not_supplied"} empty = current is None or (type(current) in (str, list, dict) and not current) return {"status": "empty" if empty else "supplied", "value": copy.deepcopy(current)} def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) prep = commands.add_parser("prepare", help="生成完整未复核草稿;P1/P2 自动早停") prep.add_argument("query", type=Path) prep.add_argument("--out", type=Path) prep.add_argument("--stop-rule", choices=["P2"]) prep.add_argument("--stop-reason") check = commands.add_parser("validate", help="本地结构校验,不代表完成审核或 PHP 合法值校验") check.add_argument("query", type=Path) check.add_argument("result", type=Path) check.add_argument("--stop-rule", choices=["P2"]) check.add_argument("--stop-reason") inspect = commands.add_parser("evidence", help="区分未提供、已知为空及实际已提供的页面/上下文证据") inspect.add_argument("query", type=Path) inspect.add_argument("--scope", choices=("page_values", "context"), default="page_values") inspect.add_argument("pointers", nargs="+") args = parser.parse_args(argv) try: query = loads(args.query.read_text(encoding="utf-8-sig")) if args.command == "validate": validate(query, loads(args.result.read_text(encoding="utf-8-sig")), stop_rule=args.stop_rule, stop_reason=args.stop_reason) print("本地结构校验通过;仍需代理完成适用规则/语义/图片核查,PHP 校验原值与合法建议。") return 0 if args.command == "prepare": result = prepare(query, stop_rule=args.stop_rule, stop_reason=args.stop_reason) else: result = {pointer: evidence(query, pointer, scope=args.scope) for pointer in args.pointers} text = json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False) + "\n" if args.command == "prepare" and args.out: _require(args.out.resolve() != args.query.resolve(), "输出不能覆盖本次页面原始快照") args.out.write_text(text, encoding="utf-8") else: print(text, end="") return 0 except (ContractError, OSError, UnicodeError) as exc: print("[错误] " + str(exc), file=sys.stderr) return 2 if __name__ == "__main__": sys.exit(main())