import { describe, expect, it } from "vitest"; import { applyAssistantMcpDiscoveryResponsePolicy } from "../src/services/assistantMcpDiscoveryResponsePolicy"; function entryPoint(overrides: Record = {}) { return { schema_version: "assistant_mcp_discovery_runtime_entry_point_v1", policy_owner: "assistantMcpDiscoveryRuntimeEntryPoint", entry_status: "bridge_executed", hot_runtime_wired: false, discovery_attempted: true, turn_input: { adapter_status: "ready" }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Confirmed scoped answer.", confirmed_lines: ["Confirmed fact"], inference_lines: ["Bounded inference"], unknown_lines: ["Unconfirmed fact"], limitation_lines: ["Limited source window"], next_step_line: null } }, reason_codes: ["runtime_entry_point_bridge_executed"], ...overrides } as any; } describe("assistant MCP discovery response policy", () => { it("applies a guarded candidate only for unsupported current-turn boundary replies", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "route is not wired", currentReplySource: "deterministic_unsupported_current_turn_boundary", modeDecisionReason: "unsupported_current_turn_meaning_boundary", addressRuntimeMeta: { mcpDiscoveryRuntimeEntryPoint: entryPoint() } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("Confirmed fact"); expect(result.reply_text).not.toContain("query_documents"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_candidate_applied"); }); it("removes routine short-answer prefix from applied guarded candidates", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "route is not wired", currentReplySource: "deterministic_unsupported_current_turn_boundary", modeDecisionReason: "unsupported_current_turn_meaning_boundary", addressRuntimeMeta: { mcpDiscoveryRuntimeEntryPoint: entryPoint({ bridge: { bridge_status: "answer_draft_ready", hot_runtime_wired: true, user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Коротко: Confirmed scoped answer.", confirmed_lines: ["Коротко: Confirmed fact"], inference_lines: [], unknown_lines: [], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.reply_text).toContain("Confirmed scoped answer."); expect(result.reply_text).not.toContain("Коротко:"); }); it("keeps current organization clarification over a checked-sources value-flow candidate", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Нужно уточнить организацию, чтобы не смешивать компании в одном ответе.\nСейчас в доступном контуре вижу такие организации:\n- ООО Альтернатива Плюс\n- ООО Ромашка", currentReplySource: "address_query_runtime_v1", currentReplyType: "partial_coverage", addressRuntimeMeta: { truth_mode: "clarification_required", answer_shape: "clarification_required", answer_shape_contract: { answer_shape: "clarification_required", reply_type: "partial_coverage" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: [], clarification_gaps: ["organization"], reason_codes: ["data_need_graph_open_scope_total_needs_organization"] } }, bridge: { bridge_status: "checked_sources_only", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "checked_sources_only", headline: "В проверенном срезе 1С входящих денежных поступлений не найдено.", confirmed_lines: ["В проверенном срезе 1С входящих денежных поступлений не найдено."], inference_lines: [], unknown_lines: [], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(false); expect(result.reply_text).toContain("Нужно уточнить организацию"); expect(result.reply_text).toContain("ООО Альтернатива Плюс"); expect(result.reply_text).not.toContain("не найдено"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_current_clarification_required_reply"); }); it("applies a grounded movement candidate over a stale inventory item clarification", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Need an item before I can continue.", currentReplySource: "address_query_runtime_v1", currentReplyType: "partial_coverage", addressRuntimeMeta: { truth_mode: "clarification_required", answer_shape: "clarification_required", answer_shape_contract: { answer_shape: "clarification_required", reply_type: "partial_coverage", capability_contract_id: "inventory_inventory_purchase_documents_for_item" }, detected_intent: "inventory_purchase_documents_for_item", selected_recipe: "address_inventory_purchase_documents_for_item_v1", capability_id: "inventory_inventory_purchase_documents_for_item", missing_required_filters: ["item"], assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "movements", asked_action_family: "list_movements", explicit_date_scope: "2020" }, data_need_graph: { business_fact_family: "movement_evidence", action_family: "list_movements" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, route_candidate: { selected_chain_id: "movement_evidence" }, pilot: { selected_chain_id: "movement_evidence", mcp_execution_performed: true }, execution_handoff: { mcp_execution_performed: true, can_use_guarded_response: false }, answer_draft: { answer_mode: "bounded_inference_only", headline: "Movement evidence for Group SVK in 2020 is bounded.", confirmed_lines: ["No confirmed movement rows were found in the checked 2020 window."], inference_lines: [], unknown_lines: [], limitation_lines: ["Full movement coverage outside the checked window is not confirmed."], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.reply_text).toContain("Movement evidence for Group SVK in 2020 is bounded."); expect(result.reply_text).not.toContain("Need an item"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_grounded_movement_candidate_priority_over_inventory_item_clarification" ); expect(result.reason_codes).toContain("mcp_discovery_response_policy_candidate_applied"); }); it("keeps the current reply when the turn is not an unsupported boundary", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "regular chat", currentReplySource: "llm_chat", modeDecisionReason: "living_chat_signal_detected", addressRuntimeMeta: { mcpDiscoveryRuntimeEntryPoint: entryPoint() } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toBe("regular chat"); expect(result.reply_source).toBe("llm_chat"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_not_unsupported_boundary"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_not_discovery_ready_chat_candidate"); }); it("applies a guarded candidate for discovery-ready llm chat business answers", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "stale llm business answer", currentReplySource: "llm_chat", modeDecisionReason: "non_domain_query_indexed", addressRuntimeMeta: { mcpDiscoveryRuntimeEntryPoint: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("Confirmed fact"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_not_unsupported_boundary"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_not_discovery_ready_chat_candidate"); }); it("applies a guarded candidate for discovery-ready deep partial answers", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "wrong deep partial answer", currentReplySource: "deep_analysis", addressRuntimeMeta: { mcpDiscoveryRuntimeEntryPoint: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true } }) } }); expect(result.applied).toBe(true); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("Confirmed fact"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_not_discovery_ready_deep_candidate"); }); it("applies a guarded candidate for discovery-ready address lane answers", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "stale exact route answer", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "list_documents_by_counterparty", assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "payout" } } }) } }); expect(result.applied).toBe(true); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("Confirmed fact"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_not_discovery_ready_address_candidate"); }); it("keeps inventory margin-ranking exact reply over stale value-flow discovery candidate", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "За период 2017 рейтинг прибыльности номенклатуры построить нельзя: нет подтвержденной себестоимости реализации.", currentReplySource: "address_query_runtime_v1", currentReplyType: "partial_coverage", addressRuntimeMeta: { detected_intent: "inventory_margin_ranking_for_nomenclature", selected_recipe: "address_inventory_margin_ranking_for_nomenclature_v1", capability_id: "inventory_inventory_margin_ranking_for_nomenclature", assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover" }, data_need_graph: { business_fact_family: "value_flow", clarification_gaps: [] } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("рейтинг прибыльности номенклатуры"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_inventory_margin_ranking_address_reply" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_candidate_applied"); }); it("lets a grounded business overview candidate override a semantically wrong exact address recipe", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Supplier and stock overlap was confirmed for 2020.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "inventory_supplier_stock_overlap_as_of_date", selected_recipe: "address_inventory_supplier_stock_overlap_as_of_date_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "inventory_inventory_supplier_stock_overlap_as_of_date" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "business_summary", asked_action_family: "broad_evaluation", unsupported_but_understood_family: "broad_business_evaluation", explicit_organization_scope: "OOO Alternative Plus", explicit_date_scope: "2020" }, data_need_graph: { business_fact_family: "business_overview", clarification_gaps: [] } }, bridge: { bridge_status: "answer_draft_ready", hot_runtime_wired: true, user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Business overview was assembled from confirmed 1C evidence.", confirmed_lines: [ "Incoming customer money flow: 200000.00 RUB.", "Outgoing supplier payouts: 150000.00 RUB." ], inference_lines: ["Net confirmed cash-flow spread is +50000.00 RUB; this is not profit."], unknown_lines: ["Profit and formal margin are not confirmed by this overview."], limitation_lines: ["The overview is limited to checked 1C rows."], next_step_line: "Check profit, VAT, debt quality, and inventory liquidity next." } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("Business overview"); expect(result.reply_text).toContain("Incoming customer money flow"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); }); it("overrides exact inbound value-flow replies when the discovery turn meaning asks for payouts", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Incoming turnover by SVK: 12 224 925.00 rub.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", selected_recipe: "address_customer_revenue_and_payments_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "payout", explicit_entity_candidates: ["SVK"], explicit_date_scope: "2020" } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_value_flow_action_conflict_allows_candidate_override" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); }); it("overrides exact document replies when the discovery turn asks for movements", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Documents for SVK: invoice 1, act 2.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "list_documents_by_counterparty", selected_recipe: "address_list_documents_by_counterparty_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "address_list_documents_by_counterparty" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "movements", asked_action_family: "list_movements", explicit_entity_candidates: ["SVK"], explicit_date_scope: "2020" } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_text).toContain("Confirmed fact"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_evidence_lane_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); }); it("uses a movement clarification candidate over a stale inventory-item clarification", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Need item before I can continue.", currentReplySource: "address_query_runtime_v1", currentReplyType: "partial_coverage", addressRuntimeMeta: { detected_intent: "inventory_purchase_documents_for_item", selected_recipe: "address_inventory_purchase_documents_for_item_v1", capability_id: "inventory_inventory_purchase_documents_for_item", truth_mode: "clarification_required", answer_shape: "clarification_required", missing_required_filters: ["item"], answer_shape_contract: { answer_shape: "clarification_required", reply_type: "partial_coverage", capability_contract_id: "inventory_inventory_purchase_documents_for_item" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "movements", asked_action_family: "list_movements", explicit_entity_candidates: ["Group SVK"], unsupported_but_understood_family: "movement_evidence" }, data_need_graph: { business_fact_family: "movement_evidence", action_family: "list_movements", clarification_gaps: ["period"] } }, bridge: { bridge_status: "needs_clarification", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "needs_clarification", headline: "I can continue by movements for Group SVK, but I need a period.", confirmed_lines: [], inference_lines: [], unknown_lines: ["The period is required before searching movements."], limitation_lines: [], next_step_line: "Specify the period and I will search movements for Group SVK." } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_text).toContain("movements for Group SVK"); expect(result.reply_text).not.toContain("Need item"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_clarification_candidate_priority_over_stale_address_clarification" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_current_clarification_required_reply"); }); it("overrides exact document-list replies for explicit counterparty received-paid-net questions", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Контрагент: Группа СВК. Найдено документов: 19.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "list_documents_by_counterparty", selected_recipe: "address_documents_by_counterparty_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "documents_drilldown" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: ["Группа СВК"], reason_codes: ["data_need_graph_built", "data_need_graph_bidirectional_value_flow"] }, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "net_value_flow", explicit_entity_candidates: ["Группа СВК"], unsupported_but_understood_family: "counterparty_bidirectional_value_flow_or_netting" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Группа СВК: получили 20 653 490 руб., заплатили 2 129 651 руб.; нетто 18 523 839 руб. в нашу сторону.", confirmed_lines: ["получили 20 653 490 руб.; заплатили 2 129 651 руб.; нетто 18 523 839 руб."], inference_lines: [], unknown_lines: [], limitation_lines: ["Это денежный срез, не бухгалтерская прибыль."], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("20 653 490"); expect(result.reply_text).toContain("2 129 651"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_value_flow_action_conflict_allows_candidate_override"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_document_list_address_reply"); }); it("keeps exact matched inventory address replies over stale metadata discovery candidates", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "По товару Шкаф картотечный 1000*400*2100 цепочка поставки и продажи подтверждена.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "inventory_purchase_to_sale_chain", selected_recipe: "address_inventory_purchase_to_sale_chain_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "inventory_inventory_purchase_to_sale_chain" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "metadata", asked_action_family: "inspect_documents", metadata_scope_hint: "склад" } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("цепочка поставки и продажи подтверждена"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); }); it("keeps exact inventory purchase-to-sale replies over stale value-flow clarification candidates", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "По товару Шкаф картотечный 1000*400*2100 закупочная часть цепочки подтверждена, но продажа/выбытие со счета 41.01 в доступных данных не найдены.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "inventory_purchase_to_sale_chain", selected_recipe: "address_inventory_purchase_to_sale_chain_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "inventory_inventory_purchase_to_sale_chain" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ bridge: { bridge_status: "needs_clarification", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "clarification_required", headline: "Коротко: Могу посчитать общий денежный поток в проверяемом окне, но для проверяемого поиска в 1С нужен проверяемый период.", confirmed_lines: [], inference_lines: [], unknown_lines: [], limitation_lines: [], next_step_line: "Уточните период, и я продолжу поиск по денежному потоку в 1С." } }, turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "payout", unsupported_but_understood_family: "counterparty_payouts_or_outflow" }, data_need_graph: { business_fact_family: "value_flow", action_family: "payout", clarification_gaps: ["period"] } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("закупочная часть цепочки подтверждена"); expect(result.reply_text).not.toContain("денежный поток"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_exact_inventory_chain_reply_over_value_flow_clarification" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_candidate_applied"); }); it("keeps confirmed supplier-overlap address replies over entity-resolution discovery candidates", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: 'По складскому остатку Основной склад на 30.09.2021 выявлен поставщик закупочного следа: Торговый дом "Союз МСК".', currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "inventory_supplier_stock_overlap_as_of_date", selected_recipe: "address_inventory_supplier_stock_overlap_as_of_date_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "inventory_inventory_supplier_stock_overlap_as_of_date" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "entity_resolution", asked_action_family: "search_business_entity", unsupported_but_understood_family: "entity_resolution", explicit_entity_candidates: ['Торговый дом "Союз"'] } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("выявлен поставщик закупочного следа"); expect(result.reply_text).not.toContain("Confirmed fact"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); }); it("lets metadata discovery override a stale exact address answer outside protected inventory chains", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "ИП Калинин Рќ.Рњ. | СЃСѓРјРјР°: 216600", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", selected_recipe: "address_customer_revenue_and_payments_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "address_customer_revenue_and_payments" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "metadata", asked_action_family: "inspect_surface", unsupported_but_understood_family: "1c_metadata_surface" }, data_need_graph: { business_fact_family: "schema_surface", decomposition_candidates: ["inspect_metadata_surface"] } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Metadata surface confirmed.", confirmed_lines: ["Available metadata object sets: Catalog.Counterparties"], inference_lines: [], unknown_lines: [], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_text).toContain("Catalog.Counterparties"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_metadata_candidate_priority"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); }); it("keeps exact receivables replies when metadata inspection is only a stale fallback candidate", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Коротко: подтвержденная дебиторская задолженность на 31.05.2017 — 1 234 567,89 руб.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "receivables_confirmed_as_of_date", selected_recipe: "address_receivables_confirmed_as_of_date_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], answer_shape_contract: { reply_type: "factual", capability_contract_id: "confirmed_receivables_as_of_date" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: null, action_family: "confirmed_snapshot", clarification_gaps: ["subject"], reason_codes: [ "data_need_graph_built", "data_need_graph_family_unknown", "data_need_graph_has_clarification_gaps" ] }, turn_meaning_ref: { asked_domain_family: "receivables", asked_action_family: "confirmed_snapshot", explicit_date_scope: "2017-05-31", unsupported_but_understood_family: "profit_margin_boundary", stale_replay_forbidden: true }, reason_codes: [ "mcp_discovery_seeded_from_followup_context", "mcp_discovery_resumed_from_saved_loop_state", "mcp_discovery_data_need_graph_built" ] }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, pilot: { pilot_scope: "metadata_inspection_v1" }, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Metadata surface confirmed.", confirmed_lines: ["Available metadata object sets: Document, AccumulationRegister"], inference_lines: [], unknown_lines: ["Detailed metadata fields were not returned by this probe."], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("дебиторская задолженность"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_exact_address_reply_over_stale_metadata_discovery" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_metadata_candidate_priority"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_candidate_applied"); }); it("keeps aligned factual address lane answers when the exact lane already matched the same semantic intent", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "ИП Калинин Н.М. | сумма: 216600 | операций: 2", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover" } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toBe("ИП Калинин Н.М. | сумма: 216600 | операций: 2"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_aligned_factual_address_reply"); }); it("does not treat an open-scope value-flow total as aligned with exact top-counterparty carryover", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "\u0421\u0430\u043c\u044b\u0439 \u0434\u043e\u0445\u043e\u0434\u043d\u044b\u0439 \u043a\u043b\u0438\u0435\u043d\u0442: \u0413\u0440\u0443\u043f\u043f\u0430 \u0421\u0412\u041a.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", selected_recipe: "address_customer_revenue_and_payments_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], dialogContinuationContract: { target_intent: "customer_revenue_and_payments" }, truth_gate_contract_status: "full_confirmed", assistant_truth_answer_policy_v1: { truth_gate: { coverage_status: "full", grounding_status: "grounded", source_truth_gate_status: "full_confirmed" } }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: [], reason_codes: ["data_need_graph_open_scope_total_without_subject"] }, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover", explicit_organization_scope: "\u041e\u041e\u041e \u0410\u043b\u044c\u0442\u0435\u0440\u043d\u0430\u0442\u0438\u0432\u0430 \u041f\u043b\u044e\u0441", explicit_date_scope: "2020" } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_aligned_factual_address_reply"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_factual_address_continuation_target"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_full_confirmed_factual_address_reply"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_open_scope_value_flow_candidate_priority"); }); it("keeps factual address follow-up replies when they already match the continuation target intent", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "ИП Калинин Н.М. | сумма: 216600 | операций: 2", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", selected_recipe: "address_customer_revenue_and_payments_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], dialogContinuationContract: { target_intent: "customer_revenue_and_payments" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover" } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_factual_address_continuation_target"); }); it("keeps factual suggested-intent pivot replies over discovery clarification candidates", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Найдены банковские операции по контрагенту Жуковка 51.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "bank_operations_by_counterparty", dialog_continuation_contract_v2: { decision: "switch_to_suggested", target_intent: "bank_operations_by_counterparty", intent_selection_mode: "switch_to_suggested_intent", suggested_intent_pivot_signal: true }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover", explicit_entity_candidates: ["ТСЖ \\Жуковка 51\\"], unsupported_but_understood_family: "counterparty_value_or_turnover" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "needs_clarification", headline: "Нужно уточнить контекст перед поиском в 1С.", confirmed_lines: [], inference_lines: [], unknown_lines: [], limitation_lines: [], next_step_line: "Уточните контрагента, период или организацию." } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toBe("Найдены банковские операции по контрагенту Жуковка 51."); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_factual_suggested_intent_pivot_target"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_candidate_applied"); }); it("keeps exact bank operation replies over generic value-flow discovery candidates", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Exact bank operation answer: incoming/outgoing rows include operation kind, payment purpose, and contract; do not classify the bank as a regular customer or supplier automatically.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "bank_operations_by_counterparty", selected_recipe: "address_bank_operations_by_counterparty_v1", mcp_call_status: "matched_non_empty", capability_route_mode: "exact", answer_grounding_check: { status: "grounded" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: ["SBERBANK"], reason_codes: ["data_need_graph_built"] }, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "payout", explicit_entity_candidates: ["SBERBANK"], explicit_date_scope: "2020" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Generic value-flow answer.", confirmed_lines: ["Outgoing payout total only."], inference_lines: ["Generic supplier payout interpretation."], unknown_lines: ["Incoming role is unknown."], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("operation kind"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_exact_bank_operations_address_reply"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_candidate_applied"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_value_flow_action_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); }); it("overrides exact bank operation replies for explicit counterparty received-paid-net questions", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Exact bank operation answer: found 13 bank operations for Group SVK, showing rows and payment purposes.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "bank_operations_by_counterparty", selected_recipe: "address_bank_operations_by_counterparty_v1", mcp_call_status: "matched_non_empty", capability_route_mode: "exact", answer_grounding_check: { status: "grounded" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: ["Group SVK"], reason_codes: ["data_need_graph_built", "data_need_graph_bidirectional_value_flow"] }, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "net_value_flow", explicit_entity_candidates: ["Group SVK"], explicit_date_scope: "2020", unsupported_but_understood_family: "counterparty_bidirectional_value_flow_or_netting" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Group SVK 2020: received 12 093 465 rub., paid 0 rub.; net 12 093 465 rub. toward us.", confirmed_lines: ["received 12 093 465 rub.; paid 0 rub.; net 12 093 465 rub."], inference_lines: [], unknown_lines: [], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("received 12 093 465"); expect(result.reply_text).toContain("paid 0"); expect(result.reply_text).toContain("net 12 093 465"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_value_flow_action_conflict_allows_candidate_override"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_bank_operations_address_reply"); }); it("overrides an exact ranking-shaped address reply when open-scope ranking still needs organization", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Самый доходный год по подтвержденным поступлениям: 2020 (15 744 052,48 ₽ по 20 операциям).", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: [], ranking_need: "top_desc", clarification_gaps: ["organization"], reason_codes: ["data_need_graph_built", "data_need_graph_ranking_top_desc"] }, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover", explicit_date_scope: "2020", seeded_ranking_need: "top_desc" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "needs_clarification", headline: "Нужно уточнить организацию.", confirmed_lines: [], inference_lines: [], unknown_lines: ["Без организации поиск по контрагентам не запустить."], limitation_lines: [], next_step_line: "Уточните организацию, и я продолжу поиск по контрагентам." } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_aligned_factual_address_reply"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_factual_address_continuation_target"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_full_confirmed_factual_address_reply"); }); it("keeps exact top-year value-flow replies over business-overview direct-money clarification", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Самый доходный год по подтвержденным поступлениям: 2020 (15 744 052,48 руб. по 20 операциям). Это денежный поток, а не чистая прибыль.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", selected_recipe: "address_customer_revenue_and_payments_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "business_overview", action_family: "profit_margin_boundary", ranking_need: "top_desc", clarification_gaps: ["organization"], reason_codes: [ "data_need_graph_built", "data_need_graph_family_business_overview", "data_need_graph_ranking_top_desc", "data_need_graph_business_overview_direct_money_answer", "data_need_graph_open_scope_total_needs_organization" ] }, turn_meaning_ref: { asked_domain_family: "business_overview", asked_action_family: "profit_margin_boundary", unsupported_but_understood_family: "profit_margin_boundary", stale_replay_forbidden: true } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "needs_clarification", headline: "Нужно уточнить организацию.", confirmed_lines: [], inference_lines: [], unknown_lines: ["Без организации бизнес-обзор не запускаю."], limitation_lines: [], next_step_line: "Уточните организацию." } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("Самый доходный год"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_exact_value_flow_reply_over_business_overview_direct_money_clarification" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_candidate_applied"); }); it("overrides an exact ranking-shaped address reply when bounded open-scope ranking already has organization and period", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Самый доходный клиент за доступное время по подтвержденным поступлениям: Группа СВК (12 224 925,00 ₽ по 16 операциям).", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", dialogContinuationContract: { target_intent: "customer_revenue_and_payments" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: [], ranking_need: "top_desc", clarification_gaps: [], reason_codes: ["data_need_graph_built", "data_need_graph_ranking_top_desc"] }, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "turnover", explicit_organization_scope: "ООО Альтернатива Плюс", explicit_date_scope: "2020", seeded_ranking_need: "top_desc" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Рейтинг по контрагентам построен по подтвержденным строкам 1С.", confirmed_lines: [ "Крупнейший входящий денежный источник — СБЕРБАНК, ПАО по организации ООО Альтернатива Плюс за период 2020: 12 792 194,31 руб. по 9 строкам с суммой. Это банк/финансовая организация; без назначения платежа или договора не считаю это обычным клиентом или выручкой." ], inference_lines: [ "Рейтинг по контрагентам по организации ООО Альтернатива Плюс за период 2020 рассчитан только по подтвержденным строкам 1С." ], unknown_lines: ["Полный исторический рейтинг вне проверенного окна не доказан."], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_text).toContain("ООО Альтернатива Плюс"); expect(result.reply_text).toContain("2020"); expect(result.reply_text).toContain("не считаю это обычным клиентом"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_aligned_factual_address_reply"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_factual_address_continuation_target"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_exact_matched_factual_address_reply"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_open_scope_value_flow_candidate_priority"); }); it("overrides a year-ranking exact reply when the user asked who brought the most money", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Самый доходный год по подтвержденным поступлениям: 2020 (47.628.853,03 ₽ по 44 операциям).\nТоп-1 лет по сумме поступлений:\n1. 2020 | сумма: 47.628.853,03 ₽ | операций: 44 | контрагентов: 13", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "customer_revenue_and_payments", selected_recipe: "address_customer_revenue_and_payments_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], dialogContinuationContract: { target_intent: "customer_revenue_and_payments" }, truth_gate_contract_status: "full_confirmed", assistant_truth_answer_policy_v1: { truth_gate: { coverage_status: "full", grounding_status: "grounded", source_truth_gate_status: "full_confirmed" } }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, data_need_graph: { business_fact_family: "value_flow", subject_candidates: ["Группа СВК"], ranking_need: "top_desc", reason_codes: ["data_need_graph_built", "data_need_graph_ranking_top_desc"] }, turn_meaning_ref: { raw_message: "И кто больше всего принес денег этой организации в 2020 году?", effective_message: "Определить, какой контрагент принёс наибольшую выручку организации в 2020 году", asked_domain_family: "counterparty_value", asked_action_family: "turnover", explicit_entity_candidates: ["Группа СВК"], explicit_organization_scope: "ООО Альтернатива Плюс", explicit_date_scope: "2020" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, route_candidate: { selected_chain_id: "value_flow_ranking", nearest_catalog_chain_template: "value_flow_ranking" }, execution_handoff: { selected_chain_id: "value_flow_ranking", mcp_execution_performed: true, can_use_guarded_response: false, must_keep_internal_mechanics_hidden: true }, pilot: { pilot_scope: "counterparty_value_flow_query_movements_v1", mcp_execution_performed: true, evidence: { evidence_status: "confirmed", coverage_status: "full", answer_permission: "confirmed_answer", confirmed_facts: [ "1C incoming value-flow rows were ranked by counterparty for the checked scope; leader=Группа СВК, rows_with_amount=13" ] } }, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "По данным 1С можно построить ограниченный рейтинг по контрагентам.", confirmed_lines: [ "В проверенных входящих поступлениях найден один контрагент Группа СВК по организации ООО Альтернатива Плюс за период 2020: 12 093 465 руб. по 13 строкам с суммой." ], inference_lines: [ "Рейтинг по контрагентам по организации ООО Альтернатива Плюс за период 2020 рассчитан только по подтвержденным строкам 1С." ], unknown_lines: ["Полный рейтинг контрагентов вне периода 2020 этим поиском не подтвержден."], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_text).toContain("Группа СВК"); expect(result.reply_text).toContain("12 093 465 руб."); expect(result.reply_text).not.toContain("Самый доходный год"); expect(result.reply_text).not.toContain("Топ-1 лет"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_grounded_value_flow_ranking_candidate_priority_over_current_exact_reply" ); expect(result.reason_codes).toContain("mcp_discovery_response_policy_candidate_applied"); }); it("keeps full-confirmed factual address replies even when discovery has a guarded candidate", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "ООО Ромашка | сумма: 128000 | операций: 3", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "receivables_confirmed_as_of_date", truth_gate_contract_status: "full_confirmed", assistant_truth_answer_policy_v1: { truth_gate: { coverage_status: "full", grounding_status: "grounded", source_truth_gate_status: "full_confirmed" } }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "receivables", asked_action_family: "confirmed_snapshot" } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toBe("ООО Ромашка | сумма: 128000 | операций: 3"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_keep_full_confirmed_factual_address_reply"); }); it("overrides a stale full-confirmed lifecycle reply when discovery proves a different net-flow question", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Коротко: активных заказчиков в 2020 году — 1.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "counterparty_activity_lifecycle", truth_gate_contract_status: "full_confirmed", assistant_truth_answer_policy_v1: { truth_gate: { coverage_status: "full", grounding_status: "grounded", source_truth_gate_status: "full_confirmed" } }, dialog_continuation_contract_v2: { target_intent: "counterparty_activity_lifecycle" }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "net_value_flow", explicit_entity_candidates: ["Группа СВК"], explicit_organization_scope: "ООО Альтернатива Плюс", explicit_date_scope: "2020", unsupported_but_understood_family: "counterparty_bidirectional_value_flow_or_netting" } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "По данным 1С найдены строки входящих и исходящих денежных движений.", confirmed_lines: ["Получили 47 628 853,03 руб.; заплатили 43 763 351,53 руб.; нетто 3 865 501,50 руб."], inference_lines: [], unknown_lines: ["Полное сальдо вне проверенного окна не подтверждено."], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("47 628 853,03"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_full_confirmed_factual_address_reply"); }); it("keeps runtime-adjusted exact VAT follow-up replies over stale discovery turn meaning", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Коротко: подтвержденный НДС к уплате за май 2017 — 0,00 руб.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "vat_liability_confirmed_for_tax_period", truth_gate_contract_status: "full_confirmed", assistant_truth_answer_policy_v1: { truth_gate: { coverage_status: "full", grounding_status: "grounded", source_truth_gate_status: "full_confirmed" }, answer_shape: { reply_type: "factual", capability_contract_id: "confirmed_vat_liability_for_tax_period" } }, assistant_state_transition_v1: { reason_codes: [ "root_followup_continue_previous", "intent_adjusted_to_vat_followup_context", "period_from_from_followup_context", "period_to_from_followup_context", "confirmed_balance_exact_vat_tax_period_intent" ] }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "confirmed_snapshot", explicit_entity_candidates: ["ООО Альтернатива Плюс"], explicit_organization_scope: "ООО Альтернатива Плюс", explicit_date_scope: "2017-05-31", unsupported_but_understood_family: "counterparty_value_or_turnover" } }, bridge: { bridge_status: "checked_sources_only", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: false, answer_draft: { answer_mode: "checked_sources_only", headline: "Я проверил доступный контур, но подтвержденного факта для ответа не получил.", confirmed_lines: [], inference_lines: [], unknown_lines: ["Полный объем входящих поступлений вне проверенного периода этим поиском не подтвержден."], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("подтвержденный НДС к уплате"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_runtime_adjusted_exact_reply_over_stale_discovery_turn_meaning" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); }); it("keeps runtime-matched exact VAT replies over a stale business overview discovery seed", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Short: confirmed VAT for 2020 is based on checked VAT rows.", currentReplySource: "address_query_runtime_v1", currentReplyType: "factual", addressRuntimeMeta: { detected_intent: "vat_liability_confirmed_for_tax_period", selected_recipe: "address_vat_liability_confirmed_tax_period_v1", mcp_call_status: "matched_non_empty", truth_mode: "confirmed", capability_binding_status: "bound", capability_binding_violations: [], truth_gate_contract_status: "full_confirmed", assistant_truth_answer_policy_v1: { truth_gate: { coverage_status: "full", grounding_status: "grounded", source_truth_gate_status: "full_confirmed" }, answer_shape: { reply_type: "factual", capability_contract_id: "confirmed_vat_liability_for_tax_period" } }, assistant_state_transition_v1: { reason_codes: [ "root_followup_continue_previous", "route_expectation_matched", "vat_period_inspection_bridge_signal_detected", "confirmed_balance_exact_vat_tax_period_intent" ] }, assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "business_overview", asked_action_family: "broad_evaluation", unsupported_but_understood_family: "broad_business_evaluation" }, data_need_graph: { business_fact_family: "business_overview", clarification_gaps: [] } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_text).toContain("confirmed VAT"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_runtime_matched_exact_reply_over_stale_discovery_turn_meaning" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_semantic_conflict_allows_candidate_override"); }); it("keeps address lane answers when discovery was not requested for the current turn", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "supported exact route answer", currentReplySource: "address_query_runtime_v1", addressRuntimeMeta: { assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "not_applicable", should_run_discovery: false } }) } }); expect(result.applied).toBe(false); expect(result.reply_text).toBe("supported exact route answer"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_not_discovery_ready_address_candidate"); }); it("keeps the current reply when the candidate has no grounded text", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "route is not wired", currentReplySource: "deterministic_unsupported_current_turn_boundary", modeDecisionReason: "unsupported_current_turn_meaning_boundary", addressRuntimeMeta: { mcpDiscoveryRuntimeEntryPoint: entryPoint({ bridge: { bridge_status: "unsupported", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: false, answer_draft: null } }) } }); expect(result.applied).toBe(false); expect(result.reply_text).toBe("route is not wired"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_candidate_not_eligible"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_kept_current_reply"); }); it("keeps deterministic broad business evaluation summary instead of replacing it with a clarification candidate", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Коротко: по уже подтвержденным данным в 1С компания выглядит живой операционно.", currentReplySource: "deterministic_broad_business_evaluation_contract", livingChatSource: "deterministic_broad_business_evaluation_contract", modeDecisionReason: "unsupported_current_turn_meaning_boundary", addressRuntimeMeta: { assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "business_summary", asked_action_family: "broad_evaluation", unsupported_but_understood_family: "broad_business_evaluation", stale_replay_forbidden: true } }, bridge: { bridge_status: "needs_clarification", user_facing_response_allowed: true, business_fact_answer_allowed: false, requires_user_clarification: true, answer_draft: { answer_mode: "needs_clarification", headline: "Нужно уточнить контекст перед поиском в 1С.", confirmed_lines: [], inference_lines: [], unknown_lines: ["MCP discovery pilot needs more scope before execution"], limitation_lines: ["MCP discovery pilot needs more scope before execution"], next_step_line: "Уточните контрагента, период или организацию." } } }) } }); expect(result.applied).toBe(false); expect(result.decision).toBe("keep_current_reply"); expect(result.reply_source).toBe("deterministic_broad_business_evaluation_contract"); expect(result.reply_text).toContain("компания выглядит живой операционно"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_keep_broad_business_summary_over_clarification_candidate" ); }); it("replaces deterministic broad business evaluation summary with a grounded business overview candidate", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "legacy broad summary", currentReplySource: "deterministic_broad_business_evaluation_contract", livingChatSource: "deterministic_broad_business_evaluation_contract", modeDecisionReason: "unsupported_current_turn_meaning_boundary", addressRuntimeMeta: { assistant_mcp_discovery_entry_point_v1: entryPoint({ turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "business_summary", asked_action_family: "broad_evaluation", unsupported_but_understood_family: "broad_business_evaluation", stale_replay_forbidden: true }, data_need_graph: { business_fact_family: "business_overview", clarification_gaps: [] } }, bridge: { bridge_status: "answer_draft_ready", user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Business overview was assembled from confirmed 1C money flow and activity rows.", confirmed_lines: [ "Incoming customer money flow: 200000.00 RUB.", "Outgoing supplier payouts: 150000.00 RUB.", "Top confirmed customer by incoming money flow: Client A - 120000.00 RUB." ], inference_lines: [ "Net confirmed cash-flow spread is +50000.00 RUB; this is not profit or margin." ], unknown_lines: [ "Profit and margin are not confirmed by this overview.", "VAT/tax position is not confirmed by this overview." ], limitation_lines: ["Business overview is limited to checked 1C rows."], next_step_line: "Check profit/margin, debt quality, VAT/tax position, and inventory liquidity." } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_source).toBe("mcp_discovery_response_candidate_guarded"); expect(result.reply_text).toContain("Incoming customer money flow"); expect(result.reply_text).toContain("this is not profit or margin"); expect(result.reply_text).toContain("VAT/tax position is not confirmed"); expect(result.reply_text).not.toContain("query_movements"); expect(result.reason_codes).toContain("mcp_discovery_response_policy_candidate_applied"); expect(result.reason_codes).not.toContain( "mcp_discovery_response_policy_keep_broad_business_summary_over_clarification_candidate" ); }); it("lets a grounded bidirectional value-flow candidate override a stale address clarification reply", () => { const result = applyAssistantMcpDiscoveryResponsePolicy({ currentReply: "Проверка данных за 2020 год по контрагенту «Группа СВК» не удалась — такой точный или аналогичный вариант имени не найден.", currentReplySource: "address_query_runtime_v1", currentReplyType: "partial_coverage", addressRuntimeMeta: { truth_mode: "clarification_required", answer_shape: "clarification_required", detected_intent: "counterparty_population_and_roles", selected_recipe: "address_counterparty_population_roles_v1", assistant_mcp_discovery_entry_point_v1: entryPoint({ hot_runtime_wired: true, turn_input: { adapter_status: "ready", should_run_discovery: true, turn_meaning_ref: { asked_domain_family: "counterparty_value", asked_action_family: "net_value_flow", explicit_entity_candidates: ["Группа СВК"], explicit_date_scope: "2020", unsupported_but_understood_family: "counterparty_bidirectional_value_flow_or_netting" }, data_need_graph: { business_fact_family: "value_flow", action_family: "net_value_flow", comparison_need: "incoming_vs_outgoing", clarification_gaps: [] } }, bridge: { bridge_status: "answer_draft_ready", hot_runtime_wired: true, user_facing_response_allowed: true, business_fact_answer_allowed: true, requires_user_clarification: false, route_candidate: { selected_chain_id: "value_flow_comparison" }, execution_handoff: { mcp_execution_performed: true, can_use_guarded_response: true, must_keep_internal_mechanics_hidden: true }, pilot: { pilot_scope: "counterparty_bidirectional_value_flow_query_movements_v1", mcp_execution_performed: true, derived_bidirectional_value_flow: { counterparty: "Группа СВК", period_scope: "2020", net_amount_human_ru: "12 093 465 руб.", net_direction: "net_incoming", coverage_limited_by_probe_limit: false, incoming_customer_revenue: { total_amount_human_ru: "12 093 465 руб." }, outgoing_supplier_payout: { total_amount_human_ru: "0 руб." } } }, answer_draft: { answer_mode: "confirmed_with_bounded_inference", headline: "Двусторонний денежный поток подтвержден.", confirmed_lines: [ "1C bidirectional value-flow rows were checked for counterparty Группа СВК: incoming=found, outgoing=found" ], inference_lines: [ "Counterparty net value-flow was calculated as incoming confirmed 1C rows minus outgoing confirmed 1C rows" ], unknown_lines: ["Full bidirectional value-flow outside the checked period is not proven by this MCP discovery pilot"], limitation_lines: [], next_step_line: null } } }) } }); expect(result.applied).toBe(true); expect(result.decision).toBe("apply_candidate"); expect(result.reply_text).toContain("Группа СВК"); expect(result.reply_text).toContain("получили 12 093 465 руб."); expect(result.reply_text).toContain("заплатили 0 руб."); expect(result.reply_text).not.toContain("не найден"); expect(result.reason_codes).toContain( "mcp_discovery_response_policy_grounded_value_flow_candidate_priority_over_current_clarification" ); expect(result.reason_codes).not.toContain("mcp_discovery_response_policy_keep_current_clarification_required_reply"); }); });