代码提交

This commit is contained in:
董宏凯 committed 2026-08-03 19:27:54 +08:00
1 parent d93cc62806
commit ddf83f7728
25 files changed
+4086 -424

No files matched your search

@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
import json
import pytest
import pytest_asyncio
@@ -13,6 +14,8 @@ from app.maf_roundtable.conversation_service import MafConversationService
from app.maf_roundtable.dispatch_contracts import (
InvalidDispatchPlanError,
MafDispatchAssignment,
MafDispatchCandidateSet,
MafDispatchCatalog,
MafDispatchPlan,
MafIntentDecision,
resolve_intent,
@@ -23,7 +26,6 @@ from deerflow.persistence.maf_roundtable import make_maf_roundtable_store
from deerflow.persistence.maf_roundtable.model import (
MafRoundtableConversationRow,
MafRoundtableParticipantRow,
MafRoundtableRunRow,
MafRoundtableSessionRow,
)
@@ -132,8 +134,8 @@ async def test_server_route_creates_participants_and_dispatches(store):
.order_by(MafRoundtableParticipantRow.sort_order)
)
).scalars().all()
assert session_row.task_payload_json["maf_v2"]["dispatch_plan"]["manager_agent_id"] == "manager-from-config"
assert [p.agent_id for p in participants] == ["manager-from-config", "seat-a", "seat-b"]
assert session_row.task_payload_json["maf_v2"]["manager_agent_id"] == "manager-from-config"
assert [p.agent_id for p in participants] == ["manager-from-config"]
assert all(p.thread_id is None for p in participants)
events = (
@@ -146,15 +148,47 @@ async def test_server_route_creates_participants_and_dispatches(store):
assert events.active_run_id == run["id"]
@pytest.mark.asyncio
async def test_direct_answer_persists_manager_only_participants(store):
dispatcher = RecordingDispatcher()
svc = MafConversationService(store, maf_config=FakeMafConfig(), dispatcher=dispatcher)
conv = await svc.create_conversation(user_id="u1", title="Manager only")
await svc.send_message(
conversation_id=conv["id"],
user_id="u1",
content="给我一个普通的直接答案",
)
assert len(dispatcher.calls) == 1
session, _run, _owner = dispatcher.calls[0]
async with store.session_factory() as db:
participants = (
await db.execute(
select(MafRoundtableParticipantRow)
.where(MafRoundtableParticipantRow.session_id == session["id"])
.order_by(MafRoundtableParticipantRow.sort_order)
)
).scalars().all()
assert [participant.agent_id for participant in participants] == [
"manager-from-config"
]
maf_v2 = session["task_payload"]["maf_v2"]
assert maf_v2["manager_agent_id"] == "manager-from-config"
assert maf_v2["candidate_seat_agent_ids"] == ["seat-a", "seat-b"]
@pytest.mark.asyncio
async def test_clarification_does_not_create_or_dispatch_run(store):
"""Short / unclear content still creates a run — the manager workflow
is responsible for detecting clarification needs, not the send path."""
dispatcher = RecordingDispatcher()
svc = MafConversationService(store, maf_config=FakeMafConfig(), dispatcher=dispatcher)
conv = await svc.create_conversation(user_id="u1", title="Need detail")
result = await svc.send_message(conversation_id=conv["id"], user_id="u1", content="不清楚")
result = await svc.send_message(conversation_id=conv["id"], user_id="u1", content="请分析这个任务")
assert result["message_id"]
assert dispatcher.calls == []
assert len(dispatcher.calls) == 1
async with store.session_factory() as db:
conv_row = (
@@ -164,17 +198,8 @@ async def test_clarification_does_not_create_or_dispatch_run(store):
)
)
).scalars().one()
assert conv_row.safe_status == "waiting_input"
assert conv_row.active_run_id is None
runs = (
await db.execute(select(MafRoundtableRunRow))
).scalars().all()
assert runs == []
# A clarification reply is allowed to claim the idle waiting-input
# conversation and launch exactly one run.
await svc.send_message(conversation_id=conv["id"], user_id="u1", content="请分析这个任务")
assert len(dispatcher.calls) == 1
assert conv_row.safe_status == "running"
assert conv_row.active_run_id is not None
@pytest.mark.asyncio
@@ -228,7 +253,7 @@ async def test_workflow_projection_whitelists_user_visible_event_data(store):
},
},
)
events = await store.conversation_events.list_events(conv["id"], after_seq=3)
events = await store.conversation_events.list_events(conv["id"], after_seq=1)
tool = next(event for event in events if event["type"] == "tool.requested")
assert tool["data"] == {"tool_name": "safe_tool", "agent_id": "seat-a", "turn_index": 1}
complete = next(event for event in events if event["type"] == "agent.message.complete")
@@ -244,6 +269,21 @@ def test_intent_resolution_is_deterministic_and_does_not_select_agents():
assert resolve_intent("给我一个普通答案").intent_type == "direct_answer"
def test_new_conversation_candidate_set_has_no_keyword_intent_decision():
catalog = MafDispatchCatalog(FakeMafConfig())
candidate_set = catalog.build_candidate_set(task_context=None)
assert candidate_set == MafDispatchCandidateSet(
manager_agent_id="manager-from-config",
candidate_seat_agent_ids=["seat-a", "seat-b"],
mode="structured",
max_rounds=8,
)
# The request wording cannot change this server-owned candidate set;
# the manager JSON contract decides intent only after this point.
assert catalog.build_candidate_set(task_context=None) == candidate_set
def test_weak_model_cannot_expand_or_duplicate_dispatch_plan():
with pytest.raises(ValueError):
MafDispatchPlan(
@@ -263,6 +303,7 @@ def test_weak_model_cannot_expand_or_duplicate_dispatch_plan():
assignments=[MafDispatchAssignment(agent_id="seat-a", sort_order=1)],
intent_type="single_seat",
max_rounds=8,
execution_mode="single",
)
with pytest.raises(InvalidDispatchPlanError):
validate_dispatch_plan(plan, trusted_agent_ids={"manager", "seat-b"}, max_seats=4)
@@ -284,3 +325,113 @@ def test_clarification_plan_is_not_constructible():
confidence=0.9,
reason_code="needs_detail",
)
def test_server_dispatch_plan_selects_the_correct_topology():
catalog = MafDispatchCatalog(FakeMafConfig())
cases = [
("direct_answer", [], "manager_only"),
("single_seat", ["seat-a"], "single"),
("parallel_consultation", ["seat-a", "seat-b"], "parallel"),
("chain_consultation", ["seat-a", "seat-b"], "chain"),
("tool_write", ["seat-a"], "single"),
]
for intent_name, expected_seats, expected_mode in cases:
plan = catalog.build_plan(
intent=MafIntentDecision(
intent_type=intent_name,
confidence=1,
reason_code="test",
),
task_context=None,
)
assert plan.seat_agent_ids == expected_seats
assert plan.execution_mode == expected_mode
assert plan.candidate_seat_agent_ids == ["seat-a", "seat-b"]
single_plan = catalog.build_plan(
intent=MafIntentDecision(
intent_type="single_seat",
confidence=1,
reason_code="test",
),
task_context=None,
)
participant_ids = [item["agent_id"] for item in catalog.participants(single_plan)]
assert participant_ids == ["manager-from-config", "seat-a", "seat-b"]
def test_manager_decision_selects_intent_only_within_trusted_candidates():
candidate_set = MafDispatchCatalog(FakeMafConfig()).build_candidate_set(task_context=None)
proposed, plan = MafDispatchCatalog.parse_manager_decision(
json.dumps({
"intent_type": "direct_answer",
"selected_seat_agent_ids": [],
"assignments": [],
"execution_mode": "manager_only",
"convergence_path": ["manager answer"],
"reason": "manager can answer directly",
}),
candidate_set=candidate_set,
max_seats=4,
)
assert proposed.intent_type == "direct_answer"
assert plan is not None
assert plan.execution_mode == "manager_only"
assert plan.seat_agent_ids == []
def test_manager_plan_is_schema_checked_and_allowlisted():
catalog = MafDispatchCatalog(FakeMafConfig())
server_plan = catalog.build_plan(
intent=MafIntentDecision(
intent_type="parallel_consultation",
confidence=1,
reason_code="test",
),
task_context=None,
)
raw = json.dumps({
"intent_type": "parallel_consultation",
"selected_seat_agent_ids": ["seat-a", "seat-b"],
"assignments": [{
"agent_id": "seat-a",
"task_goal": "Collect the first evidence set",
"delivery_requirements": ["cite evidence"],
"order": 1,
}, {
"agent_id": "seat-b",
"task_goal": "Compare the two evidence sets",
"delivery_requirements": ["cite evidence"],
"order": 2,
}],
"execution_mode": "parallel",
"convergence_path": ["manager synthesis", "cross review", "final answer"],
"reason": "seat-b has the relevant capability",
})
final_plan = catalog.parse_manager_plan(
raw,
expected_intent="parallel_consultation",
server_plan=server_plan,
max_seats=4,
)
assert final_plan.seat_agent_ids == ["seat-a", "seat-b"]
assert final_plan.source == "manager"
for invalid in (
raw.replace('"seat-b"', '"untrusted-seat"'),
raw.replace('"selected_seat_agent_ids": ["seat-a", "seat-b"]', '"selected_seat_agent_ids": ["seat-b", "seat-b"]'),
raw.replace('"execution_mode": "parallel"', '"execution_mode": "single"'),
raw.replace('"delivery_requirements": ["cite evidence"]', '"delivery_requirements": []'),
raw.replace(
'"convergence_path": ["manager synthesis", "cross review", "final answer"]',
'"convergence_path": []',
),
):
with pytest.raises(InvalidDispatchPlanError):
catalog.parse_manager_plan(
invalid,
expected_intent="parallel_consultation",
server_plan=server_plan,
max_seats=4,
)