From 9ed59b35e67ed0023672fc83363d57b0376a7d35 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:39:33 +0800 Subject: [PATCH] refactor(control-plane): retire prose stopword/token-bag routing heuristics in explore, stall_repair, and event_ledger Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../capabilities/explore/todo_branch_plan.py | 79 +++++++++++--- .../explore/worker_branch_plan.py | 101 +++++------------ loopx/control_plane/quota/stall_repair.py | 38 +++---- loopx/control_plane/runtime/event_ledger.py | 3 - .../control_plane/status/runtime_summaries.py | 2 - loopx/status.py | 16 --- ...st_reward_memory_field_vocabulary_owner.py | 26 +---- .../test_user_gate_lane_progress.py | 41 +++++++ tests/test_explore_worker_topic_affinity.py | 103 ++++++++++++++---- 9 files changed, 232 insertions(+), 177 deletions(-) diff --git a/loopx/capabilities/explore/todo_branch_plan.py b/loopx/capabilities/explore/todo_branch_plan.py index 308a4ff799..279b24226b 100644 --- a/loopx/capabilities/explore/todo_branch_plan.py +++ b/loopx/capabilities/explore/todo_branch_plan.py @@ -1,17 +1,20 @@ from __future__ import annotations -import re -from typing import Any, Mapping, Sequence +from typing import AbstractSet, Any, Mapping, Sequence from ...control_plane.todos.contract import ( TODO_STATUS_OPEN, TODO_TASK_CLASS_ADVANCEMENT, TODO_TASK_CLASS_MONITOR, + normalize_explore_result_node_refs, normalize_required_capabilities, normalize_required_write_scopes, + normalize_target_capabilities, + normalize_todo_capability_binding_ref, normalize_todo_claimed_by, normalize_todo_id, normalize_todo_status, + normalize_todo_task_domain, ) from ...control_plane.todos.todo_semantics import ( todo_item_is_actionable_open, @@ -43,31 +46,72 @@ TODO_BRANCH_PLAN_SCHEMA_VERSION = "loopx_explore_todo_branch_plan_v0" DEFAULT_BRANCH_WIDTH = 3 MAX_BRANCH_WIDTH = 8 -TOKEN_PATTERN = re.compile(r"[A-Za-z0-9_:\-]{3,}") SHARED_DEPENDENCY_CAPABILITY_PREFIXES = ( "shared_artifact:", "shared_implementation:", ) -def _tokenize(value: Any) -> set[str]: - return {match.group(0).lower() for match in TOKEN_PATTERN.finditer(str(value or ""))} +def _add_typed_ref(refs: set[str], prefix: str, value: Any) -> None: + if normalized := str(value or "").strip().lower(): + refs.add(f"{prefix}:{normalized}") -def _frontier_tokens(projection: Mapping[str, Any] | None) -> set[str]: - tokens: set[str] = set() +def _collect_item_typed_refs( + refs: set[str], + item: Mapping[str, Any], + *, + node_values: Sequence[Any], + capability_values: Sequence[Any], +) -> None: + for value in node_values: + _add_typed_ref(refs, "node", value) + _add_typed_ref(refs, "target", item.get("target_key") or item.get("scope_key")) + _add_typed_ref(refs, "binding", normalize_todo_capability_binding_ref(item.get("capability_binding_ref"))) + _add_typed_ref(refs, "domain", normalize_todo_task_domain(item.get("task_domain"))) + for value in capability_values: + _add_typed_ref(refs, "capability", value) + + +def _frontier_refs(projection: Mapping[str, Any] | None) -> frozenset[str]: + """Extract typed structured frontier/stuck reference keys from explore projection.""" + + refs: set[str] = set() if not isinstance(projection, Mapping): - return tokens + return frozenset(refs) for lane in ("frontier", "stuck"): for item in projection.get(lane) or []: if not isinstance(item, Mapping): continue - tokens.update(_tokenize(item.get("node_id"))) - tokens.update(_tokenize(item.get("title"))) - tokens.update(_tokenize(item.get("summary"))) - for tag in item.get("tags") or []: - tokens.update(_tokenize(tag)) - return tokens + caps = [ + v + for k in ("required_capabilities", "target_capabilities", "capabilities", "tags") + if isinstance(vals := item.get(k), (list, tuple, set)) + for v in vals + ] + _collect_item_typed_refs(refs, item, node_values=(item.get("node_id"),), capability_values=caps) + return frozenset(refs) + + +def _todo_frontier_refs(item: Mapping[str, Any]) -> frozenset[str]: + """Extract typed structured frontier reference keys from a Todo item.""" + + refs: set[str] = set() + raw_nodes = ( + item.get("explore_result_node_refs") + or item.get("result_node_refs") + or item.get("frontier_node_ids") + or item.get("node_refs") + ) + caps: list[Any] = [ + *normalize_required_capabilities(item.get("required_capabilities")), + *normalize_target_capabilities(item.get("target_capabilities")), + *(vals if isinstance(vals := item.get("tags"), (list, tuple, set)) else ()), + ] + _collect_item_typed_refs( + refs, item, node_values=normalize_explore_result_node_refs(raw_nodes), capability_values=caps, + ) + return frozenset(refs) def _compact_text(value: Any, *, limit: int = 240) -> str: @@ -109,7 +153,7 @@ def _branch_score( item: Mapping[str, Any], *, agent_id: str | None, - frontier: set[str], + frontier: AbstractSet[str], ) -> tuple[float, list[str], list[str]]: reason_codes: list[str] = [] hazards: list[str] = [] @@ -164,8 +208,7 @@ def _branch_score( if capabilities: reason_codes.append("declared_capabilities") - text_tokens = _tokenize(item.get("text")) | _tokenize(item.get("title")) - overlap = sorted(text_tokens & frontier) + overlap = sorted(_todo_frontier_refs(item) & frontier) if overlap: score += min(12.0, 2.5 * len(overlap)) reason_codes.append("explore_frontier_overlap") @@ -339,7 +382,7 @@ def build_explore_todo_branch_plan( if gate["state"] == GATE_STATE_DISABLED: return _disabled_todo_branch_plan(goal_id=goal_id, agent_id=normalized_agent, gate=gate) normalized_width = int(gate["effective_width"]) - frontier = _frontier_tokens(projection) + frontier = _frontier_refs(projection) candidates: list[dict[str, Any]] = [] for item in todos: diff --git a/loopx/capabilities/explore/worker_branch_plan.py b/loopx/capabilities/explore/worker_branch_plan.py index 42cb086ecc..cc2bebe161 100644 --- a/loopx/capabilities/explore/worker_branch_plan.py +++ b/loopx/capabilities/explore/worker_branch_plan.py @@ -2,12 +2,16 @@ from copy import deepcopy import re -from typing import Any, Mapping, Sequence +from typing import AbstractSet, Any, Mapping, Sequence from ...control_plane.todos.contract import ( TODO_TASK_CLASS_MONITOR, + normalize_todo_action_kind, + normalize_todo_capability_binding_ref, normalize_todo_claimed_by, normalize_todo_id, + normalize_todo_task_domain, + normalize_todo_task_repository, ) from .harness_gate import ( GATE_STATE_ANALYSIS_ONLY, @@ -33,14 +37,13 @@ from .todo_branch_plan import ( DEFAULT_BRANCH_WIDTH, MAX_BRANCH_WIDTH, - TOKEN_PATTERN, _branch_confidence, _branch_expected_evidence_units, _branch_score, _candidate_readiness, _claim_command, _compact_text, - _frontier_tokens, + _frontier_refs, _execution_exclusion, _required_capabilities, _required_write_scopes, @@ -230,55 +233,6 @@ }, } -COMMON_TOPIC_TOKENS = { - "add", - "after", - "agent", - "against", - "and", - "audit", - "before", - "between", - "branch", - "build", - "check", - "codex", - "continue", - "current", - "deliver", - "existing", - "explore", - "fix", - "from", - "goal", - "inspect", - "into", - "latest", - "loopx", - "new", - "next", - "one", - "p0", - "p1", - "p2", - "recent", - "review", - "run", - "test", - "the", - "then", - "this", - "through", - "todo", - "update", - "validate", - "when", - "while", - "with", - "without", -} - - def worker_harness_profile_names() -> tuple[str, ...]: return tuple(sorted(WORKER_HARNESS_PROFILES)) @@ -325,20 +279,6 @@ def _resolve_todo_bundle_ceiling( return max(1, min(MAX_TODOS_PER_WORKER_BRANCH, default_ceiling)), False, "profile_default" -def _ordered_topic_tokens(value: Any) -> list[str]: - """Return meaningful topic tokens in their original textual order.""" - - tokens: list[str] = [] - seen: set[str] = set() - for match in TOKEN_PATTERN.finditer(str(value or "")): - token = match.group(0).lower() - if token in COMMON_TOPIC_TOKENS or token in seen: - continue - seen.add(token) - tokens.append(token) - return tokens - - def _scope_family(scope: str) -> str: clean = str(scope or "").replace("\\", "/").strip() for marker in ("/**", "/*"): @@ -363,9 +303,16 @@ def _affinity_key(candidate: Mapping[str, Any]) -> str: ] if capabilities: return f"capability:{str(capabilities[0]).strip()}" - tokens = _ordered_topic_tokens(candidate.get("text")) - if tokens: - return f"topic:{tokens[0]}" + for prefix, raw_value in ( + ("target", candidate.get("target_key") or candidate.get("scope_key")), + ("binding", candidate.get("capability_binding_ref")), + ("domain", candidate.get("task_domain")), + ("action", candidate.get("action_kind")), + ("repo", candidate.get("task_repository")), + ): + value = str(raw_value or "").strip().lower() + if value: + return f"{prefix}:{value}" return "topic:general" @@ -383,7 +330,7 @@ def _todo_candidate( item: Mapping[str, Any], *, agent_id: str | None, - frontier: set[str], + frontier: AbstractSet[str], ) -> dict[str, Any] | None: todo_id = normalize_todo_id(item.get("todo_id")) if not todo_id: @@ -419,6 +366,16 @@ def _todo_candidate( "claim_bucket": _claim_bucket(item, agent_id=agent_id), "source_index": item.get("index"), } + if target_key := str(item.get("target_key") or item.get("scope_key") or "").strip(): + candidate["target_key"] = target_key + if binding_ref := normalize_todo_capability_binding_ref(item.get("capability_binding_ref")): + candidate["capability_binding_ref"] = binding_ref + if task_domain := normalize_todo_task_domain(item.get("task_domain")): + candidate["task_domain"] = task_domain + if action_kind := normalize_todo_action_kind(item.get("action_kind")): + candidate["action_kind"] = action_kind + if task_repo := normalize_todo_task_repository(item.get("task_repository")): + candidate["task_repository"] = task_repo candidate["affinity_key"] = _affinity_key(candidate) return candidate @@ -499,7 +456,7 @@ def _branch_candidate( "branch_id": branch_id, "todo_id": branch_id, "affinity_key": affinity_key, - "objective_slice": affinity_key.removeprefix("scope:").removeprefix("capability:").removeprefix("topic:"), + "objective_slice": affinity_key.partition(":")[2] or affinity_key, "todo_ids": todo_ids, "todo_bundle": todo_bundle, "required_write_scopes": write_scopes, @@ -616,7 +573,7 @@ def _build_worker_branch_candidates( router_state: Mapping[str, Any] | None = None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: normalized_agent = normalize_todo_claimed_by(agent_id) - frontier = _frontier_tokens(projection) + frontier = _frontier_refs(projection) todo_candidates = [ candidate for item in todos diff --git a/loopx/control_plane/quota/stall_repair.py b/loopx/control_plane/quota/stall_repair.py index c24bfb61a7..2325cb3999 100644 --- a/loopx/control_plane/quota/stall_repair.py +++ b/loopx/control_plane/quota/stall_repair.py @@ -23,7 +23,11 @@ build_required_decision_scope_repair_hint, standing_decision_authority_for_agent, ) -from ..todos.user_gate import open_todo_count, open_user_gate_todo_items +from ..todos.user_gate import ( + USER_GATE_ACTION_KIND_HINTS, + open_todo_count, + open_user_gate_todo_items, +) STALL_HEALTH_ITEM_COMPACT_FIELDS = ( "goal_id", @@ -43,21 +47,6 @@ RUNTIME_CAPABILITY_USER_GATE_REPAIR_TRIGGER, } ) -RUNTIME_RECOVERY_ACTION_TOKENS = frozenset( - { - "configure", - "execute", - "install", - "launch", - "materialize", - "rebuild", - "repair", - "restore", - "retry", - "run", - "start", - } -) def standing_decision_authority_from_status_item( @@ -114,13 +103,11 @@ def _compact_health_items( return compact -def _runtime_recovery_action(action_kind: Any) -> bool: - tokens = { - token - for token in str(action_kind or "").strip().lower().replace("-", "_").split("_") - if token - } - return bool(tokens & RUNTIME_RECOVERY_ACTION_TOKENS) +def _is_owner_gate_action_kind(action_kind: Any) -> bool: + normalized = str(action_kind or "").strip().lower() + if not normalized: + return False + return any(hint in normalized for hint in USER_GATE_ACTION_KIND_HINTS) def _source_todo_items( @@ -187,7 +174,10 @@ def build_runtime_capability_user_gate_repair_hint( continue if normalize_todo_decision_scope(gate.get("decision_scope")): continue - if not _runtime_recovery_action(gate.get("action_kind")): + action_kind = gate.get("action_kind") + if not str(action_kind or "").strip() or _is_owner_gate_action_kind( + action_kind + ): continue target_todo_id = normalize_todo_id(gate.get("unblocks_todo_id")) target = agent_items_by_id.get(cast(str, target_todo_id)) diff --git a/loopx/control_plane/runtime/event_ledger.py b/loopx/control_plane/runtime/event_ledger.py index a409d61e19..5bee653a5b 100644 --- a/loopx/control_plane/runtime/event_ledger.py +++ b/loopx/control_plane/runtime/event_ledger.py @@ -47,7 +47,6 @@ def event_ledger_event_class( run_has_external_evidence_watch_signal: RunPredicate, decision_classifications: set[str], evidence_classifications: set[str], - evidence_hints: tuple[str, ...], state_classifications: set[str], ) -> str: classification = str(run.get("classification") or "").lower() @@ -67,8 +66,6 @@ def event_ledger_event_class( return "evidence" if run_has_external_evidence_watch_signal(run): return "evidence" - if any(hint in classification for hint in evidence_hints): - return "evidence" if any( key in run for key in ( diff --git a/loopx/control_plane/status/runtime_summaries.py b/loopx/control_plane/status/runtime_summaries.py index 3c8671c027..a9a14fc857 100644 --- a/loopx/control_plane/status/runtime_summaries.py +++ b/loopx/control_plane/status/runtime_summaries.py @@ -39,7 +39,6 @@ class StatusRuntimeSummaryContext: run_has_external_evidence_watch_signal: StatusCallback decision_classifications: set[str] evidence_classifications: set[str] - evidence_hints: tuple[str, ...] state_classifications: set[str] promotion_readiness_classifications: Iterable[str] add_promotion_readiness_freshness: StatusCallback @@ -63,7 +62,6 @@ def event_ledger_event_class( run_has_external_evidence_watch_signal=context.run_has_external_evidence_watch_signal, decision_classifications=context.decision_classifications, evidence_classifications=context.evidence_classifications, - evidence_hints=context.evidence_hints, state_classifications=context.state_classifications, ) diff --git a/loopx/status.py b/loopx/status.py index cbb5528f2f..216bcb465f 100644 --- a/loopx/status.py +++ b/loopx/status.py @@ -328,21 +328,6 @@ "needs_more_read_only_evidence", "read_only_project_map", } -EVENT_LEDGER_EVIDENCE_HINTS = ( - "artifact", - "blocker", - "ci", - "data", - "deploy", - "done", - "eval", - "evidence", - "failure", - "fail", - "metric", - "monitor", - "validation", -) RUN_COMPACT_FIELDS = RUN_BASE_COMPACT_FIELDS @@ -1282,7 +1267,6 @@ def build_status_runtime_summary_context() -> StatusRuntimeSummaryContext: run_has_external_evidence_watch_signal=run_has_external_evidence_watch_signal, decision_classifications=EVENT_LEDGER_DECISION_CLASSIFICATIONS, evidence_classifications=EVENT_LEDGER_EVIDENCE_CLASSIFICATIONS, - evidence_hints=EVENT_LEDGER_EVIDENCE_HINTS, state_classifications=EVENT_LEDGER_STATE_CLASSIFICATIONS, promotion_readiness_classifications=PROMOTION_READINESS_CLASSIFICATIONS, add_promotion_readiness_freshness=add_promotion_readiness_freshness, diff --git a/tests/architecture/test_reward_memory_field_vocabulary_owner.py b/tests/architecture/test_reward_memory_field_vocabulary_owner.py index 91cec1c923..4e02f37e69 100644 --- a/tests/architecture/test_reward_memory_field_vocabulary_owner.py +++ b/tests/architecture/test_reward_memory_field_vocabulary_owner.py @@ -10,16 +10,15 @@ ``_REASONING_FIELDS`` ``reward_memory/scoped_feedback.py:42`` ``issue_fix/reward_memory.py:68`` ``_GUARD_FIELDS`` ``reward_memory/scoped_feedback.py:43`` ``issue_fix/reward_memory.py:69`` ``_SCOPE_FIELDS`` ``reward_memory/memory_utility.py:76`` ``reward_memory/utility_reducer.py:42`` -``TOKEN_PATTERN`` ``explore/todo_branch_plan.py:46`` ``explore/worker_branch_plan.py:279`` ``_REPO_PATTERN`` ``issue_fix/repository_snapshot.py:19`` ``issue_fix/repository_commit_evidence.py:15`` ================================= ================================== ==================== Owner choice is evidence, not taste. ``issue_fix/reward_memory.py`` already imports five names from ``..reward_memory.*``, and ``scoped_feedback.py`` is the module that declares the event schema those field sets gate. -``utility_reducer.py:19`` and ``worker_branch_plan.py:33`` each *already import -from the module whose constant they restated* -- the strongest form of the -"duplicate knowledge" case in this repository's own #4447 rule. +``utility_reducer.py:19`` *already imports from the module whose constant it +restated* -- the strongest form of the "duplicate knowledge" case in this +repository's own #4447 rule. ``repository_snapshot.py`` builds and stamps the ``repo`` field, while ``repository_commit_evidence.py`` only checks a declared one against it. @@ -54,7 +53,6 @@ import pytest -from loopx.capabilities.explore import todo_branch_plan, worker_branch_plan from loopx.capabilities.issue_fix import pr_description from loopx.capabilities.issue_fix import repository_commit_evidence as commit_evidence from loopx.capabilities.issue_fix import repository_snapshot @@ -94,12 +92,6 @@ } PATTERN_DECISIONS: dict[str, tuple[str, str, ModuleType, list[tuple[str, ModuleType]]]] = { - "TOKEN_PATTERN": ( - r"[A-Za-z0-9_:\-]{3,}", - "loopx/capabilities/explore/todo_branch_plan.py", - todo_branch_plan, - [("loopx/capabilities/explore/worker_branch_plan.py", worker_branch_plan)], - ), "_REPO_PATTERN": ( r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", "loopx/capabilities/issue_fix/repository_snapshot.py", @@ -334,18 +326,6 @@ def test_repo_shape_is_checked_by_the_producer_and_the_verifier() -> None: assert not commit_evidence._REPO_PATTERN.fullmatch("loopx-project/loopx/two") -def test_tokenizer_and_worker_share_one_token_rule() -> None: - """The bound and the character class are the rule; both files must read one copy.""" - - tokens = todo_branch_plan._tokenize("sync loopx_core:v2 across agents") - assert {"sync", "across", "agents", "loopx_core:v2"} == tokens - assert todo_branch_plan._tokenize("ab cd") == set() # the {3,} bound, not the class - assert todo_branch_plan._tokenize("abc de") == {"abc"} - assert worker_branch_plan.TOKEN_PATTERN is todo_branch_plan.TOKEN_PATTERN - assert worker_branch_plan.TOKEN_PATTERN.findall("ab") == [] - assert worker_branch_plan.TOKEN_PATTERN.findall("abc") == ["abc"] - - def test_architecture_field_contracts_are_a_different_question() -> None: """The surface contract table lists ``observed_at``; the envelope allows ``actor_role``.""" diff --git a/tests/control_plane/test_user_gate_lane_progress.py b/tests/control_plane/test_user_gate_lane_progress.py index 537e7ef042..6f6a6a7aec 100644 --- a/tests/control_plane/test_user_gate_lane_progress.py +++ b/tests/control_plane/test_user_gate_lane_progress.py @@ -579,3 +579,44 @@ def test_acked_human_gate_advances_despite_unrelated_historical_host_failure( assert next_app["stateful_backoff"]["progression_index"] == 1 assert next_app["recommended_rrule"] == "FREQ=MINUTELY;INTERVAL=60" assert next_app["stateful_backoff"]["apply_needed"] is True + + +@pytest.mark.parametrize("gate_action_kind", ["approve_benchmark_run", "request_credential", "", None]) +def test_runtime_capability_repair_skips_owner_gate_and_empty_action_kinds( + gate_action_kind: str | None, +) -> None: + status = _runtime_recovery_gate_status() + item = status["attention_queue"]["items"][0] + user_items = [dict(entry, action_kind=gate_action_kind) for entry in item["user_todos"]["items"]] + + repair = build_runtime_capability_user_gate_repair_hint( + user_todo_summary={"open_count": len(user_items), "items": user_items}, + agent_todo_summary=item["agent_todos"], + user_todo_source_items=user_items, + agent_todo_source_items=item["agent_todos"]["items"], + agent_id=AGENT_ID, + available_capabilities=["shell", "filesystem_write", "network", "benchmark_runner"], + ) + assert repair is None + + +@pytest.mark.parametrize("gate_action_kind", ["provision_sandbox", "修复本地端点"]) +def test_runtime_capability_repair_accepts_non_owner_and_cjk_action_kinds_without_word_bag( + gate_action_kind: str, +) -> None: + status = _runtime_recovery_gate_status() + item = status["attention_queue"]["items"][0] + user_items = [dict(entry, action_kind=gate_action_kind) for entry in item["user_todos"]["items"]] + + repair = build_runtime_capability_user_gate_repair_hint( + user_todo_summary={"open_count": len(user_items), "items": user_items}, + agent_todo_summary=item["agent_todos"], + user_todo_source_items=user_items, + agent_todo_source_items=item["agent_todos"]["items"], + agent_id=AGENT_ID, + available_capabilities=["shell", "filesystem_write", "network", "benchmark_runner"], + ) + assert repair is not None + assert repair["trigger"] == "runtime_capability_user_gate_overreach" + assert repair["gate_todo_id"] == "todo_restore_runtime" + assert repair["target_todo_id"] == "todo_runtime_recovery" diff --git a/tests/test_explore_worker_topic_affinity.py b/tests/test_explore_worker_topic_affinity.py index 48dd06fa0e..a489c66d8b 100644 --- a/tests/test_explore_worker_topic_affinity.py +++ b/tests/test_explore_worker_topic_affinity.py @@ -1,34 +1,35 @@ from __future__ import annotations -from loopx.capabilities.explore.worker_branch_plan import _affinity_key +from loopx.capabilities.explore.todo_branch_plan import build_explore_todo_branch_plan +from loopx.capabilities.explore.worker_branch_plan import ( + _affinity_key, + build_explore_worker_branch_plan, +) -def test_topic_affinity_uses_first_meaningful_token() -> None: - assert ( - _affinity_key({"text": "[P0] Audit current result graph and evidence closure"}) - == "topic:result" - ) - assert ( - _affinity_key({"text": "[P1] Review recent candidates against matched comparators"}) - == "topic:candidates" - ) - assert ( - _affinity_key({"text": "[P2] Inspect latest planner implementation and deliver reusable fix"}) - == "topic:planner" - ) +ORCHESTRATION = { + "spawn_allowed": True, + "max_children": 4, + "explore_harness": {"enabled": True}, +} -def test_topic_affinity_does_not_emit_control_vocabulary() -> None: - assert _affinity_key({"text": "[P0] Continue and update this todo"}) == "topic:general" +def test_affinity_key_ignores_prose_and_cjk_free_text() -> None: + assert _affinity_key({"text": "[P0] Audit current result graph and evidence closure"}) == "topic:general" + assert _affinity_key({"text": "[P1] Review recent candidates against matched comparators"}) == "topic:general" + assert _affinity_key({"text": "[P0] 审计当前结果图并验证收敛指标"}) == "topic:general" -def test_explicit_affinity_signals_still_take_precedence() -> None: +def test_affinity_key_uses_typed_structured_fields_in_precedence_order() -> None: assert ( _affinity_key( { - "text": "[P0] Review candidate behavior", + "text": "[P0] 审计行为", "required_write_scopes": ["loopx/capabilities/explore/**"], "required_capabilities": ["analysis"], + "target_key": "frontier_alpha", + "task_domain": "planning", + "action_kind": "audit", } ) == "scope:loopx/capabilities" @@ -36,9 +37,73 @@ def test_explicit_affinity_signals_still_take_precedence() -> None: assert ( _affinity_key( { - "text": "[P0] Review candidate behavior", + "text": "[P0] 审计行为", "required_capabilities": ["analysis"], + "target_key": "frontier_alpha", } ) == "capability:analysis" ) + assert _affinity_key({"text": "[P0] 审计行为", "target_key": "frontier_alpha"}) == "target:frontier_alpha" + assert _affinity_key({"text": "[P0] 审计行为", "capability_binding_ref": "bind_1"}) == "binding:bind_1" + assert _affinity_key({"text": "[P0] 审计行为", "task_domain": "planning"}) == "domain:planning" + assert _affinity_key({"text": "[P0] 审计行为", "action_kind": "run_probe"}) == "action:run_probe" + assert _affinity_key({"text": "[P0] 审计行为", "task_repository": "owner/repo"}) == "repo:owner/repo" + + +def test_todo_and_worker_branch_plan_match_cjk_todos_via_typed_frontier_refs() -> None: + projection = { + "frontier": [ + { + "node_id": "node_frontier_cjk", + "title": "验证中文探索分支与结构化匹配", + "target_key": "target_eval_loop", + "task_domain": "evaluation", + "required_capabilities": ["eval_runner"], + } + ], + "stuck": [], + } + typed_todo = { + "todo_id": "todo_typed_cjk", + "index": 1, + "status": "open", + "priority": "P1", + "task_class": "advancement_task", + "text": "[P1] 使用结构化引用验证目标路径", + "explore_result_node_refs": ["node_frontier_cjk"], + "target_key": "target_eval_loop", + "task_domain": "evaluation", + "required_capabilities": ["eval_runner"], + } + prose_only_todo = { + "todo_id": "todo_prose_only", + "index": 2, + "status": "open", + "priority": "P1", + "task_class": "advancement_task", + "text": "[P1] 验证中文探索分支与结构化匹配 frontier node_frontier_cjk", + } + + todo_plan = build_explore_todo_branch_plan( + goal_id="goal-typed-explore", + todos=[prose_only_todo, typed_todo], + projection=projection, + orchestration=ORCHESTRATION, + width=3, + ) + branches = {item["todo_id"]: item for item in todo_plan["selected_branches"]} + assert "explore_frontier_overlap" in branches["todo_typed_cjk"]["reason_codes"] + assert "explore_frontier_overlap" not in branches["todo_prose_only"]["reason_codes"] + assert branches["todo_typed_cjk"]["score"] > branches["todo_prose_only"]["score"] + + worker_plan = build_explore_worker_branch_plan( + goal_id="goal-typed-explore", + todos=[typed_todo, prose_only_todo], + projection=projection, + orchestration=ORCHESTRATION, + worker_width=3, + ) + selected = worker_plan["selected_worker_branches"] + assert any(branch["affinity_key"] == "capability:eval_runner" for branch in selected) + assert any(branch["affinity_key"] == "topic:general" for branch in selected)