"""Workflow spec format for synthetic typed decisions (category ``typed_synthetic``). A workflow spec is produced by the ``typed_workflow_design`` teacher job (one per domain seed). It describes the decision *state* as a list of fields with sampling distributions (the case sampler turns it into ~70 concrete cases) and 3-6 typed questions in exactly the LocalLLaMA/typed-decisions question format:: {"key": {"type": "choice"|"score"|"noul", "instructions": str, "criteria": ...}} choice criteria = ordered {option_name: description}; score criteria = list of 3..7 level descriptions (level 0 = lowest); noul criteria = {"false": desc, "true": desc}. Each question also names the state fields it depends on (``uses_fields``, >=2; never shown to the labeler or the model) so we can lint single-field shortcut questions. A field may be ``hidden``: it is sampled (and can drive correlations / snippet banks) but omitted from the state, like the latent ``factors`` of typed-decisions. ``validate_spec`` returns a list of error strings (empty = accepted) and never raises on bad teacher output. ``to_record_question`` converts a spec question to the macjev record form ``{t, ins, crit}``. """ from __future__ import annotations import json import math import re from typing import Any SPEC_VERSION = "typed-synth-spec-v1" LANGS = ("zh", "en") FIELD_TYPES = ("categorical", "boolean", "integer", "number", "text", "date", "id", "list") NUM_DISTS = ("uniform", "normal", "lognormal", "choice") MAX_FIELDS = 30 MIN_FIELDS = 4 MIN_QUESTIONS, MAX_QUESTIONS = 3, 6 CHOICE_MIN, CHOICE_MAX, ROUTING_MAX = 3, 12, 40 SCORE_MIN, SCORE_MAX = 3, 7 MAX_SNIPPET_CHARS = 400 CJK = re.compile(r"[㐀-䶿一-鿿]") WORKFLOW_ID = re.compile(r"^[a-z][a-z0-9_]{2,59}$") OPTION_BAD = re.compile(r"[\n\r\t]") # The four LocalLLaMA/typed-decisions benchmark workflows and near-synonyms. Synthetic # workflows must not overlap them (their gold labels come from a ~4B teacher; mixing a # frontier teacher's habits into the same workflows would bias the benchmark comparison). BENCHMARK_WORKFLOWS = ("agent_trace_observability", "customer_service", "invoice_processing", "security_incidents") _EXCLUDE_PATTERNS = [ # agent trace observability r"(agent|llm|model)[\s_-]*(run|trace|traces|execution)[\s_-]*(observab|review|monitor|audit|triage)", r"observability", r"trace[\s_-]*(review|triage|sampling)", r"智能体.{0,4}(轨迹|追踪|运行记录)", r"可观测", # customer service / support conversations and tickets r"customer[\s_-]*(service|support|care|success)", r"support[\s_-]*(ticket|conversation|chat|queue|inbox)", r"help[\s_-]*desk", r"service[\s_-]*desk", r"\bcsat\b", r"contact[\s_-]*cent(er|re)", r"call[\s_-]*cent(er|re)", r"客服", r"客户服务", r"客户支持", r"售后(咨询|工单|对话)", r"工单", r"呼叫中心", # invoice processing / accounts payable r"invoice", r"accounts[\s_-]*payable", r"(three|3)[\s_-]*way[\s_-]*match", r"purchase[\s_-]*order[\s_-]*match", r"vendor[\s_-]*bill", r"发票", r"应付账款", r"对账单?匹配", r"三单匹配", # security incidents r"security[\s_-]*(incident|alert|event|operations)", r"\bsoc\b", r"\bsiem\b", r"intrusion", r"threat[\s_-]*(hunt|detect|intel)", r"incident[\s_-]*response", r"安全(事件|告警|运营)", r"入侵", r"威胁(检测|情报|狩猎)", r"应急响应", # near-synonyms added in review: complaint handling / tech support (customer service), cyber attacks, # malware, phishing, breaches and vulnerability triage (security incidents), agent run monitoring r"customer[\s_-]*complaint", r"complaint[\s_-]*(ticket|handling|triage)", r"客户投诉", r"用户投诉", r"tech(nical)?[\s_-]*support", r"\bit[\s_-]*support", r"技术支持", r"phishing", r"malware", r"ransomware", r"cyber[\s_-]*(attack|security|incident|threat)", r"data[\s_-]*breach", r"vulnerabilit(y|ies)[\s_-]*(triage|report|disclosure|management)", r"钓鱼", r"恶意软件", r"勒索软件", r"网络攻击", r"数据泄露", r"漏洞(处置|分级|管理|响应|上报)", r"智能体.{0,4}(监控|审计)", r"agent[\s_-]*(monitoring|oversight)", ] EXCLUDE_RE = re.compile("|".join(_EXCLUDE_PATTERNS), re.IGNORECASE) # The MacJev runtime gate (builders/mac_gate.py) owns execute / inspect / ask with rule-derived labels; a synthetic # workflow reusing that option set would put teacher-policy labels on the same decision and conflict with it. RESERVED_OPTION_SETS = ({"execute", "inspect", "ask"},) OPTION_COPY_SHARE = 0.75 # Review finding: the literal set above missed the same decision in Chinese (pilot P010 had 直接执行 / 先检查目录 / # 请用户确认 / 拒绝执行 over gate-style state fields). Option names are mapped to the gate concepts in English and # Chinese; a choice question whose options cover execute AND inspect-first AND ask-the-user is the runtime gate # decision whatever the wording. Negated / refusing options ("拒绝执行", "do_not_run") are not "execute". _GATE_REFUSE = re.compile(r"拒绝|不(要|应|得|可|能)?执行|禁止|暂不|(^|_)(refuse|reject|deny|decline|block|abort|cancel|" r"do_not|dont|never)(_|$)", re.IGNORECASE) _GATE_CONCEPTS = ( ("execute", re.compile(r"^(execute|run|proceed|perform|do_it|go_ahead|carry_out)(_|$)|(^|_)execute(_|$)|执行|照做|" r"直接(操作|运行|做|处理)", re.IGNORECASE)), ("inspect", re.compile(r"^(inspect|observe|examine)(_|$)|(inspect|check|look|verify|observe|read|list|view|scan)_" r"(first|before)|先(检查|查看|核查|观察|看|列出|读取|浏览|确认目录)|检查后|查看后", re.IGNORECASE)), ("ask", re.compile(r"^(ask|clarify|consult)(_|$)|ask_(the_)?user|confirm_with_(the_)?user|(request|get|seek)_(user_)?" r"confirmation|^confirm(_first)?$|询问|请?用户确认|向用户确认|问用户|征求|澄清", re.IGNORECASE)), ) GATE_TRIO = frozenset({"execute", "inspect", "ask"}) def gate_concepts(option_names) -> set[str]: """Runtime-gate concepts (execute / inspect / ask / refuse) that a list of option names covers.""" found: set[str] = set() for name in option_names: n = norm_option(name) if _GATE_REFUSE.search(n): found.add("refuse") continue for concept, pat in _GATE_CONCEPTS: if pat.search(n): found.add(concept) break return found def norm_option(name: Any) -> str: return re.sub(r"[\s\-]+", "_", str(name).strip().casefold()) def benchmark_overlap(*texts: str) -> str | None: """Return the matched phrase if any text looks like one of the 4 benchmark workflows.""" for text in texts: m = EXCLUDE_RE.search(str(text or "")) if m: return m.group(0) return None def to_record_question(q: dict) -> dict: """Spec question (typed-decisions format) -> macjev record question {t, ins, crit}.""" t = q["type"] crit = q.get("criteria") if t == "choice": crit = {str(k): (v if v not in ("",) else None) for k, v in crit.items()} elif t == "score": crit = [str(c) for c in crit] elif t == "noul": crit = None if not crit else {"false": crit.get("false"), "true": crit.get("true")} return {"t": t, "ins": q["instructions"], "crit": crit} def question_option_names(q: dict) -> list[str]: t = q["type"] if t == "choice": return [str(k) for k in q["criteria"]] if t == "score": return [str(i) for i in range(len(q["criteria"]))] return ["false", "true"] def public_questions(spec: dict) -> dict: """Questions as shown to labelers (typed-decisions format, no uses_fields).""" return {k: {"type": q["type"], "instructions": q["instructions"], "criteria": q.get("criteria")} for k, q in spec["questions"].items()} def _is_num(x: Any) -> bool: return isinstance(x, (int, float)) and not isinstance(x, bool) def _has_cjk(text: str) -> bool: return bool(CJK.search(text or "")) def _covered(path: str, known: list[str]) -> bool: """A reference may name a field path or any parent object of field paths.""" return any(k == path or k.startswith(path + ".") for k in known) def _snippet_errors(bank: list, where: str, earlier: dict[str, dict], slots: dict) -> list[str]: """``{@path}`` must name an earlier VISIBLE field (a hidden latent pasted into text would leak it); ``{slot}`` must have values.""" errs: list[str] = [] for s in bank: for ref in re.findall(r"\{@([^{}\s]+)\}", str(s)): if ref not in earlier: errs.append(f"{where}: snippet references {{@{ref}}} which is not an earlier field") elif isinstance(earlier[ref], dict) and earlier[ref].get("hidden"): errs.append(f"{where}: snippet references hidden field {{@{ref}}} (would leak the latent factor)") for slot in re.findall(r"\{([A-Za-z_][A-Za-z0-9_]*)\}", str(s)): if slot not in (slots or {}): errs.append(f"{where}: snippet uses slot {{{slot}}} with no values") return errs def _clip_saturation_errors(f: dict, dep: dict, where: str) -> list[str]: """The sampler applies ``depends`` (x * scale + shift) and THEN clips to [min, max]; for ``uniform`` the same min/max are also the base range. A transform that moves the distribution outside the clip bounds silently piles the values on a bound (review finding: uniform 1..12 with shift +18 gave 12 for every case). Reject it: for uniform the whole transformed range, for other dists the transformed centre (mean / median / middle value) must lie in [min, max].""" lo, hi = f.get("min"), f.get("max") lo = lo if _is_num(lo) else None hi = hi if _is_num(hi) else None if lo is None and hi is None: return [] dist = f.get("dist", "uniform") if dist == "uniform" and _is_num(f.get("min")) and _is_num(f.get("max")): base = [f["min"], f["max"]] elif dist == "normal" and _is_num(f.get("mean")): base = [f["mean"]] elif dist == "lognormal" and _is_num(f.get("mean")): base = [math.exp(min(f["mean"], 700))] elif dist == "choice" and isinstance(f.get("values"), list): vals = sorted(v for v in f["values"] if _is_num(v)) base = [vals[len(vals) // 2]] if vals else [] else: return [] # malformed distribution: reported by the checks above shift, scale = dep.get("shift") or {}, dep.get("scale") or {} errs = [] for pv in sorted(set(map(str, shift)) | set(map(str, scale))): moved = [x * float(scale.get(pv, 1.0)) + float(shift.get(pv, 0.0)) for x in base] if any((lo is not None and m < lo - 1e-9) or (hi is not None and m > hi + 1e-9) for m in moved): what = "range" if dist == "uniform" else "centre" errs.append(f"{where}: depends for {pv!r} moves the {dist} {what} to " f"{[round(m, 3) for m in moved]}, outside the clip bounds [{lo}, {hi}] (values would pile up on " "a bound); widen min/max or use a normal/lognormal dist whose clip bounds cover every parent value") return errs def _field_errors(f: dict, where: str, earlier: dict[str, dict], nested: bool = False) -> list[str]: """Field lint that never raises: unexpected shapes become error strings.""" try: return _field_errors_raw(f, where, earlier, nested) except (TypeError, AttributeError, KeyError, ValueError, IndexError) as exc: return [f"{where}: malformed field ({type(exc).__name__}: {exc})"] def _field_errors_raw(f: dict, where: str, earlier: dict[str, dict], nested: bool = False) -> list[str]: errs: list[str] = [] t = f.get("type") if t not in FIELD_TYPES: return [f"{where}: unknown field type {t!r}"] if nested and t == "list": errs.append(f"{where}: lists may not be nested") mp = f.get("missing_prob", 0) if not _is_num(mp) or not 0 <= mp <= 0.5: errs.append(f"{where}: missing_prob must be in [0, 0.5]") def parent_ok(ref: Any, kinds: tuple[str, ...], label: str) -> dict | None: if not isinstance(ref, str) or ref not in earlier: errs.append(f"{where}: {label} refers to {ref!r}, which is not an earlier field") return None if earlier[ref].get("type") not in kinds: errs.append(f"{where}: {label} parent {ref!r} must be one of {kinds}") return None return earlier[ref] def parent_keys(parent: dict) -> set[str]: if parent["type"] == "boolean": return {"true", "false"} return {str(v) for v in parent.get("values", [])} when = f.get("when") if when is not None: if not isinstance(when, dict) or not isinstance(when.get("in"), list) or not when["in"]: errs.append(f"{where}: when must be {{field, in: [values]}}") else: p = parent_ok(when.get("field"), ("categorical", "boolean"), "when") if p is not None and not {str(v).lower() if isinstance(v, bool) else str(v) for v in when["in"]} <= parent_keys(p): errs.append(f"{where}: when.in has values the parent never takes") dep = f.get("depends") if t == "categorical": vals = f.get("values") if not isinstance(vals, list) or not 2 <= len(vals) <= 20 or len({str(v) for v in vals}) != len(vals): errs.append(f"{where}: categorical needs 2..20 distinct values") vals = [] w = f.get("weights") if w is not None and (not isinstance(w, list) or len(w) != len(vals) or not all(_is_num(x) and x >= 0 for x in w) or sum(w) <= 0): errs.append(f"{where}: weights must be non-negative numbers aligned with values") if dep is not None: p = parent_ok(dep.get("field") if isinstance(dep, dict) else None, ("categorical", "boolean"), "depends") table = dep.get("weights") if isinstance(dep, dict) else None if p is not None: if not isinstance(table, dict) or not table: errs.append(f"{where}: categorical depends needs weights per parent value") else: for pv, row in table.items(): if str(pv) not in parent_keys(p): errs.append(f"{where}: depends key {pv!r} is not a parent value") if not isinstance(row, list) or len(row) != len(vals) or not all(_is_num(x) and x >= 0 for x in row) or sum(row) <= 0: errs.append(f"{where}: depends weights for {pv!r} must align with values") elif t == "boolean": p_true = f.get("p_true", 0.5) if not _is_num(p_true) or not 0 <= p_true <= 1: errs.append(f"{where}: p_true must be in [0, 1]") if dep is not None: p = parent_ok(dep.get("field") if isinstance(dep, dict) else None, ("categorical", "boolean"), "depends") table = dep.get("p_true") if isinstance(dep, dict) else None if p is not None: if not isinstance(table, dict) or not table or not all(_is_num(v) and 0 <= v <= 1 for v in table.values()): errs.append(f"{where}: boolean depends needs p_true per parent value in [0, 1]") elif not set(map(str, table)) <= parent_keys(p): errs.append(f"{where}: boolean depends keys must be parent values") elif t in ("integer", "number"): dist = f.get("dist", "uniform") if dist not in NUM_DISTS: errs.append(f"{where}: dist must be one of {NUM_DISTS}") if dist == "uniform" and not (_is_num(f.get("min")) and _is_num(f.get("max")) and f["min"] <= f["max"]): errs.append(f"{where}: uniform needs min <= max") if dist == "normal" and not (_is_num(f.get("mean")) and _is_num(f.get("sd")) and f["sd"] >= 0): errs.append(f"{where}: normal needs mean and sd >= 0") if dist == "lognormal" and not (_is_num(f.get("mean")) and _is_num(f.get("sigma")) and f["sigma"] >= 0): errs.append(f"{where}: lognormal needs mean (of log) and sigma >= 0") if dist == "choice": vals = f.get("values") if not isinstance(vals, list) or len(vals) < 2 or not all(_is_num(v) for v in vals): errs.append(f"{where}: numeric choice needs >= 2 numeric values") for bound in ("min", "max"): if bound in f and f[bound] is not None and not _is_num(f[bound]): errs.append(f"{where}: {bound} must be numeric") if dep is not None: p = parent_ok(dep.get("field") if isinstance(dep, dict) else None, ("categorical", "boolean"), "depends") if p is not None: tables_ok = True for kind in ("shift", "scale"): table = dep.get(kind, {}) if not isinstance(table, dict) or not all(_is_num(v) for v in table.values()): errs.append(f"{where}: depends.{kind} must map parent values to numbers") tables_ok = False elif not set(map(str, table)) <= parent_keys(p): errs.append(f"{where}: depends.{kind} keys must be parent values") if tables_ok: errs.extend(_clip_saturation_errors(f, dep, where)) elif t == "text": bank, bank_by = f.get("bank"), f.get("bank_by") banks: list[list] = [] if bank is None and bank_by is None: errs.append(f"{where}: text needs bank or bank_by") if bank is not None: banks.append(bank) if bank_by is not None: p = parent_ok(bank_by.get("field") if isinstance(bank_by, dict) else None, ("categorical", "boolean"), "bank_by") by = bank_by.get("banks") if isinstance(bank_by, dict) else None if p is not None: if not isinstance(by, dict) or not by: errs.append(f"{where}: bank_by.banks must map parent values to snippet lists") else: if not set(map(str, by)) <= parent_keys(p): errs.append(f"{where}: bank_by keys must be parent values") missing = parent_keys(p) - set(map(str, by)) if missing and not bank_by.get("default") and bank is None: errs.append(f"{where}: bank_by lacks {sorted(missing)[:3]} and has no default/bank") banks.extend(by.values()) if isinstance(bank_by, dict) and bank_by.get("default") is not None: banks.append(bank_by["default"]) for b in banks: if not isinstance(b, list) or len(b) < 2 or not all(isinstance(s, str) and s.strip() for s in b): errs.append(f"{where}: every snippet bank needs >= 2 non-empty strings") elif any(len(s) > MAX_SNIPPET_CHARS for s in b): errs.append(f"{where}: snippets must be <= {MAX_SNIPPET_CHARS} chars") slots = f.get("slots", {}) if slots is None: slots = {} if not isinstance(slots, dict) or not all(isinstance(v, list) and v for v in slots.values()): errs.append(f"{where}: slots must map names to non-empty value lists") slots = slots if isinstance(slots, dict) else {} for b in banks: if isinstance(b, list): errs.extend(_snippet_errors(b, where, earlier, slots)) elif t == "date": off = f.get("offset_days") if not (isinstance(off, list) and len(off) == 2 and all(isinstance(x, int) for x in off) and off[0] <= off[1]): errs.append(f"{where}: date needs offset_days [lo, hi] (integers)") if dep is not None: p = parent_ok(dep.get("field") if isinstance(dep, dict) else None, ("categorical", "boolean"), "depends") if p is not None and (not isinstance(dep.get("shift"), dict) or not all(_is_num(v) for v in dep["shift"].values())): errs.append(f"{where}: date depends needs shift (days) per parent value") elif t == "id": pat = f.get("pattern") if not isinstance(pat, str) or not re.search(r"[#@]", pat) or len(pat) > 40: errs.append(f"{where}: id needs a pattern with # (digit) or @ (letter), <= 40 chars") elif t == "list": lo, hi = f.get("min_items", 1), f.get("max_items", 3) if not (isinstance(lo, int) and isinstance(hi, int) and 0 <= lo <= hi <= 8): errs.append(f"{where}: list needs 0 <= min_items <= max_items <= 8") items, bank = f.get("items"), f.get("item_bank") if (items is None) == (bank is None): errs.append(f"{where}: list needs exactly one of items (object fields) or item_bank (strings)") if bank is not None and (not isinstance(bank, list) or len(bank) < max(2, hi) or not all(isinstance(s, str) and s.strip() for s in bank)): errs.append(f"{where}: item_bank needs >= max(2, max_items) non-empty strings") elif bank is not None: slots = f.get("slots") or {} if not isinstance(slots, dict) or not all(isinstance(v, list) and v for v in slots.values()): errs.append(f"{where}: slots must map names to non-empty value lists") slots = {} errs.extend(_snippet_errors(bank, where, earlier, slots)) if items is not None: if not isinstance(items, list) or not items: errs.append(f"{where}: items must be a non-empty list of field specs") else: local: dict[str, dict] = dict(earlier) seen: set[str] = set() for j, sub in enumerate(items): if not isinstance(sub, dict) or not isinstance(sub.get("path"), str) or not sub["path"]: errs.append(f"{where}.items[{j}]: needs a path") continue if sub["path"] in seen: errs.append(f"{where}.items[{j}]: duplicate path") seen.add(sub["path"]) errs.extend(_field_errors(sub, f"{where}.items[{j}]({sub['path']})", local, nested=True)) local[sub["path"]] = sub return errs # Choice option sets of the 4 benchmark workflows (LocalLLaMA/typed-decisions train parquet, checked in review); # an exact copy is a copied benchmark question. Kept literal so validation works without the parquet. BENCHMARK_OPTION_SETS = tuple(frozenset(x) for x in ( ("continue", "human_review", "observe", "stop"), ("failure", "harmful", "partial", "success"), ("answer_directly", "close_no_action", "escalate_to_human", "execute_refund", "request_information"), ("account", "billing", "delivery", "refund", "technical"), ("approve", "hold", "manual_review", "reject"), ("close_benign", "contain", "investigate", "monitor"))) def validate_spec(spec: Any, *, benchmark_instructions: set[str] | None = None) -> list[str]: """All problems with a workflow spec; empty list means the spec is accepted. Never raises.""" try: return _validate_spec(spec, benchmark_instructions) except (TypeError, AttributeError, KeyError, ValueError, IndexError) as exc: return [f"malformed spec ({type(exc).__name__}: {exc})"] def _validate_spec(spec: Any, benchmark_instructions: set[str] | None) -> list[str]: if not isinstance(spec, dict): return ["spec must be a JSON object"] errs: list[str] = [] wid = spec.get("workflow_id") if not isinstance(wid, str) or not WORKFLOW_ID.match(wid): errs.append("workflow_id must be snake_case ascii, 3..60 chars") lang = spec.get("language") if lang not in LANGS: errs.append(f"language must be one of {LANGS}") for key in ("domain", "title", "description"): if not isinstance(spec.get(key), str) or not spec[key].strip(): errs.append(f"{key} must be non-empty text") if isinstance(spec.get("description"), str) and len(spec["description"]) < 20: errs.append("description is too short") hit = benchmark_overlap(spec.get("workflow_id"), spec.get("domain"), spec.get("title"), spec.get("description")) if hit: errs.append(f"overlaps a held-out benchmark workflow ({hit!r})") routing = bool(spec.get("routing", False)) ref_date = spec.get("reference_date") if ref_date is not None and not (isinstance(ref_date, str) and re.match(r"^\d{4}-\d{2}-\d{2}$", ref_date)): errs.append("reference_date must be YYYY-MM-DD") fields = (spec.get("state_schema") or {}).get("fields") if isinstance(spec.get("state_schema"), dict) else None earlier: dict[str, dict] = {} if not isinstance(fields, list) or not MIN_FIELDS <= len(fields) <= MAX_FIELDS: errs.append(f"state_schema.fields must list {MIN_FIELDS}..{MAX_FIELDS} fields") fields = fields if isinstance(fields, list) else [] for i, f in enumerate(fields): if not isinstance(f, dict) or not isinstance(f.get("path"), str) or not re.match(r"^[^.\s][^\s]*$", f["path"]): errs.append(f"fields[{i}]: needs a dotted path without spaces") continue path = f["path"] if path in earlier: errs.append(f"fields[{i}]: duplicate path {path!r}") if any(p.startswith(path + ".") or path.startswith(p + ".") for p in earlier): errs.append(f"fields[{i}]: path {path!r} conflicts with another field (leaf vs object)") errs.extend(_field_errors(f, f"fields[{i}]({path})", earlier)) earlier[path] = f visible = [p for p, f in earlier.items() if not f.get("hidden")] for p, f in earlier.items(): if "hidden" in f and not isinstance(f["hidden"], bool): errs.append(f"field {p!r}: hidden must be a boolean") if fields and len(visible) < 3: errs.append("state needs at least 3 visible (non-hidden) fields") if fields and not any(f.get("type") in ("text", "list") and not f.get("hidden") for f in fields if isinstance(f, dict)): errs.append("state needs at least one visible free-text or list field (text snippets)") qs = spec.get("questions") if not isinstance(qs, dict) or not MIN_QUESTIONS <= len(qs) <= MAX_QUESTIONS: errs.append(f"questions must be an object with {MIN_QUESTIONS}..{MAX_QUESTIONS} entries") qs = qs if isinstance(qs, dict) else {} types = [q.get("type") for q in qs.values() if isinstance(q, dict)] if qs and "choice" not in types: errs.append("at least one choice question is required") if qs and not ({"score", "noul"} & set(types)): errs.append("at least one score or noul question is required") known_paths = [p for p, f in earlier.items() if not f.get("hidden")] cat_values = {p: {str(v) for v in f.get("values", [])} for p, f in earlier.items() if f.get("type") == "categorical" and not f.get("hidden")} for key, q in qs.items(): where = f"questions.{key}" if not isinstance(key, str) or not key.strip() or len(key) > 60: errs.append(f"{where}: bad key") if not isinstance(q, dict): errs.append(f"{where}: must be an object") continue t, ins, crit = q.get("type"), q.get("instructions"), q.get("criteria") if not isinstance(ins, str) or len(ins.strip()) < 8: errs.append(f"{where}: instructions must be a real sentence") ins = "" if lang == "zh" and ins and not _has_cjk(ins): errs.append(f"{where}: zh workflow needs Chinese instructions") if lang == "en" and ins and _has_cjk(ins): errs.append(f"{where}: en workflow must not use Chinese instructions") if benchmark_instructions and ins.strip().lower() in benchmark_instructions: errs.append(f"{where}: instruction copied from the benchmark") if t == "choice": cap = ROUTING_MAX if routing else CHOICE_MAX if not isinstance(crit, dict) or not CHOICE_MIN <= len(crit) <= cap: errs.append(f"{where}: choice needs {CHOICE_MIN}..{cap} options") else: norm = [str(k).strip().casefold() for k in crit] if len(set(norm)) != len(norm): errs.append(f"{where}: option names collide after normalisation") for name, desc in crit.items(): if not name.strip() or name != name.strip() or len(name) > 48 or OPTION_BAD.search(name): errs.append(f"{where}: bad option name {name!r}") if name.strip().isdigit(): errs.append(f"{where}: option name {name!r} is purely numeric (clashes with score levels)") if not isinstance(desc, str) or not desc.strip(): errs.append(f"{where}: option {name!r} needs a description") opts = {norm_option(k) for k in crit} for p, vals in cat_values.items(): nvals = {norm_option(v) for v in vals} shared = opts & nvals if opts <= nvals or (len(shared) >= 2 and len(shared) >= OPTION_COPY_SHARE * len(opts)): errs.append(f"{where}: options are just the values of field {p!r} (label copies a field)") if frozenset(opts) in BENCHMARK_OPTION_SETS: errs.append(f"{where}: option set copies a typed-decisions benchmark question {sorted(opts)}") reserved_hit = any(reserved <= opts for reserved in RESERVED_OPTION_SETS) if reserved_hit or GATE_TRIO <= gate_concepts(crit): errs.append(f"{where}: options reuse the MacJev runtime gate set execute / inspect / ask (in any " "language; owned by the mac_gate builder with rule-derived labels)") elif t == "score": if not isinstance(crit, list) or not SCORE_MIN <= len(crit) <= SCORE_MAX or not all(isinstance(c, str) and c.strip() for c in crit): errs.append(f"{where}: score needs {SCORE_MIN}..{SCORE_MAX} level descriptions") elif t == "noul": if not isinstance(crit, dict) or set(crit) != {"false", "true"} or not all(isinstance(v, str) and v.strip() for v in crit.values()): errs.append(f"{where}: noul criteria must be {{false: desc, true: desc}}") else: errs.append(f"{where}: type must be choice, score or noul") uses = q.get("uses_fields") if not isinstance(uses, list) or len(uses) < 2: errs.append(f"{where}: uses_fields must name >= 2 state fields") else: for u in uses: if not isinstance(u, str) or not _covered(u, known_paths): errs.append(f"{where}: uses_fields entry {u!r} is not a visible state field") if routing and not any(isinstance(q, dict) and q.get("type") == "choice" and isinstance(q.get("criteria"), dict) and len(q["criteria"]) > CHOICE_MAX for q in qs.values()): errs.append("routing workflows must have one choice question with 13..40 options") try: json.dumps(spec, ensure_ascii=False, allow_nan=False) except (TypeError, ValueError) as exc: errs.append(f"not JSON-serialisable: {exc}") return errs _BENCH_CACHE: set[str] | None = None def load_benchmark_instructions() -> set[str]: """Lower-cased question instructions of the 4 benchmark workflows (local train parquet).""" global _BENCH_CACHE if _BENCH_CACHE is not None: return _BENCH_CACHE from ..paths import ROOT out: set[str] = set() for pq in (ROOT / "data" / "public_raw" / "LocalLLaMA--typed-decisions").glob("*/all/*.parquet"): import pandas as pd df = pd.read_parquet(pq, columns=["questions"]) for qs in df["questions"]: for q in json.loads(qs).values(): out.add(str(q.get("instructions", "")).strip().lower()) _BENCH_CACHE = out return out