update
This commit is contained in:
@@ -26,9 +26,9 @@ def test_staged_report_makes_one_model_call_per_slice_and_resumes_every_group():
|
||||
assert len(operations)-before==1;continue
|
||||
break
|
||||
else:pytest.fail('workflow did not complete')
|
||||
assert operations==[name for name,_,_ in GROUPS]+['verify','verify']
|
||||
assert operations==[name for name,_,_ in GROUPS]+['verify']
|
||||
assert result['findings'][0]['finding']==raw['findings'][0]['finding']
|
||||
assert saved[-1]['workflow_steps']==6
|
||||
assert saved[-1]['workflow_steps']==5
|
||||
|
||||
|
||||
def test_incomplete_generation_cannot_be_saved_as_a_finished_unit():
|
||||
@@ -52,7 +52,7 @@ def test_broken_link_is_repaired_without_regenerating_completed_sections():
|
||||
except JobDeferred:continue
|
||||
break
|
||||
else:pytest.fail('link repair did not progress')
|
||||
assert calls==['repair','verify','verify']
|
||||
assert calls==['repair','verify']
|
||||
assert result['directions'][0]['activity_id']=='work'
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ def test_verification_automatically_shrinks_after_truncation_without_rechecking_
|
||||
except JobDeferred:continue
|
||||
break
|
||||
else:pytest.fail('adaptive verification did not complete')
|
||||
assert list(map(len,batches))==[4,2,2,1]
|
||||
assert list(map(len,batches))==[5,2,2,1]
|
||||
assert [key for batch in batches[1:] for key in batch]==list(profile.KEYS)
|
||||
assert saved[-1]['verification_batch_size']==2
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
from copy import deepcopy
|
||||
|
||||
from app.modules.work_assistant.decomposition import Source, Task
|
||||
from app.modules.work_assistant.goal_review import GoalReviewRequest, review_goal
|
||||
from app.modules.work_assistant.model_gateway import ModelUnavailable
|
||||
|
||||
|
||||
def standalone_task():
|
||||
task = Task(id=17, parent_id=0, name="提交财务核对清单",
|
||||
content="把本周财务核对清单交给财务负责人确认", assignee="23")
|
||||
source = Source(id="task:17", title=task.name, text=task.content)
|
||||
return GoalReviewRequest(goal=task, children=[], sources=[source], subject_kind="task")
|
||||
|
||||
|
||||
def valid_evaluation(payload):
|
||||
evidence = {"source_id": "task:17", "quote": payload.goal.content}
|
||||
detail = {"detail": "提交核对清单给财务负责人确认", "evidence": evidence}
|
||||
return {
|
||||
"description_check": {
|
||||
"status": "sufficient", "work_scope": detail, "expected_result": detail,
|
||||
"completion_condition": detail, "missing_details": [],
|
||||
},
|
||||
"understanding": "本项工作是提交本周的财务核对清单。",
|
||||
"assessment": "提交对象和确认要求已经明确。",
|
||||
"verdict": "sound",
|
||||
"evidence": [evidence],
|
||||
"actions": [],
|
||||
}
|
||||
|
||||
|
||||
def test_invalid_citation_is_corrected_before_finishing_the_review():
|
||||
payload = standalone_task()
|
||||
good = valid_evaluation(payload)
|
||||
bad = deepcopy(good)
|
||||
bad["evidence"][0]["quote"] = "不存在的原文"
|
||||
calls = []
|
||||
|
||||
def invoke(instruction, data, schema, **kwargs):
|
||||
assert data["phase"] == "review_commentary"
|
||||
calls.append(instruction)
|
||||
return bad if len(calls) == 1 else good
|
||||
|
||||
result = review_goal(payload, invoke=invoke)
|
||||
assert len(calls) == 2 and "上一轮未通过核对" in calls[1]
|
||||
assert result["model_completed"] is True
|
||||
assert result["commentary"]["evidence"] == good["evidence"]
|
||||
assert result["analysis_error"] is None
|
||||
|
||||
|
||||
def test_repeated_invalid_evidence_keeps_review_incomplete():
|
||||
payload = standalone_task()
|
||||
bad = valid_evaluation(payload)
|
||||
bad["evidence"][0]["quote"] = "不存在的原文"
|
||||
|
||||
result = review_goal(payload, invoke=lambda *_args, **_kwargs: bad)
|
||||
|
||||
assert result["model_completed"] is False
|
||||
assert result["commentary"]["status"] == "incomplete"
|
||||
assert result["analysis_error"]["code"] == "model_output_invalid"
|
||||
|
||||
|
||||
def test_busy_model_is_reported_to_the_background_scheduler_without_inline_retry():
|
||||
calls = []
|
||||
|
||||
def invoke(*_args, **_kwargs):
|
||||
calls.append(True)
|
||||
raise ModelUnavailable("queue_timeout")
|
||||
|
||||
result = review_goal(standalone_task(), invoke=invoke)
|
||||
|
||||
assert len(calls) == 1
|
||||
assert result["model_completed"] is False
|
||||
assert result["analysis_error"]["code"] == "model_waiting"
|
||||
@@ -0,0 +1,208 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.work_assistant import orchestration
|
||||
from app.modules.work_assistant.adaptive import continue_adaptive
|
||||
from app.modules.work_assistant.answers import compose_verified_answer
|
||||
from app.modules.work_assistant.protocol import normalize_proposal
|
||||
from app.modules.work_assistant.schemas import AnswerRequest, ContinueRequest, PlanRequest
|
||||
|
||||
|
||||
RESOURCES = [
|
||||
{"id": "meetings", "name": "会议记录", "scope": "module", "operations": ["list", "count"],
|
||||
"aliases": ["晨会", "周例会"], "fields": {"name": "会议名称"}, "relations": {},
|
||||
"time_bindings": {"recorded": ["date_from", "date_to"]},
|
||||
"filters": {"type": {"values": {"daily": "晨夕会", "weekly": "周例会"}},
|
||||
"date_from": {"type": "date"}, "date_to": {"type": "date"}}},
|
||||
{"id": "tasks", "name": "新任务", "scope": "assistant", "operations": ["list", "count"],
|
||||
"fields": {"name": "任务名称"}, "relations": {},
|
||||
"filters": {"status": {"values": {"today": "今日到期及计划", "overdue": "逾期未完成"}}}},
|
||||
{"id": "menu-expense", "name": "报销请款", "scope": "module", "operations": ["list", "count"],
|
||||
"fields": {"name": "报销事项"}, "relations": {},
|
||||
"filters": {"status": {"values": {"done": "已通过", "open": "待审核"}}}},
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def planner_settings(monkeypatch):
|
||||
settings = SimpleNamespace(work_assistant_model_enabled=True, work_assistant_planner_timeout_seconds=20)
|
||||
monkeypatch.setattr(orchestration, "get_settings", lambda: settings)
|
||||
return settings
|
||||
|
||||
|
||||
def request(question, **kwargs):
|
||||
return PlanRequest(message=question, allowed_skills=[], protocol_version=2,
|
||||
today="2026-11-25", resources=kwargs.pop("resources", RESOURCES), **kwargs)
|
||||
|
||||
|
||||
def no_model(*args, **kwargs):
|
||||
pytest.fail("A verified catalog read called the model")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("question", "resource", "operation", "scope"), [
|
||||
("会议记录有哪些?", "meetings", "list", "accessible"),
|
||||
("报销请款里一共有多少条记录?", "menu-expense", "count", "accessible"),
|
||||
("帮我列出新任务清单。", "tasks", "list", "mine"),
|
||||
])
|
||||
def test_reviewed_catalog_reads_work_without_model(question, resource, operation, scope, planner_settings):
|
||||
planner_settings.work_assistant_model_enabled = False
|
||||
plan = orchestration.plan_turn(request(question), invoke_model=no_model)
|
||||
assert plan.routing == "rules" and plan.question_spec["catalog_read"] and not plan.clarification
|
||||
assert [(q.resource, q.operation, q.scope) for q in plan.resource_queries] == [(resource, operation, scope)]
|
||||
|
||||
|
||||
def test_followup_count_rereads_exact_latest_query():
|
||||
active = "我今天有哪些任务要处理?"
|
||||
spec = {"question": active, "primary_queries": [{"resource": "tasks", "scope": "mine",
|
||||
"operation": "list", "filters": {"status": "today"}, "fields": ["name"], "offset": 8}]}
|
||||
context = {"active_question": active, "last_assistant_act": "answered", "question_spec": spec}
|
||||
plan = orchestration.plan_turn(request("那一共多少项?", dialogue_context=context), invoke_model=no_model)
|
||||
query, = plan.resource_queries
|
||||
assert plan.dialogue_mode == "followup"
|
||||
assert (query.operation, query.offset, query.scope, query.filters) == ("count", 0, "mine", {"status": "today"})
|
||||
|
||||
|
||||
def test_period_only_followup_keeps_original_conditions_and_date_basis():
|
||||
active = "本月晨会一共有多少场?"
|
||||
spec = {"question": active, "primary_queries": [{"resource": "meetings", "scope": "accessible",
|
||||
"operation": "count", "filters": {"type": "daily", "date_from": "2026-11-01", "date_to": "2026-11-30"}}]}
|
||||
context = {"active_question": active, "last_assistant_act": "answered", "question_spec": spec}
|
||||
result = orchestration.plan_turn(request("那去年的呢?", dialogue_context=context), invoke_model=no_model)
|
||||
query, = result.resource_queries
|
||||
assert result.dialogue_mode == "followup" and result.resolved_question == "那去年的呢?"
|
||||
assert (query.operation, query.scope, query.filters) == (
|
||||
"count", "accessible", {"type": "daily", "date_from": "2025-01-01", "date_to": "2025-12-31"})
|
||||
|
||||
|
||||
def test_catalog_uses_declared_date_basis():
|
||||
plan = orchestration.plan_turn(request("上周的会议记录有多少场?"), invoke_model=no_model)
|
||||
query, = plan.resource_queries
|
||||
assert query.operation == "count" and query.filters == {"date_from": "2026-11-16", "date_to": "2026-11-22"}
|
||||
|
||||
|
||||
def test_read_meeting_agenda_uses_typed_items_on_exact_day():
|
||||
meeting = {**RESOURCES[0], "filters": {**RESOURCES[0]["filters"], "date": {"type": "date"}},
|
||||
"relations": {"items": {"target": "meeting-items"}}}
|
||||
result = orchestration.plan_turn(request("2026年11月25日晨会具体安排了哪些工作?", resources=[meeting]), invoke_model=no_model)
|
||||
query, = result.resource_queries
|
||||
assert (query.resource, query.include, query.filters) == ("meetings", ["items"], {"date": "2026-11-25", "type": "daily"})
|
||||
|
||||
|
||||
def test_submission_count_uses_authenticated_actor_and_actual_submission_date():
|
||||
log = {"id": "work-logs", "name": "日志提交记录", "operations": ["count"],
|
||||
"filters": {"type": {"values": {"daily": "日报", "weekly": "周报"}},
|
||||
"submitted_from": {"type": "date"}, "submitted_to": {"type": "date"}},
|
||||
"time_bindings": {"submitted": ["submitted_from", "submitted_to"]}}
|
||||
result = orchestration.plan_turn(request("我在2026年11月25日实际提交了几份日报?只按提交时间查。", resources=[log]), invoke_model=no_model)
|
||||
query, = result.resource_queries
|
||||
assert (query.operation, query.scope, query.filters) == (
|
||||
"count", "mine", {"type": "daily", "submitted_from": "2026-11-25", "submitted_to": "2026-11-25"})
|
||||
|
||||
|
||||
def test_catalog_keeps_dates_separate_for_two_explicit_reads():
|
||||
plan = orchestration.plan_turn(request("上周的会议记录有多少场?再查一下报销请款列表。"), invoke_model=no_model)
|
||||
assert [(q.resource, q.operation, q.filters) for q in plan.resource_queries] == [
|
||||
("meetings", "count", {"date_from": "2026-11-16", "date_to": "2026-11-22"}),
|
||||
("menu-expense", "list", {}),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("question", ["周例会有哪些?", "我们部门的报销请款有哪些?",
|
||||
"今天报销请款有多少条?", "会议记录有哪些,顺便查一下报销?"])
|
||||
def test_catalog_does_not_drop_qualifiers(question, planner_settings):
|
||||
planner_settings.work_assistant_model_enabled = False
|
||||
assert not orchestration.plan_turn(request(question), invoke_model=no_model).resource_queries
|
||||
|
||||
|
||||
def test_absent_or_ambiguous_resources_do_not_become_direct_queries(planner_settings):
|
||||
planner_settings.work_assistant_model_enabled = False
|
||||
same_name = [{**RESOURCES[0], "id": "menu-meetings"}, RESOURCES[0]]
|
||||
for visible in (same_name, RESOURCES[1:]):
|
||||
plan = orchestration.plan_turn(request("会议记录有哪些?", resources=visible), invoke_model=no_model)
|
||||
assert not plan.resource_queries
|
||||
|
||||
|
||||
def test_unknown_condition_is_repaired_without_dropping_other_queries():
|
||||
attempts = []
|
||||
|
||||
def model(instruction, content, schema, **kwargs):
|
||||
attempts.append(content)
|
||||
if len(attempts) == 2:
|
||||
assert content["errors"][0]["type"] == "unknown_filter_value"
|
||||
return {"intent": "business", "plan": {"resource_queries": [
|
||||
{"resource": "tasks", "operation": "count", "filters": {"status": "逾期未完成"}},
|
||||
{"resource": "menu-expense", "operation": "count", "filters": {"status": "待审核" if len(attempts) == 2 else "pending"}},
|
||||
]}}
|
||||
|
||||
plan = orchestration.plan_turn(request("我的逾期任务和待审核报销各有多少?"), invoke_model=model)
|
||||
assert len(attempts) == 2 and not plan.clarification
|
||||
assert [(q.resource, q.filters) for q in plan.resource_queries] == [
|
||||
("tasks", {"status": "overdue"}), ("menu-expense", {"status": "open"})]
|
||||
|
||||
|
||||
def test_ambiguous_enum_labels_and_business_names_are_preserved():
|
||||
resource = {"id": "records", "filters": {"name": {}, "status": {"values": {"A": "处理", "B": "处理"}}}}
|
||||
query = {"resource": "records", "filters": {"name": "处理", "status": "处理"}}
|
||||
assert normalize_proposal({"plan": {"resource_queries": [query]}}, [resource])["plan"]["resource_queries"] == [query]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("date_value", "evidence"), [
|
||||
("2026年11月25日", "2026年11月25日"), ("2026-11-25", "2026-11-25"), ("2026/11/25", "2026/11/25"),
|
||||
("2026年11月25日", "2026-11-25"), ("2026年11月25日", "2026年11月25日我实际交了"), ("2026年11月25日", ""),
|
||||
])
|
||||
def test_existing_read_conditions_supply_missing_explicit_focus_dates(date_value, evidence):
|
||||
log = {"id": "work-logs", "name": "日志提交记录", "scope": "assistant", "operations": ["count"],
|
||||
"fields": {}, "filters": {key: {"type": "date"} for key in ("date_from", "date_to", "submitted_from", "submitted_to")},
|
||||
"time_bindings": {"reported": ["date_from", "date_to"], "submitted": ["submitted_from", "submitted_to"]}}
|
||||
calls = []
|
||||
|
||||
def provider(*args, **kwargs):
|
||||
calls.append(1)
|
||||
return {"intent": "business", "focus": {"subject_action": "self", "time_action": "set", "time_evidence": evidence},
|
||||
"plan": {"resource_queries": [{"resource": "work-logs", "operation": "count",
|
||||
"filters": {"submitted_from": "2026-11-25", "submitted_to": "2026-11-25"}}]}}
|
||||
|
||||
planned = orchestration.plan_turn(request(f"{date_value}我实际交了几份?", resources=[log]), invoke_model=provider)
|
||||
query, = planned.resource_queries
|
||||
assert len(calls) == 1 and query.filters == {"submitted_from": "2026-11-25", "submitted_to": "2026-11-25"}
|
||||
assert planned.question_spec["period"]["basis"] == "submitted"
|
||||
|
||||
|
||||
def test_explicit_time_recovery_requires_matching_dates_and_literal_scope():
|
||||
from app.modules.work_assistant.schemas import ResourceQuery
|
||||
|
||||
literal = "2026年11月25日"
|
||||
patch = orchestration.FocusPatch(time_action="set", time_evidence=literal)
|
||||
query = ResourceQuery(resource="meetings", filters={"date_from": "2026-11-24", "date_to": "2026-11-24"})
|
||||
orchestration._restore_explicit_period(patch, [query], {"meetings": RESOURCES[0]}, literal)
|
||||
assert not patch.date_from
|
||||
query.filters = {"date_from": "2026-11-25", "date_to": "2026-11-25"}
|
||||
orchestration._restore_explicit_period(patch, [query], {"meetings": RESOURCES[0]}, literal + "以前的会议")
|
||||
assert not patch.date_from
|
||||
|
||||
|
||||
def test_known_list_and_partial_multiquery_show_records_without_model(monkeypatch):
|
||||
monkeypatch.setattr("app.modules.work_assistant.investigation.complete_json", no_model)
|
||||
good = {"query": "resource:meetings", "title": "会议记录", "resource": "meetings", "status": "ok",
|
||||
"total": 1, "fields": {"name": "会议名称"}, "rows": [{"id": "22", "name": "测试会议"}]}
|
||||
decision = continue_adaptive(ContinueRequest(**request("会议记录有哪些?").model_dump(),
|
||||
evidence=[good], question_spec={"catalog_read": True}))
|
||||
assert not decision.answer and not decision.resource_queries and not decision.note
|
||||
common = dict(message="会议记录有哪些?", skill_ids=[], scope_label="账号可见范围", data_time="2026-11-25",
|
||||
available_resources=RESOURCES, protocol_version=2)
|
||||
reply = compose_verified_answer(AnswerRequest(**common, question_spec={"catalog_read": True}, evidence=[good]),
|
||||
invoke_model=no_model)
|
||||
assert reply["answer_status"] == "complete" and reply["source_ids"] == ["meetings:22"]
|
||||
failed = {"query": "resource:menu-expense", "title": "报销请款", "resource": "menu-expense", "status": "error",
|
||||
"note": "请确认涉及哪位申请人。"}
|
||||
partial = compose_verified_answer(AnswerRequest(**common, evidence=[good, failed]), invoke_model=no_model)
|
||||
assert partial["answer_status"] == "partial" and partial["source_ids"] == ["meetings:22"]
|
||||
assert "测试会议" in partial["answer"] and "哪位申请人" in partial["answer"] and "共 0 项" not in partial["answer"]
|
||||
|
||||
|
||||
def test_empty_success_does_not_invoke_synthesis(monkeypatch):
|
||||
monkeypatch.setattr("app.modules.work_assistant.investigation.complete_json", no_model)
|
||||
evidence = {"query": "resource:meetings", "resource": "meetings", "title": "会议记录", "status": "ok", "total": 0, "rows": []}
|
||||
decision = continue_adaptive(ContinueRequest(**request("星河楼会谈有什么安排?").model_dump(), evidence=[evidence]))
|
||||
assert not decision.answer and not decision.resource_queries and not decision.note
|
||||
Reference in New Issue
Block a user