"""Proposed delivery router; hypothesis, not production-ready. No external dependencies or actions. Reads features; does not extract facts from language, authenticate evidence, accept commitments, or authorize execution. Missing values stay unknown. Ordered predicates use three-valued logic. """ from __future__ import annotations import argparse import json from pathlib import Path import sys from typing import Any HERE = Path(__file__).resolve().parent def read_json(path: Path) -> Any: with path.open(encoding="utf-8") as handle: return json.load(handle) def get_value(item: dict, field: str) -> Any: value: Any = item for part in field.split("."): if not isinstance(value, dict) or part not in value: return None value = value[part] return None if value == "unknown" else value def evaluate(predicate: dict, item: dict) -> tuple[bool | None, list[str]]: """Evaluate the deliberately small, data-only predicate language.""" if "time_has" in predicate: expected = predicate["time_has"] if expected in time_kinds(item): return True, [] constraints = item.get("time_constraints") if isinstance(constraints, list): if any(entry.get("kind") in (None, "unknown") for entry in constraints): return None, ["time_constraints"] return False, [] if get_value(item, "axes.time_constraint") is not None: return False, [] return None, ["time_constraints", "axes.time_constraint"] if "all" in predicate or "any" in predicate: operator = "all" if "all" in predicate else "any" parts = [evaluate(child, item) for child in predicate[operator]] states = [state for state, _ in parts] if operator == "all" and False in states: return False, [] if operator == "any" and True in states: return True, [] missing = sorted({field for state, fields in parts if state is None for field in fields}) if missing: return None, missing return operator == "all", [] operator = "eq" if "eq" in predicate else "in" field, expected = predicate[operator] actual = get_value(item, field) if actual is None: return None, [field] if operator == "eq": return type(actual) is type(expected) and actual == expected, [] return actual in expected, [] def schema_errors(value: Any, schema: dict, path: str = "$") -> list[str]: """Validate the subset of JSON Schema used by classifier.schema.json. This is not a general JSON Schema implementation. Unsupported schema keywords must not be assumed supported if the input schema is extended later. """ errors: list[str] = [] if "enum" in schema: if not any(type(value) is type(option) and value == option for option in schema["enum"]): return [f"{path}: значение отсутствует в enum"] if "type" in schema: accepted = schema["type"] if isinstance(accepted, str): accepted = [accepted] python_types = {"object": dict, "array": list, "string": str, "boolean": bool, "null": type(None)} if not any(type(value) is python_types[name] for name in accepted): return [f"{path}: ожидался тип {accepted}; получен {type(value).__name__}"] if isinstance(value, str) and len(value) < schema.get("minLength", 0): errors.append(f"{path}: пустая строка запрещена") if isinstance(value, dict): properties = schema.get("properties", {}) for name in schema.get("required", []): if name not in value: errors.append(f"{path}.{name}: обязательное поле отсутствует") for name, child in value.items(): if name not in properties and schema.get("additionalProperties") is False: errors.append(f"{path}.{name}: неизвестное поле") elif name in properties: errors.extend(schema_errors(child, properties[name], f"{path}.{name}")) if isinstance(value, list) and "items" in schema: for index, child in enumerate(value): errors.extend(schema_errors(child, schema["items"], f"{path}[{index}]")) return errors def semantic_conflicts(item: dict) -> list[str]: issues = [] confirmed = get_value(item, "signals.emergency_confirmed") urgency = get_value(item, "axes.urgency") if confirmed is False and urgency == "active_emergency": issues.append("Emergency одновременно отрицается и указан как active_emergency.") if confirmed is True and urgency in ("normal", "time_critical"): issues.append("Подтверждённый emergency противоречит явно некритической urgency.") if get_value(item, "axes.input_quality") == "conflicting": issues.append("Источники признаков помечены как conflicting.") if get_value(item, "signals.scope_flexible") is True and get_value(item, "signals.fixed_scope") is True: issues.append("Scope одновременно разрешено сокращать и полностью запрещено сокращать.") if item.get("parent_id") and item.get("parent_id") == item.get("id"): issues.append("Обязательство не может быть собственным родителем.") if len(item.get("outcomes") or []) > 1 and get_value(item, "signals.composite_outcomes") is False: issues.append("Несколько отдельно принимаемых outcomes противоречат composite_outcomes=false.") if get_value(item, "signals.scrum_contract_accepted") is True: for field in ("common_product_goal", "usable_increment"): if get_value(item, f"signals.{field}") is False: issues.append(f"Принятый Scrum-контракт несовместим с signals.{field}=false.") if get_value(item, "dispatch_required") is True and get_value(item, "software_change") is True: issues.append("Смешаны software change и физический/сервисный слот как результат: уточнить единицу, окно выпуска не меняет режим.") if get_value(item, "active_mode") == "SCRUM" and get_value(item, "signals.scrum_contract_accepted") is False: issues.append("Действующий SCRUM одновременно отрицается признаком scrum_contract_accepted=false.") if get_value(item, "active_mode") == "BET" and get_value(item, "signals.protected_team") is False: issues.append("Действующая защищённая ставка противоречит protected_team=false.") return issues def time_kinds(item: dict) -> set[str]: kinds = {entry.get("kind") for entry in item.get("time_constraints") or []} kinds.add(get_value(item, "axes.time_constraint")) return {kind for kind in kinds if kind not in (None, "unknown", "none")} def safety_attention(item: Any) -> bool: if not isinstance(item, dict): return False return any(get_value(item, field) is True for field in ("signals.emergency_confirmed", "signals.emergency_suspected")) or \ get_value(item, "axes.urgency") == "active_emergency" def route_work(item: Any, model: dict | None = None, schema: dict | None = None) -> dict: model = model if model is not None else read_json(HERE / "delivery-model.json") schema = schema if schema is not None else read_json(HERE / "classifier.schema.json") result = { "item_id": item.get("id") if isinstance(item, dict) else None, "model_version": model["model_version"], "evidence_status": "гипотеза", "production_ready": False, "status": "NEEDS_CLASSIFICATION", "primary_mode": None, "mode_variant": None, "rule_id": None, "matched_profiles": [], "unresolved_profiles": [], "layers": [], "mode_parameters": {}, "proposed_child_modes": [], "service_class": None, "time_constraints": item.get("time_constraints") if isinstance(item, dict) else None, "active_contract_id": item.get("active_contract_id") if isinstance(item, dict) else None, "holds": ["PROTOTYPE_NEVER_AUTHORIZES_EXECUTION"], "required_fields": [], "issues": [], "trace": [], "human_triage_owner": item.get("human_triage_owner") if isinstance(item, dict) else None, "escalation": "normal", "next_step": "human_triage", "execution_authorized": False, "commitment_accepted": False, "resources_booked": False, } def stop(rule_id: str, issues: list[str], fields: list[str] | None = None, status: str = "NEEDS_CLASSIFICATION", immediate: bool = False) -> dict: result.update(status=status, rule_id=rule_id, issues=issues, required_fields=sorted(set(fields or [])), escalation="immediate" if immediate else "normal") result["trace"].append({"rule_id": rule_id, "state": status}) if status == "SPLIT_REQUIRED": result["next_step"] = "human_decomposition_and_reclassification" return result errors = schema_errors(item, schema) if errors: return stop("R00_INVALID", errors, immediate=safety_attention(item)) conflicts = semantic_conflicts(item) if conflicts: return stop("R00_CONFLICT", conflicts, immediate=safety_attention(item)) if get_value(item, "axes.authorization") != "approved": result["holds"].append("EXECUTION_APPROVAL_PENDING_OR_UNKNOWN") for profile in model["profiles"]: state, _ = evaluate(profile["match"], item) if state is True: result["matched_profiles"].append(profile["id"]) elif state is None: result["unresolved_profiles"].append(profile["id"]) def choose(mode: str, rule_id: str, variant: str | None = None, children: list[dict] | None = None) -> dict: mode_definition = next(value for value in model["modes"] if value["id"] == mode) parameters = {name: None for name in mode_definition["parameters"]} if "variant" in parameters: parameters["variant"] = variant layers = ["DRI"] policies = [policy for policy in model["combination_policies"] if policy["primary"] == mode] for policy in policies: for layer in policy["layers"]: if layer == "XP_CD" and get_value(item, "software_change") is not True: continue if layer == "SOP_IF_KNOWN": if get_value(item, "signals.known_operation") is True: layers.append("SOP") continue layers.append(layer) windows = time_kinds(item) & {"appointment", "biological_window", "maintenance_window"} if windows and mode != "DISPATCH": layers.append("RELEASE_WINDOW" if get_value(item, "software_change") is True else "RESOURCE_WINDOW") if mode in ("SCRUM", "BET") and get_value(item, "axes.uncertainty") == "experiment_required": layers.append("EXPERIMENT_SUBORDINATE") if mode in ("SCRUM", "BET") and get_value(item, "signals.known_operation") is True: layers.append("SOP_SUBORDINATE") if mode in ("FLOW", "CASE") and get_value(item, "axes.uncertainty") == "expert_analyzable": layers.append("EXPERT_DIAGNOSTICS") if mode == "INCIDENT": service_class = "EMERGENCY" elif get_value(item, "axes.urgency") == "time_critical": service_class = "TIME_CRITICAL" elif "hard_deadline" in time_kinds(item): service_class = "FIXED_DATE" elif mode == "ROUTINE": service_class = "RECURRING" elif get_value(item, "axes.urgency") == "normal": service_class = "STANDARD" else: service_class = "UNKNOWN" if "service_class" in parameters: parameters["service_class"] = service_class result.update(status="ROUTED", primary_mode=mode, mode_variant=variant, rule_id=rule_id, layers=sorted(set(layers)), mode_parameters=parameters, proposed_child_modes=children or [], service_class=service_class, next_step="human_review_route_and_policy", escalation="immediate" if mode == "INCIDENT" else "normal") result["trace"].append({"rule_id": rule_id, "state": "matched"}) return result if get_value(item, "signals.emergency_confirmed") is True: return choose("INCIDENT", "R01_INCIDENT") if get_value(item, "signals.emergency_suspected") is True: return stop("R02_SUSPECTED", ["Возможен существенный ущерб: нужна оперативная человеческая triage."], ["signals.emergency_confirmed"], immediate=True) missing_safety = [field for field in ("signals.emergency_confirmed", "signals.emergency_suspected") if get_value(item, field) is None] if missing_safety: return stop("R03_SAFETY_UNKNOWN", ["Emergency не исключён: неизвестное не считается false."], missing_safety, immediate=safety_attention(item)) if get_value(item, "axes.input_quality") != "sufficient": return stop("R04_INPUT", ["Качество входных сведений не подтверждено."], ["axes.input_quality"]) if not (item.get("outcome") or "").strip(): return stop("R04_INPUT", ["Нужен принимаемый результат обязательства."], ["outcome"]) if get_value(item, "signals.composite_outcomes") is True: return stop("R05_COMPOSITE", ["Разделить принимаемые результаты и повторить классификацию детей."], status="SPLIT_REQUIRED") if get_value(item, "axes.size") == "needs_split": return stop("R05_SIZE", ["Обязательная декомпозиция предшествует любому обычному режиму, включая действующий контракт."], status="SPLIT_REQUIRED") if get_value(item, "signals.composite_outcomes") is None: return stop("R05_COMPOSITE", ["Неизвестно, является ли запись составной."], ["signals.composite_outcomes"]) core = ("axes.level", "axes.purpose", "axes.uncertainty", "axes.size") missing_core = [field for field in core if get_value(item, field) is None] if missing_core: return stop("R06_CORE", ["Не хватает ключевых признаков для обычного выбора."], missing_core) active_mode = get_value(item, "active_mode") if active_mode is None: return stop("R07_ACTIVE_CONTRACT", ["Неизвестен действующий контракт: нельзя назначать новый режим карточке молча."], ["active_mode"]) if active_mode != "none": compatible = get_value(item, "active_contract_compatible") if compatible is not True: return stop("R07_CONTRACT_CONFLICT" if compatible is False else "R07_ACTIVE_CONTRACT", ["Действующая политика несовместима или совместимость не подтверждена; пересмотр делает уполномоченный человек."], ["active_contract_compatible"]) if not (item.get("active_contract_id") or "").strip(): return stop("R07_ACTIVE_CONTRACT", ["Нужна ссылка на действующий контракт."], ["active_contract_id"]) if get_value(item, "dispatch_required") is True: return stop("R07_CONTRACT_CONFLICT", ["Физический/сервисный слот требует выделенной дочерней операции или явного пересмотра действующего контракта."], ["dispatch_required"]) if get_value(item, "dispatch_required") is None: return stop("R07_ACTIVE_CONTRACT", ["Нужно исключить отдельное физическое/сервисное обязательство, несовместимое с единицей контракта."], ["dispatch_required"]) return choose(active_mode, "R07_ACTIVE_CONTRACT") for rule in model["ordered_routing_rules"]: state, missing = evaluate(rule["when"], item) if state is False: result["trace"].append({"rule_id": rule["id"], "state": "skipped"}) continue if state is None: return stop(rule["id"], ["Более ранний допустимый режим ещё нельзя ни выбрать, ни исключить."], missing) action = rule["action"] if action == "SPLIT_REQUIRED": return stop(rule["id"], ["Размер превышает локальную политику: нужна декомпозиция."], status="SPLIT_REQUIRED") if action != "network": return choose(action, rule["id"]) network_known = get_value(item, "signals.network_known") known_milestones = get_value(item, "signals.known_milestones") if network_known is None: return stop(rule["id"], ["Нельзя считать сеть известной без подтверждения."], ["signals.network_known"]) children = [] if network_known is False: if known_milestones is not True: return stop(rule["id"], ["Нет подтверждённой сети или известных вех; сроки неизвестной работы не строятся."], ["signals.known_milestones"]) child_mode = "EXPERIMENT" if get_value(item, "axes.uncertainty") == "experiment_required" else None children = [{"mode": child_mode, "scope": "unknown_work_packages", "status": "PROPOSED" if child_mode else "NEEDS_CLASSIFICATION", "reason": "Неполнота сети сама не определяет способ получения недостающих сведений.", "requires_separate_classification": True, "dates_generated": False}] resource = get_value(item, "axes.resource") if resource is None: return stop(rule["id"], ["Для сетевого контракта нужно определить ресурсное ограничение."], ["axes.resource"]) variant = "CPM" if resource == "shared_bottleneck": capability = get_value(item, "signals.buffer_management_capable") if capability is None: return stop(rule["id"], ["Неизвестна способность управлять CCPM-буферами и выпуском."], ["signals.buffer_management_capable"]) if capability is True: variant = "CCPM" return choose("NETWORK", rule["id"], variant, children) return stop("R99_UNRESOLVED", ["Нет обоснованного контракта: уточнить результат и декомпозицию либо вопрос исследования."], ["axes.size", "signals.independently_acceptable"]) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", nargs="?", help="JSON-файл карточки/массива; иначе stdin") args = parser.parse_args() try: data = read_json(Path(args.input)) if args.input else json.load(sys.stdin) model = read_json(HERE / "delivery-model.json") schema = read_json(HERE / "classifier.schema.json") results = [route_work(item, model, schema) for item in data] if isinstance(data, list) else route_work(data, model, schema) print(json.dumps(results, ensure_ascii=False, indent=2)) except (OSError, json.JSONDecodeError) as error: print(json.dumps({"error": str(error), "execution_authorized": False}, ensure_ascii=False), file=sys.stderr) return 2 return 0 if __name__ == "__main__": raise SystemExit(main())