From 1ae94dfb1fac1a460491aad520b8191ece093aeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E4=BA=9A=E9=B9=8F?= <1480083907@qq.com> Date: Wed, 25 Nov 2026 20:46:42 +0800 Subject: [PATCH] update --- app/modules/work_assistant/adaptive.py | 5 + app/modules/work_assistant/answers.py | 7 +- app/modules/work_assistant/calendar.py | 23 ++ app/modules/work_assistant/catalog_reads.py | 157 +++++++++++++ app/modules/work_assistant/decomposition.py | 1 + app/modules/work_assistant/goal_review.py | 1 + app/modules/work_assistant/orchestration.py | 79 ++++++- .../work_assistant/personnel_profile.py | 19 +- app/modules/work_assistant/protocol.py | 6 +- .../work_assistant/requirement_review.py | 6 +- .../work_assistant/review_commentary.py | 73 ++++-- app/modules/work_assistant/review_failure.py | 13 +- app/modules/work_assistant/routes.py | 6 + .../work_assistant/standalone_review.py | 3 +- tests/test_personnel_workflow.py | 8 +- tests/test_task_review_recovery.py | 73 ++++++ tests/test_work_assistant_catalog.py | 208 ++++++++++++++++++ 17 files changed, 633 insertions(+), 55 deletions(-) create mode 100644 app/modules/work_assistant/catalog_reads.py create mode 100644 tests/test_task_review_recovery.py create mode 100644 tests/test_work_assistant_catalog.py diff --git a/app/modules/work_assistant/adaptive.py b/app/modules/work_assistant/adaptive.py index 359c735..9cffec0 100644 --- a/app/modules/work_assistant/adaptive.py +++ b/app/modules/work_assistant/adaptive.py @@ -20,6 +20,11 @@ def continue_adaptive(payload): precise=precise_answer(payload) if precise is not None: return precise + if payload.question_spec.get("catalog_read"): + return ContinueDecision() + if all(item.status == "ok" and item.total == 0 for item in payload.evidence): + # A completed empty read supports a scoped no-records answer, without guessing why. + return ContinueDecision() records, allowed, partial = evidence_context(payload.evidence, resources=payload.resources, question=payload.message) from app.modules.work_assistant.answer_audit import add_calendar_facts add_calendar_facts(records, _today(payload).isoformat()) diff --git a/app/modules/work_assistant/answers.py b/app/modules/work_assistant/answers.py index 7b01cf7..77da084 100644 --- a/app/modules/work_assistant/answers.py +++ b/app/modules/work_assistant/answers.py @@ -132,10 +132,11 @@ def compose_verified_answer(payload: AnswerRequest, *, invoke_model=None) -> dic # Prefixing it again repeats a caveat already explained in context. rendered['verification'] = 'source_bound' return rendered - incomplete = bool(payload.investigation_note) + catalog_read = payload.question_spec.get("catalog_read", False) + incomplete = bool(payload.investigation_note) or any(item.status != "ok" for item in payload.evidence) # A failed synthesis must not trigger another model call just to display # records. Keep a short, clearly labelled partial result under outages. - selected = {} if incomplete else select_evidence(payload, invoke_model=invoke_model) + selected = {} if incomplete or catalog_read else select_evidence(payload, invoke_model=invoke_model) definitions = {item["id"]: item for item in payload.available_resources if "id" in item} blocks, citations, facts = [], [], [] if incomplete: @@ -151,7 +152,7 @@ def compose_verified_answer(payload: AnswerRequest, *, invoke_model=None) -> dic indexed = list(enumerate(payload.evidence)) indexed.sort(key=lambda pair: 0 if pair[1].purpose == "primary" else 1) for index, item in indexed: - if incomplete and len(item.rows) > 3: + if incomplete and not catalog_read and len(item.rows) > 3: item = item.model_copy(update={"rows": item.rows[:3]}) if item.query == "current-user": from app.modules.work_assistant.service import compose_answer diff --git a/app/modules/work_assistant/calendar.py b/app/modules/work_assistant/calendar.py index 759617c..e94fe00 100644 --- a/app/modules/work_assistant/calendar.py +++ b/app/modules/work_assistant/calendar.py @@ -5,6 +5,29 @@ import re from calendar import monthrange +_DAY = r"(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})日?" +_CLOSED_DATES = re.compile(rf"(? tuple[str, str] | None: + """Parse a complete date or a closed range, including Chinese date notation.""" + match = _CLOSED_DATES.fullmatch(text.strip()) + if not match: + return None + digits = match.groups() + try: + first = date(*map(int, digits[:3])) + last = date(*map(int, digits[3:])) if digits[3] else first + except ValueError: + return None + return (first.isoformat(), last.isoformat()) if first <= last else None + + +def single_explicit_date_span(text: str) -> str: + spans = list(_CLOSED_DATES.finditer(text)) + return spans[0].group() if len(spans) == 1 else "" + + def explicit_relative_period(message: str): """Canonical whole periods only; mixed ranges and specific weekdays stay explicit. diff --git a/app/modules/work_assistant/catalog_reads.py b/app/modules/work_assistant/catalog_reads.py new file mode 100644 index 0000000..f69b2b5 --- /dev/null +++ b/app/modules/work_assistant/catalog_reads.py @@ -0,0 +1,157 @@ +"""Resolve explicit catalog reads without asking a model to invent a query.""" +import re + +from pydantic import ValidationError + +from app.modules.work_assistant.calendar import calendar_context, explicit_date_bounds, explicit_relative_period, single_explicit_date_span +from app.modules.work_assistant.schemas import Plan, ResourceQuery + + +COUNT = r"(?:(?:一共|总共|总计)有?|共有|还有|有)?(?:多少|几)(?:条|项|个|件|份|场)?(?:记录)?" +LIST = r"(?:有哪些|有什么|列表|清单|有哪些记录)" + + +def catalog_read(payload, previous_spec): + """Only take over when the whole question identifies a read and its scope.""" + question = payload.message.strip().rstrip("??。!! ") + definitions = {item["id"]: item for item in payload.resources} + submission = _own_submission_count(question, definitions, payload.today) + if submission: + return Plan(resource_queries=[submission], reply_mode="count"), "new" + count_only = re.fullmatch(r"(?:那|所以)?(?:" + COUNT + r"|数量呢|总数呢)(?:呢|啊|呀)?", question) + period = explicit_relative_period(question) + period_only = period and re.fullmatch(r"(?:那|那么)?" + re.escape(period[1]) + r"(?:的)?(?:呢|啊|呀)?", question) + if count_only or period_only: + # A short follow-up needs a single successfully executed query to inherit. + if payload.dialogue_context.last_assistant_act not in {"answered", "empty"}: + return None + if previous_spec.get("question") != payload.dialogue_context.active_question: + return None + queries = previous_spec.get("primary_queries", []) + if (len(queries) != 1 or previous_spec.get("requested_assessments") or previous_spec.get("limitation") + or previous_spec.get("subject", {}).get("mode") == "record"): + return None + try: + query = ResourceQuery.model_validate(queries[0]) + except ValidationError: + return None + definition = definitions.get(query.resource, {}) + if (query.operation not in {"list", "count"} or query.record_id or query.analysis or query.include + or {"summary", "group_by", "sort_by", "sort_direction"} & query.filters.keys()): + return None + if count_only: + if "count" not in definition.get("operations", []): + return None + query.operation, query.fields, query.limit = "count", [], 1 + else: + dates = {key for key in query.filters if definition.get("filters", {}).get(key, {}).get("type") == "date"} + pairs = {tuple(pair) for pair in definition.get("time_bindings", {}).values() if len(pair) == 2 and set(pair) == dates} + if len(pairs) != 1 or query.operation not in definition.get("operations", []): + return None + if query.resource in {"tasks", "task-assignees"} and query.filters.get("status") in {"today", "week", "overdue"}: + return None + first, last = pairs.pop() + bounds = calendar_context(payload.today)[period[0]] + query.filters[first] = bounds if isinstance(bounds, str) else bounds["date_from"] + query.filters[last] = bounds if isinstance(bounds, str) else bounds["date_to"] + query.offset = 0 + return Plan(resource_queries=[query], reply_mode="count" if query.operation == "count" else "details"), "followup" + + clauses = re.split(r"\s*[,,;;??。]+\s*", question) + if len(clauses) > 4: + return None + queries = [_catalog_query(clause, payload, definitions) for clause in clauses] + if any(query is None for query in queries): + return None + if len({(q.resource, q.operation, tuple(q.filters.items())) for q in queries}) != len(queries): + return None + return Plan(resource_queries=queries, reply_mode="summary" if len(queries) > 1 else + "count" if queries[0].operation == "count" else "details"), "new" + + +def _catalog_query(question, payload, definitions): + # Use reviewed names here. Short aliases can imply extra conditions, such as 周例会. + text = re.sub(r"^(?:(?:请|帮我|再)?(?:查看|查询|查一下|列出)\s*)", "", question) + period = explicit_relative_period(text) + bounds = None + if period and text.startswith(period[1]): + text = text[len(period[1]):].removeprefix("的").strip() + bounds = calendar_context(payload.today)[period[0]] + elif span := single_explicit_date_span(text): + if text.startswith(span) and (dates := explicit_date_bounds(span)): + text = text[len(span):].removeprefix("的").strip() + bounds = dates[0] if dates[0] == dates[1] else {"date_from": dates[0], "date_to": dates[1]} + meeting = _meeting_agenda(text, bounds, definitions.get("meetings", {})) + if meeting: + return meeting + matches = [] + for definition in definitions.values(): + name = definition.get("name", "") + if not definition.get("operations") or len(name) < 2 or definition.get("parent_filter"): + continue + match = re.fullmatch(re.escape(name) + r"(?:里|中|的)?\s*(" + COUNT + "|" + LIST + ")", text) + if match: + matches.append((definition, "count" if re.fullmatch(COUNT, match[1]) else "list")) + if len(matches) != 1: + return None + definition, operation = matches[0] + if operation not in definition["operations"]: + return None + if any(re.search(rule["pattern"], question) for rule in definition.get("selection_conflicts", [])): + return None + # Task and approval reads default to this account. Menu readers use existing data scope. + scope = "mine" if definition["id"] in {"tasks", "approvals", "work-logs", "log-checks"} or definition.get("scope") == "personal" else "accessible" + if definition["id"] == "task-assignees" and not payload.allow_organization: + return None + filters = {} + if bounds: + bindings = definition.get("time_bindings", {}) + # An unqualified period can be read directly only with one date meaning. + # 日报的覆盖日期和提交日期 are distinct, for example. + if len(bindings) != 1: + return None + first, last = next(iter(bindings.values())) + if not all(definition.get("filters", {}).get(key, {}).get("type") == "date" for key in (first, last)): + return None + filters = {first: bounds if isinstance(bounds, str) else bounds["date_from"], + last: bounds if isinstance(bounds, str) else bounds["date_to"]} + return ResourceQuery(resource=definition["id"], operation=operation, scope=scope, + filters=filters, limit=1 if operation == "count" else 12) + + +def _own_submission_count(question, definitions, today): + definition = definitions.get("work-logs", {}) + if ("count" not in definition.get("operations", []) or + definition.get("time_bindings", {}).get("submitted") != ["submitted_from", "submitted_to"]): + return None + span = single_explicit_date_span(question) + bounds = explicit_date_bounds(span) + if not bounds: + period = explicit_relative_period(question) + value = calendar_context(today)[period[0]] if period else None + if not isinstance(value, str): + return None + span, bounds = period[1], (value, value) + match = re.fullmatch(r"(?:我|本人)(?:在)?" + re.escape(span) + + r"(?:实际)?(?:提交|上交|交)(?:了)?(?:多少|几)(?:份|篇|条)?(日报|周报)(?:记录)?" + r"(?:[??,,]\s*只按(?:实际)?提交(?:时间|日期)查)?", question) + if not match: + return None + kind = {"日报": "daily", "周报": "weekly"}[match[1]] + if kind not in definition.get("filters", {}).get("type", {}).get("values", {}): + return None + return ResourceQuery(resource="work-logs", operation="count", limit=1, + filters={"type": kind, "submitted_from": bounds[0], "submitted_to": bounds[1]}) + + +def _meeting_agenda(text, day, definition): + if (not isinstance(day, str) or "list" not in definition.get("operations", []) + or not definition.get("relations", {}).get("items") or "date" not in definition.get("filters", {})): + return None + match = re.fullmatch(r"(晨会|早会|晨夕会|周例会)(?:上)?(?:具体)?(?:安排了哪些(?:事|工作)|安排了什么(?:事|工作)?|有哪些(?:工作)?安排|讲了什么|讨论了什么)", text) + if not match: + return None + kind = "weekly" if match[1] == "周例会" else "daily" + if kind not in definition.get("filters", {}).get("type", {}).get("values", {}): + return None + return ResourceQuery(resource="meetings", scope="accessible", filters={"date": day, "type": kind}, include=["items"], limit=12) diff --git a/app/modules/work_assistant/decomposition.py b/app/modules/work_assistant/decomposition.py index 5c37edd..1c571f7 100644 --- a/app/modules/work_assistant/decomposition.py +++ b/app/modules/work_assistant/decomposition.py @@ -334,6 +334,7 @@ def review_decomposition(payload: ReviewRequest, *, invoke=None) -> dict: limitations = list(payload.limitations) if not model_ok: limitations.append(analysis_error['message']) + analysis_error = analysis_error or (commentary or {}).get("analysis_error") or requirements.get("analysis_error") return {"status": status, "summary": summary, "findings": findings, "limitations": limitations, "alignment": alignment, "workflow": workflow, "schedule": schedule, "model_completed": model_ok, "analysis_error": analysis_error, "requirements": requirements, diff --git a/app/modules/work_assistant/goal_review.py b/app/modules/work_assistant/goal_review.py index e2cb299..938f1a1 100644 --- a/app/modules/work_assistant/goal_review.py +++ b/app/modules/work_assistant/goal_review.py @@ -220,6 +220,7 @@ def review_goal(payload: GoalReviewRequest, *, invoke=None) -> dict: limitations = list(payload.limitations) if not model_ok: limitations.append(analysis_error['message']) + analysis_error = analysis_error or (commentary or {}).get("analysis_error") or requirements.get("analysis_error") return dict(status=status,summary=commentary.get("assessment", "本次具体评价未完成。") if commentary else "本次分析未完成。",review_kind="goal",goal_name=goal.name, goal_suggestions=suggestions,child_issues=issues,findings=findings,alignment=None,workflow=workflow, schedule=schedule,limitations=limitations,model_completed=model_ok,analysis_error=analysis_error, diff --git a/app/modules/work_assistant/orchestration.py b/app/modules/work_assistant/orchestration.py index 0d7d655..02a25a4 100644 --- a/app/modules/work_assistant/orchestration.py +++ b/app/modules/work_assistant/orchestration.py @@ -11,14 +11,14 @@ import logging import re import time from dataclasses import dataclass -from typing import Literal, TypedDict +from typing import Literal, TypedDict, get_args from langgraph.graph import END, START, StateGraph from langgraph.runtime import Runtime from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator from app.core.config import get_settings -from app.modules.work_assistant.calendar import calendar_context, explicit_relative_period +from app.modules.work_assistant.calendar import calendar_context, explicit_date_bounds, explicit_relative_period, single_explicit_date_span from app.modules.work_assistant.model_gateway import complete_json from app.modules.work_assistant.schemas import Plan, PlanRequest from app.modules.work_assistant.protocol import normalize_proposal @@ -111,6 +111,7 @@ class TurnRuntime: decision_mode: str = "" confirmed_spec: dict | None = None reference_model: object = None + catalog_read: bool = False class RecordReferenceVerdict(BaseModel): @@ -137,6 +138,40 @@ def check_record_reference(message, selected_name, invoke): return verdict +def _restore_explicit_period(patch, queries, definitions, message): + """Use literal date bounds if the model already bound them to the same business dates.""" + if patch.date_from and patch.date_to: + return + span = patch.time_evidence if patch.time_evidence in message and explicit_date_bounds(patch.time_evidence) else single_explicit_date_span(message) + bounds = explicit_date_bounds(span) + if not bounds or (patch.date_from and patch.date_from != bounds[0]) or (patch.date_to and patch.date_to != bounds[1]): + return + literal = re.escape(span) + if re.search(r"(?:截至|截止到|早于|晚于)\s*" + literal + r"|" + literal + r"\s*(?:之前|以前|之后|以后|以来|起|[至到~~—–])", message): + return + indices = patch.focus_queries or ([0] if len(queries) == 1 else []) + if not indices or any(index < 0 or index >= len(queries) for index in indices): + return + selected_bases = set() + for index in indices: + query = queries[index] + definition = definitions.get(query.resource, {}) + bindings = definition.get("time_bindings", {}) + matches = {basis for basis, pair in bindings.items() if tuple(query.filters.get(key) for key in pair) == bounds} + if (not matches and len(bindings) == 1 and bounds[0] == bounds[1] == query.filters.get("date") + and definition.get("filters", {}).get("date", {}).get("type") == "date"): + matches = set(bindings) + if patch.time_basis: + matches.intersection_update({patch.time_basis}) + if len(matches) != 1: + return + selected_bases.update(matches) + if len(selected_bases) == 1 and selected_bases <= set(get_args(FocusPatch.model_fields["time_basis"].annotation)): + patch.time_basis = selected_bases.pop() + patch.date_from, patch.date_to = bounds + patch.time_evidence = span + + INSTRUCTION = """你是公司工作助手的主决策者。先理解用户真正目的和上下文,再决定直接回答、读取业务资料或澄清。只能返回符合schema的JSON。 一、决定行动 @@ -192,6 +227,18 @@ focus与plan是同级成员,scope只放在每个resource_queries元素中。 def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: context = runtime.context payload = context.request + from app.modules.work_assistant.catalog_reads import catalog_read + direct = catalog_read(payload, context.previous_spec) + if direct: + plan, mode = direct + context.catalog_read = True + context.decision_mode = mode + resolved = (context.previous_spec["question"] if mode == "followup" and not explicit_relative_period(payload.message) + else payload.message) + return {"proposal": TurnProposal(intent="business", mode=mode, resolved_question=resolved, plan=plan).model_dump()} + if not get_settings().work_assistant_model_enabled: + return {"proposal": TurnProposal(mode="clarify", resolved_question=payload.message, + plan=Plan(clarification="智能问答模型当前未启用。", response_kind="clarification")).model_dump()} visible = {r["id"] for r in payload.resources} objects = [o for o in payload.context_objects if o.get("resource") in visible] from app.modules.work_assistant.module_skills import retrieve_descriptions, resource_index @@ -315,6 +362,8 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: if 0 <= index < len(candidate.plan.resource_queries): definition = definitions.get(candidate.plan.resource_queries[index].resource, {}) known_periods.update(definition.get("time_periods", {})) + if patch.period not in known_periods: + _restore_explicit_period(patch, candidate.plan.resource_queries, definitions, payload.message) if patch.period not in known_periods and not (patch.date_from and patch.date_to): errors.append({"location": ["focus", "period"], "type": "unknown_time_period", "allowed": sorted(known_periods), @@ -368,13 +417,18 @@ def _propose(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: if not set(values) <= set(allowed): errors.append({"location": location+[field], "type": "undeclared_query_member", "allowed": list(allowed)}) if "record_ids" in query.filters and "record_ids" in definition.get("filters",{}): + trusted={str(obj.get("id","")) for obj in objects if obj.get("resource")==query.resource} try: ids=json.loads(query.filters["record_ids"]) - trusted={str(obj.get("id","")) for obj in objects if obj.get("resource")==query.resource} valid=isinstance(ids,list) and 0 dict: logger.warning("Assistant proposal contract mismatch fields=%s", locations) if remaining < 2: raise ValueError("Query contract mismatch") - relevant = {q.get("resource") for q in raw.get("plan", {}).get("resource_queries", []) if isinstance(q,dict)} + raw_plan = raw.get("plan") + raw_queries = raw_plan.get("resource_queries") if isinstance(raw_plan, dict) else None + relevant = {q["resource"] for q in raw_queries if isinstance(q, dict) and isinstance(q.get("resource"), str)} if isinstance(raw_queries, list) else set() for error in locations: relevant.update(error.get('alternatives', [])) + if not relevant.intersection(visible): + relevant.update(resource["id"] for resource in selected_resources) repaired = invoke( INSTRUCTION + ANALYSIS_INSTRUCTIONS + "仅修复上一份规划的格式错误,保持用户原意和权限目录不变。按errors定位,不扩展查询范围。", {"question": payload.message, "proposal": raw, "errors": locations, @@ -553,7 +611,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: subject = _subject_from_object(patch.selected_source_id, payload) elif patch.subject_action == "clear": subject = {} - if subject.get('mode') == 'record' and context.reference_model: + if subject.get('mode') == 'record' and context.reference_model and not context.catalog_read: selected = next((obj for obj in payload.context_objects if obj.get('source_id') == subject.get('source_id')), {}) selected_name = str(selected.get('fields', {}).get('name') or selected.get('title') or '') parent = next((r for r in payload.resources if r['id'] == subject.get('resource')), {}) @@ -667,7 +725,8 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: continue if field not in query.filters and field in old[0].get("filters",{}): query.filters[field]=old[0]["filters"][field] - for index in patch.focus_queries: + # Catalog reads already carry the intended scope and predicates, including an exact count follow-up. + for index in (() if context.catalog_read else patch.focus_queries): if index < 0 or index >= len(plan.resource_queries): raise ValueError("查询对象尚未定位,请重试。") query = plan.resource_queries[index] @@ -806,7 +865,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: restored.fields = [] plan.resource_queries[index] = restored scope_notes.append('关联明细沿用刚才的上级记录范围;明细若分页,仅能就实际展示的记录列出符合条件的项,不能推断全部数量。') - if context.reference_model: + if context.reference_model and not context.catalog_read: for query in plan.resource_queries: definition = definitions.get(query.resource, {}) relations = definition.get('relations', {}) @@ -844,7 +903,7 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: pair = definition.get("time_bindings", {}).get(basis) if pair and all(key in query.filters for key in pair): period = {"date_from": str(query.filters[pair[0]]), "date_to": str(query.filters[pair[1]]), "basis": basis, "label": ""} - plan.routing = "model" + plan.routing = "rules" if context.catalog_read else "model" missing_rules = [] for reference in proposal.requested_assessments: definition = next((r for r in payload.resources if r["id"] == reference.resource), {}) @@ -871,6 +930,8 @@ def _compile(state: TurnState, runtime: Runtime[TurnRuntime]) -> dict: "requested_assessments": [reference.model_dump() for reference in proposal.requested_assessments], "query_time_scopes": {plan.resource_queries[index].query_id: value for index,value in query_time_scopes.items() if indexlimit: # Verification is already local to cited rows. Split the pending # assertions before narrowing a single row's reference context. - if stage=='verify' and not payload.get('adjudication') and verification_batch_size>1: - verification_batch_size=max(1,verification_batch_size//2) + if verification_rows>1: + verification_batch_size=verification_rows//2 remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections)) raise JobDeferred() nested='material' in payload and 'evidence_columns' in payload['material'] @@ -1293,10 +1300,10 @@ def review_profile(entry: ProfileRequest, *, invoke=complete_json, checkpoint=No # These pages are already below the bounded input limit. A # different upstream capacity must not reopen the same page forever. raise ModelUnavailable('profile_context_limit') from exc - if staged and stage=='verify' and not payload.get('adjudication') and verification_batch_size>1 and exc.reason in {'direct_output_truncated','gateway_output_truncated','direct_timeout','model_context_full','context_capacity'}: + if staged and verification_rows>1 and exc.reason in {'direct_output_truncated','gateway_output_truncated','direct_timeout','model_context_full','context_capacity'}: # A long verification response is a unit-size problem. Keep all # accepted rows and automatically retry a smaller pending batch. - verification_batch_size=max(1,verification_batch_size//2) + verification_batch_size=verification_rows//2 remember(last_checkpoint.get('candidate',raw),last_checkpoint.get('corrections',corrections),last_checkpoint.get('validation_feedback')) raise JobDeferred() from exc if staged and stage!='scan' and exc.reason in {'model_context_full','context_capacity'}: diff --git a/app/modules/work_assistant/protocol.py b/app/modules/work_assistant/protocol.py index da2329a..e9e743c 100644 --- a/app/modules/work_assistant/protocol.py +++ b/app/modules/work_assistant/protocol.py @@ -131,11 +131,15 @@ def normalize_proposal(raw: dict, resources: list[dict]) -> dict: del query[alias] if isinstance(query.get("filters"), dict): for name, value in list(query["filters"].items()): + codes = allowed_filters.get(name, {}).get("values", {}) if isinstance(value, bool): query["filters"][name] = "true" if value else "false" + elif isinstance(value, (str, int)) and str(value) not in codes: + matches = [key for key, label in codes.items() if label == str(value).strip()] + if len(matches) == 1: + query["filters"][name] = matches[0] elif isinstance(value,list) and value and all(isinstance(v,(str,int)) and not isinstance(v,bool) for v in value): values=[str(v) for v in value] - codes=allowed_filters.get(name,{}).get("values",{}) def code(v): candidates=[key for key,label in codes.items() if label==v] return candidates[0] if v not in codes and len(candidates)==1 else v diff --git a/app/modules/work_assistant/requirement_review.py b/app/modules/work_assistant/requirement_review.py index 8fc26a2..4bfa1ca 100644 --- a/app/modules/work_assistant/requirement_review.py +++ b/app/modules/work_assistant/requirement_review.py @@ -3,6 +3,7 @@ from typing import Literal from pydantic import BaseModel, ConfigDict, Field from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY +from .review_failure import review_failure class TaskEvidence(BaseModel): @@ -109,9 +110,10 @@ def review_requirements(subject, tasks, sources, *, invoke, timeout_seconds): for item in result["items"]: for proof in item["evidence"]: proof["task_name"] = tasks_by_id[proof["task_id"]].name - except Exception: + except Exception as exc: result["status"] = "incomplete" - result["message"] = "项目要求核对未完成,可重新分析。已核实的日期问题仍保留。" + result["analysis_error"] = review_failure(exc) + result["message"] = "项目要求核对未完成。已核实的日期问题仍保留。" for item in result["items"]: if item["status"] == "pending": item.update(status="unverified", reason="本次尚未完成核对。", suggestion="") diff --git a/app/modules/work_assistant/review_commentary.py b/app/modules/work_assistant/review_commentary.py index 8028e51..aa83183 100644 --- a/app/modules/work_assistant/review_commentary.py +++ b/app/modules/work_assistant/review_commentary.py @@ -1,9 +1,11 @@ """Task-specific explanations, grounded in the authorized review snapshot.""" import logging +import time from typing import Literal from pydantic import BaseModel, ConfigDict, Field, model_validator from .confidential_delivery import CONFIDENTIAL_DELIVERY_POLICY +from .review_failure import review_failure logger = logging.getLogger(__name__) @@ -145,6 +147,7 @@ def citation_schema(sources): def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow, alignment, findings, schedule, requirements, limitations, invoke, timeout_seconds, child_issues=None): + deadline = time.monotonic() + timeout_seconds try: if timeout_seconds < 1: raise TimeoutError() @@ -182,30 +185,52 @@ def review_commentary(*, subject, goal, tasks, sources, review_kind, workflow, if alignment and alignment['status'] == 'unrelated': schema['properties']['verdict']['enum'] = ['adjust'] instruction += '\n本次已根据原文核实:当前任务不属于所挂上级目标。即使任务自身描述清楚,也必须说明这项归属冲突并建议核对挂靠,不能给sound;不要把技术任务改写成另一种业务任务。' - result = Commentary.model_validate(invoke(instruction, data, schema, - timeout_seconds=min(18, timeout_seconds), max_tokens=3000)) available = {s['id']: s['text'] for s in data['sources']} - description = result.description_check - description_details = [description.work_scope, description.expected_result, description.completion_condition] - for citation in [*result.evidence, *(c for a in result.actions for c in a.evidence), - *(d.evidence for d in description_details if d)]: - source = available.get(citation.source_id) - if source is None or not citation.quote.strip() or citation.quote not in source: - raise ValueError("评价引用了未读取的依据") - if not any(c.source_id == f"task:{subject.id}" for c in result.evidence): - raise ValueError("缺少当前工作原文依据") - subject_actions = [a for a in result.actions if a.scope == "subject"] - if description.status == 'needs_detail' and (result.verdict == 'sound' or not subject_actions): - raise ValueError('任务要求不充分不能显示暂无调整建议') - if review_kind == 'task' and any(a.scope != 'subject' for a in result.actions): - raise ValueError("当前任务评价不得混入整体分工建议") - if result.verdict != "sound" and not (subject_actions if review_kind == 'task' else result.actions): - raise ValueError("当前工作评价不能由其他任务的缺口替代") - if result.verdict == "sound" and subject_actions: - raise ValueError("当前工作判断与修改意见不一致") - if alignment and alignment["status"] == "unrelated" and result.verdict != "adjust": - raise ValueError("评价与已核实的任务归属不一致") + + def evaluate(): + remaining = deadline - time.monotonic() + if remaining < 1: + raise TimeoutError() + raw = invoke(instruction, data, schema, timeout_seconds=min(30, remaining), max_tokens=3000) + return validate_commentary(raw, subject.id, available, review_kind, alignment) + + try: + result = evaluate() + except ValueError: + if deadline - time.monotonic() < 8: + raise + instruction += ( + '\n上一轮未通过核对。按结构完整重写,引用直接使用对应来源的候选原文,' + '至少一条引用来自当前任务,结论、描述充分性和整改意见必须一致。' + ) + result = evaluate() return dict(status="complete", **result.model_dump()) except Exception as exc: - logger.warning("review_commentary_incomplete error_type=%s", type(exc).__name__) - return dict(status="incomplete", message="本次具体评价未完成,请重新分析。已核实的依据仍可查看。") + failure = review_failure(exc) + logger.warning("review_commentary_incomplete reason=%s error_type=%s", failure["code"], type(exc).__name__) + return dict(status="incomplete", message=failure["message"], analysis_error=failure) + + +def validate_commentary(raw, subject_id, available, review_kind, alignment): + result = Commentary.model_validate(raw) + description = result.description_check + description_details = [description.work_scope, description.expected_result, description.completion_condition] + for citation in [*result.evidence, *(c for a in result.actions for c in a.evidence), + *(d.evidence for d in description_details if d)]: + source = available.get(citation.source_id) + if source is None or not citation.quote.strip() or citation.quote not in source: + raise ValueError("评价引用了未读取的依据") + if not any(c.source_id == f"task:{subject_id}" for c in result.evidence): + raise ValueError("缺少当前工作原文依据") + subject_actions = [a for a in result.actions if a.scope == "subject"] + if description.status == 'needs_detail' and (result.verdict == 'sound' or not subject_actions): + raise ValueError('任务要求不充分不能显示暂无调整建议') + if review_kind == 'task' and any(a.scope != 'subject' for a in result.actions): + raise ValueError("当前任务评价不得混入整体分工建议") + if result.verdict != "sound" and not (subject_actions if review_kind == 'task' else result.actions): + raise ValueError("当前工作评价不能由其他任务的缺口替代") + if result.verdict == "sound" and subject_actions: + raise ValueError("当前工作判断与修改意见不一致") + if alignment and alignment["status"] == "unrelated" and result.verdict != "adjust": + raise ValueError("评价与已核实的任务归属不一致") + return result diff --git a/app/modules/work_assistant/review_failure.py b/app/modules/work_assistant/review_failure.py index b7c91d8..a09c17e 100644 --- a/app/modules/work_assistant/review_failure.py +++ b/app/modules/work_assistant/review_failure.py @@ -2,14 +2,19 @@ def review_failure(exc): - if getattr(exc, 'reason', None) == 'model_account_unavailable': + reason = getattr(exc, 'reason', None) + if reason == 'model_account_unavailable': return { 'code': 'model_account_unavailable', - 'message': '模型服务账户暂不可用,请联系管理员检查账户余额及服务状态,恢复后重新分析。', + 'message': '模型服务账户暂不可用,请联系管理员检查账户余额及服务状态。', } - if isinstance(exc, TimeoutError) or getattr(exc, 'reason', None) in ('gateway_timeout', 'direct_timeout'): + if reason in ('queue_full', 'queue_timeout', 'circuit_open', 'review_continuation'): + return {'code': 'model_waiting', 'message': '模型服务暂忙,本轮未取得完整结果。'} + if isinstance(exc, TimeoutError) or reason in ('gateway_timeout', 'direct_timeout', 'direct_deadline'): return {'code': 'model_timeout', 'message': '模型核对超时,未生成完整建议。'} + if isinstance(exc, ValueError) or reason in ('direct_output_truncated', 'gateway_output_truncated'): + return {'code': 'model_output_invalid', 'message': '本轮分析未通过格式或原文核对。'} return { 'code': 'analysis_incomplete', - 'message': '本次分析未完成,请稍后重新分析;无需因此修改目标或任务描述。', + 'message': '本轮未取得完整的分析结果。', } diff --git a/app/modules/work_assistant/routes.py b/app/modules/work_assistant/routes.py index 836e15c..b11558a 100644 --- a/app/modules/work_assistant/routes.py +++ b/app/modules/work_assistant/routes.py @@ -308,17 +308,23 @@ def plan_review(payload: PlanReviewRequest) -> dict: @router.post("/goal-review") def goal_review(payload: GoalReviewRequest) -> dict: + token = background_review.set(True) try: return review_goal(payload) except ValueError: raise HTTPException(422, "目标检查的输入依据不完整或关联不一致") + finally: + background_review.reset(token) @router.post("/decomposition") def decomposition(payload: ReviewRequest) -> dict: + token = background_review.set(True) try: return review_decomposition(payload) except ValueError: raise HTTPException(422, "分解检查的输入依据不完整或关联不一致") + finally: + background_review.reset(token) @router.get("/skills") diff --git a/app/modules/work_assistant/standalone_review.py b/app/modules/work_assistant/standalone_review.py index 257bae3..509c49a 100644 --- a/app/modules/work_assistant/standalone_review.py +++ b/app/modules/work_assistant/standalone_review.py @@ -45,5 +45,6 @@ def review_standalone(payload, *, invoke): return dict(status=status, summary=commentary.get('assessment',commentary.get('message','')), review_kind='task', standalone=True, subject_name=task.name, findings=findings, alignment=None, workflow=[], schedule=schedule, commentary=commentary, requirements=requirements, - model_completed=complete, analysis_error=None, limitations=list(payload.limitations), + model_completed=complete, analysis_error=commentary.get('analysis_error') or requirements.get('analysis_error'), + limitations=list(payload.limitations), rule_version=GOAL_RULE, schema_version=SCHEMA_VERSION, sources=[s.model_dump(mode='json') for s in payload.sources]) diff --git a/tests/test_personnel_workflow.py b/tests/test_personnel_workflow.py index dd3a34c..88ec8d4 100644 --- a/tests/test_personnel_workflow.py +++ b/tests/test_personnel_workflow.py @@ -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 diff --git a/tests/test_task_review_recovery.py b/tests/test_task_review_recovery.py new file mode 100644 index 0000000..146e96b --- /dev/null +++ b/tests/test_task_review_recovery.py @@ -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" diff --git a/tests/test_work_assistant_catalog.py b/tests/test_work_assistant_catalog.py new file mode 100644 index 0000000..e97c8b4 --- /dev/null +++ b/tests/test_work_assistant_catalog.py @@ -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