walk_graph_json.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. """V3 游走配置入口(M4A):读 walk_graph / walk_policy / platform_profiles 并校验。
  2. 镜像 walk_strategy_json.WalkStrategyStore 的 load+validate+raise 结构。
  3. walk_policy 的拍板值可能带 {value, provenance, tbd} 包裹(留痕),load_policy 解包成纯值。
  4. """
  5. from __future__ import annotations
  6. import os
  7. from dataclasses import dataclass
  8. from pathlib import Path
  9. from typing import Any
  10. from content_agent.findings import fail as _fail
  11. WALK_GRAPH_PATH = Path("tech_documents/数据接口与来源/walk_graph.json")
  12. WALK_POLICY_PATH = Path("tech_documents/数据接口与来源/walk_policy.json")
  13. PROFILE_DIR = Path("tech_documents/数据接口与来源/platform_profiles")
  14. EDGE_CATALOG_PATH = Path("product_documents/抖音游走策略/douyin_walk_strategy.v1.json")
  15. PERMISSION_ACTIONS = ["ADD_TO_CONTENT_POOL", "KEEP_CONTENT_FOR_REVIEW", "REJECT_CONTENT"]
  16. _PERMISSION_META_KEYS = {"_meaning", "_provenance", "note", "tbd"}
  17. def _unwrap(value: Any) -> Any:
  18. if isinstance(value, dict) and "value" in value:
  19. return value["value"]
  20. return value
  21. def low_budget(budget: int) -> int:
  22. """low_budget 档:减半向下取整,至少 1(2026-06-11 拍板,policy 值 halve_min_1)。"""
  23. return max(1, budget // 2)
  24. def edge_permission(policy: dict[str, Any], decision_action: str | None, edge_id: str) -> str:
  25. """判定结果 → 该出边通行证;无判定/未列入的组合一律 deny(从严)。"""
  26. row = policy["edge_permissions"].get(decision_action or "", {})
  27. return row.get(edge_id, "deny")
  28. def edge_supported(profile: dict[str, Any], edge_id: str) -> bool:
  29. """profile 未列出的边 = 平台无关控制边(终端边),恒 supported。"""
  30. return profile["edges"].get(edge_id, {"status": "supported"})["status"] == "supported"
  31. @dataclass(frozen=True)
  32. class WalkGraphStore:
  33. root_dir: Path = Path(".")
  34. def load_graph(self) -> dict[str, Any]:
  35. from content_agent.integrations import config_store
  36. graph, _ = config_store.load_json(self.root_dir / WALK_GRAPH_PATH)
  37. catalog, _ = config_store.load_json(self.root_dir / EDGE_CATALOG_PATH)
  38. catalog_ids = {row["edge_id"] for row in catalog["walk_edge_catalog"]}
  39. _raise_on_fail(_validate_graph(graph, catalog_ids), "walk graph")
  40. return graph
  41. def load_policy(self) -> dict[str, Any]:
  42. from content_agent.integrations import config_store
  43. raw_policy, _ = config_store.load_json(self.root_dir / WALK_POLICY_PATH)
  44. policy = _unwrap_policy(raw_policy)
  45. edge_ids = {edge["edge_id"] for edge in self.load_graph()["edges"]}
  46. _raise_on_fail(_validate_policy(policy, edge_ids), "walk policy")
  47. return policy
  48. def load_profile(self, platform: str) -> dict[str, Any]:
  49. from content_agent.integrations import config_store
  50. profile, _ = config_store.load_json(self.root_dir / PROFILE_DIR / f"{platform}.json")
  51. edge_ids = {edge["edge_id"] for edge in self.load_graph()["edges"]}
  52. _raise_on_fail(_validate_profile(profile, edge_ids), f"platform profile {platform}")
  53. return profile
  54. def _unwrap_policy(raw: dict[str, Any]) -> dict[str, Any]:
  55. policy = dict(raw)
  56. policy["global"] = {key: _unwrap(value) for key, value in raw["global"].items()}
  57. _apply_global_env_overrides(policy["global"])
  58. policy["edge_permissions"] = {
  59. action: {edge: _unwrap(perm) for edge, perm in row.items() if edge not in _PERMISSION_META_KEYS}
  60. for action, row in raw["edge_permissions"].items()
  61. if action in PERMISSION_ACTIONS
  62. }
  63. policy["budget_tiers"] = {key: _unwrap(value) for key, value in raw["budget_tiers"].items()}
  64. policy["edge_budgets_by_id"] = {row["edge_id"]: row for row in raw["edge_budgets"]}
  65. return policy
  66. def _apply_global_env_overrides(global_policy: dict[str, Any]) -> None:
  67. overrides = {
  68. "CONTENT_AGENT_WALK_MAX_TOTAL_ACTIONS_PER_RUN": "max_total_actions_per_run",
  69. "CONTENT_AGENT_GEMINI_MAX_WORKERS": "gemini_max_workers",
  70. }
  71. for env_key, policy_key in overrides.items():
  72. value = _optional_positive_int(os.environ.get(env_key))
  73. if value is not None:
  74. global_policy[policy_key] = value
  75. def _optional_positive_int(value: str | None) -> int | None:
  76. if value is None or value == "":
  77. return None
  78. try:
  79. parsed = int(value)
  80. except ValueError:
  81. return None
  82. return parsed if parsed > 0 else None
  83. def _validate_graph(graph: dict[str, Any], catalog_ids: set[str]) -> list[dict[str, Any]]:
  84. findings: list[dict[str, Any]] = []
  85. node_types = {node["node_type"] for node in graph.get("nodes", [])}
  86. for edge in graph.get("edges", []):
  87. if edge.get("edge_id") not in catalog_ids:
  88. _fail(findings, "edge_not_in_catalog", f"{edge.get('edge_id')} not in walk_edge_catalog")
  89. for field in ["from_node", "to_node"]:
  90. if edge.get(field) not in node_types:
  91. _fail(findings, "edge_node_ref", f"{edge.get('edge_id')} unknown {field}: {edge.get(field)}")
  92. return findings
  93. def _validate_policy(policy: dict[str, Any], edge_ids: set[str]) -> list[dict[str, Any]]:
  94. findings: list[dict[str, Any]] = []
  95. for row in policy.get("edge_budgets", []):
  96. if row.get("edge_id") not in edge_ids:
  97. _fail(findings, "budget_edge_ref", f"edge_budgets unknown edge_id: {row.get('edge_id')}")
  98. permission_rows = policy.get("edge_permissions", {})
  99. key_sets = []
  100. for action in PERMISSION_ACTIONS:
  101. if action not in permission_rows:
  102. _fail(findings, "permission_action_missing", f"edge_permissions missing action: {action}")
  103. continue
  104. keys = set(permission_rows[action])
  105. key_sets.append(keys)
  106. for edge_id in keys - edge_ids:
  107. _fail(findings, "permission_edge_ref", f"{action} unknown edge_id: {edge_id}")
  108. if key_sets and any(keys != key_sets[0] for keys in key_sets[1:]):
  109. _fail(findings, "permission_closure", "edge_permissions edge keys differ across actions")
  110. return findings
  111. def _validate_profile(profile: dict[str, Any], edge_ids: set[str]) -> list[dict[str, Any]]:
  112. findings: list[dict[str, Any]] = []
  113. for edge_id, spec in profile.get("edges", {}).items():
  114. if edge_id not in edge_ids:
  115. _fail(findings, "profile_edge_ref", f"profile unknown edge_id: {edge_id}")
  116. if spec.get("status") not in {"supported", "blocked"}:
  117. _fail(findings, "profile_edge_status", f"{edge_id} invalid status: {spec.get('status')}")
  118. return findings
  119. def _raise_on_fail(findings: list[dict[str, Any]], label: str) -> None:
  120. failures = [finding for finding in findings if finding["level"] == "fail"]
  121. if failures:
  122. raise ValueError(f"invalid {label} config: {failures}")