"""格式校验器(方案 §13 第1步):技能条目与 curator 编辑操作的机械校验。 校验的是"可执行性与可归因性",不是内容好坏: · plan 的工具名/参数必须在 tool_schema 内且取值合法 · 数值不得埋在自然语言字段(trigger/note 里出现 k=8、±10s 这类 → 拒) · trigger 不得是无区分度写法("任何问题"/"always") · target_buckets 必须是合法桶 · plan 步骤数 ≤ MAX_PLAN_STEPS,代价 ≤ 预算 · stop_condition / anti_pattern 必须是机器可判定结构 · plan 与 stop_condition.max_tool_calls 不得自相矛盾(旧版 stop-loss 与 global-then-local 冲突) """ import re from typing import Any, Dict, List, Tuple from .tool_schema import TOOL_SCHEMA, MAX_PLAN_STEPS, DEFAULT_BUDGET, plan_cost from .skill_schema import VALID_BUCKETS, FAILURE_MODES # 自然语言字段里出现数值参数 = 参数埋藏(curator 无法按条修改) _NUM_IN_TEXT = re.compile(r"(k\s*=\s*\d+|top-?\d+|±\s*\d+\s*s|\b\d+\s*(?:s|sec|秒|frames?|帧)\b" r"|\b\d+\s*次\b|max\s*\d+)", re.I) _VAGUE_TRIGGER = re.compile(r"(any question|always applicable|任何问题|始终适用|all questions)", re.I) # 运行时才能定值的参数(技能里允许缺省或写占位符) RUNTIME_PARAMS = {"query", "object", "t_start", "t_end", "t_min", "t_max"} _PLACEHOLDER = re.compile(r"^\$(now|hit\.t|anchor\.t_start|anchor\.t_end)([+-]\d+(\.\d+)?)?$") def validate_skill(sk: Dict[str, Any], budget: int = DEFAULT_BUDGET) -> Tuple[bool, List[str]]: errs: List[str] = [] # 必填字段 for f in ("skill_id", "trigger", "target_buckets", "plan", "params", "stop_condition", "anti_pattern", "stats"): if f not in sk: errs.append(f"缺字段 {f}") if errs: return False, errs # trigger 区分度 if _VAGUE_TRIGGER.search(sk["trigger"]): errs.append("trigger 无区分度(禁'任何问题/始终适用'——全局预算属系统配置,不是技能)") if len(sk["trigger"].strip()) < 12: errs.append("trigger 过短,无法判定适用性") # 参数埋藏检查(trigger + 各步 note) for field, text in [("trigger", sk["trigger"])] + \ [(f"plan[{i}].note", s.get("note", "")) for i, s in enumerate(sk["plan"])]: m = _NUM_IN_TEXT.search(str(text)) if m: errs.append(f"{field} 中埋了数值参数 '{m.group(0)}' —— 必须移到 params") # 桶合法性 if not sk["target_buckets"]: errs.append("target_buckets 为空(注入靠桶精确匹配,空则永不命中)") for b in sk["target_buckets"]: if b not in VALID_BUCKETS: errs.append(f"非法桶 {b}") # plan 结构 if not isinstance(sk["plan"], list) or not sk["plan"]: errs.append("plan 必须是非空步骤列表") elif len(sk["plan"]) > MAX_PLAN_STEPS: errs.append(f"plan 步骤 {len(sk['plan'])} > 上限 {MAX_PLAN_STEPS}") else: for i, st in enumerate(sk["plan"]): tool = st.get("tool") if tool not in TOOL_SCHEMA: errs.append(f"plan[{i}] 未知工具 {tool}") continue spec = TOOL_SCHEMA[tool]["params"] for p, v in (st.get("params") or {}).items(): if p not in spec: errs.append(f"plan[{i}] {tool} 无参数 {p}") continue d = spec[p] if isinstance(v, str) and v.startswith("$"): continue # 占位符,运行时解析 if "range" in d: try: if not (d["range"][0] <= float(v) <= d["range"][1]): errs.append(f"plan[{i}] {tool}.{p}={v} 越界 {d['range']}") except (TypeError, ValueError): errs.append(f"plan[{i}] {tool}.{p}={v} 非数值") if "choices" in d and v not in d["choices"]: errs.append(f"plan[{i}] {tool}.{p}={v} 不在 {d['choices']}") # 运行时参数:query 由问题/选项生成;时间参数可用占位符引用前序步骤命中 # 支持 "$hit.t-10" / "$hit.t+10" / "$anchor.t_start" / "$now" 等 for p, d in spec.items(): if not d.get("required") or p in RUNTIME_PARAMS: continue if p not in (st.get("params") or {}): errs.append(f"plan[{i}] {tool} 缺必填参数 {p}") for p, v_ in (st.get("params") or {}).items(): if isinstance(v_, str) and v_.startswith("$") and not _PLACEHOLDER.match(v_): errs.append(f"plan[{i}] {tool}.{p} 占位符 '{v_}' 非法" f"(合法: $now / $hit.t±N / $anchor.t_start±N / $anchor.t_end±N)") # stop_condition 可判定性 + 与 plan 的一致性 sc = sk.get("stop_condition") or {} if "max_tool_calls" not in sc: errs.append("stop_condition 缺 max_tool_calls(必须可机械判定)") elif isinstance(sk.get("plan"), list) and len(sk["plan"]) > int(sc["max_tool_calls"]): errs.append(f"自相矛盾: plan {len(sk['plan'])} 步 > max_tool_calls {sc['max_tool_calls']}") # anti_pattern 可判定性 ap = sk.get("anti_pattern") or {} if "forbidden_sequence" not in ap: errs.append("anti_pattern 必须含 forbidden_sequence(列表形式,可机械判定)") else: for seq in ap["forbidden_sequence"]: if not isinstance(seq, list) or any(t not in TOOL_SCHEMA for t in seq): errs.append(f"anti_pattern 序列 {seq} 含未知工具或非列表") # 预算 if isinstance(sk.get("plan"), list): c = plan_cost(sk["plan"]) if c > budget: errs.append(f"plan 代价 {c} > 预算 {budget}") return not errs, errs def validate_edit(op: Dict[str, Any], lib: Dict[str, Any]) -> Tuple[bool, List[str]]: """校验 curator 的编辑操作(方案 §6.2 的四种顶层算子)。""" errs = [] t = op.get("op") if t not in ("add", "modify", "delete", "merge"): return False, [f"未知算子 {t}"] if not op.get("failure_mode") or op["failure_mode"] not in FAILURE_MODES: errs.append(f"failure_mode 必须来自枚举,收到 {op.get('failure_mode')}") if op.get("failure_mode") in ("bucket_misclassified", "low_adherence") and t in ("add", "delete"): errs.append(f"{op['failure_mode']} 的修复对象不是技能内容,不应 {t}") if not op.get("evidence_rollouts"): errs.append("缺 evidence_rollouts(必须指明依据哪些 rollout 对照)") ids = {s["skill_id"] for s in lib.get("skills", [])} if t == "add": ok, e = validate_skill(op.get("skill") or {}) errs += [f"新技能: {x}" for x in e] elif t == "modify": if op.get("skill_id") not in ids: errs.append(f"目标技能不存在 {op.get('skill_id')}") if not op.get("changes"): errs.append("modify 缺 changes") elif t == "delete": if op.get("skill_id") not in ids: errs.append(f"目标技能不存在 {op.get('skill_id')}") elif t == "merge": if len(op.get("skill_ids") or []) < 2 or not set(op["skill_ids"]) <= ids: errs.append("merge 需 ≥2 个存在的 skill_id") ok, e = validate_skill(op.get("skill") or {}) errs += [f"合并结果: {x}" for x in e] return not errs, errs