diff --git a/AGENTS.md b/AGENTS.md index e0e5f6d..854b962 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,3 +32,13 @@ Rules: - If a case falls outside the current routed contour because the route/intent/capability is not wired yet, treat it as domain enablement work for this project, not as automatic out-of-scope rejection. - For new unmarked domains, `needs_exact_capability` means "bootstrap or extend the contour" rather than "close the case as unsupported". - A case can be marked `accepted` only when analyst verdict is at least `80/100`, no unresolved `P0` remains, and the rerun does not mask heuristic output as confirmed. + +## agent_semantic_runs +- `АГЕНТНЫЙ ПРОГОН` is a targeted full semantic replay for the current architecture fix, not a generic smoke test. +- Use it to validate human user questions, human model answers, technical chats, business logic, and system routing together. +- Build question lists around the active fix: mix direct domain questions with contextual chains, meta interruptions, cross-domain pivots, and follow-up edges that specifically hit the architecture change under validation. +- Save agent-built question packs into autoruns under `Пользовательские сессии` with title prefix `AGENT | ...`. +- Preferred repo-native save path: `python scripts/save_agent_semantic_run.py --spec `. +- Agent semantic runs must remain runnable by the user from the autoruns UI like any other saved user session. +- Do not run or save an `АГЕНТНЫЙ ПРОГОН` on every turn by default. +- Run it when the user explicitly asks for it, or when a substantial architecture/domain fix needs critical semantic proof beyond unit tests and narrow synthetic checks. diff --git a/docs/orchestration/address_truth_harness_inventory_provenance_restore.json b/docs/orchestration/address_truth_harness_inventory_provenance_restore.json new file mode 100644 index 0000000..0c9332d --- /dev/null +++ b/docs/orchestration/address_truth_harness_inventory_provenance_restore.json @@ -0,0 +1,91 @@ +{ + "schema_version": "domain_truth_harness_spec_v1", + "scenario_id": "address_truth_harness_inventory_provenance_restore", + "domain": "inventory_selected_object_provenance_restore", + "title": "Targeted live replay for selected-object supplier provenance and root restore", + "description": "Strict short replay for the March 2021 stock snapshot, selected-item supplier question, item documents, and same-date root restore.", + "bindings": {}, + "steps": [ + { + "step_id": "step_01_inventory_march_2021", + "title": "Inventory stock snapshot at March 2021", + "question": "какие остатки на складе на март 2021", + "allowed_reply_types": [ + "factual" + ], + "expected_intents": [ + "inventory_on_hand_as_of_date" + ], + "required_filters": { + "as_of_date": "2021-03-31", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "required_direct_answer_patterns_any": [ + "31\\.03\\.2021", + "(?i)на складе", + "(?i)столешница 600\\*3050\\*26 альмандин" + ] + }, + { + "step_id": "step_02_selected_item_supplier", + "title": "Selected-object supplier provenance", + "question": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "allowed_reply_types": [ + "factual" + ], + "expected_intents": [ + "inventory_purchase_provenance_for_item" + ], + "required_direct_answer_patterns_any": [ + "(?i)столешница 600\\*3050\\*26 альмандин", + "(?i)поставщик|поставил|куплен", + "(?i)союз|торговый дом" + ], + "forbidden_direct_answer_patterns": [ + "(?i)^на 31\\.03\\.2021 на складе", + "(?i)^не могу надежно подтвердить ответ" + ] + }, + { + "step_id": "step_03_selected_item_documents", + "title": "Selected-object purchase documents", + "question": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "allowed_reply_types": [ + "factual" + ], + "expected_intents": [ + "inventory_purchase_documents_for_item" + ], + "required_direct_answer_patterns_any": [ + "(?i)столешница 600\\*3050\\*26 альмандин", + "(?i)документ", + "(?i)союз|торговый дом" + ] + }, + { + "step_id": "step_04_inventory_same_date_restore", + "title": "Restore root inventory snapshot on the same date", + "question": "покажи еще раз остатки на эту же дату", + "allowed_reply_types": [ + "factual" + ], + "expected_intents": [ + "inventory_on_hand_as_of_date" + ], + "required_filters": { + "as_of_date": "2021-03-31", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "required_direct_answer_patterns_any": [ + "31\\.03\\.2021", + "(?i)на складе" + ], + "forbidden_direct_answer_patterns": [ + "(?i)^не могу надежно подтвердить ответ", + "(?i)transition_not_supported_by_capability" + ] + } + ] +} diff --git a/llm_normalizer/backend/dist/routes/autoRuns.js b/llm_normalizer/backend/dist/routes/autoRuns.js index f7c5bf9..3d4a932 100644 --- a/llm_normalizer/backend/dist/routes/autoRuns.js +++ b/llm_normalizer/backend/dist/routes/autoRuns.js @@ -183,7 +183,13 @@ function readAutoGenHistory() { : null, source_session_id: toStringSafe(toRecord(item.context)?.source_session_id), saved_session_file: toStringSafe(toRecord(item.context)?.saved_session_file), - saved_case_set_kind: toStringSafe(toRecord(item.context)?.saved_case_set_kind) + saved_case_set_kind: toStringSafe(toRecord(item.context)?.saved_case_set_kind), + agent_run: toBooleanSafe(toRecord(item.context)?.agent_run), + agent_focus: toStringSafe(toRecord(item.context)?.agent_focus) + ? repairAutogenMojibake(String(toRecord(item.context)?.agent_focus)) + : null, + architecture_phase: toStringSafe(toRecord(item.context)?.architecture_phase), + source_spec_file: toStringSafe(toRecord(item.context)?.source_spec_file) } : null })) @@ -1486,7 +1492,7 @@ function buildSavedSessionCaseSetPayload(input) { ? [ { case_id: caseId, - scenario_tag: "saved_user_sessions", + scenario_tag: toStringSafe(input.scenarioTag) ?? "saved_user_sessions", title: input.title, question_type: turns.length > 1 ? "followup" : "direct", broadness_level: "medium", @@ -1515,7 +1521,10 @@ function rewriteAutoGenCaseSetFile(record) { ? buildSavedSessionCaseSetPayload({ generationId: record.generation_id, title: record.title, - questions: record.questions + questions: record.questions, + scenarioTag: record.context?.saved_case_set_kind === "agent_semantic_scenario" + ? "agent_saved_user_sessions" + : "saved_user_sessions" }) : buildAutogenCaseSetPayload({ generationId: record.generation_id, @@ -2064,7 +2073,8 @@ function buildAutoRunsRouter(services, openaiClient = new openaiResponsesClient_ writeJsonFile(caseSetPath, buildSavedSessionCaseSetPayload({ generationId, title, - questions + questions, + scenarioTag: "saved_user_sessions" })); const snapshotFile = writeSavedAssistantSessionSnapshot({ generationId, diff --git a/llm_normalizer/backend/dist/services/addressQueryService.js b/llm_normalizer/backend/dist/services/addressQueryService.js index a83eb38..6d62e6e 100644 --- a/llm_normalizer/backend/dist/services/addressQueryService.js +++ b/llm_normalizer/backend/dist/services/addressQueryService.js @@ -3430,6 +3430,107 @@ class AddressQueryService { debug: debugPayload }; }; + const buildFactualExecutionResult = (input) => { + const resultSemantics = mergeAddressResultSemantics(deriveAddressResultSemantics({ + intent: intent.intent, + selectedRecipe: input.selectedRecipe, + filters: input.extractedFilters ?? filters.extracted_filters, + semanticFrame: input.semanticFrame ?? semanticFrame, + responseType: input.responseType, + rowsMatched: input.rowsMatched + }), input.responseSemantics); + const routeExpectationAudit = input.routeExpectationAudit ?? + buildRouteExpectationAudit({ + intent: routeExpectationIntent, + selectedRecipe: input.selectedRecipe, + requestedResultMode, + resultMode: resultSemantics.result_mode + }); + const debugPayload = (0, addressTruthGatePolicy_1.attachAddressTruthGate)({ + detected_mode: mode.mode, + detected_mode_confidence: mode.confidence, + query_shape: shape.shape, + query_shape_confidence: shape.confidence, + detected_intent: intent.intent, + detected_intent_confidence: intent.confidence, + extracted_filters: input.extractedFilters ?? filters.extracted_filters, + missing_required_filters: [], + selected_recipe: input.selectedRecipe, + mcp_call_status_legacy: toLegacyMcpStatus(input.mcpCallStatus), + account_scope_mode: input.accountScopeMode, + account_scope_fallback_applied: input.accountScopeFallbackApplied, + anchor_type: input.anchor.anchor_type, + anchor_value_raw: input.anchor.anchor_value_raw, + anchor_value_resolved: input.anchor.anchor_value_resolved, + resolver_confidence: input.anchor.resolver_confidence, + ambiguity_count: input.anchor.ambiguity_count, + match_failure_stage: input.matchFailureStage, + match_failure_reason: input.matchFailureReason, + mcp_call_status: input.mcpCallStatus, + rows_fetched: input.rowsFetched, + raw_rows_received: input.rawRowsReceived, + rows_after_account_scope: input.rowsAfterAccountScope, + rows_after_recipe_filter: input.rowsAfterRecipeFilter, + rows_materialized: input.rowsMaterialized, + rows_matched: input.rowsMatched, + raw_row_keys_sample: input.rawRowKeysSample, + materialization_drop_reason: input.materializationDropReason, + account_token_raw: input.accountScopeAudit.accountTokenRaw, + account_token_normalized: input.accountScopeAudit.accountTokenNormalized, + account_scope_fields_checked: input.accountScopeAudit.accountScopeFieldsChecked, + account_scope_match_strategy: input.accountScopeAudit.accountScopeMatchStrategy, + account_scope_drop_reason: input.accountScopeAudit.accountScopeDropReason, + runtime_readiness: input.runtimeReadiness ?? "LIVE_QUERYABLE_WITH_LIMITS", + limited_reason_category: input.limitedReasonCategory ?? null, + response_type: input.responseType, + route_expectation_status: routeExpectationAudit.status, + route_expectation_reason: routeExpectationAudit.reason, + route_expectation_expected_selected_recipes: routeExpectationAudit.expectedSelectedRecipes, + route_expectation_expected_requested_result_modes: routeExpectationAudit.expectedRequestedResultModes, + route_expectation_expected_result_modes: routeExpectationAudit.expectedResultModes, + semantic_frame: input.semanticFrame ?? semanticFrame, + ...resultSemantics, + limitations: input.limitations, + reasons: input.reasons, + ...(input.capabilityAudit + ? { + capability_id: input.capabilityAudit.capabilityId, + capability_layer: input.capabilityAudit.layer, + capability_route_mode: input.capabilityAudit.routeMode, + capability_route_enabled: input.capabilityAudit.enabled, + capability_route_reason: input.capabilityAudit.reason + } + : {}), + ...(input.shadowRouteAudit + ? { + shadow_route_intent: input.shadowRouteAudit.intent, + shadow_route_selected_recipe: input.shadowRouteAudit.selectedRecipe, + shadow_route_status: input.shadowRouteAudit.status + } + : {}) + }, { + intent: intent.intent, + filters: input.extractedFilters ?? filters.extracted_filters, + semanticFrame: input.semanticFrame ?? semanticFrame, + selectedRecipe: input.selectedRecipe, + truthGateStatusHint: input.truthGateStatusHint ?? null, + rowsMatched: input.rowsMatched, + limitedReasonCategory: input.limitedReasonCategory ?? null, + runtimeReadiness: input.runtimeReadiness ?? "LIVE_QUERYABLE_WITH_LIMITS", + limitations: input.limitations, + reasons: input.reasons, + routeExpectationStatus: routeExpectationAudit.status, + routeExpectationReason: routeExpectationAudit.reason, + replyType: (0, composeStage_1.inferReplyType)(input.responseType) + }); + return { + handled: true, + reply_text: input.replyText, + reply_type: (0, composeStage_1.inferReplyType)(input.responseType), + response_type: input.responseType, + debug: debugPayload + }; + }; if (organizationWarehouseRecoveryApplied) { if (!baseReasons.includes("organization_scope_live_grounding_recovered_rows")) { baseReasons.push("organization_scope_live_grounding_recovered_rows"); @@ -3481,60 +3582,33 @@ class AddressQueryService { const replyPrefix = recoveredBankRows.length > 0 ? "Документный фильтр в live дал пустой набор; показываю связанные банковские операции по договору." : "Документный фильтр в live дал пустой набор; показываю найденные строки по договорному якорю."; - return { - handled: true, - reply_text: `${replyPrefix}\n${factual.text}`, - reply_type: (0, composeStage_1.inferReplyType)(factual.responseType), - response_type: factual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: effectiveRecipeId, - mcp_call_status_legacy: toLegacyMcpStatus("matched_non_empty"), - account_scope_mode: plan.account_scope_mode, - account_scope_fallback_applied: accountScopeFallbackApplied, - anchor_type: anchor.anchor_type, - anchor_value_raw: anchor.anchor_value_raw, - anchor_value_resolved: anchor.anchor_value_resolved, - resolver_confidence: anchor.resolver_confidence, - ambiguity_count: anchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: "matched_non_empty", - rows_fetched: mcp.fetched_rows, - raw_rows_received: mcp.raw_rows.length, - rows_after_account_scope: normalizedRows.length, - rows_after_recipe_filter: filterByAnchors.length, - rows_materialized: normalizedRows.length, - rows_matched: recoveredRows.length, - raw_row_keys_sample: rowDiagnostics.rawRowKeysSample, - materialization_drop_reason: rowDiagnostics.materializationDropReason, - account_token_raw: accountScopeAudit.accountTokenRaw, - account_token_normalized: accountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: accountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: accountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: accountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: factual.responseType, - ...mergeAddressResultSemantics(deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: effectiveRecipeId, - filters: filters.extracted_filters, - semanticFrame, - responseType: factual.responseType, - rowsMatched: recoveredRows.length - }), factual.semantics), - limitations: [...filters.warnings, recoveryReason], - reasons: withConfirmedBalanceFallbackReason([...baseReasons, recoveryReason], requestedResultMode, factual.semantics) - } - }; + return buildFactualExecutionResult({ + replyText: `${replyPrefix}\n${factual.text}`, + responseType: factual.responseType, + responseSemantics: factual.semantics, + selectedRecipe: effectiveRecipeId, + mcpCallStatus: "matched_non_empty", + rowsFetched: mcp.fetched_rows, + rawRowsReceived: mcp.raw_rows.length, + rowsAfterAccountScope: normalizedRows.length, + rowsAfterRecipeFilter: filterByAnchors.length, + rowsMaterialized: normalizedRows.length, + rowsMatched: recoveredRows.length, + rawRowKeysSample: rowDiagnostics.rawRowKeysSample, + materializationDropReason: rowDiagnostics.materializationDropReason, + accountScopeMode: plan.account_scope_mode, + accountScopeFallbackApplied, + accountScopeAudit, + anchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: [...filters.warnings, recoveryReason], + reasons: withConfirmedBalanceFallbackReason([...baseReasons, recoveryReason], requestedResultMode, factual.semantics), + limitedReasonCategory: "recipe_visibility_gap", + capabilityAudit, + shadowRouteAudit, + semanticFrame + }); } } if (filteredRows.length === 0 && @@ -3605,60 +3679,32 @@ class AddressQueryService { const expandedPrefix = `Период сохранен. Глубина live-выборки автоматически расширена до ${expandedPlan.limit} строк.`; const expandedLimitations = [...filters.warnings, "query_limit_auto_expanded_for_anchor_recovery"]; const expandedReasons = [...baseReasons, "query_limit_auto_expanded_for_anchor_recovery"]; - return { - handled: true, - reply_text: `${expandedPrefix}\n${expandedFactual.text}`, - reply_type: (0, composeStage_1.inferReplyType)(expandedFactual.responseType), - response_type: expandedFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: expandedSelection.selected_recipe.recipe_id, - mcp_call_status_legacy: toLegacyMcpStatus(expandedStageStatus), - account_scope_mode: expandedPlan.account_scope_mode, - account_scope_fallback_applied: expandedAccountScopeFallbackApplied, - anchor_type: expandedAnchor.anchor_type, - anchor_value_raw: expandedAnchor.anchor_value_raw, - anchor_value_resolved: expandedAnchor.anchor_value_resolved, - resolver_confidence: expandedAnchor.resolver_confidence, - ambiguity_count: expandedAnchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: expandedStageStatus, - rows_fetched: expandedMcp.fetched_rows, - raw_rows_received: expandedMcp.raw_rows.length, - rows_after_account_scope: expandedNormalizedRows.length, - rows_after_recipe_filter: expandedRowsByAnchor.length, - rows_materialized: expandedNormalizedRows.length, - rows_matched: expandedFilteredRows.length, - raw_row_keys_sample: expandedRowDiagnostics.rawRowKeysSample, - materialization_drop_reason: expandedRowDiagnostics.materializationDropReason, - account_token_raw: expandedAccountScopeAudit.accountTokenRaw, - account_token_normalized: expandedAccountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: expandedAccountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: expandedAccountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: expandedAccountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: expandedFactual.responseType, - ...mergeAddressResultSemantics(deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: expandedSelection.selected_recipe.recipe_id, - filters: filters.extracted_filters, - semanticFrame, - responseType: expandedFactual.responseType, - rowsMatched: expandedFilteredRows.length - }), expandedFactual.semantics), - limitations: expandedLimitations, - reasons: withConfirmedBalanceFallbackReason(expandedReasons, requestedResultMode, expandedFactual.semantics) - } - }; + return buildFactualExecutionResult({ + replyText: `${expandedPrefix}\n${expandedFactual.text}`, + responseType: expandedFactual.responseType, + responseSemantics: expandedFactual.semantics, + selectedRecipe: expandedSelection.selected_recipe.recipe_id, + mcpCallStatus: expandedStageStatus, + rowsFetched: expandedMcp.fetched_rows, + rawRowsReceived: expandedMcp.raw_rows.length, + rowsAfterAccountScope: expandedNormalizedRows.length, + rowsAfterRecipeFilter: expandedRowsByAnchor.length, + rowsMaterialized: expandedNormalizedRows.length, + rowsMatched: expandedFilteredRows.length, + rawRowKeysSample: expandedRowDiagnostics.rawRowKeysSample, + materializationDropReason: expandedRowDiagnostics.materializationDropReason, + accountScopeMode: expandedPlan.account_scope_mode, + accountScopeFallbackApplied: expandedAccountScopeFallbackApplied, + accountScopeAudit: expandedAccountScopeAudit, + anchor: expandedAnchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: expandedLimitations, + reasons: withConfirmedBalanceFallbackReason(expandedReasons, requestedResultMode, expandedFactual.semantics), + capabilityAudit, + shadowRouteAudit, + semanticFrame + }); } } } @@ -3752,67 +3798,34 @@ class AddressQueryService { requestedResultMode, resultMode: broadenedResultSemantics.result_mode }); - return { - handled: true, - reply_text: injectNoticeAfterLeadLine(broadenedFactual.text, broadenedPrefix), - reply_type: (0, composeStage_1.inferReplyType)(broadenedFactual.responseType), - response_type: broadenedFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: broadenedSelection.selected_recipe.recipe_id, - mcp_call_status_legacy: toLegacyMcpStatus(broadenedStageStatus), - account_scope_mode: broadenedPlan.account_scope_mode, - account_scope_fallback_applied: broadenedAccountScopeFallbackApplied, - anchor_type: broadenedAnchor.anchor_type, - anchor_value_raw: broadenedAnchor.anchor_value_raw, - anchor_value_resolved: broadenedAnchor.anchor_value_resolved, - resolver_confidence: broadenedAnchor.resolver_confidence, - ambiguity_count: broadenedAnchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: broadenedStageStatus, - rows_fetched: broadenedMcp.fetched_rows, - raw_rows_received: broadenedMcp.raw_rows.length, - rows_after_account_scope: broadenedNormalizedRows.length, - rows_after_recipe_filter: broadenedRowsByAnchor.length, - rows_materialized: broadenedNormalizedRows.length, - rows_matched: broadenedFilteredRows.length, - raw_row_keys_sample: broadenedRowDiagnostics.rawRowKeysSample, - materialization_drop_reason: broadenedRowDiagnostics.materializationDropReason, - account_token_raw: broadenedAccountScopeAudit.accountTokenRaw, - account_token_normalized: broadenedAccountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: broadenedAccountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: broadenedAccountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: broadenedAccountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: broadenedFactual.responseType, - capability_id: capabilityAudit.capabilityId, - capability_layer: capabilityAudit.layer, - capability_route_mode: capabilityAudit.routeMode, - capability_route_enabled: capabilityAudit.enabled, - capability_route_reason: capabilityAudit.reason, - shadow_route_intent: shadowRouteAudit.intent, - shadow_route_selected_recipe: shadowRouteAudit.selectedRecipe, - shadow_route_status: shadowRouteAudit.status, - route_expectation_status: broadenedRouteExpectationAudit.status, - route_expectation_reason: broadenedRouteExpectationAudit.reason, - route_expectation_expected_selected_recipes: broadenedRouteExpectationAudit.expectedSelectedRecipes, - route_expectation_expected_requested_result_modes: broadenedRouteExpectationAudit.expectedRequestedResultModes, - route_expectation_expected_result_modes: broadenedRouteExpectationAudit.expectedResultModes, - semantic_frame: semanticFrame, - ...broadenedResultSemantics, - limitations: broadenedLimitations, - reasons: withConfirmedBalanceFallbackReason(broadenedReasons, requestedResultMode, broadenedFactual.semantics) - } - }; + return buildFactualExecutionResult({ + replyText: injectNoticeAfterLeadLine(broadenedFactual.text, broadenedPrefix), + responseType: broadenedFactual.responseType, + responseSemantics: broadenedFactual.semantics, + selectedRecipe: broadenedSelection.selected_recipe.recipe_id, + mcpCallStatus: broadenedStageStatus, + rowsFetched: broadenedMcp.fetched_rows, + rawRowsReceived: broadenedMcp.raw_rows.length, + rowsAfterAccountScope: broadenedNormalizedRows.length, + rowsAfterRecipeFilter: broadenedRowsByAnchor.length, + rowsMaterialized: broadenedNormalizedRows.length, + rowsMatched: broadenedFilteredRows.length, + rawRowKeysSample: broadenedRowDiagnostics.rawRowKeysSample, + materializationDropReason: broadenedRowDiagnostics.materializationDropReason, + accountScopeMode: broadenedPlan.account_scope_mode, + accountScopeFallbackApplied: broadenedAccountScopeFallbackApplied, + accountScopeAudit: broadenedAccountScopeAudit, + anchor: broadenedAnchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: broadenedLimitations, + reasons: withConfirmedBalanceFallbackReason(broadenedReasons, requestedResultMode, broadenedFactual.semantics), + routeExpectationAudit: broadenedRouteExpectationAudit, + capabilityAudit, + shadowRouteAudit, + semanticFrame, + truthGateStatusHint: "limited_temporal_or_contextual" + }); } } } @@ -3887,60 +3900,33 @@ class AddressQueryService { : ""; const historicalLimitations = [...filters.warnings, "historical_window_sort_recovery_applied"]; const historicalReasons = [...baseReasons, "historical_window_sort_recovery_applied"]; - return { - handled: true, - reply_text: `${historicalPrefix}\n${historicalFactual.text}${historicalSuggestion}`, - reply_type: (0, composeStage_1.inferReplyType)(historicalFactual.responseType), - response_type: historicalFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: historicalSelection.selected_recipe.recipe_id, - mcp_call_status_legacy: toLegacyMcpStatus(historicalStageStatus), - account_scope_mode: historicalPlan.account_scope_mode, - account_scope_fallback_applied: historicalAccountScopeFallbackApplied, - anchor_type: historicalAnchor.anchor_type, - anchor_value_raw: historicalAnchor.anchor_value_raw, - anchor_value_resolved: historicalAnchor.anchor_value_resolved, - resolver_confidence: historicalAnchor.resolver_confidence, - ambiguity_count: historicalAnchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: historicalStageStatus, - rows_fetched: historicalMcp.fetched_rows, - raw_rows_received: historicalMcp.raw_rows.length, - rows_after_account_scope: historicalNormalizedRows.length, - rows_after_recipe_filter: historicalRowsByAnchor.length, - rows_materialized: historicalNormalizedRows.length, - rows_matched: historicalFilteredRows.length, - raw_row_keys_sample: historicalRowDiagnostics.rawRowKeysSample, - materialization_drop_reason: historicalRowDiagnostics.materializationDropReason, - account_token_raw: historicalAccountScopeAudit.accountTokenRaw, - account_token_normalized: historicalAccountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: historicalAccountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: historicalAccountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: historicalAccountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: historicalFactual.responseType, - ...mergeAddressResultSemantics(deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: historicalSelection.selected_recipe.recipe_id, - filters: filters.extracted_filters, - semanticFrame, - responseType: historicalFactual.responseType, - rowsMatched: historicalFilteredRows.length - }), historicalFactual.semantics), - limitations: historicalLimitations, - reasons: withConfirmedBalanceFallbackReason(historicalReasons, requestedResultMode, historicalFactual.semantics) - } - }; + return buildFactualExecutionResult({ + replyText: `${historicalPrefix}\n${historicalFactual.text}${historicalSuggestion}`, + responseType: historicalFactual.responseType, + responseSemantics: historicalFactual.semantics, + selectedRecipe: historicalSelection.selected_recipe.recipe_id, + mcpCallStatus: historicalStageStatus, + rowsFetched: historicalMcp.fetched_rows, + rawRowsReceived: historicalMcp.raw_rows.length, + rowsAfterAccountScope: historicalNormalizedRows.length, + rowsAfterRecipeFilter: historicalRowsByAnchor.length, + rowsMaterialized: historicalNormalizedRows.length, + rowsMatched: historicalFilteredRows.length, + rawRowKeysSample: historicalRowDiagnostics.rawRowKeysSample, + materializationDropReason: historicalRowDiagnostics.materializationDropReason, + accountScopeMode: historicalPlan.account_scope_mode, + accountScopeFallbackApplied: historicalAccountScopeFallbackApplied, + accountScopeAudit: historicalAccountScopeAudit, + anchor: historicalAnchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: historicalLimitations, + reasons: withConfirmedBalanceFallbackReason(historicalReasons, requestedResultMode, historicalFactual.semantics), + capabilityAudit, + shadowRouteAudit, + semanticFrame, + truthGateStatusHint: "limited_temporal_or_contextual" + }); } } } @@ -3959,60 +3945,33 @@ class AddressQueryService { : ""; const fallbackLimitations = [...filters.warnings, "anchor_not_matched_fallback_rows"]; const fallbackReasons = [...baseReasons, "anchor_not_matched_fallback_rows"]; - return { - handled: true, - reply_text: `${fallbackPrefix}\n${fallbackFactual.text}${fallbackSuggestion}`, - reply_type: (0, composeStage_1.inferReplyType)(fallbackFactual.responseType), - response_type: fallbackFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: effectiveRecipeId, - mcp_call_status_legacy: "matched_non_empty", - account_scope_mode: plan.account_scope_mode, - account_scope_fallback_applied: accountScopeFallbackApplied, - anchor_type: anchor.anchor_type, - anchor_value_raw: anchor.anchor_value_raw, - anchor_value_resolved: anchor.anchor_value_resolved, - resolver_confidence: anchor.resolver_confidence, - ambiguity_count: anchor.ambiguity_count, - match_failure_stage: matchFailureStage, - match_failure_reason: matchFailureReason, - mcp_call_status: "matched_non_empty", - rows_fetched: mcp.fetched_rows, - raw_rows_received: mcp.raw_rows.length, - rows_after_account_scope: normalizedRows.length, - rows_after_recipe_filter: filterByAnchors.length, - rows_materialized: normalizedRows.length, - rows_matched: documentBankFallbackRows.length, - raw_row_keys_sample: rowDiagnostics.rawRowKeysSample, - materialization_drop_reason: rowDiagnostics.materializationDropReason, - account_token_raw: accountScopeAudit.accountTokenRaw, - account_token_normalized: accountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: accountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: accountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: accountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: fallbackFactual.responseType, - ...mergeAddressResultSemantics(deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: effectiveRecipeId, - filters: filters.extracted_filters, - semanticFrame, - responseType: fallbackFactual.responseType, - rowsMatched: documentBankFallbackRows.length - }), fallbackFactual.semantics), - limitations: fallbackLimitations, - reasons: withConfirmedBalanceFallbackReason(fallbackReasons, requestedResultMode, fallbackFactual.semantics) - } - }; + return buildFactualExecutionResult({ + replyText: `${fallbackPrefix}\n${fallbackFactual.text}${fallbackSuggestion}`, + responseType: fallbackFactual.responseType, + responseSemantics: fallbackFactual.semantics, + selectedRecipe: effectiveRecipeId, + mcpCallStatus: "matched_non_empty", + rowsFetched: mcp.fetched_rows, + rawRowsReceived: mcp.raw_rows.length, + rowsAfterAccountScope: normalizedRows.length, + rowsAfterRecipeFilter: filterByAnchors.length, + rowsMaterialized: normalizedRows.length, + rowsMatched: documentBankFallbackRows.length, + rawRowKeysSample: rowDiagnostics.rawRowKeysSample, + materializationDropReason: rowDiagnostics.materializationDropReason, + accountScopeMode: plan.account_scope_mode, + accountScopeFallbackApplied, + accountScopeAudit, + anchor, + matchFailureStage, + matchFailureReason, + limitations: fallbackLimitations, + reasons: withConfirmedBalanceFallbackReason(fallbackReasons, requestedResultMode, fallbackFactual.semantics), + capabilityAudit, + shadowRouteAudit, + limitedReasonCategory: "recipe_visibility_gap", + semanticFrame + }); } } const allowConfirmedAsOfZeroSnapshot = filteredRows.length === 0 && @@ -4297,67 +4256,33 @@ class AddressQueryService { const reasonsWithRouteExpectation = finalRouteExpectationAudit.status === "mismatch" ? [...baseReasons, `route_expectation_mismatch:${finalRouteExpectationAudit.reason}`] : baseReasons; - return { - handled: true, - reply_text: factual.text, - reply_type: (0, composeStage_1.inferReplyType)(factual.responseType), - response_type: factual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: effectiveRecipeId, - mcp_call_status_legacy: toLegacyMcpStatus(stageStatus), - account_scope_mode: plan.account_scope_mode, - account_scope_fallback_applied: accountScopeFallbackApplied, - anchor_type: anchor.anchor_type, - anchor_value_raw: anchor.anchor_value_raw, - anchor_value_resolved: anchor.anchor_value_resolved, - resolver_confidence: anchor.resolver_confidence, - ambiguity_count: anchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: stageStatus, - rows_fetched: mcp.fetched_rows, - raw_rows_received: mcp.raw_rows.length, - rows_after_account_scope: normalizedRows.length, - rows_after_recipe_filter: filterByAnchors.length, - rows_materialized: normalizedRows.length, - rows_matched: filteredRows.length, - raw_row_keys_sample: rowDiagnostics.rawRowKeysSample, - materialization_drop_reason: rowDiagnostics.materializationDropReason, - account_token_raw: accountScopeAudit.accountTokenRaw, - account_token_normalized: accountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: accountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: accountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: accountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: factual.responseType, - capability_id: capabilityAudit.capabilityId, - capability_layer: capabilityAudit.layer, - capability_route_mode: capabilityAudit.routeMode, - capability_route_enabled: capabilityAudit.enabled, - capability_route_reason: capabilityAudit.reason, - shadow_route_intent: shadowRouteAudit.intent, - shadow_route_selected_recipe: shadowRouteAudit.selectedRecipe, - shadow_route_status: shadowRouteAudit.status, - route_expectation_status: finalRouteExpectationAudit.status, - route_expectation_reason: finalRouteExpectationAudit.reason, - route_expectation_expected_selected_recipes: finalRouteExpectationAudit.expectedSelectedRecipes, - route_expectation_expected_requested_result_modes: finalRouteExpectationAudit.expectedRequestedResultModes, - route_expectation_expected_result_modes: finalRouteExpectationAudit.expectedResultModes, - semantic_frame: semanticFrame, - ...factualResultSemantics, - limitations: factualLimitations, - reasons: withConfirmedBalanceFallbackReason(reasonsWithRouteExpectation, requestedResultMode, factual.semantics, factualResultSemantics.result_mode) - } - }; + return buildFactualExecutionResult({ + replyText: factual.text, + responseType: factual.responseType, + responseSemantics: factual.semantics, + selectedRecipe: effectiveRecipeId, + mcpCallStatus: stageStatus, + rowsFetched: mcp.fetched_rows, + rawRowsReceived: mcp.raw_rows.length, + rowsAfterAccountScope: normalizedRows.length, + rowsAfterRecipeFilter: filterByAnchors.length, + rowsMaterialized: normalizedRows.length, + rowsMatched: filteredRows.length, + rawRowKeysSample: rowDiagnostics.rawRowKeysSample, + materializationDropReason: rowDiagnostics.materializationDropReason, + accountScopeMode: plan.account_scope_mode, + accountScopeFallbackApplied, + accountScopeAudit, + anchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: factualLimitations, + reasons: withConfirmedBalanceFallbackReason(reasonsWithRouteExpectation, requestedResultMode, factual.semantics, factualResultSemantics.result_mode), + routeExpectationAudit: finalRouteExpectationAudit, + capabilityAudit, + shadowRouteAudit, + semanticFrame + }); } } exports.AddressQueryService = AddressQueryService; diff --git a/llm_normalizer/backend/dist/services/addressTruthGatePolicy.js b/llm_normalizer/backend/dist/services/addressTruthGatePolicy.js index 1a4b169..991cdda 100644 --- a/llm_normalizer/backend/dist/services/addressTruthGatePolicy.js +++ b/llm_normalizer/backend/dist/services/addressTruthGatePolicy.js @@ -115,6 +115,9 @@ function hasReusableRootScope(input) { return Boolean(input.semanticFrame && input.semanticFrame.scope_kind !== "none"); } function truthGateStatusFrom(input) { + if (input.truthGateStatusHint) { + return input.truthGateStatusHint; + } const missingRequiredFilters = input.missingRequiredFilters ?? []; if (input.routeExpectationStatus === "mismatch") { return "blocked_route_expectation_failure"; diff --git a/llm_normalizer/backend/dist/services/assistantRuntimeContractRegistry.js b/llm_normalizer/backend/dist/services/assistantRuntimeContractRegistry.js index 98f6df7..75f459f 100644 --- a/llm_normalizer/backend/dist/services/assistantRuntimeContractRegistry.js +++ b/llm_normalizer/backend/dist/services/assistantRuntimeContractRegistry.js @@ -192,7 +192,7 @@ exports.INVENTORY_CAPABILITY_CONTRACTS = [ capability_id: "confirmed_inventory_on_hand_as_of_date", intent_ids: ["inventory_on_hand_as_of_date"], entry_modes: ["root_entry", "root_followup", "clarification_resume"], - transitions: ["T1", "T2", "T7"], + transitions: ["T1", "T2", "T6", "T7"], requiresFocusObject: false, requiredAnchors: [], resultShape: "item_list_with_quantity_cost_warehouse_organization", diff --git a/llm_normalizer/backend/dist/services/inventoryLifecycleCueHelpers.js b/llm_normalizer/backend/dist/services/inventoryLifecycleCueHelpers.js index cb841a5..db75198 100644 --- a/llm_normalizer/backend/dist/services/inventoryLifecycleCueHelpers.js +++ b/llm_normalizer/backend/dist/services/inventoryLifecycleCueHelpers.js @@ -18,7 +18,7 @@ function hasInventorySupplierCue(text) { if (/(?:кто\s+(?:был\s+)?продавец|кто\s+нам\s+продал|кто\s+продал\s+нам|(?:^|[\s,.;:!?()\-])(?:продавец|seller)(?=$|[\s,.;:!?()\-]))/iu.test(value)) { return true; } - if (/(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|откуда\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test(value)) { + if (/(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?(?:это|этот\s+товар|эту\s+позицию)\s+поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|откуда\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test(value)) { return true; } return hasInventoryPurchaseStem(value) && /(?:у\s+кого|от\s+кого|где)/iu.test(value); diff --git a/llm_normalizer/backend/src/routes/autoRuns.ts b/llm_normalizer/backend/src/routes/autoRuns.ts index 1bd36cf..2c91c0f 100644 --- a/llm_normalizer/backend/src/routes/autoRuns.ts +++ b/llm_normalizer/backend/src/routes/autoRuns.ts @@ -193,6 +193,10 @@ interface AutoGenHistoryRecord { source_session_id?: string | null; saved_session_file?: string | null; saved_case_set_kind?: string | null; + agent_run?: boolean | null; + agent_focus?: string | null; + architecture_phase?: string | null; + source_spec_file?: string | null; } | null; } @@ -365,7 +369,13 @@ function readAutoGenHistory(): AutoGenHistoryRecord[] { : null, source_session_id: toStringSafe(toRecord(item.context)?.source_session_id), saved_session_file: toStringSafe(toRecord(item.context)?.saved_session_file), - saved_case_set_kind: toStringSafe(toRecord(item.context)?.saved_case_set_kind) + saved_case_set_kind: toStringSafe(toRecord(item.context)?.saved_case_set_kind), + agent_run: toBooleanSafe(toRecord(item.context)?.agent_run), + agent_focus: toStringSafe(toRecord(item.context)?.agent_focus) + ? repairAutogenMojibake(String(toRecord(item.context)?.agent_focus)) + : null, + architecture_phase: toStringSafe(toRecord(item.context)?.architecture_phase), + source_spec_file: toStringSafe(toRecord(item.context)?.source_spec_file) } : null })) @@ -1797,6 +1807,7 @@ function buildSavedSessionCaseSetPayload(input: { generationId: string; title: string | null; questions: string[]; + scenarioTag?: string | null; }): Record { const questions = parseAssistantSessionQuestions(input.questions); const turns = questions.map((question) => ({ @@ -1818,7 +1829,7 @@ function buildSavedSessionCaseSetPayload(input: { ? [ { case_id: caseId, - scenario_tag: "saved_user_sessions", + scenario_tag: toStringSafe(input.scenarioTag) ?? "saved_user_sessions", title: input.title, question_type: turns.length > 1 ? "followup" : "direct", broadness_level: "medium", @@ -1851,7 +1862,11 @@ function rewriteAutoGenCaseSetFile(record: AutoGenHistoryRecord): string | null ? buildSavedSessionCaseSetPayload({ generationId: record.generation_id, title: record.title, - questions: record.questions + questions: record.questions, + scenarioTag: + record.context?.saved_case_set_kind === "agent_semantic_scenario" + ? "agent_saved_user_sessions" + : "saved_user_sessions" }) : buildAutogenCaseSetPayload({ generationId: record.generation_id, @@ -2468,7 +2483,8 @@ export function buildAutoRunsRouter(services: AppServices, openaiClient = new Op buildSavedSessionCaseSetPayload({ generationId, title, - questions + questions, + scenarioTag: "saved_user_sessions" }) ); diff --git a/llm_normalizer/backend/src/services/addressQueryService.ts b/llm_normalizer/backend/src/services/addressQueryService.ts index fc1ff75..913de9a 100644 --- a/llm_normalizer/backend/src/services/addressQueryService.ts +++ b/llm_normalizer/backend/src/services/addressQueryService.ts @@ -9,6 +9,7 @@ import { FEATURE_ASSISTANT_ADDRESS_QUERY_LIVE_V1, SHARED_LLM_CONNECTION_FILE } from "../config"; +import type { AssistantTruthGateContractStatus } from "../types/assistantRuntimeContracts"; import type { AddressCapabilityLayer, AddressCapabilityRouteMode, @@ -4207,6 +4208,150 @@ export class AddressQueryService { debug: debugPayload }; }; + const buildFactualExecutionResult = (input: { + replyText: string; + responseType: AddressResponseType; + responseSemantics?: ComposeReplySemantics; + selectedRecipe: string | null; + mcpCallStatus: AddressMcpCallStatus; + rowsFetched: number; + rawRowsReceived: number; + rowsAfterAccountScope: number; + rowsAfterRecipeFilter: number; + rowsMaterialized: number; + rowsMatched: number; + rawRowKeysSample: string[]; + materializationDropReason: + | "none" + | "dropped_by_account_scope_filter" + | "missing_period_and_registrator_fields" + | "missing_period_field" + | "missing_registrator_field" + | "unknown_row_shape"; + accountScopeMode: "strict" | "preferred"; + accountScopeFallbackApplied: boolean; + accountScopeAudit: AccountScopeAuditDebug; + anchor: AnchorResolutionDebug; + matchFailureStage: AddressMatchFailureStage; + matchFailureReason: string | null; + limitations: string[]; + reasons: string[]; + routeExpectationAudit?: AddressRouteExpectationAuditState; + capabilityAudit?: AddressCapabilityAudit; + shadowRouteAudit?: AddressShadowRouteAudit; + semanticFrame?: AddressSemanticFrame | null; + runtimeReadiness?: AddressRuntimeReadiness; + limitedReasonCategory?: AddressLimitedReasonCategory | null; + truthGateStatusHint?: AssistantTruthGateContractStatus | null; + extractedFilters?: AddressFilterSet; + }): AddressExecutionResult => { + const resultSemantics = mergeAddressResultSemantics( + deriveAddressResultSemantics({ + intent: intent.intent, + selectedRecipe: input.selectedRecipe, + filters: input.extractedFilters ?? filters.extracted_filters, + semanticFrame: input.semanticFrame ?? semanticFrame, + responseType: input.responseType, + rowsMatched: input.rowsMatched + }), + input.responseSemantics + ); + const routeExpectationAudit = + input.routeExpectationAudit ?? + buildRouteExpectationAudit({ + intent: routeExpectationIntent, + selectedRecipe: input.selectedRecipe, + requestedResultMode, + resultMode: resultSemantics.result_mode + }); + const debugPayload = attachAddressTruthGate( + { + detected_mode: mode.mode, + detected_mode_confidence: mode.confidence, + query_shape: shape.shape, + query_shape_confidence: shape.confidence, + detected_intent: intent.intent, + detected_intent_confidence: intent.confidence, + extracted_filters: input.extractedFilters ?? filters.extracted_filters, + missing_required_filters: [], + selected_recipe: input.selectedRecipe, + mcp_call_status_legacy: toLegacyMcpStatus(input.mcpCallStatus), + account_scope_mode: input.accountScopeMode, + account_scope_fallback_applied: input.accountScopeFallbackApplied, + anchor_type: input.anchor.anchor_type, + anchor_value_raw: input.anchor.anchor_value_raw, + anchor_value_resolved: input.anchor.anchor_value_resolved, + resolver_confidence: input.anchor.resolver_confidence, + ambiguity_count: input.anchor.ambiguity_count, + match_failure_stage: input.matchFailureStage, + match_failure_reason: input.matchFailureReason, + mcp_call_status: input.mcpCallStatus, + rows_fetched: input.rowsFetched, + raw_rows_received: input.rawRowsReceived, + rows_after_account_scope: input.rowsAfterAccountScope, + rows_after_recipe_filter: input.rowsAfterRecipeFilter, + rows_materialized: input.rowsMaterialized, + rows_matched: input.rowsMatched, + raw_row_keys_sample: input.rawRowKeysSample, + materialization_drop_reason: input.materializationDropReason, + account_token_raw: input.accountScopeAudit.accountTokenRaw, + account_token_normalized: input.accountScopeAudit.accountTokenNormalized, + account_scope_fields_checked: input.accountScopeAudit.accountScopeFieldsChecked, + account_scope_match_strategy: input.accountScopeAudit.accountScopeMatchStrategy, + account_scope_drop_reason: input.accountScopeAudit.accountScopeDropReason, + runtime_readiness: input.runtimeReadiness ?? "LIVE_QUERYABLE_WITH_LIMITS", + limited_reason_category: input.limitedReasonCategory ?? null, + response_type: input.responseType, + route_expectation_status: routeExpectationAudit.status, + route_expectation_reason: routeExpectationAudit.reason, + route_expectation_expected_selected_recipes: routeExpectationAudit.expectedSelectedRecipes, + route_expectation_expected_requested_result_modes: routeExpectationAudit.expectedRequestedResultModes, + route_expectation_expected_result_modes: routeExpectationAudit.expectedResultModes, + semantic_frame: input.semanticFrame ?? semanticFrame, + ...resultSemantics, + limitations: input.limitations, + reasons: input.reasons, + ...(input.capabilityAudit + ? { + capability_id: input.capabilityAudit.capabilityId, + capability_layer: input.capabilityAudit.layer, + capability_route_mode: input.capabilityAudit.routeMode, + capability_route_enabled: input.capabilityAudit.enabled, + capability_route_reason: input.capabilityAudit.reason + } + : {}), + ...(input.shadowRouteAudit + ? { + shadow_route_intent: input.shadowRouteAudit.intent, + shadow_route_selected_recipe: input.shadowRouteAudit.selectedRecipe, + shadow_route_status: input.shadowRouteAudit.status + } + : {}) + }, + { + intent: intent.intent, + filters: input.extractedFilters ?? filters.extracted_filters, + semanticFrame: input.semanticFrame ?? semanticFrame, + selectedRecipe: input.selectedRecipe, + truthGateStatusHint: input.truthGateStatusHint ?? null, + rowsMatched: input.rowsMatched, + limitedReasonCategory: input.limitedReasonCategory ?? null, + runtimeReadiness: input.runtimeReadiness ?? "LIVE_QUERYABLE_WITH_LIMITS", + limitations: input.limitations, + reasons: input.reasons, + routeExpectationStatus: routeExpectationAudit.status, + routeExpectationReason: routeExpectationAudit.reason, + replyType: inferReplyType(input.responseType) + } + ); + return { + handled: true, + reply_text: input.replyText, + reply_type: inferReplyType(input.responseType), + response_type: input.responseType, + debug: debugPayload + }; + }; if (organizationWarehouseRecoveryApplied) { if (!baseReasons.includes("organization_scope_live_grounding_recovered_rows")) { baseReasons.push("organization_scope_live_grounding_recovered_rows"); @@ -4262,67 +4407,33 @@ export class AddressQueryService { recoveredBankRows.length > 0 ? "Документный фильтр в live дал пустой набор; показываю связанные банковские операции по договору." : "Документный фильтр в live дал пустой набор; показываю найденные строки по договорному якорю."; - return { - handled: true, - reply_text: `${replyPrefix}\n${factual.text}`, - reply_type: inferReplyType(factual.responseType), - response_type: factual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: effectiveRecipeId, - mcp_call_status_legacy: toLegacyMcpStatus("matched_non_empty"), - account_scope_mode: plan.account_scope_mode, - account_scope_fallback_applied: accountScopeFallbackApplied, - anchor_type: anchor.anchor_type, - anchor_value_raw: anchor.anchor_value_raw, - anchor_value_resolved: anchor.anchor_value_resolved, - resolver_confidence: anchor.resolver_confidence, - ambiguity_count: anchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: "matched_non_empty", - rows_fetched: mcp.fetched_rows, - raw_rows_received: mcp.raw_rows.length, - rows_after_account_scope: normalizedRows.length, - rows_after_recipe_filter: filterByAnchors.length, - rows_materialized: normalizedRows.length, - rows_matched: recoveredRows.length, - raw_row_keys_sample: rowDiagnostics.rawRowKeysSample, - materialization_drop_reason: rowDiagnostics.materializationDropReason, - account_token_raw: accountScopeAudit.accountTokenRaw, - account_token_normalized: accountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: accountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: accountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: accountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: factual.responseType, - ...mergeAddressResultSemantics( - deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: effectiveRecipeId, - filters: filters.extracted_filters, - semanticFrame, - responseType: factual.responseType, - rowsMatched: recoveredRows.length - }), - factual.semantics - ), - limitations: [...filters.warnings, recoveryReason], - reasons: withConfirmedBalanceFallbackReason( - [...baseReasons, recoveryReason], - requestedResultMode, - factual.semantics - ) - } - }; + return buildFactualExecutionResult({ + replyText: `${replyPrefix}\n${factual.text}`, + responseType: factual.responseType, + responseSemantics: factual.semantics, + selectedRecipe: effectiveRecipeId, + mcpCallStatus: "matched_non_empty", + rowsFetched: mcp.fetched_rows, + rawRowsReceived: mcp.raw_rows.length, + rowsAfterAccountScope: normalizedRows.length, + rowsAfterRecipeFilter: filterByAnchors.length, + rowsMaterialized: normalizedRows.length, + rowsMatched: recoveredRows.length, + rawRowKeysSample: rowDiagnostics.rawRowKeysSample, + materializationDropReason: rowDiagnostics.materializationDropReason, + accountScopeMode: plan.account_scope_mode, + accountScopeFallbackApplied, + accountScopeAudit, + anchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: [...filters.warnings, recoveryReason], + reasons: withConfirmedBalanceFallbackReason([...baseReasons, recoveryReason], requestedResultMode, factual.semantics), + limitedReasonCategory: "recipe_visibility_gap", + capabilityAudit, + shadowRouteAudit, + semanticFrame + }); } } @@ -4411,67 +4522,32 @@ export class AddressQueryService { const expandedPrefix = `Период сохранен. Глубина live-выборки автоматически расширена до ${expandedPlan.limit} строк.`; const expandedLimitations = [...filters.warnings, "query_limit_auto_expanded_for_anchor_recovery"]; const expandedReasons = [...baseReasons, "query_limit_auto_expanded_for_anchor_recovery"]; - return { - handled: true, - reply_text: `${expandedPrefix}\n${expandedFactual.text}`, - reply_type: inferReplyType(expandedFactual.responseType), - response_type: expandedFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: expandedSelection.selected_recipe.recipe_id, - mcp_call_status_legacy: toLegacyMcpStatus(expandedStageStatus), - account_scope_mode: expandedPlan.account_scope_mode, - account_scope_fallback_applied: expandedAccountScopeFallbackApplied, - anchor_type: expandedAnchor.anchor_type, - anchor_value_raw: expandedAnchor.anchor_value_raw, - anchor_value_resolved: expandedAnchor.anchor_value_resolved, - resolver_confidence: expandedAnchor.resolver_confidence, - ambiguity_count: expandedAnchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: expandedStageStatus, - rows_fetched: expandedMcp.fetched_rows, - raw_rows_received: expandedMcp.raw_rows.length, - rows_after_account_scope: expandedNormalizedRows.length, - rows_after_recipe_filter: expandedRowsByAnchor.length, - rows_materialized: expandedNormalizedRows.length, - rows_matched: expandedFilteredRows.length, - raw_row_keys_sample: expandedRowDiagnostics.rawRowKeysSample, - materialization_drop_reason: expandedRowDiagnostics.materializationDropReason, - account_token_raw: expandedAccountScopeAudit.accountTokenRaw, - account_token_normalized: expandedAccountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: expandedAccountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: expandedAccountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: expandedAccountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: expandedFactual.responseType, - ...mergeAddressResultSemantics( - deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: expandedSelection.selected_recipe.recipe_id, - filters: filters.extracted_filters, - semanticFrame, - responseType: expandedFactual.responseType, - rowsMatched: expandedFilteredRows.length - }), - expandedFactual.semantics - ), - limitations: expandedLimitations, - reasons: withConfirmedBalanceFallbackReason( - expandedReasons, - requestedResultMode, - expandedFactual.semantics - ) - } - }; + return buildFactualExecutionResult({ + replyText: `${expandedPrefix}\n${expandedFactual.text}`, + responseType: expandedFactual.responseType, + responseSemantics: expandedFactual.semantics, + selectedRecipe: expandedSelection.selected_recipe.recipe_id, + mcpCallStatus: expandedStageStatus, + rowsFetched: expandedMcp.fetched_rows, + rawRowsReceived: expandedMcp.raw_rows.length, + rowsAfterAccountScope: expandedNormalizedRows.length, + rowsAfterRecipeFilter: expandedRowsByAnchor.length, + rowsMaterialized: expandedNormalizedRows.length, + rowsMatched: expandedFilteredRows.length, + rawRowKeysSample: expandedRowDiagnostics.rawRowKeysSample, + materializationDropReason: expandedRowDiagnostics.materializationDropReason, + accountScopeMode: expandedPlan.account_scope_mode, + accountScopeFallbackApplied: expandedAccountScopeFallbackApplied, + accountScopeAudit: expandedAccountScopeAudit, + anchor: expandedAnchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: expandedLimitations, + reasons: withConfirmedBalanceFallbackReason(expandedReasons, requestedResultMode, expandedFactual.semantics), + capabilityAudit, + shadowRouteAudit, + semanticFrame + }); } } } @@ -4586,72 +4662,34 @@ export class AddressQueryService { requestedResultMode, resultMode: broadenedResultSemantics.result_mode }); - return { - handled: true, - reply_text: injectNoticeAfterLeadLine(broadenedFactual.text, broadenedPrefix), - reply_type: inferReplyType(broadenedFactual.responseType), - response_type: broadenedFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: broadenedSelection.selected_recipe.recipe_id, - mcp_call_status_legacy: toLegacyMcpStatus(broadenedStageStatus), - account_scope_mode: broadenedPlan.account_scope_mode, - account_scope_fallback_applied: broadenedAccountScopeFallbackApplied, - anchor_type: broadenedAnchor.anchor_type, - anchor_value_raw: broadenedAnchor.anchor_value_raw, - anchor_value_resolved: broadenedAnchor.anchor_value_resolved, - resolver_confidence: broadenedAnchor.resolver_confidence, - ambiguity_count: broadenedAnchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: broadenedStageStatus, - rows_fetched: broadenedMcp.fetched_rows, - raw_rows_received: broadenedMcp.raw_rows.length, - rows_after_account_scope: broadenedNormalizedRows.length, - rows_after_recipe_filter: broadenedRowsByAnchor.length, - rows_materialized: broadenedNormalizedRows.length, - rows_matched: broadenedFilteredRows.length, - raw_row_keys_sample: broadenedRowDiagnostics.rawRowKeysSample, - materialization_drop_reason: broadenedRowDiagnostics.materializationDropReason, - account_token_raw: broadenedAccountScopeAudit.accountTokenRaw, - account_token_normalized: broadenedAccountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: broadenedAccountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: broadenedAccountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: broadenedAccountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: broadenedFactual.responseType, - capability_id: capabilityAudit.capabilityId, - capability_layer: capabilityAudit.layer, - capability_route_mode: capabilityAudit.routeMode, - capability_route_enabled: capabilityAudit.enabled, - capability_route_reason: capabilityAudit.reason, - shadow_route_intent: shadowRouteAudit.intent, - shadow_route_selected_recipe: shadowRouteAudit.selectedRecipe, - shadow_route_status: shadowRouteAudit.status, - route_expectation_status: broadenedRouteExpectationAudit.status, - route_expectation_reason: broadenedRouteExpectationAudit.reason, - route_expectation_expected_selected_recipes: broadenedRouteExpectationAudit.expectedSelectedRecipes, - route_expectation_expected_requested_result_modes: - broadenedRouteExpectationAudit.expectedRequestedResultModes, - route_expectation_expected_result_modes: broadenedRouteExpectationAudit.expectedResultModes, - semantic_frame: semanticFrame, - ...broadenedResultSemantics, - limitations: broadenedLimitations, - reasons: withConfirmedBalanceFallbackReason( - broadenedReasons, - requestedResultMode, - broadenedFactual.semantics - ) - } - }; + return buildFactualExecutionResult({ + replyText: injectNoticeAfterLeadLine(broadenedFactual.text, broadenedPrefix), + responseType: broadenedFactual.responseType, + responseSemantics: broadenedFactual.semantics, + selectedRecipe: broadenedSelection.selected_recipe.recipe_id, + mcpCallStatus: broadenedStageStatus, + rowsFetched: broadenedMcp.fetched_rows, + rawRowsReceived: broadenedMcp.raw_rows.length, + rowsAfterAccountScope: broadenedNormalizedRows.length, + rowsAfterRecipeFilter: broadenedRowsByAnchor.length, + rowsMaterialized: broadenedNormalizedRows.length, + rowsMatched: broadenedFilteredRows.length, + rawRowKeysSample: broadenedRowDiagnostics.rawRowKeysSample, + materializationDropReason: broadenedRowDiagnostics.materializationDropReason, + accountScopeMode: broadenedPlan.account_scope_mode, + accountScopeFallbackApplied: broadenedAccountScopeFallbackApplied, + accountScopeAudit: broadenedAccountScopeAudit, + anchor: broadenedAnchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: broadenedLimitations, + reasons: withConfirmedBalanceFallbackReason(broadenedReasons, requestedResultMode, broadenedFactual.semantics), + routeExpectationAudit: broadenedRouteExpectationAudit, + capabilityAudit, + shadowRouteAudit, + semanticFrame, + truthGateStatusHint: "limited_temporal_or_contextual" + }); } } } @@ -4745,67 +4783,33 @@ export class AddressQueryService { : ""; const historicalLimitations = [...filters.warnings, "historical_window_sort_recovery_applied"]; const historicalReasons = [...baseReasons, "historical_window_sort_recovery_applied"]; - return { - handled: true, - reply_text: `${historicalPrefix}\n${historicalFactual.text}${historicalSuggestion}`, - reply_type: inferReplyType(historicalFactual.responseType), - response_type: historicalFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: historicalSelection.selected_recipe.recipe_id, - mcp_call_status_legacy: toLegacyMcpStatus(historicalStageStatus), - account_scope_mode: historicalPlan.account_scope_mode, - account_scope_fallback_applied: historicalAccountScopeFallbackApplied, - anchor_type: historicalAnchor.anchor_type, - anchor_value_raw: historicalAnchor.anchor_value_raw, - anchor_value_resolved: historicalAnchor.anchor_value_resolved, - resolver_confidence: historicalAnchor.resolver_confidence, - ambiguity_count: historicalAnchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: historicalStageStatus, - rows_fetched: historicalMcp.fetched_rows, - raw_rows_received: historicalMcp.raw_rows.length, - rows_after_account_scope: historicalNormalizedRows.length, - rows_after_recipe_filter: historicalRowsByAnchor.length, - rows_materialized: historicalNormalizedRows.length, - rows_matched: historicalFilteredRows.length, - raw_row_keys_sample: historicalRowDiagnostics.rawRowKeysSample, - materialization_drop_reason: historicalRowDiagnostics.materializationDropReason, - account_token_raw: historicalAccountScopeAudit.accountTokenRaw, - account_token_normalized: historicalAccountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: historicalAccountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: historicalAccountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: historicalAccountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: historicalFactual.responseType, - ...mergeAddressResultSemantics( - deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: historicalSelection.selected_recipe.recipe_id, - filters: filters.extracted_filters, - semanticFrame, - responseType: historicalFactual.responseType, - rowsMatched: historicalFilteredRows.length - }), - historicalFactual.semantics - ), - limitations: historicalLimitations, - reasons: withConfirmedBalanceFallbackReason( - historicalReasons, - requestedResultMode, - historicalFactual.semantics - ) - } - }; + return buildFactualExecutionResult({ + replyText: `${historicalPrefix}\n${historicalFactual.text}${historicalSuggestion}`, + responseType: historicalFactual.responseType, + responseSemantics: historicalFactual.semantics, + selectedRecipe: historicalSelection.selected_recipe.recipe_id, + mcpCallStatus: historicalStageStatus, + rowsFetched: historicalMcp.fetched_rows, + rawRowsReceived: historicalMcp.raw_rows.length, + rowsAfterAccountScope: historicalNormalizedRows.length, + rowsAfterRecipeFilter: historicalRowsByAnchor.length, + rowsMaterialized: historicalNormalizedRows.length, + rowsMatched: historicalFilteredRows.length, + rawRowKeysSample: historicalRowDiagnostics.rawRowKeysSample, + materializationDropReason: historicalRowDiagnostics.materializationDropReason, + accountScopeMode: historicalPlan.account_scope_mode, + accountScopeFallbackApplied: historicalAccountScopeFallbackApplied, + accountScopeAudit: historicalAccountScopeAudit, + anchor: historicalAnchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: historicalLimitations, + reasons: withConfirmedBalanceFallbackReason(historicalReasons, requestedResultMode, historicalFactual.semantics), + capabilityAudit, + shadowRouteAudit, + semanticFrame, + truthGateStatusHint: "limited_temporal_or_contextual" + }); } } } @@ -4832,67 +4836,33 @@ export class AddressQueryService { : ""; const fallbackLimitations = [...filters.warnings, "anchor_not_matched_fallback_rows"]; const fallbackReasons = [...baseReasons, "anchor_not_matched_fallback_rows"]; - return { - handled: true, - reply_text: `${fallbackPrefix}\n${fallbackFactual.text}${fallbackSuggestion}`, - reply_type: inferReplyType(fallbackFactual.responseType), - response_type: fallbackFactual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: effectiveRecipeId, - mcp_call_status_legacy: "matched_non_empty", - account_scope_mode: plan.account_scope_mode, - account_scope_fallback_applied: accountScopeFallbackApplied, - anchor_type: anchor.anchor_type, - anchor_value_raw: anchor.anchor_value_raw, - anchor_value_resolved: anchor.anchor_value_resolved, - resolver_confidence: anchor.resolver_confidence, - ambiguity_count: anchor.ambiguity_count, - match_failure_stage: matchFailureStage, - match_failure_reason: matchFailureReason, - mcp_call_status: "matched_non_empty", - rows_fetched: mcp.fetched_rows, - raw_rows_received: mcp.raw_rows.length, - rows_after_account_scope: normalizedRows.length, - rows_after_recipe_filter: filterByAnchors.length, - rows_materialized: normalizedRows.length, - rows_matched: documentBankFallbackRows.length, - raw_row_keys_sample: rowDiagnostics.rawRowKeysSample, - materialization_drop_reason: rowDiagnostics.materializationDropReason, - account_token_raw: accountScopeAudit.accountTokenRaw, - account_token_normalized: accountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: accountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: accountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: accountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: fallbackFactual.responseType, - ...mergeAddressResultSemantics( - deriveAddressResultSemantics({ - intent: intent.intent, - selectedRecipe: effectiveRecipeId, - filters: filters.extracted_filters, - semanticFrame, - responseType: fallbackFactual.responseType, - rowsMatched: documentBankFallbackRows.length - }), - fallbackFactual.semantics - ), - limitations: fallbackLimitations, - reasons: withConfirmedBalanceFallbackReason( - fallbackReasons, - requestedResultMode, - fallbackFactual.semantics - ) - } - }; + return buildFactualExecutionResult({ + replyText: `${fallbackPrefix}\n${fallbackFactual.text}${fallbackSuggestion}`, + responseType: fallbackFactual.responseType, + responseSemantics: fallbackFactual.semantics, + selectedRecipe: effectiveRecipeId, + mcpCallStatus: "matched_non_empty", + rowsFetched: mcp.fetched_rows, + rawRowsReceived: mcp.raw_rows.length, + rowsAfterAccountScope: normalizedRows.length, + rowsAfterRecipeFilter: filterByAnchors.length, + rowsMaterialized: normalizedRows.length, + rowsMatched: documentBankFallbackRows.length, + rawRowKeysSample: rowDiagnostics.rawRowKeysSample, + materializationDropReason: rowDiagnostics.materializationDropReason, + accountScopeMode: plan.account_scope_mode, + accountScopeFallbackApplied, + accountScopeAudit, + anchor, + matchFailureStage, + matchFailureReason, + limitations: fallbackLimitations, + reasons: withConfirmedBalanceFallbackReason(fallbackReasons, requestedResultMode, fallbackFactual.semantics), + capabilityAudit, + shadowRouteAudit, + limitedReasonCategory: "recipe_visibility_gap", + semanticFrame + }); } } @@ -5223,71 +5193,37 @@ export class AddressQueryService { finalRouteExpectationAudit.status === "mismatch" ? [...baseReasons, `route_expectation_mismatch:${finalRouteExpectationAudit.reason}`] : baseReasons; - return { - handled: true, - reply_text: factual.text, - reply_type: inferReplyType(factual.responseType), - response_type: factual.responseType, - debug: { - detected_mode: mode.mode, - detected_mode_confidence: mode.confidence, - query_shape: shape.shape, - query_shape_confidence: shape.confidence, - detected_intent: intent.intent, - detected_intent_confidence: intent.confidence, - extracted_filters: filters.extracted_filters, - missing_required_filters: [], - selected_recipe: effectiveRecipeId, - mcp_call_status_legacy: toLegacyMcpStatus(stageStatus), - account_scope_mode: plan.account_scope_mode, - account_scope_fallback_applied: accountScopeFallbackApplied, - anchor_type: anchor.anchor_type, - anchor_value_raw: anchor.anchor_value_raw, - anchor_value_resolved: anchor.anchor_value_resolved, - resolver_confidence: anchor.resolver_confidence, - ambiguity_count: anchor.ambiguity_count, - match_failure_stage: "none", - match_failure_reason: null, - mcp_call_status: stageStatus, - rows_fetched: mcp.fetched_rows, - raw_rows_received: mcp.raw_rows.length, - rows_after_account_scope: normalizedRows.length, - rows_after_recipe_filter: filterByAnchors.length, - rows_materialized: normalizedRows.length, - rows_matched: filteredRows.length, - raw_row_keys_sample: rowDiagnostics.rawRowKeysSample, - materialization_drop_reason: rowDiagnostics.materializationDropReason, - account_token_raw: accountScopeAudit.accountTokenRaw, - account_token_normalized: accountScopeAudit.accountTokenNormalized, - account_scope_fields_checked: accountScopeAudit.accountScopeFieldsChecked, - account_scope_match_strategy: accountScopeAudit.accountScopeMatchStrategy, - account_scope_drop_reason: accountScopeAudit.accountScopeDropReason, - runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", - limited_reason_category: null, - response_type: factual.responseType, - capability_id: capabilityAudit.capabilityId, - capability_layer: capabilityAudit.layer, - capability_route_mode: capabilityAudit.routeMode, - capability_route_enabled: capabilityAudit.enabled, - capability_route_reason: capabilityAudit.reason, - shadow_route_intent: shadowRouteAudit.intent, - shadow_route_selected_recipe: shadowRouteAudit.selectedRecipe, - shadow_route_status: shadowRouteAudit.status, - route_expectation_status: finalRouteExpectationAudit.status, - route_expectation_reason: finalRouteExpectationAudit.reason, - route_expectation_expected_selected_recipes: finalRouteExpectationAudit.expectedSelectedRecipes, - route_expectation_expected_requested_result_modes: finalRouteExpectationAudit.expectedRequestedResultModes, - route_expectation_expected_result_modes: finalRouteExpectationAudit.expectedResultModes, - semantic_frame: semanticFrame, - ...factualResultSemantics, - limitations: factualLimitations, - reasons: withConfirmedBalanceFallbackReason( - reasonsWithRouteExpectation, - requestedResultMode, - factual.semantics, - factualResultSemantics.result_mode - ) - } - }; + return buildFactualExecutionResult({ + replyText: factual.text, + responseType: factual.responseType, + responseSemantics: factual.semantics, + selectedRecipe: effectiveRecipeId, + mcpCallStatus: stageStatus, + rowsFetched: mcp.fetched_rows, + rawRowsReceived: mcp.raw_rows.length, + rowsAfterAccountScope: normalizedRows.length, + rowsAfterRecipeFilter: filterByAnchors.length, + rowsMaterialized: normalizedRows.length, + rowsMatched: filteredRows.length, + rawRowKeysSample: rowDiagnostics.rawRowKeysSample, + materializationDropReason: rowDiagnostics.materializationDropReason, + accountScopeMode: plan.account_scope_mode, + accountScopeFallbackApplied, + accountScopeAudit, + anchor, + matchFailureStage: "none", + matchFailureReason: null, + limitations: factualLimitations, + reasons: withConfirmedBalanceFallbackReason( + reasonsWithRouteExpectation, + requestedResultMode, + factual.semantics, + factualResultSemantics.result_mode + ), + routeExpectationAudit: finalRouteExpectationAudit, + capabilityAudit, + shadowRouteAudit, + semanticFrame + }); } } diff --git a/llm_normalizer/backend/src/services/addressTruthGatePolicy.ts b/llm_normalizer/backend/src/services/addressTruthGatePolicy.ts index bb84e37..bc35cc5 100644 --- a/llm_normalizer/backend/src/services/addressTruthGatePolicy.ts +++ b/llm_normalizer/backend/src/services/addressTruthGatePolicy.ts @@ -28,6 +28,7 @@ export interface ResolveAddressTruthGateInput { filters?: AddressFilterSet | null; semanticFrame?: AddressSemanticFrame | null; selectedRecipe?: string | null; + truthGateStatusHint?: AssistantTruthGateContractStatus | null; rowsMatched?: number; limitedReasonCategory?: AddressLimitedReasonCategory | null; runtimeReadiness?: AddressRuntimeReadiness | null; @@ -170,6 +171,9 @@ function hasReusableRootScope(input: ResolveAddressTruthGateInput): boolean { } function truthGateStatusFrom(input: ResolveAddressTruthGateInput): AssistantTruthGateContractStatus { + if (input.truthGateStatusHint) { + return input.truthGateStatusHint; + } const missingRequiredFilters = input.missingRequiredFilters ?? []; if (input.routeExpectationStatus === "mismatch") { return "blocked_route_expectation_failure"; diff --git a/llm_normalizer/backend/src/services/assistantRuntimeContractRegistry.ts b/llm_normalizer/backend/src/services/assistantRuntimeContractRegistry.ts index 4a63b35..1fe1463 100644 --- a/llm_normalizer/backend/src/services/assistantRuntimeContractRegistry.ts +++ b/llm_normalizer/backend/src/services/assistantRuntimeContractRegistry.ts @@ -207,7 +207,7 @@ export const INVENTORY_CAPABILITY_CONTRACTS: readonly AssistantCapabilityContrac capability_id: "confirmed_inventory_on_hand_as_of_date", intent_ids: ["inventory_on_hand_as_of_date"], entry_modes: ["root_entry", "root_followup", "clarification_resume"], - transitions: ["T1", "T2", "T7"], + transitions: ["T1", "T2", "T6", "T7"], requiresFocusObject: false, requiredAnchors: [], resultShape: "item_list_with_quantity_cost_warehouse_organization", diff --git a/llm_normalizer/backend/src/services/inventoryLifecycleCueHelpers.ts b/llm_normalizer/backend/src/services/inventoryLifecycleCueHelpers.ts index c202c7d..88fdd8d 100644 --- a/llm_normalizer/backend/src/services/inventoryLifecycleCueHelpers.ts +++ b/llm_normalizer/backend/src/services/inventoryLifecycleCueHelpers.ts @@ -15,7 +15,7 @@ export function hasInventorySupplierCue(text: string): boolean { return true; } if ( - /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|откуда\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test( + /(?:кто\s+(?:(?:это|этот\s+товар|эту\s+позицию)\s+)?(?:нам\s+)?поставил|кто\s+(?:нам\s+)?(?:это|этот\s+товар|эту\s+позицию)\s+поставил|кто\s+(?:нам\s+)?поставил\s+(?:это|этот\s+товар|эту\s+позицию)|от\s+какого\s+поставщика|у\s+какого\s+поставщика|от\s+кого\s+куплен|у\s+кого\s+купили|у\s+кого\s+куплено|где\s+(?:мы\s+)?купили(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|откуда\s+(?:мы\s+)?взяли(?:\s+(?:это|его|этот\s+товар|эту\s+позицию))?|где\s+куплено|supplier|vendor|поставщик)/iu.test( value ) ) { diff --git a/llm_normalizer/backend/tests/addressCounterpartyItemFlowAndOpenItemsRoute.test.ts b/llm_normalizer/backend/tests/addressCounterpartyItemFlowAndOpenItemsRoute.test.ts index 5467aeb..6026356 100644 --- a/llm_normalizer/backend/tests/addressCounterpartyItemFlowAndOpenItemsRoute.test.ts +++ b/llm_normalizer/backend/tests/addressCounterpartyItemFlowAndOpenItemsRoute.test.ts @@ -114,6 +114,7 @@ describe("counterparty shipment item flow and open-items routing", () => { expect(result?.handled).toBe(true); expect(result?.response_type).toBe("FACTUAL_LIST"); expect(result?.debug.detected_intent).toBe("list_documents_by_counterparty"); + expect(result?.debug.address_truth_gate_v1?.truth_gate_status).toBe("full_confirmed"); expect(String(result?.reply_text ?? "")).toContain("Контрагент: Чепурнов П.Д."); expect(String(result?.reply_text ?? "")).toContain("Позиции:"); expect(String(result?.reply_text ?? "")).toContain("Кабель силовой"); diff --git a/llm_normalizer/backend/tests/addressInventoryRootFrameRegression.test.ts b/llm_normalizer/backend/tests/addressInventoryRootFrameRegression.test.ts index d78e472..f008184 100644 --- a/llm_normalizer/backend/tests/addressInventoryRootFrameRegression.test.ts +++ b/llm_normalizer/backend/tests/addressInventoryRootFrameRegression.test.ts @@ -144,6 +144,38 @@ describe("inventory root frame regressions", () => { expect(result?.baseReasons).toContain("address_followup_context_applied"); }); + it("restores inventory root frame for 'покажи еще раз остатки на эту же дату' after item documents drilldown", () => { + const result = runAddressDecomposeStage("покажи еще раз остатки на эту же дату", { + previous_intent: "inventory_purchase_documents_for_item", + previous_filters: { + item: "Столешница 600*3050*26 альмандин", + organization: 'ООО "Альтернатива Плюс"', + as_of_date: "2021-03-31" + }, + previous_anchor_type: "item", + previous_anchor_value: "Столешница 600*3050*26 альмандин", + root_intent: "inventory_on_hand_as_of_date", + root_filters: { + organization: 'ООО "Альтернатива Плюс"', + period_from: "2021-03-01", + period_to: "2021-03-31", + as_of_date: "2021-03-31" + }, + root_anchor_type: "organization", + root_anchor_value: 'ООО "Альтернатива Плюс"', + current_frame_kind: "inventory_drilldown" + }); + + expect(result).not.toBeNull(); + expect(result?.intent.intent).toBe("inventory_on_hand_as_of_date"); + expect(result?.intent.reasons).toContain("intent_restored_to_inventory_root_frame"); + expect(result?.filters.extracted_filters.organization).toBe('ООО "Альтернатива Плюс"'); + expect(result?.filters.extracted_filters.as_of_date).toBe("2021-03-31"); + expect(result?.filters.extracted_filters.period_from).toBe("2021-03-01"); + expect(result?.filters.extracted_filters.period_to).toBe("2021-03-31"); + expect(result?.filters.extracted_filters.item).toBeUndefined(); + }); + it("restores inventory root frame for root-context-only month follow-up after drilldown", () => { const result = runAddressDecomposeStage("остатки на июль 2019", { previous_filters: { diff --git a/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts b/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts index 6e7dda1..60257c6 100644 --- a/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts +++ b/llm_normalizer/backend/tests/addressInventorySelectedObjectFollowup.test.ts @@ -107,6 +107,8 @@ describe("inventory selected-object follow-up", () => { expect(result?.debug.capability_route_mode).toBe("exact"); expect(result?.debug.reasons).toContain("period_window_auto_broadened_to_available_data"); expect(result?.debug.limitations).toContain("period_window_auto_broadened_to_available_data"); + expect(result?.debug.address_truth_gate_v1?.truth_gate_status).toBe("limited_temporal_or_contextual"); + expect(result?.debug.address_truth_gate_v1?.carryover_eligibility).toBe("object_only"); const replyLines = String(result?.reply_text ?? "").split("\n"); expect(replyLines[0]).toContain("По позиции Кромка с клеем 33 альмандин 137 м"); expect(replyLines[0]).toContain("до 31.03.2021 подтвержден поставщик"); @@ -197,6 +199,56 @@ describe("inventory selected-object follow-up", () => { expect(String(result?.reply_text ?? "")).toContain("Торговый дом \\Союз МСК\\"); }); + it("handles selected-object supplier wording 'кто нам это поставил' as provenance follow-up", async () => { + executeAddressMcpQueryMock.mockResolvedValueOnce({ + fetched_rows: 1, + matched_rows: 1, + raw_rows: [ + { + Period: "2019-02-12T00:00:00Z", + Registrator: "Поступление товаров и услуг 00000000003 от 12.02.2019 0:00:00", + AccountDt: "41.01", + AccountKt: "60.01", + Amount: 3690, + SubcontoDt1: "Столешница 600*3050*26 альмандин", + SubcontoDt3: "Основной склад", + SubcontoKt1: "Торговый дом \\Союз", + SubcontoKt2: "Договор поставки № 12 от 01.02.2019", + Organization: "ООО \\Альтернатива Плюс\\" + } + ], + rows: [], + error: null + }); + + const service = new AddressQueryService(); + const result = await service.tryHandle( + 'По выбранному объекту "Столешница 600*3050*26 альмандин": кто нам это поставил?', + { + followupContext: { + previous_intent: "inventory_on_hand_as_of_date", + previous_filters: { + as_of_date: "2021-03-31", + period_from: "2021-03-01", + period_to: "2021-03-31", + warehouse: "Основной склад", + organization: "ООО \\Альтернатива Плюс\\" + }, + previous_anchor_type: "unknown", + previous_anchor_value: null + } + } + ); + + expect(result?.handled).toBe(true); + expect(result?.response_type).toBe("FACTUAL_SUMMARY"); + expect(result?.debug.detected_intent).toBe("inventory_purchase_provenance_for_item"); + expect(result?.debug.extracted_filters?.item).toBe("Столешница 600*3050*26 альмандин"); + expect(result?.debug.extracted_filters?.as_of_date).toBeUndefined(); + expect(result?.debug.capability_id).toBe("inventory_inventory_purchase_provenance_for_item"); + expect(String(result?.reply_text ?? "")).toContain("Торговый дом \\Союз"); + }); + it("handles selected-object colloquial supplier wording 'у кого купили' as provenance follow-up", async () => { executeAddressMcpQueryMock.mockResolvedValueOnce({ fetched_rows: 1, diff --git a/llm_normalizer/backend/tests/assistantCapabilityRuntimeBindingAdapter.test.ts b/llm_normalizer/backend/tests/assistantCapabilityRuntimeBindingAdapter.test.ts index 554d441..2f4da70 100644 --- a/llm_normalizer/backend/tests/assistantCapabilityRuntimeBindingAdapter.test.ts +++ b/llm_normalizer/backend/tests/assistantCapabilityRuntimeBindingAdapter.test.ts @@ -123,6 +123,38 @@ describe("assistant capability runtime binding adapter", () => { expect(binding.violations).toContain("transition_not_supported_by_capability"); }); + it("allows inventory root capability to return through T6 after a drilldown pivot", () => { + const binding = resolveAssistantCapabilityRuntimeBinding({ + addressDebug: { + capability_id: "confirmed_inventory_on_hand_as_of_date", + detected_intent: "inventory_on_hand_as_of_date", + detected_mode: "address_query", + capability_layer: "compute", + capability_route_mode: "exact", + rows_matched: 11, + route_expectation_status: "matched" + }, + runtimeContractShadow: { + schema_version: "assistant_runtime_contracts_v1", + transition_contract_id: "T6", + transition_contract_title: "Domain Pivot With Root-Only Carryover", + transition_contract_reason: ["root_context_reused_after_drilldown_context"], + capability_contract_id: "confirmed_inventory_on_hand_as_of_date", + capability_contract_reason: ["debug_capability_id_matched_contract"], + truth_gate_contract_status: "full_confirmed", + carryover_eligibility: "root_only" + }, + groundingStatus: "grounded", + replyType: "factual" + }); + + expect(binding.binding_status).toBe("bound"); + expect(binding.binding_action).toBe("allow"); + expect(binding.transition_id).toBe("T6"); + expect(binding.transition_allowed).toBe(true); + expect(binding.violations).toEqual([]); + }); + it("attaches compact debug fields and preserves the binding contract", () => { const debug = attachAssistantCapabilityRuntimeBinding( { diff --git a/llm_normalizer/backend/tests/assistantTruthAnswerPolicyRuntimeAdapter.test.ts b/llm_normalizer/backend/tests/assistantTruthAnswerPolicyRuntimeAdapter.test.ts index bccf0c0..bfa5e8d 100644 --- a/llm_normalizer/backend/tests/assistantTruthAnswerPolicyRuntimeAdapter.test.ts +++ b/llm_normalizer/backend/tests/assistantTruthAnswerPolicyRuntimeAdapter.test.ts @@ -117,6 +117,33 @@ describe("assistant truth answer policy runtime adapter", () => { expect(policy.answer_shape.may_power_followup).toBe(true); }); + it("keeps explicit temporal-limited factual answers limited in the truth contract", () => { + const policy = resolveAssistantTruthAnswerPolicyRuntime({ + addressDebug: { + capability_id: "inventory_inventory_purchase_provenance_for_item", + rows_matched: 2, + address_truth_gate_v1: { + schema_version: "address_truth_gate_v1", + policy_owner: "addressTruthGatePolicy", + truth_gate_status: "limited_temporal_or_contextual", + carryover_eligibility: "object_only", + limited_reason_category: null, + runtime_readiness: "LIVE_QUERYABLE_WITH_LIMITS", + reason_codes: ["period_window_auto_broadened_to_available_data"], + blocked_or_limited_explanation: "temporal_or_contextual_limit" + } + }, + replyType: "factual" + }); + + expect(policy.truth_gate.coverage_status).toBe("partial"); + expect(policy.truth_gate.truth_mode).toBe("limited"); + expect(policy.truth_gate.carryover_eligibility).toBe("object_only"); + expect(policy.truth_gate.blocked_or_limited_explanation).toBe("temporal_or_contextual_limit"); + expect(policy.answer_shape.answer_shape).toBe("limited_with_reason"); + expect(policy.answer_shape.must_include_limitation).toBe(true); + }); + it("attaches top-level debug fields without hiding the nested contract", () => { const debug = attachAssistantTruthAnswerPolicy( { diff --git a/llm_normalizer/data/autorun_generators/history.json b/llm_normalizer/data/autorun_generators/history.json index 288dd7d..2b5aaa9 100644 --- a/llm_normalizer/data/autorun_generators/history.json +++ b/llm_normalizer/data/autorun_generators/history.json @@ -1,4 +1,41 @@ [ + { + "generation_id": "gen-mo2kcds2-tlqmvng", + "created_at": "2026-04-17T07:04:48.581Z", + "mode": "saved_user_sessions", + "title": "Ручная сессия 17.04.2026, 10:04:19 ТЕМП", + "count": 13, + "domain": null, + "questions": [ + "покажи все документы по чепурнову", + "что нам отгружал чепурнов, какой товар или услугу?", + "какие остатки на складе на сегодня?", + "хвосты по счету 60 на август 2022", + "какие остатки на складе на март 2021", + "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "покажи еще раз остатки на эту же дату", + "какие остатки на складе на март 2016", + "на июль 2019", + "на сентябрь", + "а на март", + "это по общей базе" + ], + "generated_by": "manual_reviewer", + "saved_case_set_file": "assistant_autogen_saved_user_sessions_20260417070448_gen-mo2kcds2-tlqmvng.json", + "context": { + "llm_provider": "local", + "model": "unsloth/qwen3-30b-a3b-instruct-2507", + "assistant_prompt_version": "address_query_runtime_v1", + "decomposition_prompt_version": "normalizer_v2_0_2", + "prompt_fingerprint": "Ты semantic-normalizer для бухгалтерского ассистента NDC.\nТвоя роль: только нормализация запроса пользователя в строгий JSON-контракт.\n\nЖесткие правила:\n1) Не давай бухгалтерский ответ по сути вопроса.\n2) Возвращай только JSON без markdown и пояснений.\n3) JSON обязан соответствовать переданной schema normalized_query_v1.\n4) Если период не указан, не выдумывай его; отмечай ambiguity.\n5) Для цепочек документов/проводок/оплат поднимай causal и cross-entity признаки.\n6) Для точечного object trace (номер/строка/ref) поднимай needs_exact_object_trace=true.\n7) Используй терминологию NDC.||You are semantic-normalizer for accounting assistant NDC.\nReturn strict JSON only, no markdown, no comments.\n\nTarget schema: normalized_query_v2_0_2.\n\nCore behavior (v2.0.2):\n1. Decompose message into semantic fragments.\n2. Classify fragment domain relevance and business scope.\n3. Fill route-critical flags and candidate labels.\n4. For each fragment set execution state fields:\n - execution_readiness\n - clarification_reason\n - soft_assumption_used\n - route_status\n - no_route_reason\n5. Clarification must be rare and justified.\n\nExecution-state policy:\n- Every in-scope fragment must produce a consistent execution state.\n- If a fragment is routable, mark it as executable or executable_with_soft_assumptions.\n- Do not leave routable fragments in unresolved state.\n- If a fragment cannot be routed, set route_status=no_route and provide explicit no_route_reason.\n\nReadiness values:\n- executable\n- executable_with_soft_assumptions\n- needs_clarification\n- no_route\n\nRoute status values:\n- routed\n- no_route\n\nNo-route reason values:\n- out_of_scope\n- insufficient_specificity\n- missing_mapping\n- unsupported_fragment_type\n\nDo not over-require formality:\n- Do not require document IDs, exact periods, or exact object references for scan/review/anomaly/rule-check requests.\n- Colloquial accounting phrases like \"что висит\", \"что подозрительно\", \"что не сходится\", \"что криво\", \"что аукнется\" are executable if accounting area is understandable.\n\nFragment required fields:\n- fragment_id\n- raw_fragment_text\n- normalized_fragment_text\n- domain_relevance\n- business_scope\n- entity_hints\n- account_hints\n- document_hints\n- register_hints\n- time_scope\n- flags\n- candidate_labels\n- confidence\n- execution_readiness\n- clarification_reason\n- soft_assumption_used\n- route_status\n- no_route_reason\n\nSoft assumptions (`soft_assumption_used`) allowed values:\n- period_from_session_context\n- company_scope_defaulted\n- problem_scan_mode_enabled\n\nGlobal notes:\n- global_notes.needs_clarification should be true only when execution is truly blocked for all in-scope fragments.\n- global_notes.clarification_reason must explain the blocker.\n\nSchema version must be:\n- \"schema_version\": \"normalized_query_v2_0_2\"||Контекст домена: бухгалтерия 1С/NDC.\n\nКлючевые счета:\n- 01, 02, 10, 41, 51, 60, 62, 68.02, 90, 97.\n\nТиповые сущности:\n- контрагент, договор, документ реализации, документ поступления, оплата, проводка, регистр, закрывающий документ.\n\nЛексика causal и сверки (сильные сигналы для cross_entity):\n- \"не бьется\", \"не сходится\", \"не видно\", \"не собралось\", \"повисло\", \"хвост\";\n- \"разложи по документам/оплатам/закрывающим\";\n- \"чем подтверждается\", \"где ошибка в цепочке\", \"что пошло криво\".\n\nЛексика точечного drilldown:\n- \"документ №...\", \"ref\", \"строка проводки\", \"покажи конкретную операцию\", \"точный source-of-record\".\n\nЛексика rule-based контроля:\n- \"проверь настройки\", \"ошибка срока/даты\", \"контроль 97/10/ОС\", \"нарушение правила учета\".\n\nЛексика обзорной аналитики:\n- \"рейтинг\", \"топ рисков\", \"в целом по компании\", \"перед закрытием периода\", \"приоритизация проверок\".\n\nВажное правило:\nЕсли в одном вопросе есть и риск-лексика, и цепочка document/payment/posting, не понижать задачу до чистого `store_feature_risk`.\nПриоритет у causal cross-entity семантики.||v2.0.2: execution-state hardening + explicit route_status/no_route_reason. Схема normalized_query_v2_0_2.||Q: По каким поставщикам висят хвосты по 60, что подозрительно по цепочке оплат?\nA: in_scope fragment, execution_readiness=executable_with_soft_assumptions, route_status=routed, no_route_reason=null.\n\nQ: Покажи записи по 97, которые повисли и могут аукнуться.\nA: in_scope fragment, execution_readiness=executable_with_soft_assumptions, route_status=routed, no_route_reason=null.\n\nQ: Чекни, что у нас не так.\nA: unclear/in_scope fragment, execution_readiness=needs_clarification, route_status=no_route, no_route_reason=insufficient_specificity.\n\nQ: Как вообще по ФСБУ правильно?\nA: out_of_scope fragment, execution_readiness=no_route, route_status=no_route, no_route_reason=out_of_scope.", + "autogen_personality_id": null, + "autogen_personality_prompt": null, + "source_session_id": "asst-kBU5iS0mEt", + "saved_session_file": "assistant_saved_session_20260417070448_gen-mo2kcds2-tlqmvng.json", + "saved_case_set_kind": "assistant_session_scenario" + } + }, { "generation_id": "gen-mo1t93wq-jy0453e", "created_at": "2026-04-16T18:26:26.191Z", diff --git a/llm_normalizer/data/autorun_generators/saved_sessions/assistant_saved_session_20260417070448_gen-mo2kcds2-tlqmvng.json b/llm_normalizer/data/autorun_generators/saved_sessions/assistant_saved_session_20260417070448_gen-mo2kcds2-tlqmvng.json new file mode 100644 index 0000000..9f35ce0 --- /dev/null +++ b/llm_normalizer/data/autorun_generators/saved_sessions/assistant_saved_session_20260417070448_gen-mo2kcds2-tlqmvng.json @@ -0,0 +1,9242 @@ +{ + "saved_at": "2026-04-17T07:04:48.578Z", + "generation_id": "gen-mo2kcds2-tlqmvng", + "mode": "saved_user_sessions", + "title": "Ручная сессия 17.04.2026, 10:04:19 ТЕМП", + "source_session_id": "asst-kBU5iS0mEt", + "questions": [ + "покажи все документы по чепурнову", + "что нам отгружал чепурнов, какой товар или услугу?", + "какие остатки на складе на сегодня?", + "хвосты по счету 60 на август 2022", + "какие остатки на складе на март 2021", + "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "покажи еще раз остатки на эту же дату", + "какие остатки на складе на март 2016", + "на июль 2019", + "на сентябрь", + "а на март", + "это по общей базе" + ], + "session": { + "session_id": "asst-kBU5iS0mEt", + "updated_at": "2026-04-17T07:04:19.453Z", + "items": [ + { + "message_id": "msg-SK5XOEQmHz", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "покажи все документы по чепурнову", + "reply_type": null, + "created_at": "2026-04-17T06:59:00.190Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-FbPrdbojCb", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "Контрагент: Чепурнов П.Д. Найдено документов: 1.\nКонтрагент: Чепурнов П.Д.\n1. 2022-01-20T12:00:03Z | Поступление на расчетный счет 00000000001 от 20.01.2022 12:00:03 | 0 / 0 | 890660 | аналитика: Чепурнов П.Д.; Договор № 11/1 от 25.11.2020 г.", + "reply_type": "factual", + "created_at": "2026-04-17T06:59:13.677Z", + "trace_id": "address-FB16cxDHD5", + "debug": { + "trace_id": "address-FB16cxDHD5", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "DOCUMENT_LIST", + "query_shape_confidence": "medium", + "detected_intent": "list_documents_by_counterparty", + "detected_intent_confidence": "medium", + "extracted_filters": { + "sort": "period_desc", + "limit": 20, + "counterparty": "Чепурнов П.Д." + }, + "missing_required_filters": [], + "selected_recipe": "address_documents_by_counterparty_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "preferred", + "account_scope_fallback_applied": false, + "anchor_type": "counterparty", + "anchor_value_raw": "чепурнов", + "anchor_value_resolved": "Чепурнов П.Д.", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 1000, + "raw_rows_received": 1000, + "rows_after_account_scope": 124, + "rows_after_recipe_filter": 1, + "rows_materialized": 124, + "rows_matched": 1, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Контрагент", + "Договор", + "Period", + "Registrator", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "capability_id": "documents_drilldown", + "capability_layer": "navigation", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "drilldown_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_documents_by_counterparty_v1" + ], + "route_expectation_expected_requested_result_modes": [], + "route_expectation_expected_result_modes": [ + "heuristic_candidates", + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "-Avqj4zSSt7qV3", + "llm_decomposition_effective_message": "документы по контрагенту чепурнову", + "llm_decomposition_reason": "fallback_rule_preferred_over_llm_candidate_anchor_quality", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "покажи все документы по чепурнову", + "canonical_message": "документы по контрагенту чепурнову", + "mode": "address_query", + "mode_confidence": "medium", + "query_shape": "DOCUMENT_LIST", + "query_shape_confidence": "medium", + "intent": "list_documents_by_counterparty", + "intent_confidence": "medium", + "entities": { + "account": null, + "counterparty": "чепурнов", + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "explicit_anchor", + "anchor_kind": "counterparty", + "anchor_value": "чепурнов", + "date_scope_kind": "implicit_current", + "date_basis_hint": "implicit_current_snapshot", + "self_scope_detected": false, + "selected_object_scope_detected": false + }, + "aggregation_profile": "list_lookup" + }, + "fallback_rule_hit": "documents_counterparty_rewrite", + "sanitized_user_message": "покажи все документы по чепурнову", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "medium", + "address_intent": "list_documents_by_counterparty", + "address_intent_confidence": "medium", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": false, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "покажи все документы по чепурнову", + "effective_message": "документы по контрагенту чепурнову", + "decision": "new_topic", + "decision_reasons": [ + "effective_message_rewritten_by_predecompose", + "llm_contract_intent_available" + ], + "followup_context_applied": false, + "previous_intent": null, + "target_intent": "list_documents_by_counterparty", + "intent_selection_mode": null, + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "-Avqj4zSSt7qV3", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "документы по контрагенту чепурнову" + }, + "address_followup_offer": { + "enabled": true, + "source_intent": "list_documents_by_counterparty", + "anchor_type": "counterparty", + "anchor_value": "Чепурнов П.Д.", + "suggested_intents": [ + "bank_operations_by_counterparty", + "list_contracts_by_counterparty" + ] + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": null, + "transition_contract_title": null, + "transition_contract_reason": [ + "transition_contract_not_resolved" + ], + "capability_contract_id": null, + "capability_contract_reason": [ + "debug_capability_id_has_no_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "none" + }, + "transition_contract_id": null, + "capability_contract_id": null, + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": null, + "transition_contract_id": null, + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": false, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": null, + "transition_contract_id": null, + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": false, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": null, + "transition_title": null, + "application_status": "unresolved", + "declared_carryover_depth": null, + "truth_gate_carryover_depth": "none", + "effective_carryover_depth": "none", + "required_prior_state": [], + "expected_answer_mode": null, + "state_mutations": [], + "forbidden_carryover": [ + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "none", + "root_frame_state": "none", + "selected_object_frame_state": "none", + "meta_frame_state": "none", + "clarification_state": "none", + "coverage_gate_state": "none", + "answer_context_state": "none" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + }, + "reason_codes": [ + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": null, + "transition_title": null, + "application_status": "unresolved", + "declared_carryover_depth": null, + "truth_gate_carryover_depth": "none", + "effective_carryover_depth": "none", + "required_prior_state": [], + "expected_answer_mode": null, + "state_mutations": [], + "forbidden_carryover": [ + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "none", + "root_frame_state": "none", + "selected_object_frame_state": "none", + "meta_frame_state": "none", + "clarification_state": "none", + "coverage_gate_state": "none", + "answer_context_state": "none" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + }, + "reason_codes": [ + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + }, + "state_transition_id": null, + "state_transition_status": "unresolved", + "effective_carryover_depth": "none", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "documents_drilldown", + "capability_contract_id": null, + "binding_status": "contract_missing", + "binding_action": "observe_only", + "runtime_lane_expected": null, + "runtime_lane_observed": "address_exact", + "execution_adapter": null, + "transition_id": null, + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "limit", + "counterparty" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": null, + "answer_object_shape": null, + "truth_gate_behavior": null, + "truth_fallback_allowed": null, + "answer_shape_compatible": false, + "violations": [ + "capability_contract_missing" + ], + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "documents_drilldown", + "capability_contract_id": null, + "binding_status": "contract_missing", + "binding_action": "observe_only", + "runtime_lane_expected": null, + "runtime_lane_observed": "address_exact", + "execution_adapter": null, + "transition_id": null, + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "limit", + "counterparty" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": null, + "answer_object_shape": null, + "truth_gate_behavior": null, + "truth_fallback_allowed": null, + "answer_shape_compatible": false, + "violations": [ + "capability_contract_missing" + ], + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + }, + "capability_binding_status": "contract_missing", + "capability_binding_action": "observe_only", + "capability_binding_violations": [ + "capability_contract_missing" + ], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "observe_only", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "docs_or_bank_signal_detected", + "anchor_like_token_detected", + "document_list_signal_detected", + "documents_by_counterparty_signal_detected" + ] + } + } + }, + { + "message_id": "msg-31gb2_Ca-t", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "что нам отгружал чепурнов, какой товар или услугу?", + "reply_type": null, + "created_at": "2026-04-17T06:59:14.857Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-F31DDcZwOL", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "Контрагент: Чепурнов П.Д. Подтвержденных поставок товаров или услуг не найдено.\nПозиции: подтвержденных поставок товаров или услуг не найдено.\nПо связанным расчетам с контрагентом найдено возвратов от поставщика: 1 на 890 660,00 ₽.\nДоговор: Договор № 11/1 от 25.11.2020 г..\nВозвраты от поставщика:\n1. Поступление на расчетный счет 00000000001 от 20.01.2022 12:00:03 | дата: 2022-01-20T12:00:03Z | сумма: 890 660,00 ₽ | договор: Договор № 11/1 от 25.11.2020 г.", + "reply_type": "factual", + "created_at": "2026-04-17T06:59:28.924Z", + "trace_id": "address-_x0DkTrgTY", + "debug": { + "trace_id": "address-_x0DkTrgTY", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "high", + "query_shape": "OBJECT_LOOKUP", + "query_shape_confidence": "medium", + "detected_intent": "list_documents_by_counterparty", + "detected_intent_confidence": "medium", + "extracted_filters": { + "sort": "period_desc", + "limit": 20, + "counterparty": "Чепурнов П.Д." + }, + "missing_required_filters": [], + "selected_recipe": "address_documents_by_counterparty_v1", + "mcp_call_status_legacy": "no_raw_rows", + "account_scope_mode": "preferred", + "account_scope_fallback_applied": false, + "anchor_type": "counterparty", + "anchor_value_raw": "Чепурновым", + "anchor_value_resolved": "Чепурнов П.Д.", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "no_raw_rows", + "rows_fetched": 0, + "raw_rows_received": 0, + "rows_after_account_scope": 0, + "rows_after_recipe_filter": 0, + "rows_materialized": 0, + "rows_matched": 0, + "raw_row_keys_sample": [], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_SUMMARY", + "capability_id": "documents_drilldown", + "capability_layer": "navigation", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "drilldown_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_documents_by_counterparty_v1" + ], + "route_expectation_expected_requested_result_modes": [], + "route_expectation_expected_result_modes": [ + "heuristic_candidates", + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "YmU_wxWYUMaSm6", + "llm_decomposition_effective_message": "Узнать, какие товары или услуги были отгружены нашей компании контрагентом Чепурновым", + "llm_decomposition_reason": "normalized_fragment_applied", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "что нам отгружал чепурнов, какой товар или услугу?", + "canonical_message": "Узнать, какие товары или услуги были отгружены нашей компании контрагентом Чепурновым", + "mode": "address_query", + "mode_confidence": "high", + "query_shape": "OBJECT_LOOKUP", + "query_shape_confidence": "medium", + "intent": "list_documents_by_counterparty", + "intent_confidence": "medium", + "entities": { + "account": null, + "counterparty": "Чепурновым", + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "implicit_current", + "date_basis_hint": "implicit_current_snapshot", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "list_lookup" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "что нам отгружал чепурнов, какой товар или услугу?", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "high", + "address_intent": "list_documents_by_counterparty", + "address_intent_confidence": "medium", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": false, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "что нам отгружал чепурнов, какой товар или услугу?", + "effective_message": "Узнать, какие товары или услуги были отгружены нашей компании контрагентом Чепурновым", + "decision": "new_topic", + "decision_reasons": [ + "effective_message_rewritten_by_predecompose", + "llm_contract_intent_available" + ], + "followup_context_applied": false, + "previous_intent": null, + "target_intent": "list_documents_by_counterparty", + "intent_selection_mode": null, + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "YmU_wxWYUMaSm6", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "Узнать, какие товары или услуги были отгружены нашей компании контрагентом Чепурновым" + }, + "address_followup_offer": { + "enabled": true, + "source_intent": "list_documents_by_counterparty", + "anchor_type": "counterparty", + "anchor_value": "Чепурнов П.Д.", + "suggested_intents": [ + "bank_operations_by_counterparty", + "list_contracts_by_counterparty" + ] + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": null, + "transition_contract_title": null, + "transition_contract_reason": [ + "transition_contract_not_resolved" + ], + "capability_contract_id": null, + "capability_contract_reason": [ + "debug_capability_id_has_no_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "none" + }, + "transition_contract_id": null, + "capability_contract_id": null, + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": null, + "transition_contract_id": null, + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": false, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": null, + "transition_contract_id": null, + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": false, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": null, + "transition_title": null, + "application_status": "unresolved", + "declared_carryover_depth": null, + "truth_gate_carryover_depth": "none", + "effective_carryover_depth": "none", + "required_prior_state": [], + "expected_answer_mode": null, + "state_mutations": [], + "forbidden_carryover": [ + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "none", + "root_frame_state": "none", + "selected_object_frame_state": "none", + "meta_frame_state": "none", + "clarification_state": "none", + "coverage_gate_state": "none", + "answer_context_state": "none" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + }, + "reason_codes": [ + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": null, + "transition_title": null, + "application_status": "unresolved", + "declared_carryover_depth": null, + "truth_gate_carryover_depth": "none", + "effective_carryover_depth": "none", + "required_prior_state": [], + "expected_answer_mode": null, + "state_mutations": [], + "forbidden_carryover": [ + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "none", + "root_frame_state": "none", + "selected_object_frame_state": "none", + "meta_frame_state": "none", + "clarification_state": "none", + "coverage_gate_state": "none", + "answer_context_state": "none" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + }, + "reason_codes": [ + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + }, + "state_transition_id": null, + "state_transition_status": "unresolved", + "effective_carryover_depth": "none", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "documents_drilldown", + "capability_contract_id": null, + "binding_status": "contract_missing", + "binding_action": "observe_only", + "runtime_lane_expected": null, + "runtime_lane_observed": "address_exact", + "execution_adapter": null, + "transition_id": null, + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "limit", + "counterparty" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": null, + "answer_object_shape": null, + "truth_gate_behavior": null, + "truth_fallback_allowed": null, + "answer_shape_compatible": false, + "violations": [ + "capability_contract_missing" + ], + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "documents_drilldown", + "capability_contract_id": null, + "binding_status": "contract_missing", + "binding_action": "observe_only", + "runtime_lane_expected": null, + "runtime_lane_observed": "address_exact", + "execution_adapter": null, + "transition_id": null, + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "limit", + "counterparty" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": null, + "answer_object_shape": null, + "truth_gate_behavior": null, + "truth_fallback_allowed": null, + "answer_shape_compatible": false, + "violations": [ + "capability_contract_missing" + ], + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + }, + "capability_binding_status": "contract_missing", + "capability_binding_action": "observe_only", + "capability_binding_violations": [ + "capability_contract_missing" + ], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "observe_only", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "object_signal_detected", + "counterparty_item_flow_signal_detected", + "counterparty_item_flow_query_override_to_purchase_documents", + "counterparty_item_flow_no_supply_but_bank_activity_explained" + ] + } + } + }, + { + "message_id": "msg-ob_ucrIz0e", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "какие остатки на складе на сегодня?", + "reply_type": null, + "created_at": "2026-04-17T06:59:38.991Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-3BxJ--X0gY", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 17.04.2026 на складе подтверждено 11 позиций с остатком на 716.418,33 ₽.\n\nПозиции:\n1. Модуль прямоугольый 1400*110*750 | склад: Основной склад | количество: 22,000 | стоимость: 148.261,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n2. Конструкция трансформер рабочей станции 1300*900*2000 | склад: Основной склад | количество: 3,000 | стоимость: 498.472,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n3. Диван трехместный | склад: Основной склад | количество: 1,000 | стоимость: 34.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n4. Кресло орион | склад: Основной склад | количество: 1,000 | стоимость: 13.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n5. Зеркало для инвалидов поворотное травмобезопасное | склад: Основной склад | количество: 1,000 | стоимость: 7.250,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n6. Пуф арий | склад: Основной склад | количество: 1,000 | стоимость: 6.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n7. Столешница 600*3050*26 дуб ниагара | склад: Основной склад | количество: 1,000 | стоимость: 3.724,17 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n8. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n9. Четки Пост (84*117) | склад: Основной склад | количество: 1,000 | стоимость: 833,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n10. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n11. Кромка с клеем 33 дуб ниагара 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2026-04-17T23:59:59Z\n\nПодтверждение:\n- Дата среза: 17.04.2026.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 11.\n- Уникальных складов: 1.\n- Суммарное количество: 34,000.", + "reply_type": "factual", + "created_at": "2026-04-17T06:59:50.036Z", + "trace_id": "address-Ov7Sfq7RCk", + "debug": { + "trace_id": "address-Ov7Sfq7RCk", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "high", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "high", + "extracted_filters": { + "sort": "period_desc", + "as_of_date": "2026-04-17", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "unknown", + "anchor_value_raw": null, + "anchor_value_resolved": null, + "resolver_confidence": "low", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 11, + "raw_rows_received": 11, + "rows_after_account_scope": 11, + "rows_after_recipe_filter": 11, + "rows_materialized": 11, + "rows_matched": 11, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "07SeIS--6iv3ys", + "llm_decomposition_effective_message": "Какие остатки по складу на текущую дату?", + "llm_decomposition_reason": "normalized_fragment_applied", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "какие остатки на складе на сегодня?", + "canonical_message": "Какие остатки по складу на текущую дату?", + "mode": "address_query", + "mode_confidence": "high", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "inventory_on_hand_as_of_date", + "intent_confidence": "high", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "as_of", + "period_from": null, + "period_to": null, + "as_of_date": "2026-04-17", + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "implicit_current", + "date_basis_hint": "implicit_current_snapshot", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "какие остатки на складе на сегодня?", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "high", + "address_intent": "inventory_on_hand_as_of_date", + "address_intent_confidence": "high", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": false, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "какие остатки на складе на сегодня?", + "effective_message": "Какие остатки по складу на текущую дату?", + "decision": "new_topic", + "decision_reasons": [ + "effective_message_rewritten_by_predecompose", + "llm_contract_intent_available" + ], + "followup_context_applied": false, + "previous_intent": null, + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": null, + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "07SeIS--6iv3ys", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "Какие остатки по складу на текущую дату?" + }, + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T1", + "transition_contract_title": "Root Query Entry", + "transition_contract_reason": [ + "capability_contract_root_or_new_entry" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T1", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T1", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T1", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T1", + "transition_title": "Root Query Entry", + "application_status": "applied", + "declared_carryover_depth": "none", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "none", + "required_prior_state": [ + "living_mode_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "create_root_frame_state", + "clear_selected_object_frame_state", + "create_coverage_gate_state" + ], + "forbidden_carryover": [ + "stale_focus_object", + "stale_object_intent", + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "create", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T1", + "transition_title": "Root Query Entry", + "application_status": "applied", + "declared_carryover_depth": "none", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "none", + "required_prior_state": [ + "living_mode_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "create_root_frame_state", + "clear_selected_object_frame_state", + "create_coverage_gate_state" + ], + "forbidden_carryover": [ + "stale_focus_object", + "stale_object_intent", + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "create", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + }, + "state_transition_id": "T1", + "state_transition_status": "applied", + "effective_carryover_depth": "none", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T1", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T1", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "confirmed_balance_exact_inventory_intent", + "organization_grounded_from_observed_rows" + ] + } + } + }, + { + "message_id": "msg-2xDanycewl", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "хвосты по счету 60 на август 2022", + "reply_type": null, + "created_at": "2026-04-17T07:00:02.181Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-MXOH4cg-7h", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "По счету 60 за период 2022-08-01..2022-08-31 открытых остатков не найдено.\nОрганизация: ООО \\Альтернатива Плюс\\.", + "reply_type": "factual", + "created_at": "2026-04-17T07:00:16.065Z", + "trace_id": "address-K5uGp--oGV", + "debug": { + "trace_id": "address-K5uGp--oGV", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "high", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "open_items_by_counterparty_or_contract", + "detected_intent_confidence": "medium", + "extracted_filters": { + "sort": "period_desc", + "limit": 20, + "account": "60", + "period_from": "2022-08-01", + "period_to": "2022-08-31", + "as_of_date": "2022-08-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "missing_required_filters": [], + "selected_recipe": "address_open_items_by_party_or_contract_v1", + "mcp_call_status_legacy": "no_raw_rows", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "no_raw_rows", + "rows_fetched": 0, + "raw_rows_received": 0, + "rows_after_account_scope": 0, + "rows_after_recipe_filter": 0, + "rows_materialized": 0, + "rows_matched": 0, + "raw_row_keys_sample": [], + "materialization_drop_reason": "none", + "account_token_raw": "60", + "account_token_normalized": "60", + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_SUMMARY", + "requested_result_mode": "confirmed_balance", + "result_mode": "heuristic_candidates", + "evidence_strength": "weak", + "balance_confirmed": false, + "as_of_date_basis": "period_range", + "capability_id": "address_open_items_by_counterparty_or_contract", + "capability_layer": "compute", + "capability_route_mode": "heuristic", + "capability_route_enabled": true, + "capability_route_reason": "receivables_heuristic_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "not_found", + "route_expectation_reason": "route_expectation_not_defined_for_intent", + "route_expectation_expected_selected_recipes": [], + "route_expectation_expected_requested_result_modes": [], + "route_expectation_expected_result_modes": [], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "pawnDc0VTNs75s", + "llm_decomposition_effective_message": "поиск хвостов по счету 60 за август 2022 года", + "llm_decomposition_reason": "normalized_fragment_applied", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "хвосты по счету 60 на август 2022", + "canonical_message": "поиск хвостов по счету 60 за август 2022 года", + "mode": "address_query", + "mode_confidence": "high", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "open_items_by_counterparty_or_contract", + "intent_confidence": "medium", + "entities": { + "account": "60", + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "as_of", + "period_from": "2022-08-01", + "period_to": "2022-08-31", + "as_of_date": "2022-08-31", + "has_explicit_period": true + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "explicit", + "date_basis_hint": "period_range", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "open_items" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "хвосты по счету 60 на август 2022", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "high", + "address_intent": "open_items_by_counterparty_or_contract", + "address_intent_confidence": "medium", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": false, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [ + "deep_investigation_signal_detected" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": true, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": false, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "хвосты по счету 60 на август 2022", + "effective_message": "поиск хвостов по счету 60 за август 2022 года", + "decision": "new_topic", + "decision_reasons": [ + "effective_message_rewritten_by_predecompose", + "llm_contract_intent_available" + ], + "followup_context_applied": false, + "previous_intent": null, + "target_intent": "open_items_by_counterparty_or_contract", + "intent_selection_mode": null, + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "pawnDc0VTNs75s", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "поиск хвостов по счету 60 за август 2022 года" + }, + "address_followup_offer": { + "enabled": true, + "source_intent": "open_items_by_counterparty_or_contract", + "anchor_type": "organization", + "anchor_value": "ООО \\Альтернатива Плюс\\", + "suggested_intents": [ + "list_documents_by_counterparty", + "bank_operations_by_counterparty" + ] + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": null, + "transition_contract_title": null, + "transition_contract_reason": [ + "transition_contract_not_resolved" + ], + "capability_contract_id": null, + "capability_contract_reason": [ + "debug_capability_id_has_no_contract" + ], + "truth_gate_contract_status": "unknown", + "carryover_eligibility": "none" + }, + "transition_contract_id": null, + "capability_contract_id": null, + "truth_gate_contract_status": "unknown", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "blocked", + "evidence_grade": "weak", + "grounding_status": "grounded", + "truth_mode": "unsupported", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_unknown", + "truth_mode_unsupported", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ], + "source_truth_gate_status": "unknown", + "blocked_or_limited_explanation": "truth_gate_not_confirmed" + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "blocked_no_answer", + "reply_type": "factual", + "capability_contract_id": null, + "transition_contract_id": null, + "may_state_confirmed_facts": false, + "must_include_limitation": true, + "may_power_followup": false, + "required_sections": [ + "blocked_reason", + "safe_next_step" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "blocked", + "evidence_grade": "weak", + "grounding_status": "grounded", + "truth_mode": "unsupported", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_unknown", + "truth_mode_unsupported", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ], + "source_truth_gate_status": "unknown", + "blocked_or_limited_explanation": "truth_gate_not_confirmed" + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "blocked_no_answer", + "reply_type": "factual", + "capability_contract_id": null, + "transition_contract_id": null, + "may_state_confirmed_facts": false, + "must_include_limitation": true, + "may_power_followup": false, + "required_sections": [ + "blocked_reason", + "safe_next_step" + ], + "downgrade_only": true + }, + "truth_mode": "unsupported", + "carryover_eligibility": "none", + "answer_shape": "blocked_no_answer", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": null, + "transition_title": null, + "application_status": "unresolved", + "declared_carryover_depth": null, + "truth_gate_carryover_depth": "none", + "effective_carryover_depth": "none", + "required_prior_state": [], + "expected_answer_mode": null, + "state_mutations": [], + "forbidden_carryover": [ + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "none", + "root_frame_state": "none", + "selected_object_frame_state": "none", + "meta_frame_state": "none", + "clarification_state": "none", + "coverage_gate_state": "none", + "answer_context_state": "none" + }, + "coverage_gate_state": { + "coverage_status": "blocked", + "evidence_grade": "weak", + "grounding_status": "grounded", + "truth_mode": "unsupported", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_unknown", + "truth_mode_unsupported", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + }, + "reason_codes": [ + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_unknown", + "truth_mode_unsupported", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": null, + "transition_title": null, + "application_status": "unresolved", + "declared_carryover_depth": null, + "truth_gate_carryover_depth": "none", + "effective_carryover_depth": "none", + "required_prior_state": [], + "expected_answer_mode": null, + "state_mutations": [], + "forbidden_carryover": [ + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "none", + "root_frame_state": "none", + "selected_object_frame_state": "none", + "meta_frame_state": "none", + "clarification_state": "none", + "coverage_gate_state": "none", + "answer_context_state": "none" + }, + "coverage_gate_state": { + "coverage_status": "blocked", + "evidence_grade": "weak", + "grounding_status": "grounded", + "truth_mode": "unsupported", + "carryover_eligibility": "none", + "reason_codes": [ + "truth_gate_unknown", + "truth_mode_unsupported", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + }, + "reason_codes": [ + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_unknown", + "truth_mode_unsupported", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + }, + "state_transition_id": null, + "state_transition_status": "unresolved", + "effective_carryover_depth": "none", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "address_open_items_by_counterparty_or_contract", + "capability_contract_id": null, + "binding_status": "contract_missing", + "binding_action": "observe_only", + "runtime_lane_expected": null, + "runtime_lane_observed": "unknown", + "execution_adapter": null, + "transition_id": null, + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "limit", + "account", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": null, + "answer_object_shape": null, + "truth_gate_behavior": null, + "truth_fallback_allowed": null, + "answer_shape_compatible": false, + "violations": [ + "capability_contract_missing" + ], + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_unknown", + "truth_mode_unsupported", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "address_open_items_by_counterparty_or_contract", + "capability_contract_id": null, + "binding_status": "contract_missing", + "binding_action": "observe_only", + "runtime_lane_expected": null, + "runtime_lane_observed": "unknown", + "execution_adapter": null, + "transition_id": null, + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "limit", + "account", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": null, + "answer_object_shape": null, + "truth_gate_behavior": null, + "truth_fallback_allowed": null, + "answer_shape_compatible": false, + "violations": [ + "capability_contract_missing" + ], + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_unknown", + "truth_mode_unsupported", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + }, + "capability_binding_status": "contract_missing", + "capability_binding_action": "observe_only", + "capability_binding_violations": [ + "capability_contract_missing" + ], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "observe_only", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_contract_missing", + "binding_action_observe_only", + "capability_contract_missing", + "transition_status_unresolved", + "transition_unresolved", + "transition_contract_not_resolved", + "debug_capability_id_has_no_contract", + "truth_gate_unknown", + "truth_mode_unsupported", + "route_expectation_not_defined_for_intent", + "address_action_detected", + "address_entity_detected", + "shape_not_detected", + "open_items_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_unavailable_fallback_to_heuristic_candidates", + "open_items_account_query_override_to_movements", + "open_items_account_exact_negative_response" + ] + } + } + }, + { + "message_id": "msg-bWwgVggGD1", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "какие остатки на складе на март 2021", + "reply_type": null, + "created_at": "2026-04-17T07:00:36.924Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-yllv_YMGcL", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 31.03.2021 на складе подтверждено 11 позиций с остатком на 716.418,33 ₽.\n\nПозиции:\n1. Модуль прямоугольый 1400*110*750 | склад: Основной склад | количество: 22,000 | стоимость: 148.261,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n2. Конструкция трансформер рабочей станции 1300*900*2000 | склад: Основной склад | количество: 3,000 | стоимость: 498.472,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n3. Диван трехместный | склад: Основной склад | количество: 1,000 | стоимость: 34.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n4. Кресло орион | склад: Основной склад | количество: 1,000 | стоимость: 13.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n5. Зеркало для инвалидов поворотное травмобезопасное | склад: Основной склад | количество: 1,000 | стоимость: 7.250,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n6. Пуф арий | склад: Основной склад | количество: 1,000 | стоимость: 6.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n7. Столешница 600*3050*26 дуб ниагара | склад: Основной склад | количество: 1,000 | стоимость: 3.724,17 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n8. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n9. Четки Пост (84*117) | склад: Основной склад | количество: 1,000 | стоимость: 833,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n10. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n11. Кромка с клеем 33 дуб ниагара 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n\nПодтверждение:\n- Дата среза: 31.03.2021.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 11.\n- Уникальных складов: 1.\n- Суммарное количество: 34,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:00:49.064Z", + "trace_id": "address-ldgT4KtD3f", + "debug": { + "trace_id": "address-ldgT4KtD3f", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "high", + "extracted_filters": { + "sort": "period_desc", + "period_from": "2021-03-01", + "period_to": "2021-03-31", + "as_of_date": "2021-03-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 11, + "raw_rows_received": 11, + "rows_after_account_scope": 11, + "rows_after_recipe_filter": 11, + "rows_materialized": 11, + "rows_matched": 11, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "period_range", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "n10pc0MALsnCY9", + "llm_decomposition_effective_message": "получить остатки по складу за март 2021 года", + "llm_decomposition_reason": "normalized_fragment_applied", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "какие остатки на складе на март 2021", + "canonical_message": "получить остатки по складу за март 2021 года", + "mode": "address_query", + "mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "inventory_on_hand_as_of_date", + "intent_confidence": "high", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "as_of", + "period_from": "2021-03-01", + "period_to": "2021-03-31", + "as_of_date": "2021-03-31", + "has_explicit_period": true + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "explicit", + "date_basis_hint": "period_range", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "какие остатки на складе на март 2021", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "medium", + "address_intent": "inventory_on_hand_as_of_date", + "address_intent_confidence": "high", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": false, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "какие остатки на складе на март 2021", + "effective_message": "получить остатки по складу за март 2021 года", + "decision": "new_topic", + "decision_reasons": [ + "effective_message_rewritten_by_predecompose", + "llm_contract_intent_available" + ], + "followup_context_applied": false, + "previous_intent": null, + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": null, + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "n10pc0MALsnCY9", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "получить остатки по складу за март 2021 года" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T1", + "transition_contract_title": "Root Query Entry", + "transition_contract_reason": [ + "capability_contract_root_or_new_entry" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T1", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T1", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T1", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T1", + "transition_title": "Root Query Entry", + "application_status": "applied", + "declared_carryover_depth": "none", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "none", + "required_prior_state": [ + "living_mode_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "create_root_frame_state", + "clear_selected_object_frame_state", + "create_coverage_gate_state" + ], + "forbidden_carryover": [ + "stale_focus_object", + "stale_object_intent", + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "create", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T1", + "transition_title": "Root Query Entry", + "application_status": "applied", + "declared_carryover_depth": "none", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "none", + "required_prior_state": [ + "living_mode_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "create_root_frame_state", + "clear_selected_object_frame_state", + "create_coverage_gate_state" + ], + "forbidden_carryover": [ + "stale_focus_object", + "stale_object_intent", + "implicit_followup_reuse" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "create", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T1", + "state_transition_status": "applied", + "effective_carryover_depth": "none", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T1", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T1", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T1", + "capability_contract_root_or_new_entry", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + }, + { + "message_id": "msg-Ghjyg-PlaW", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "reply_type": null, + "created_at": "2026-04-17T07:00:58.621Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-ursK5G5ZoO", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 31.03.2021 на складе подтверждено 2 позиций с остатком на 3.240,83 ₽.\n\nПозиции:\n1. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n2. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2021-03-31T23:59:59Z\n\nПодтверждение:\n- Дата среза: 31.03.2021.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 2.\n- Уникальных складов: 1.\n- Суммарное количество: 2,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:01:11.435Z", + "trace_id": "address-QYcF1mkhg2", + "debug": { + "trace_id": "address-QYcF1mkhg2", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "as_of_date": "2021-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "item": "Столешница 600*3050*26 альмандин", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 11, + "raw_rows_received": 11, + "rows_after_account_scope": 11, + "rows_after_recipe_filter": 2, + "rows_materialized": 11, + "rows_matched": 2, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": false, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "Ha4-mqbgDCE638", + "llm_decomposition_effective_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "llm_decomposition_reason": "followup_raw_message_preferred_over_llm_rewrite", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "canonical_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "mode": "address_query", + "mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "unknown", + "intent_confidence": "low", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "none", + "anchor_kind": "none", + "anchor_value": null, + "date_scope_kind": "none", + "date_basis_hint": null, + "self_scope_detected": false, + "selected_object_scope_detected": true + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "по выбранному объекту \"столешница 600*3050*26 альмандин\": кто нам это поставил?", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "medium", + "address_intent": "unknown", + "address_intent_confidence": "low", + "strong_data_signal_detected": false, + "data_retrieval_signal_detected": false, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [ + "unsupported_low_confidence_contract", + "rewrite_without_structured_gain" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": false, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "effective_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": "carry_previous_intent", + "anchor_type": "organization", + "anchor_value": "ООО \\Альтернатива Плюс\\", + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "Ha4-mqbgDCE638", + "prompt_version": "normalizer_v2_0_2", + "applied": false, + "effective_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2021-03-31", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T2", + "transition_contract_title": "Root Follow-Up With Date Or Scope Change", + "transition_contract_reason": [ + "root_followup_continue_previous" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T2", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T2", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "item", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "item", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "item_from_explicit_quote", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + }, + { + "message_id": "msg-BXkKSt1eQw", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "reply_type": null, + "created_at": "2026-04-17T07:01:39.623Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-3JlrNX8e49", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "По позиции Столешница 600*3050*26 альмандин найдено 1 подтвержденных документов закупки до 17.04.2026.\n\nПодтверждение:\n- Дата верхней границы: 17.04.2026.\n- Операций поступления в выборке: 1.\n- Поставщик: Торговый дом \\Союз\n\nДокументы:\n1. Поступление товаров и услуг 00000000003 от 12.02.2019 0:00:00 | дата: 12.02.2019 | сумма: 3.690,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | контрагент: Торговый дом \\Союз", + "reply_type": "factual", + "created_at": "2026-04-17T07:01:52.029Z", + "trace_id": "address-ICvNYuY0ps", + "debug": { + "trace_id": "address-ICvNYuY0ps", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "high", + "query_shape": "DOCUMENT_LIST", + "query_shape_confidence": "medium", + "detected_intent": "inventory_purchase_documents_for_item", + "detected_intent_confidence": "medium", + "extracted_filters": { + "sort": "period_desc", + "item": "Столешница 600*3050*26 альмандин", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_purchase_documents_for_item_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "item", + "anchor_value_raw": "Столешница 600*3050*26 альмандин", + "anchor_value_resolved": "Столешница 600*3050*26 альмандин", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 1, + "raw_rows_received": 1, + "rows_after_account_scope": 1, + "rows_after_recipe_filter": 1, + "rows_materialized": 1, + "rows_matched": 1, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Контрагент", + "Договор", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "inventory_inventory_purchase_documents_for_item", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_trace_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_purchase_documents_for_item_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": false, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "kLmPDN9bcU-wyu", + "llm_decomposition_effective_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "llm_decomposition_reason": "normalized_fragment_rejected_intent_conflict", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "canonical_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "mode": "address_query", + "mode_confidence": "high", + "query_shape": "DOCUMENT_LIST", + "query_shape_confidence": "medium", + "intent": "inventory_purchase_documents_for_item", + "intent_confidence": "medium", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "selected_object_scope", + "anchor_kind": "item", + "anchor_value": "Столешница 600*3050*26 альмандин", + "date_scope_kind": "implicit_current", + "date_basis_hint": "implicit_current_snapshot", + "self_scope_detected": false, + "selected_object_scope_detected": true + }, + "aggregation_profile": "list_lookup" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "по выбранному объекту \"столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "high", + "address_intent": "inventory_purchase_documents_for_item", + "address_intent_confidence": "medium", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": true, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "effective_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected", + "llm_contract_intent_available" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_purchase_documents_for_item", + "intent_selection_mode": "carry_previous_intent", + "anchor_type": "organization", + "anchor_value": "ООО \\Альтернатива Плюс\\", + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "kLmPDN9bcU-wyu", + "prompt_version": "normalizer_v2_0_2", + "applied": false, + "effective_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2021-03-31", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T4", + "transition_contract_title": "Short Action Follow-Up On Selected Object", + "transition_contract_reason": [ + "selected_object_capability_continue_previous" + ], + "capability_contract_id": "inventory_inventory_purchase_documents_for_item", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "object_only" + }, + "transition_contract_id": "T4", + "capability_contract_id": "inventory_inventory_purchase_documents_for_item", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "object_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "inventory_inventory_purchase_documents_for_item", + "transition_contract_id": "T4", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "object_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "inventory_inventory_purchase_documents_for_item", + "transition_contract_id": "T4", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "object_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T4", + "transition_title": "Short Action Follow-Up On Selected Object", + "application_status": "applied", + "declared_carryover_depth": "object_only", + "truth_gate_carryover_depth": "object_only", + "effective_carryover_depth": "object_only", + "required_prior_state": [ + "selected_object_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "reuse_selected_object_frame_state", + "route_to_compatible_item_action" + ], + "forbidden_carryover": [ + "generic_chat_fallback", + "data_scope_selection_fallback", + "object_focus_reset" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "preserve", + "selected_object_frame_state": "reuse", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "object_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T4", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T4", + "transition_title": "Short Action Follow-Up On Selected Object", + "application_status": "applied", + "declared_carryover_depth": "object_only", + "truth_gate_carryover_depth": "object_only", + "effective_carryover_depth": "object_only", + "required_prior_state": [ + "selected_object_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "reuse_selected_object_frame_state", + "route_to_compatible_item_action" + ], + "forbidden_carryover": [ + "generic_chat_fallback", + "data_scope_selection_fallback", + "object_focus_reset" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "preserve", + "selected_object_frame_state": "reuse", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "object_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T4", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + }, + "state_transition_id": "T4", + "state_transition_status": "applied", + "effective_carryover_depth": "object_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "inventory_inventory_purchase_documents_for_item", + "capability_contract_id": "inventory_inventory_purchase_documents_for_item", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T4", + "transition_allowed": true, + "required_anchors": [ + "item" + ], + "provided_anchors": [ + "sort", + "item", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": true, + "focus_object_binding_status": "inferred_from_anchor", + "result_shape": "purchase_document_list_for_selected_item", + "answer_object_shape": "inventory_purchase_documents_bundle", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T4", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "inventory_inventory_purchase_documents_for_item", + "capability_contract_id": "inventory_inventory_purchase_documents_for_item", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T4", + "transition_allowed": true, + "required_anchors": [ + "item" + ], + "provided_anchors": [ + "sort", + "item", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": true, + "focus_object_binding_status": "inferred_from_anchor", + "result_shape": "purchase_document_list_for_selected_item", + "answer_object_shape": "inventory_purchase_documents_bundle", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T4", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T4", + "selected_object_capability_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "address_action_detected", + "address_entity_detected", + "document_list_signal_detected", + "inventory_selected_object_purchase_documents_signal_detected", + "organization_from_followup_context", + "address_followup_context_applied" + ] + } + } + }, + { + "message_id": "msg-keO-4TDjD_", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "покажи еще раз остатки на эту же дату", + "reply_type": null, + "created_at": "2026-04-17T07:02:07.766Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-G6BtQFSdJv", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "Не могу надежно подтвердить ответ в текущем контексте.\nПроверка сценария остановила ответ: transition_not_supported_by_capability.\nЛучше уточнить объект или перезапустить вопрос от корневого запроса, чем выдавать это как подтвержденный факт.", + "reply_type": "partial_coverage", + "created_at": "2026-04-17T07:02:19.571Z", + "trace_id": "address-cCylCuneeR", + "debug": { + "trace_id": "address-cCylCuneeR", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "COMPOUND_FACTUAL_QUERY", + "query_shape_confidence": "medium", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "as_of_date": "2021-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 11, + "raw_rows_received": 11, + "rows_after_account_scope": 11, + "rows_after_recipe_filter": 11, + "rows_materialized": 11, + "rows_matched": 11, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": false, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "iIkIedvfxgUuUF", + "llm_decomposition_effective_message": "покажи еще раз остатки на эту же дату", + "llm_decomposition_reason": "normalized_fragment_rejected_semantic_guard", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "покажи еще раз остатки на эту же дату", + "canonical_message": "покажи еще раз остатки на эту же дату", + "mode": "unsupported", + "mode_confidence": "low", + "query_shape": "COMPOUND_FACTUAL_QUERY", + "query_shape_confidence": "medium", + "intent": "unknown", + "intent_confidence": "low", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "implicit_current", + "date_basis_hint": "implicit_current_snapshot", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "покажи еще раз остатки на эту же дату", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_signal_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "unsupported", + "address_mode_confidence": "low", + "address_intent": "unknown", + "address_intent_confidence": "low", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": false, + "semantic_apply_canonical_recommended": false, + "semantic_reason_codes": [ + "unsupported_low_confidence_contract" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": false, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": true + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_signal_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "покажи еще раз остатки на эту же дату", + "effective_message": "покажи еще раз остатки на эту же дату", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected" + ], + "followup_context_applied": true, + "previous_intent": "inventory_purchase_documents_for_item", + "target_intent": "inventory_purchase_documents_for_item", + "intent_selection_mode": "carry_previous_intent", + "anchor_type": "item", + "anchor_value": "Столешница 600*3050*26 альмандин", + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "iIkIedvfxgUuUF", + "prompt_version": "normalizer_v2_0_2", + "applied": false, + "effective_message": "покажи еще раз остатки на эту же дату" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_drilldown", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2021-03-31", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T6", + "transition_contract_title": "Domain Pivot With Root-Only Carryover", + "transition_contract_reason": [ + "root_context_reused_after_drilldown_context" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T6", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T6", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T6", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T6", + "transition_title": "Domain Pivot With Root-Only Carryover", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state", + "selected_object_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "preserve_root_frame_state", + "drop_selected_object_frame_state" + ], + "forbidden_carryover": [ + "object_route_replay_into_new_domain" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "preserve", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T6", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T6", + "transition_title": "Domain Pivot With Root-Only Carryover", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state", + "selected_object_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "preserve_root_frame_state", + "drop_selected_object_frame_state" + ], + "forbidden_carryover": [ + "object_route_replay_into_new_domain" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "preserve", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T6", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T6", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "blocked", + "binding_action": "block", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T6", + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to", + "selected_object" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [ + "transition_not_supported_by_capability" + ], + "reason_codes": [ + "binding_status_blocked", + "binding_action_block", + "transition_not_supported_by_capability", + "transition_status_applied", + "transition_T6", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "blocked", + "binding_action": "block", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T6", + "transition_allowed": false, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to", + "selected_object" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [ + "transition_not_supported_by_capability" + ], + "reason_codes": [ + "binding_status_blocked", + "binding_action_block", + "transition_not_supported_by_capability", + "transition_status_applied", + "transition_T6", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "blocked", + "capability_binding_action": "block", + "capability_binding_violations": [ + "transition_not_supported_by_capability" + ], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": true, + "action": "block", + "original_reply_type": "factual", + "guarded_reply_type": "partial_coverage", + "reason_codes": [ + "binding_status_blocked", + "binding_action_block", + "transition_not_supported_by_capability", + "transition_status_applied", + "transition_T6", + "root_context_reused_after_drilldown_context", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "compound_signal_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent", + "capability_binding_guard_blocked_reply" + ] + } + } + }, + { + "message_id": "msg-6yaObspNjm", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "какие остатки на складе на март 2016", + "reply_type": null, + "created_at": "2026-04-17T07:02:49.149Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-U3T1-nXZm8", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 31.03.2016 на складе подтверждено 2 позиций с остатком на 812.786,49 ₽.\n\nПозиции:\n1. Шкаф для одежды 824*437*2010 | склад: Основной склад | количество: 11,000 | стоимость: 117.426,49 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2016-03-31T23:59:59Z\n2. Рабочая станция универсального специалиста (индивидуальное изготовление) | склад: Основной склад | количество: 3,000 | стоимость: 695.360,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2016-03-31T23:59:59Z\n\nПодтверждение:\n- Дата среза: 31.03.2016.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 2.\n- Уникальных складов: 1.\n- Суммарное количество: 14,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:03:01.200Z", + "trace_id": "address-BWikalW8P7", + "debug": { + "trace_id": "address-BWikalW8P7", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "period_from": "2016-03-01", + "period_to": "2016-03-31", + "as_of_date": "2016-03-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 2, + "raw_rows_received": 2, + "rows_after_account_scope": 2, + "rows_after_recipe_filter": 2, + "rows_materialized": 2, + "rows_matched": 2, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "period_range", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "pa9OQsVipEgvnZ", + "llm_decomposition_effective_message": "получить остатки по складу за март 2016 года", + "llm_decomposition_reason": "normalized_fragment_applied", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "какие остатки на складе на март 2016", + "canonical_message": "получить остатки по складу за март 2016 года", + "mode": "address_query", + "mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "inventory_on_hand_as_of_date", + "intent_confidence": "high", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "as_of", + "period_from": "2016-03-01", + "period_to": "2016-03-31", + "as_of_date": "2016-03-31", + "has_explicit_period": true + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "explicit", + "date_basis_hint": "period_range", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "какие остатки на складе на март 2016", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "medium", + "address_intent": "inventory_on_hand_as_of_date", + "address_intent_confidence": "high", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": true, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [], + "semantic_route_arbitration": { + "supported_address_intent_detected": true, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "какие остатки на складе на март 2016", + "effective_message": "получить остатки по складу за март 2016 года", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected", + "effective_message_rewritten_by_predecompose", + "llm_contract_intent_available", + "root_context_only_carryover" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": "carry_root_context", + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "pa9OQsVipEgvnZ", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "получить остатки по складу за март 2016 года" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2021-03-31", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T2", + "transition_contract_title": "Root Follow-Up With Date Or Scope Change", + "transition_contract_reason": [ + "root_followup_continue_previous" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T2", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T2", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "inventory_on_hand_signal_detected", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + }, + { + "message_id": "msg-YoVErCg5BW", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "на июль 2019", + "reply_type": null, + "created_at": "2026-04-17T07:03:04.550Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-WTR742ctqv", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 31.07.2019 на складе подтверждено 18 позиций с остатком на 3.521.729,24 ₽.\n\nПозиции:\n1. Подсветка | склад: Основной склад | количество: 90,000 | стоимость: 243.381,35 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n2. Секция мобильная. Тип 1. | склад: Основной склад | количество: 67,000 | стоимость: 1.016.166,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n3. Секция монолитная. Тип 1 | склад: Основной склад | количество: 57,000 | стоимость: 819.375,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n4. Модуль прямоугольый 1400*110*750 | склад: Основной склад | количество: 22,000 | стоимость: 148.261,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n5. Моноблок леново | склад: Основной склад | количество: 13,000 | стоимость: 614.098,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n6. Принтер НР М203 | склад: Основной склад | количество: 13,000 | стоимость: 138.255,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n7. Источник бесперебойного питания | склад: Основной склад | количество: 13,000 | стоимость: 107.347,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n8. Шкаф для одежды 824*437*2010 | склад: Основной склад | количество: 9,000 | стоимость: 96.076,22 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n9. Модульная система хранения гардеробная. Тип 1 | склад: Основной склад | количество: 2,000 | стоимость: 110.916,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n10. Конструкция трансформер рабочей станции. Тип 2 | склад: Основной склад | количество: 1,000 | стоимость: 165.416,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n11. Диван трехместный | склад: Основной склад | количество: 1,000 | стоимость: 34.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n12. Кресло орион | склад: Основной склад | количество: 1,000 | стоимость: 13.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n13. Пуф арий | склад: Основной склад | количество: 1,000 | стоимость: 6.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n14. Столешница 600*3050*26 дуб ниагара | склад: Основной склад | количество: 1,000 | стоимость: 3.724,17 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n15. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n16. Четки Пост (84*117) | склад: Основной склад | количество: 1,000 | стоимость: 833,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n17. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n18. Кромка с клеем 33 дуб ниагара 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-07-31T23:59:59Z\n\nПодтверждение:\n- Дата среза: 31.07.2019.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 18.\n- Уникальных складов: 1.\n- Суммарное количество: 295,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:03:15.384Z", + "trace_id": "address-rtREGdk79X", + "debug": { + "trace_id": "address-rtREGdk79X", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "period_from": "2019-07-01", + "period_to": "2019-07-31", + "as_of_date": "2019-07-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 18, + "raw_rows_received": 18, + "rows_after_account_scope": 18, + "rows_after_recipe_filter": 18, + "rows_materialized": 18, + "rows_matched": 18, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "period_range", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": false, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "kHpRaijpcfbNyG", + "llm_decomposition_effective_message": "на июль 2019", + "llm_decomposition_reason": "followup_raw_message_preferred_over_llm_rewrite", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "на июль 2019", + "canonical_message": "на июль 2019", + "mode": "unsupported", + "mode_confidence": "low", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "unknown", + "intent_confidence": "low", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "range", + "period_from": "2019-07-01", + "period_to": "2019-07-31", + "as_of_date": null, + "has_explicit_period": true + }, + "semantics": { + "scope_kind": "none", + "anchor_kind": "none", + "anchor_value": null, + "date_scope_kind": "explicit", + "date_basis_hint": "period_range", + "self_scope_detected": false, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "на июль 2019", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "followup_context_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "unsupported", + "address_mode_confidence": "low", + "address_intent": "unknown", + "address_intent_confidence": "low", + "strong_data_signal_detected": false, + "data_retrieval_signal_detected": false, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [ + "unsupported_low_confidence_contract", + "rewrite_without_structured_gain" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": false, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": true + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "followup_context_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "на июль 2019", + "effective_message": "на июль 2019", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected", + "root_context_only_carryover" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": "carry_root_context", + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "kHpRaijpcfbNyG", + "prompt_version": "normalizer_v2_0_2", + "applied": false, + "effective_message": "на июль 2019" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2016-03-31", + "period_from": "2016-03-01", + "period_to": "2016-03-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T2", + "transition_contract_title": "Root Follow-Up With Date Or Scope Change", + "transition_contract_reason": [ + "root_followup_continue_previous" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T2", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T2", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "period_from", + "period_to", + "as_of_date", + "organization" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + }, + { + "message_id": "msg-O6Iu81GiUk", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "на сентябрь", + "reply_type": null, + "created_at": "2026-04-17T07:03:28.874Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-fYRfbQICPz", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 30.09.2019 на складе подтверждено 11 позиций с остатком на 550.153,40 ₽.\n\nПозиции:\n1. Подсветка | склад: Основной склад | количество: 90,000 | стоимость: 243.381,35 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n2. Модуль прямоугольый 1400*110*750 | склад: Основной склад | количество: 22,000 | стоимость: 148.261,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n3. Шкаф для одежды 824*437*2010 | склад: Основной склад | количество: 9,000 | стоимость: 96.076,22 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n4. Диван трехместный | склад: Основной склад | количество: 1,000 | стоимость: 34.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n5. Кресло орион | склад: Основной склад | количество: 1,000 | стоимость: 13.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n6. Пуф арий | склад: Основной склад | количество: 1,000 | стоимость: 6.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n7. Столешница 600*3050*26 дуб ниагара | склад: Основной склад | количество: 1,000 | стоимость: 3.724,17 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n8. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n9. Четки Пост (84*117) | склад: Основной склад | количество: 1,000 | стоимость: 833,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n10. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n11. Кромка с клеем 33 дуб ниагара 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-09-30T23:59:59Z\n\nПодтверждение:\n- Дата среза: 30.09.2019.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 11.\n- Уникальных складов: 1.\n- Суммарное количество: 129,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:03:39.788Z", + "trace_id": "address-TI3CCh0UJC", + "debug": { + "trace_id": "address-TI3CCh0UJC", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "as_of_date": "2019-09-30", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2019-09-01", + "period_to": "2019-09-30" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 11, + "raw_rows_received": 11, + "rows_after_account_scope": 11, + "rows_after_recipe_filter": 11, + "rows_materialized": 11, + "rows_matched": 11, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": false, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "Fsm5wTbcGCRICj", + "llm_decomposition_effective_message": "на сентябрь", + "llm_decomposition_reason": "followup_raw_message_preferred_over_llm_rewrite", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "на сентябрь", + "canonical_message": "на сентябрь", + "mode": "unsupported", + "mode_confidence": "low", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "unknown", + "intent_confidence": "low", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "none", + "anchor_kind": "none", + "anchor_value": null, + "date_scope_kind": "none", + "date_basis_hint": null, + "self_scope_detected": false, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "на сентябрь", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "followup_context_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "unsupported", + "address_mode_confidence": "low", + "address_intent": "unknown", + "address_intent_confidence": "low", + "strong_data_signal_detected": false, + "data_retrieval_signal_detected": false, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [ + "unsupported_low_confidence_contract", + "rewrite_without_structured_gain" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": false, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": true + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "followup_context_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "на сентябрь", + "effective_message": "на сентябрь", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected", + "root_context_only_carryover" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": "carry_root_context", + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "Fsm5wTbcGCRICj", + "prompt_version": "normalizer_v2_0_2", + "applied": false, + "effective_message": "на сентябрь" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2019-07-31", + "period_from": "2019-07-01", + "period_to": "2019-07-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T2", + "transition_contract_title": "Root Follow-Up With Date Or Scope Change", + "transition_contract_reason": [ + "root_followup_continue_previous" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T2", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T2", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + }, + { + "message_id": "msg-SFZT_WYkYY", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "а на март", + "reply_type": null, + "created_at": "2026-04-17T07:03:48.893Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-eV8Drg_UC9", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 31.03.2019 на складе подтверждено 16 позиций с остатком на 1.664.391,73 ₽.\n\nПозиции:\n1. Подсветка | склад: Основной склад | количество: 90,000 | стоимость: 243.381,35 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n2. Модуль на монолитном каркасе. Тип 1 | склад: Основной склад | количество: 30,000 | стоимость: 186.325,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n3. Модуль прямоугольый 1400*110*750 | склад: Основной склад | количество: 22,000 | стоимость: 148.261,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n4. Модуль на монолитном каркасе передвижной. Тип 1. | склад: Основной склад | количество: 15,000 | стоимость: 68.212,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n5. Моноблок леново | склад: Основной склад | количество: 13,000 | стоимость: 614.098,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n6. Принтер НР М203 | склад: Основной склад | количество: 13,000 | стоимость: 138.255,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n7. Источник бесперебойного питания | склад: Основной склад | количество: 13,000 | стоимость: 107.347,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n8. Шкаф для одежды 824*437*2010 | склад: Основной склад | количество: 9,000 | стоимость: 96.076,22 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n9. Диван трехместный | склад: Основной склад | количество: 1,000 | стоимость: 34.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n10. Кресло орион | склад: Основной склад | количество: 1,000 | стоимость: 13.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n11. Пуф арий | склад: Основной склад | количество: 1,000 | стоимость: 6.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n12. Столешница 600*3050*26 дуб ниагара | склад: Основной склад | количество: 1,000 | стоимость: 3.724,17 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n13. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n14. Четки Пост (84*117) | склад: Основной склад | количество: 1,000 | стоимость: 833,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n15. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n16. Кромка с клеем 33 дуб ниагара 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n\nПодтверждение:\n- Дата среза: 31.03.2019.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 16.\n- Уникальных складов: 1.\n- Суммарное количество: 213,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:04:01.195Z", + "trace_id": "address-A2lTDmKun-", + "debug": { + "trace_id": "address-A2lTDmKun-", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "as_of_date": "2019-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 16, + "raw_rows_received": 16, + "rows_after_account_scope": 16, + "rows_after_recipe_filter": 16, + "rows_materialized": 16, + "rows_matched": 16, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": false, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "V6jhCz4oijXA22", + "llm_decomposition_effective_message": "а на март", + "llm_decomposition_reason": "followup_raw_message_preferred_over_llm_rewrite", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "а на март", + "canonical_message": "а на март", + "mode": "unsupported", + "mode_confidence": "low", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "unknown", + "intent_confidence": "low", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "none", + "anchor_kind": "none", + "anchor_value": null, + "date_scope_kind": "none", + "date_basis_hint": null, + "self_scope_detected": false, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "а на март", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "followup_context_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "unsupported", + "address_mode_confidence": "low", + "address_intent": "unknown", + "address_intent_confidence": "low", + "strong_data_signal_detected": false, + "data_retrieval_signal_detected": false, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [ + "unsupported_low_confidence_contract", + "rewrite_without_structured_gain" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": false, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": true + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "followup_context_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "а на март", + "effective_message": "а на март", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected", + "root_context_only_carryover" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": "carry_root_context", + "anchor_type": null, + "anchor_value": null, + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "V6jhCz4oijXA22", + "prompt_version": "normalizer_v2_0_2", + "applied": false, + "effective_message": "а на март" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2019-09-30", + "period_from": "2019-09-01", + "period_to": "2019-09-30" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T2", + "transition_contract_title": "Root Follow-Up With Date Or Scope Change", + "transition_contract_reason": [ + "root_followup_continue_previous" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T2", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T2", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "no_address_or_deep_signal", + "address_mode_from_followup_context", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "intent_restored_to_inventory_root_frame", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_derived_from_inventory_root_frame_year", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + }, + { + "message_id": "msg-6yHi1t4n78", + "session_id": "asst-kBU5iS0mEt", + "role": "user", + "text": "это по общей базе", + "reply_type": null, + "created_at": "2026-04-17T07:04:08.964Z", + "trace_id": null, + "debug": null + }, + { + "message_id": "msg-GcM8aL1yJc", + "session_id": "asst-kBU5iS0mEt", + "role": "assistant", + "text": "На 31.03.2019 на складе подтверждено 16 позиций с остатком на 1.664.391,73 ₽.\n\nПозиции:\n1. Подсветка | склад: Основной склад | количество: 90,000 | стоимость: 243.381,35 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n2. Модуль на монолитном каркасе. Тип 1 | склад: Основной склад | количество: 30,000 | стоимость: 186.325,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n3. Модуль прямоугольый 1400*110*750 | склад: Основной склад | количество: 22,000 | стоимость: 148.261,67 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n4. Модуль на монолитном каркасе передвижной. Тип 1. | склад: Основной склад | количество: 15,000 | стоимость: 68.212,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n5. Моноблок леново | склад: Основной склад | количество: 13,000 | стоимость: 614.098,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n6. Принтер НР М203 | склад: Основной склад | количество: 13,000 | стоимость: 138.255,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n7. Источник бесперебойного питания | склад: Основной склад | количество: 13,000 | стоимость: 107.347,50 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n8. Шкаф для одежды 824*437*2010 | склад: Основной склад | количество: 9,000 | стоимость: 96.076,22 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n9. Диван трехместный | склад: Основной склад | количество: 1,000 | стоимость: 34.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n10. Кресло орион | склад: Основной склад | количество: 1,000 | стоимость: 13.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n11. Пуф арий | склад: Основной склад | количество: 1,000 | стоимость: 6.490,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n12. Столешница 600*3050*26 дуб ниагара | склад: Основной склад | количество: 1,000 | стоимость: 3.724,17 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n13. Столешница 600*3050*26 альмандин | склад: Основной склад | количество: 1,000 | стоимость: 3.075,00 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n14. Четки Пост (84*117) | склад: Основной склад | количество: 1,000 | стоимость: 833,33 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n15. Кромка с клеем 33 альмандин 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n16. Кромка с клеем 33 дуб ниагара 137 м | склад: Основной склад | количество: 1,000 | стоимость: 165,83 ₽ | организация: ООО \\Альтернатива Плюс\\ | дата строки: 2019-03-31T23:59:59Z\n\nПодтверждение:\n- Дата среза: 31.03.2019.\n- Контур: остатки по счету 41.01 «Товары на складах».\n- Уникальных товаров: 16.\n- Уникальных складов: 1.\n- Суммарное количество: 213,000.", + "reply_type": "factual", + "created_at": "2026-04-17T07:04:19.453Z", + "trace_id": "address-srwtOvv1jk", + "debug": { + "trace_id": "address-srwtOvv1jk", + "prompt_version": "address_query_runtime_v1", + "schema_version": "address_query_runtime_v1", + "fallback_type": "none", + "route_summary": null, + "fragments": [], + "requirements_extracted": [], + "coverage_report": { + "requirements_total": 0, + "requirements_covered": 0, + "requirements_uncovered": [], + "requirements_partially_covered": [], + "clarification_needed_for": [], + "out_of_scope_requirements": [] + }, + "routes": [], + "retrieval_status": [], + "retrieval_results": [], + "answer_grounding_check": { + "status": "grounded", + "route_subject_match": true, + "missing_requirements": [], + "reasons": [ + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "why_included_summary": [], + "selection_reason_summary": [] + }, + "dropped_intent_segments": [], + "detected_mode": "address_query", + "detected_mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "detected_intent": "inventory_on_hand_as_of_date", + "detected_intent_confidence": "low", + "extracted_filters": { + "sort": "period_desc", + "as_of_date": "2019-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "missing_required_filters": [], + "selected_recipe": "address_inventory_on_hand_as_of_date_v1", + "mcp_call_status_legacy": "matched_non_empty", + "account_scope_mode": "strict", + "account_scope_fallback_applied": false, + "anchor_type": "organization", + "anchor_value_raw": "ООО \\Альтернатива Плюс\\", + "anchor_value_resolved": "ООО \\Альтернатива Плюс\\", + "resolver_confidence": "medium", + "ambiguity_count": 0, + "match_failure_stage": "none", + "match_failure_reason": null, + "mcp_call_status": "matched_non_empty", + "rows_fetched": 16, + "raw_rows_received": 16, + "rows_after_account_scope": 16, + "rows_after_recipe_filter": 16, + "rows_materialized": 16, + "rows_matched": 16, + "raw_row_keys_sample": [ + "Период", + "Регистратор", + "СчетДт", + "СчетКт", + "Сумма", + "Номенклатура", + "Склад", + "Организация", + "Количество", + "Period", + "Registrator", + "AccountDt", + "Amount" + ], + "materialization_drop_reason": "none", + "account_token_raw": null, + "account_token_normalized": null, + "account_scope_fields_checked": [ + "account_dt", + "account_kt", + "registrator", + "analytics" + ], + "account_scope_match_strategy": "account_code_regex_plus_alias_map_v1", + "account_scope_drop_reason": "not_applicable", + "runtime_readiness": "LIVE_QUERYABLE_WITH_LIMITS", + "limited_reason_category": null, + "response_type": "FACTUAL_LIST", + "requested_result_mode": "confirmed_balance", + "result_mode": "confirmed_balance", + "evidence_strength": "strong", + "balance_confirmed": true, + "as_of_date_basis": "implicit_current_snapshot", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_layer": "compute", + "capability_route_mode": "exact", + "capability_route_enabled": true, + "capability_route_reason": "inventory_on_hand_route_enabled", + "shadow_route_status": "skipped", + "route_expectation_status": "matched", + "route_expectation_reason": "route_expectation_matched", + "route_expectation_expected_selected_recipes": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "route_expectation_expected_requested_result_modes": [ + "confirmed_balance" + ], + "route_expectation_expected_result_modes": [ + "confirmed_balance" + ], + "execution_lane": "address_query", + "llm_decomposition_applied": true, + "llm_decomposition_attempted": true, + "llm_provider_used": "local", + "llm_decomposition_trace_id": "GUwBiOWS9Jln1c", + "llm_decomposition_effective_message": "анализ по общей базе компании", + "llm_decomposition_reason": "normalized_fragment_applied", + "llm_canonical_candidate_detected": true, + "llm_predecompose_contract": { + "schema_version": "address_llm_predecompose_contract_v1", + "source_message": "это по общей базе", + "canonical_message": "анализ по общей базе компании", + "mode": "address_query", + "mode_confidence": "medium", + "query_shape": "UNKNOWN", + "query_shape_confidence": "low", + "intent": "unknown", + "intent_confidence": "low", + "entities": { + "account": null, + "counterparty": null, + "contract": null, + "document_type": null, + "document_ref": null, + "organization": null + }, + "period": { + "scope": "unspecified", + "period_from": null, + "period_to": null, + "as_of_date": null, + "has_explicit_period": false + }, + "semantics": { + "scope_kind": "implicit_self_scope", + "anchor_kind": "self_scope", + "anchor_value": null, + "date_scope_kind": "implicit_current", + "date_basis_hint": "implicit_current_snapshot", + "self_scope_detected": true, + "selected_object_scope_detected": false + }, + "aggregation_profile": "unknown" + }, + "fallback_rule_hit": null, + "sanitized_user_message": "это по общей базе", + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "orchestration_contract_v1": { + "schema_version": "assistant_orchestration_contract_v1", + "hard_meta_mode": null, + "address_mode": "address_query", + "address_mode_confidence": "medium", + "address_intent": "unknown", + "address_intent_confidence": "low", + "strong_data_signal_detected": true, + "data_retrieval_signal_detected": false, + "semantic_contract_valid": true, + "semantic_apply_canonical_recommended": true, + "semantic_reason_codes": [ + "rewrite_without_structured_gain" + ], + "semantic_route_arbitration": { + "supported_address_intent_detected": false, + "strict_deep_investigation_bypass_allowed": false, + "semantic_deep_investigation_hint_detected": false, + "semantic_aggregate_shape_detected": false, + "followup_semantic_override_to_deep_allowed": false + }, + "followup_context_detected": true, + "unsupported_address_intent_fallback_to_deep": false, + "deep_analysis_signal_fallback_to_deep": false, + "aggregate_analytics_signal_fallback_to_deep": false, + "deep_session_continuation_fallback_to_deep": false, + "final_decision": { + "run_address_lane": true, + "tool_gate_decision": "run_address_lane", + "tool_gate_reason": "address_mode_classifier_detected", + "living_mode": "address_data", + "living_reason": "address_lane_triggered" + } + }, + "dialog_continuation_contract_v2": { + "schema_version": "address_dialog_continuation_contract_v2", + "source_message": "это по общей базе", + "effective_message": "анализ по общей базе компании", + "decision": "continue_previous", + "decision_reasons": [ + "followup_context_detected", + "effective_message_rewritten_by_predecompose" + ], + "followup_context_applied": true, + "previous_intent": "inventory_on_hand_as_of_date", + "target_intent": "inventory_on_hand_as_of_date", + "intent_selection_mode": "carry_previous_intent", + "anchor_type": "organization", + "anchor_value": "ООО \\Альтернатива Плюс\\", + "implicit_continuation_signal": false + }, + "address_retry_audit": { + "attempted": false, + "reason": null, + "initial_limited_category": null, + "retry_message": null, + "retry_used_followup_context": false, + "retry_result_category": null + }, + "answer_structure_v11": null, + "investigation_state_snapshot": null, + "normalized": null, + "normalizer_output": { + "trace_id": "GUwBiOWS9Jln1c", + "prompt_version": "normalizer_v2_0_2", + "applied": true, + "effective_message": "анализ по общей базе компании" + }, + "assistant_known_organizations": [ + "ООО \\Альтернатива Плюс\\" + ], + "assistant_active_organization": "ООО \\Альтернатива Плюс\\", + "address_root_frame_context": { + "root_intent": "inventory_on_hand_as_of_date", + "current_frame_kind": "inventory_root", + "organization": "ООО \\Альтернатива Плюс\\", + "as_of_date": "2019-03-31", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "assistant_runtime_contract_v1": { + "schema_version": "assistant_runtime_contracts_v1", + "transition_contract_id": "T2", + "transition_contract_title": "Root Follow-Up With Date Or Scope Change", + "transition_contract_reason": [ + "root_followup_continue_previous" + ], + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_reason": [ + "debug_capability_id_matched_contract" + ], + "truth_gate_contract_status": "full_confirmed", + "carryover_eligibility": "root_only" + }, + "transition_contract_id": "T2", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "truth_gate_contract_status": "full_confirmed", + "assistant_truth_answer_policy_v1": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "truth_gate": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + } + }, + "coverage_gate_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ], + "source_truth_gate_status": "full_confirmed", + "blocked_or_limited_explanation": null + }, + "answer_shape_contract": { + "schema_version": "assistant_truth_answer_policy_runtime_v1", + "policy_owner": "assistantTruthAnswerPolicyRuntimeAdapter", + "answer_shape": "confirmed_factual", + "reply_type": "factual", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "transition_contract_id": "T2", + "may_state_confirmed_facts": true, + "must_include_limitation": false, + "may_power_followup": true, + "required_sections": [ + "direct_answer", + "evidence_basis" + ], + "downgrade_only": true + }, + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "answer_shape": "confirmed_factual", + "assistant_state_transition_v1": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_contract": { + "schema_version": "assistant_state_transition_runtime_v1", + "state_owner": "assistantStateTransitionRuntimeAdapter", + "transition_id": "T2", + "transition_title": "Root Follow-Up With Date Or Scope Change", + "application_status": "applied", + "declared_carryover_depth": "root_only", + "truth_gate_carryover_depth": "root_only", + "effective_carryover_depth": "root_only", + "required_prior_state": [ + "root_frame_state" + ], + "expected_answer_mode": "confirmed", + "state_mutations": [ + "update_root_frame_state", + "run_exact_route", + "refresh_coverage_gate_state" + ], + "forbidden_carryover": [ + "incompatible_selected_object_route" + ], + "state_actions": { + "living_mode_state": "update", + "root_frame_state": "update", + "selected_object_frame_state": "clear", + "meta_frame_state": "clear", + "clarification_state": "clear", + "coverage_gate_state": "create", + "answer_context_state": "create" + }, + "coverage_gate_state": { + "coverage_status": "full", + "evidence_grade": "strong", + "grounding_status": "grounded", + "truth_mode": "confirmed", + "carryover_eligibility": "root_only", + "reason_codes": [ + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "reason_codes": [ + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "state_transition_id": "T2", + "state_transition_status": "applied", + "effective_carryover_depth": "root_only", + "assistant_capability_binding_v1": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_contract": { + "schema_version": "assistant_capability_runtime_binding_v1", + "binding_owner": "assistantCapabilityRuntimeBindingAdapter", + "capability_id": "confirmed_inventory_on_hand_as_of_date", + "capability_contract_id": "confirmed_inventory_on_hand_as_of_date", + "binding_status": "bound", + "binding_action": "allow", + "runtime_lane_expected": "address_exact", + "runtime_lane_observed": "address_exact", + "execution_adapter": "AddressQueryService", + "transition_id": "T2", + "transition_allowed": true, + "required_anchors": [], + "provided_anchors": [ + "sort", + "as_of_date", + "organization", + "period_from", + "period_to" + ], + "missing_anchors": [], + "requires_focus_object": false, + "focus_object_binding_status": "not_required", + "result_shape": "item_list_with_quantity_cost_warehouse_organization", + "answer_object_shape": "inventory_stock_snapshot", + "truth_gate_behavior": "partial_or_blocked_if_evidence_insufficient", + "truth_fallback_allowed": true, + "answer_shape_compatible": true, + "violations": [], + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + }, + "capability_binding_status": "bound", + "capability_binding_action": "allow", + "capability_binding_violations": [], + "capability_binding_response_guard": { + "schema_version": "assistant_capability_binding_response_guard_v1", + "guard_owner": "assistantCapabilityBindingResponseGuard", + "applied": false, + "action": "allow", + "original_reply_type": "factual", + "guarded_reply_type": "factual", + "reason_codes": [ + "binding_status_bound", + "binding_action_allow", + "transition_status_applied", + "transition_T2", + "root_followup_continue_previous", + "debug_capability_id_matched_contract", + "truth_gate_full_confirmed", + "truth_mode_confirmed", + "route_expectation_matched", + "loose_by_anchor_detected", + "shape_not_detected", + "intent_not_supported_in_v1", + "intent_from_followup_context", + "organization_from_followup_context", + "as_of_date_from_followup_context", + "period_from_followup_context", + "address_followup_context_applied", + "confirmed_balance_exact_inventory_intent" + ] + } + } + } + ], + "investigation_state": { + "schema_version": "investigation_state_v1", + "session_id": "asst-kBU5iS0mEt", + "status": "idle", + "turn_index": 0, + "updated_at": "2026-04-17T06:59:00.189Z", + "question_id": null, + "question_scope_id": null, + "scope_origin": null, + "focus": { + "domain": null, + "period": null, + "primary_accounts": [], + "active_query_subject": null + }, + "narrowing_status": "unknown", + "evidence_refs": [], + "open_uncertainties": [], + "last_answer_mode": null, + "followup_context": null, + "query_mode_hint": "direct_answer" + }, + "address_navigation_state": { + "schema_version": "address_navigation_state_v1", + "session_id": "asst-kBU5iS0mEt", + "updated_at": "2026-04-17T07:04:19.453Z", + "session_context": { + "active_result_set_id": "rs-msg-GcM8aL1yJc", + "active_focus_object": { + "object_type": "organization", + "object_id": "organization:ооо \\альтернатива плюс\\", + "label": "ООО \\Альтернатива Плюс\\", + "provenance_result_set_id": "rs-msg-GcM8aL1yJc", + "selected_at": "2026-04-17T07:04:19.453Z" + }, + "last_confirmed_route": "address_inventory_on_hand_as_of_date_v1", + "date_scope": { + "as_of_date": "2019-03-31", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "organization_scope": "ООО \\Альтернатива Плюс\\" + }, + "result_sets": [ + { + "result_set_id": "rs-msg-FbPrdbojCb", + "type": "document_list", + "intent": "list_documents_by_counterparty", + "route_id": "address_documents_by_counterparty_v1", + "filters": { + "sort": "period_desc", + "limit": 20, + "counterparty": "Чепурнов П.Д." + }, + "source_refs": [ + "address_documents_by_counterparty_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "document_ref", + "value": "2022-01-20T12:00:03Z" + } + ], + "created_from_turn": 1, + "created_at": "2026-04-17T06:59:13.677Z" + }, + { + "result_set_id": "rs-msg-F31DDcZwOL", + "type": "document_list", + "intent": "list_documents_by_counterparty", + "route_id": "address_documents_by_counterparty_v1", + "filters": { + "sort": "period_desc", + "limit": 20, + "counterparty": "Чепурнов П.Д." + }, + "source_refs": [ + "address_documents_by_counterparty_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "document_ref", + "value": "Поступление на расчетный счет 00000000001 от 20.01.2022 12:00:03" + } + ], + "created_from_turn": 3, + "created_at": "2026-04-17T06:59:28.924Z" + }, + { + "result_set_id": "rs-msg-3BxJ--X0gY", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "as_of_date": "2026-04-17", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Модуль прямоугольый 1400*110*750" + }, + { + "index": 2, + "entity_type": "item", + "value": "Конструкция трансформер рабочей станции 1300*900*2000" + }, + { + "index": 3, + "entity_type": "item", + "value": "Диван трехместный" + }, + { + "index": 4, + "entity_type": "item", + "value": "Кресло орион" + }, + { + "index": 5, + "entity_type": "item", + "value": "Зеркало для инвалидов поворотное травмобезопасное" + }, + { + "index": 6, + "entity_type": "item", + "value": "Пуф арий" + }, + { + "index": 7, + "entity_type": "item", + "value": "Столешница 600*3050*26 дуб ниагара" + }, + { + "index": 8, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 9, + "entity_type": "item", + "value": "Четки Пост (84*117)" + }, + { + "index": 10, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + }, + { + "index": 11, + "entity_type": "item", + "value": "Кромка с клеем 33 дуб ниагара 137 м" + } + ], + "created_from_turn": 5, + "created_at": "2026-04-17T06:59:50.036Z" + }, + { + "result_set_id": "rs-msg-MXOH4cg-7h", + "type": "open_items_list", + "intent": "open_items_by_counterparty_or_contract", + "route_id": "address_open_items_by_party_or_contract_v1", + "filters": { + "sort": "period_desc", + "limit": 20, + "account": "60", + "period_from": "2022-08-01", + "period_to": "2022-08-31", + "as_of_date": "2022-08-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "source_refs": [ + "address_open_items_by_party_or_contract_v1" + ], + "entity_refs": [], + "created_from_turn": 7, + "created_at": "2026-04-17T07:00:16.065Z" + }, + { + "result_set_id": "rs-msg-yllv_YMGcL", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "period_from": "2021-03-01", + "period_to": "2021-03-31", + "as_of_date": "2021-03-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Модуль прямоугольый 1400*110*750" + }, + { + "index": 2, + "entity_type": "item", + "value": "Конструкция трансформер рабочей станции 1300*900*2000" + }, + { + "index": 3, + "entity_type": "item", + "value": "Диван трехместный" + }, + { + "index": 4, + "entity_type": "item", + "value": "Кресло орион" + }, + { + "index": 5, + "entity_type": "item", + "value": "Зеркало для инвалидов поворотное травмобезопасное" + }, + { + "index": 6, + "entity_type": "item", + "value": "Пуф арий" + }, + { + "index": 7, + "entity_type": "item", + "value": "Столешница 600*3050*26 дуб ниагара" + }, + { + "index": 8, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 9, + "entity_type": "item", + "value": "Четки Пост (84*117)" + }, + { + "index": 10, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + }, + { + "index": 11, + "entity_type": "item", + "value": "Кромка с клеем 33 дуб ниагара 137 м" + } + ], + "created_from_turn": 9, + "created_at": "2026-04-17T07:00:49.064Z" + }, + { + "result_set_id": "rs-msg-ursK5G5ZoO", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "as_of_date": "2021-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "item": "Столешница 600*3050*26 альмандин", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 2, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + } + ], + "created_from_turn": 11, + "created_at": "2026-04-17T07:01:11.435Z" + }, + { + "result_set_id": "rs-msg-3JlrNX8e49", + "type": "inventory_trace", + "intent": "inventory_purchase_documents_for_item", + "route_id": "address_inventory_purchase_documents_for_item_v1", + "filters": { + "sort": "period_desc", + "item": "Столешница 600*3050*26 альмандин", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "source_refs": [ + "address_inventory_purchase_documents_for_item_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Поступление товаров и услуг 00000000003 от 12.02.2019 0:00:00" + } + ], + "created_from_turn": 13, + "created_at": "2026-04-17T07:01:52.029Z" + }, + { + "result_set_id": "rs-msg-G6BtQFSdJv", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "as_of_date": "2021-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2021-03-01", + "period_to": "2021-03-31" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [], + "created_from_turn": 15, + "created_at": "2026-04-17T07:02:19.571Z" + }, + { + "result_set_id": "rs-msg-U3T1-nXZm8", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "period_from": "2016-03-01", + "period_to": "2016-03-31", + "as_of_date": "2016-03-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Шкаф для одежды 824*437*2010" + }, + { + "index": 2, + "entity_type": "item", + "value": "Рабочая станция универсального специалиста (индивидуальное изготовление)" + } + ], + "created_from_turn": 17, + "created_at": "2026-04-17T07:03:01.200Z" + }, + { + "result_set_id": "rs-msg-WTR742ctqv", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "period_from": "2019-07-01", + "period_to": "2019-07-31", + "as_of_date": "2019-07-31", + "organization": "ООО \\Альтернатива Плюс\\" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Подсветка" + }, + { + "index": 2, + "entity_type": "item", + "value": "Секция мобильная. Тип 1." + }, + { + "index": 3, + "entity_type": "item", + "value": "Секция монолитная. Тип 1" + }, + { + "index": 4, + "entity_type": "item", + "value": "Модуль прямоугольый 1400*110*750" + }, + { + "index": 5, + "entity_type": "item", + "value": "Моноблок леново" + }, + { + "index": 6, + "entity_type": "item", + "value": "Принтер НР М203" + }, + { + "index": 7, + "entity_type": "item", + "value": "Источник бесперебойного питания" + }, + { + "index": 8, + "entity_type": "item", + "value": "Шкаф для одежды 824*437*2010" + }, + { + "index": 9, + "entity_type": "item", + "value": "Модульная система хранения гардеробная. Тип 1" + }, + { + "index": 10, + "entity_type": "item", + "value": "Конструкция трансформер рабочей станции. Тип 2" + }, + { + "index": 11, + "entity_type": "item", + "value": "Диван трехместный" + }, + { + "index": 12, + "entity_type": "item", + "value": "Кресло орион" + }, + { + "index": 13, + "entity_type": "item", + "value": "Пуф арий" + }, + { + "index": 14, + "entity_type": "item", + "value": "Столешница 600*3050*26 дуб ниагара" + }, + { + "index": 15, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 16, + "entity_type": "item", + "value": "Четки Пост (84*117)" + }, + { + "index": 17, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + }, + { + "index": 18, + "entity_type": "item", + "value": "Кромка с клеем 33 дуб ниагара 137 м" + } + ], + "created_from_turn": 19, + "created_at": "2026-04-17T07:03:15.384Z" + }, + { + "result_set_id": "rs-msg-fYRfbQICPz", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "as_of_date": "2019-09-30", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2019-09-01", + "period_to": "2019-09-30" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Подсветка" + }, + { + "index": 2, + "entity_type": "item", + "value": "Модуль прямоугольый 1400*110*750" + }, + { + "index": 3, + "entity_type": "item", + "value": "Шкаф для одежды 824*437*2010" + }, + { + "index": 4, + "entity_type": "item", + "value": "Диван трехместный" + }, + { + "index": 5, + "entity_type": "item", + "value": "Кресло орион" + }, + { + "index": 6, + "entity_type": "item", + "value": "Пуф арий" + }, + { + "index": 7, + "entity_type": "item", + "value": "Столешница 600*3050*26 дуб ниагара" + }, + { + "index": 8, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 9, + "entity_type": "item", + "value": "Четки Пост (84*117)" + }, + { + "index": 10, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + }, + { + "index": 11, + "entity_type": "item", + "value": "Кромка с клеем 33 дуб ниагара 137 м" + } + ], + "created_from_turn": 21, + "created_at": "2026-04-17T07:03:39.788Z" + }, + { + "result_set_id": "rs-msg-eV8Drg_UC9", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "as_of_date": "2019-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Подсветка" + }, + { + "index": 2, + "entity_type": "item", + "value": "Модуль на монолитном каркасе. Тип 1" + }, + { + "index": 3, + "entity_type": "item", + "value": "Модуль прямоугольый 1400*110*750" + }, + { + "index": 4, + "entity_type": "item", + "value": "Модуль на монолитном каркасе передвижной. Тип 1." + }, + { + "index": 5, + "entity_type": "item", + "value": "Моноблок леново" + }, + { + "index": 6, + "entity_type": "item", + "value": "Принтер НР М203" + }, + { + "index": 7, + "entity_type": "item", + "value": "Источник бесперебойного питания" + }, + { + "index": 8, + "entity_type": "item", + "value": "Шкаф для одежды 824*437*2010" + }, + { + "index": 9, + "entity_type": "item", + "value": "Диван трехместный" + }, + { + "index": 10, + "entity_type": "item", + "value": "Кресло орион" + }, + { + "index": 11, + "entity_type": "item", + "value": "Пуф арий" + }, + { + "index": 12, + "entity_type": "item", + "value": "Столешница 600*3050*26 дуб ниагара" + }, + { + "index": 13, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 14, + "entity_type": "item", + "value": "Четки Пост (84*117)" + }, + { + "index": 15, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + }, + { + "index": 16, + "entity_type": "item", + "value": "Кромка с клеем 33 дуб ниагара 137 м" + } + ], + "created_from_turn": 23, + "created_at": "2026-04-17T07:04:01.195Z" + }, + { + "result_set_id": "rs-msg-GcM8aL1yJc", + "type": "inventory_snapshot", + "intent": "inventory_on_hand_as_of_date", + "route_id": "address_inventory_on_hand_as_of_date_v1", + "filters": { + "sort": "period_desc", + "as_of_date": "2019-03-31", + "organization": "ООО \\Альтернатива Плюс\\", + "period_from": "2019-03-01", + "period_to": "2019-03-31" + }, + "source_refs": [ + "address_inventory_on_hand_as_of_date_v1" + ], + "entity_refs": [ + { + "index": 1, + "entity_type": "item", + "value": "Подсветка" + }, + { + "index": 2, + "entity_type": "item", + "value": "Модуль на монолитном каркасе. Тип 1" + }, + { + "index": 3, + "entity_type": "item", + "value": "Модуль прямоугольый 1400*110*750" + }, + { + "index": 4, + "entity_type": "item", + "value": "Модуль на монолитном каркасе передвижной. Тип 1." + }, + { + "index": 5, + "entity_type": "item", + "value": "Моноблок леново" + }, + { + "index": 6, + "entity_type": "item", + "value": "Принтер НР М203" + }, + { + "index": 7, + "entity_type": "item", + "value": "Источник бесперебойного питания" + }, + { + "index": 8, + "entity_type": "item", + "value": "Шкаф для одежды 824*437*2010" + }, + { + "index": 9, + "entity_type": "item", + "value": "Диван трехместный" + }, + { + "index": 10, + "entity_type": "item", + "value": "Кресло орион" + }, + { + "index": 11, + "entity_type": "item", + "value": "Пуф арий" + }, + { + "index": 12, + "entity_type": "item", + "value": "Столешница 600*3050*26 дуб ниагара" + }, + { + "index": 13, + "entity_type": "item", + "value": "Столешница 600*3050*26 альмандин" + }, + { + "index": 14, + "entity_type": "item", + "value": "Четки Пост (84*117)" + }, + { + "index": 15, + "entity_type": "item", + "value": "Кромка с клеем 33 альмандин 137 м" + }, + { + "index": 16, + "entity_type": "item", + "value": "Кромка с клеем 33 дуб ниагара 137 м" + } + ], + "created_from_turn": 25, + "created_at": "2026-04-17T07:04:19.453Z" + } + ], + "navigation_history": [ + { + "event_id": "nav-YmhSdHpzBl", + "action": "open", + "source_result_set_id": null, + "target_object_id": "counterparty:чепурнов п.д.", + "derived_result_set_id": "rs-msg-FbPrdbojCb", + "turn_index": 1, + "created_at": "2026-04-17T06:59:13.677Z" + }, + { + "event_id": "nav-U-0Ob8-Wxb", + "action": "open", + "source_result_set_id": "rs-msg-FbPrdbojCb", + "target_object_id": "counterparty:чепурнов п.д.", + "derived_result_set_id": "rs-msg-F31DDcZwOL", + "turn_index": 3, + "created_at": "2026-04-17T06:59:28.924Z" + }, + { + "event_id": "nav-kXjQouHEvP", + "action": "open", + "source_result_set_id": "rs-msg-F31DDcZwOL", + "target_object_id": null, + "derived_result_set_id": "rs-msg-3BxJ--X0gY", + "turn_index": 5, + "created_at": "2026-04-17T06:59:50.036Z" + }, + { + "event_id": "nav-JDr1Tuby_3", + "action": "open", + "source_result_set_id": "rs-msg-3BxJ--X0gY", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-MXOH4cg-7h", + "turn_index": 7, + "created_at": "2026-04-17T07:00:16.065Z" + }, + { + "event_id": "nav-tPireHieCq", + "action": "open", + "source_result_set_id": "rs-msg-MXOH4cg-7h", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-yllv_YMGcL", + "turn_index": 9, + "created_at": "2026-04-17T07:00:49.064Z" + }, + { + "event_id": "nav-bp6gS4sq3j", + "action": "drilldown", + "source_result_set_id": "rs-msg-yllv_YMGcL", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-ursK5G5ZoO", + "turn_index": 11, + "created_at": "2026-04-17T07:01:11.435Z" + }, + { + "event_id": "nav-evQf0N6Gkk", + "action": "drilldown", + "source_result_set_id": "rs-msg-ursK5G5ZoO", + "target_object_id": "item:столешница 600*3050*26 альмандин", + "derived_result_set_id": "rs-msg-3JlrNX8e49", + "turn_index": 13, + "created_at": "2026-04-17T07:01:52.029Z" + }, + { + "event_id": "nav-DhBjSUIz7H", + "action": "drilldown", + "source_result_set_id": "rs-msg-3JlrNX8e49", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-G6BtQFSdJv", + "turn_index": 15, + "created_at": "2026-04-17T07:02:19.571Z" + }, + { + "event_id": "nav-rbeNIjhdc4", + "action": "drilldown", + "source_result_set_id": "rs-msg-G6BtQFSdJv", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-U3T1-nXZm8", + "turn_index": 17, + "created_at": "2026-04-17T07:03:01.200Z" + }, + { + "event_id": "nav-qxXvPocs3g", + "action": "drilldown", + "source_result_set_id": "rs-msg-U3T1-nXZm8", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-WTR742ctqv", + "turn_index": 19, + "created_at": "2026-04-17T07:03:15.384Z" + }, + { + "event_id": "nav-2pqCjY7jPi", + "action": "drilldown", + "source_result_set_id": "rs-msg-WTR742ctqv", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-fYRfbQICPz", + "turn_index": 21, + "created_at": "2026-04-17T07:03:39.788Z" + }, + { + "event_id": "nav-BoSkITaptR", + "action": "drilldown", + "source_result_set_id": "rs-msg-fYRfbQICPz", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-eV8Drg_UC9", + "turn_index": 23, + "created_at": "2026-04-17T07:04:01.195Z" + }, + { + "event_id": "nav-65j4e6ilHC", + "action": "drilldown", + "source_result_set_id": "rs-msg-eV8Drg_UC9", + "target_object_id": "organization:ооо \\альтернатива плюс\\", + "derived_result_set_id": "rs-msg-GcM8aL1yJc", + "turn_index": 25, + "created_at": "2026-04-17T07:04:19.453Z" + } + ] + } + } +} \ No newline at end of file diff --git a/llm_normalizer/data/eval_cases/assistant_autogen_saved_user_sessions_20260417070448_gen-mo2kcds2-tlqmvng.json b/llm_normalizer/data/eval_cases/assistant_autogen_saved_user_sessions_20260417070448_gen-mo2kcds2-tlqmvng.json new file mode 100644 index 0000000..6910724 --- /dev/null +++ b/llm_normalizer/data/eval_cases/assistant_autogen_saved_user_sessions_20260417070448_gen-mo2kcds2-tlqmvng.json @@ -0,0 +1,63 @@ +{ + "suite_id": "assistant_saved_session_gen-mo2kcds2-tlqmvng", + "suite_version": "0.1.0", + "schema_version": "assistant_saved_session_suite_v0_1", + "generated_at": "2026-04-17T07:04:48.578Z", + "generation_id": "gen-mo2kcds2-tlqmvng", + "mode": "saved_user_sessions", + "title": "Ручная сессия 17.04.2026, 10:04:19 ТЕМП", + "scenario_count": 1, + "case_ids": [ + "SAVED-001" + ], + "cases": [ + { + "case_id": "SAVED-001", + "scenario_tag": "saved_user_sessions", + "title": "Ручная сессия 17.04.2026, 10:04:19 ТЕМП", + "question_type": "followup", + "broadness_level": "medium", + "turns": [ + { + "user_message": "покажи все документы по чепурнову" + }, + { + "user_message": "что нам отгружал чепурнов, какой товар или услугу?" + }, + { + "user_message": "какие остатки на складе на сегодня?" + }, + { + "user_message": "хвосты по счету 60 на август 2022" + }, + { + "user_message": "какие остатки на складе на март 2021" + }, + { + "user_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": кто нам это поставил?" + }, + { + "user_message": "По выбранному объекту \"Столешница 600*3050*26 альмандин\": покажи документы по этой позиции" + }, + { + "user_message": "покажи еще раз остатки на эту же дату" + }, + { + "user_message": "какие остатки на складе на март 2016" + }, + { + "user_message": "на июль 2019" + }, + { + "user_message": "на сентябрь" + }, + { + "user_message": "а на март" + }, + { + "user_message": "это по общей базе" + } + ] + } + ] +} \ No newline at end of file diff --git a/llm_normalizer/frontend/dist/assets/index-Bw40I8e3.js b/llm_normalizer/frontend/dist/assets/index-BIzNO_Mb.js similarity index 63% rename from llm_normalizer/frontend/dist/assets/index-Bw40I8e3.js rename to llm_normalizer/frontend/dist/assets/index-BIzNO_Mb.js index 24bf258..6e00fc4 100644 --- a/llm_normalizer/frontend/dist/assets/index-Bw40I8e3.js +++ b/llm_normalizer/frontend/dist/assets/index-BIzNO_Mb.js @@ -1,24 +1,24 @@ -(function(){const g=document.createElement("link").relList;if(g&&g.supports&&g.supports("modulepreload"))return;for(const E of document.querySelectorAll('link[rel="modulepreload"]'))R(E);new MutationObserver(E=>{for(const A of E)if(A.type==="childList")for(const Q of A.addedNodes)Q.tagName==="LINK"&&Q.rel==="modulepreload"&&R(Q)}).observe(document,{childList:!0,subtree:!0});function f(E){const A={};return E.integrity&&(A.integrity=E.integrity),E.referrerPolicy&&(A.referrerPolicy=E.referrerPolicy),E.crossOrigin==="use-credentials"?A.credentials="include":E.crossOrigin==="anonymous"?A.credentials="omit":A.credentials="same-origin",A}function R(E){if(E.ep)return;E.ep=!0;const A=f(E);fetch(E.href,A)}})();function qc(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Zi={exports:{}},vo={},ea={exports:{}},fe={};var jc;function vf(){if(jc)return fe;jc=1;var i=Symbol.for("react.element"),g=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),E=Symbol.for("react.profiler"),A=Symbol.for("react.provider"),Q=Symbol.for("react.context"),le=Symbol.for("react.forward_ref"),te=Symbol.for("react.suspense"),z=Symbol.for("react.memo"),Y=Symbol.for("react.lazy"),X=Symbol.iterator;function ee(v){return v===null||typeof v!="object"?null:(v=X&&v[X]||v["@@iterator"],typeof v=="function"?v:null)}var Te={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ce=Object.assign,de={};function pe(v,w,re){this.props=v,this.context=w,this.refs=de,this.updater=re||Te}pe.prototype.isReactComponent={},pe.prototype.setState=function(v,w){if(typeof v!="object"&&typeof v!="function"&&v!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,v,w,"setState")},pe.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function Qe(){}Qe.prototype=pe.prototype;function Je(v,w,re){this.props=v,this.context=w,this.refs=de,this.updater=re||Te}var be=Je.prototype=new Qe;be.constructor=Je,ce(be,pe.prototype),be.isPureReactComponent=!0;var Re=Array.isArray,F=Object.prototype.hasOwnProperty,oe={current:null},Ce={key:!0,ref:!0,__self:!0,__source:!0};function $e(v,w,re){var ie,ae={},he=null,xe=null;if(w!=null)for(ie in w.ref!==void 0&&(xe=w.ref),w.key!==void 0&&(he=""+w.key),w)F.call(w,ie)&&!Ce.hasOwnProperty(ie)&&(ae[ie]=w[ie]);var _e=arguments.length-2;if(_e===1)ae.children=re;else if(1<_e){for(var we=Array(_e),lt=0;lt<_e;lt++)we[lt]=arguments[lt+2];ae.children=we}if(v&&v.defaultProps)for(ie in _e=v.defaultProps,_e)ae[ie]===void 0&&(ae[ie]=_e[ie]);return{$$typeof:i,type:v,key:he,ref:xe,props:ae,_owner:oe.current}}function dt(v,w){return{$$typeof:i,type:v.type,key:w,ref:v.ref,props:v.props,_owner:v._owner}}function st(v){return typeof v=="object"&&v!==null&&v.$$typeof===i}function Dt(v){var w={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(re){return w[re]})}var ot=/\/+/g;function H(v,w){return typeof v=="object"&&v!==null&&v.key!=null?Dt(""+v.key):w.toString(36)}function Me(v,w,re,ie,ae){var he=typeof v;(he==="undefined"||he==="boolean")&&(v=null);var xe=!1;if(v===null)xe=!0;else switch(he){case"string":case"number":xe=!0;break;case"object":switch(v.$$typeof){case i:case g:xe=!0}}if(xe)return xe=v,ae=ae(xe),v=ie===""?"."+H(xe,0):ie,Re(ae)?(re="",v!=null&&(re=v.replace(ot,"$&/")+"/"),Me(ae,w,re,"",function(lt){return lt})):ae!=null&&(st(ae)&&(ae=dt(ae,re+(!ae.key||xe&&xe.key===ae.key?"":(""+ae.key).replace(ot,"$&/")+"/")+v)),w.push(ae)),1;if(xe=0,ie=ie===""?".":ie+":",Re(v))for(var _e=0;_e>>1,w=M[v];if(0>>1;vE(ae,L))heE(xe,ae)?(M[v]=xe,M[he]=L,v=he):(M[v]=ae,M[ie]=L,v=ie);else if(heE(xe,L))M[v]=xe,M[he]=L,v=he;else break e}}return U}function E(M,U){var L=M.sortIndex-U.sortIndex;return L!==0?L:M.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var A=performance;i.unstable_now=function(){return A.now()}}else{var Q=Date,le=Q.now();i.unstable_now=function(){return Q.now()-le}}var te=[],z=[],Y=1,X=null,ee=3,Te=!1,ce=!1,de=!1,pe=typeof setTimeout=="function"?setTimeout:null,Qe=typeof clearTimeout=="function"?clearTimeout:null,Je=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function be(M){for(var U=f(z);U!==null;){if(U.callback===null)R(z);else if(U.startTime<=M)R(z),U.sortIndex=U.expirationTime,g(te,U);else break;U=f(z)}}function Re(M){if(de=!1,be(M),!ce)if(f(te)!==null)ce=!0,ne(F);else{var U=f(z);U!==null&&Z(Re,U.startTime-M)}}function F(M,U){ce=!1,de&&(de=!1,Qe($e),$e=-1),Te=!0;var L=ee;try{for(be(U),X=f(te);X!==null&&(!(X.expirationTime>U)||M&&!Dt());){var v=X.callback;if(typeof v=="function"){X.callback=null,ee=X.priorityLevel;var w=v(X.expirationTime<=U);U=i.unstable_now(),typeof w=="function"?X.callback=w:X===f(te)&&R(te),be(U)}else R(te);X=f(te)}if(X!==null)var re=!0;else{var ie=f(z);ie!==null&&Z(Re,ie.startTime-U),re=!1}return re}finally{X=null,ee=L,Te=!1}}var oe=!1,Ce=null,$e=-1,dt=5,st=-1;function Dt(){return!(i.unstable_now()-stM||125v?(M.sortIndex=L,g(z,M),f(te)===null&&M===f(z)&&(de?(Qe($e),$e=-1):de=!0,Z(Re,L-v))):(M.sortIndex=w,g(te,M),ce||Te||(ce=!0,ne(F))),M},i.unstable_shouldYield=Dt,i.unstable_wrapCallback=function(M){var U=ee;return function(){var L=ee;ee=U;try{return M.apply(this,arguments)}finally{ee=L}}}})(ra)),ra}var Tc;function wf(){return Tc||(Tc=1,na.exports=Sf()),na.exports}var Rc;function kf(){if(Rc)return It;Rc=1;var i=fa(),g=wf();function f(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),te=Object.prototype.hasOwnProperty,z=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Y={},X={};function ee(e){return te.call(X,e)?!0:te.call(Y,e)?!1:z.test(e)?X[e]=!0:(Y[e]=!0,!1)}function Te(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ce(e,t,n,r){if(t===null||typeof t>"u"||Te(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function de(e,t,n,r,s,o,u){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=u}var pe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){pe[e]=new de(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];pe[t]=new de(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){pe[e]=new de(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){pe[e]=new de(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){pe[e]=new de(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){pe[e]=new de(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){pe[e]=new de(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){pe[e]=new de(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){pe[e]=new de(e,5,!1,e.toLowerCase(),null,!1,!1)});var Qe=/[\-:]([a-z])/g;function Je(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Qe,Je);pe[t]=new de(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Qe,Je);pe[t]=new de(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Qe,Je);pe[t]=new de(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){pe[e]=new de(e,1,!1,e.toLowerCase(),null,!1,!1)}),pe.xlinkHref=new de("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){pe[e]=new de(e,1,!1,e.toLowerCase(),null,!0,!0)});function be(e,t,n,r){var s=pe.hasOwnProperty(t)?pe[t]:null;(s!==null?s.type!==0:r||!(2{for(const L of E)if(L.type==="childList")for(const Q of L.addedNodes)Q.tagName==="LINK"&&Q.rel==="modulepreload"&&R(Q)}).observe(document,{childList:!0,subtree:!0});function f(E){const L={};return E.integrity&&(L.integrity=E.integrity),E.referrerPolicy&&(L.referrerPolicy=E.referrerPolicy),E.crossOrigin==="use-credentials"?L.credentials="include":E.crossOrigin==="anonymous"?L.credentials="omit":L.credentials="same-origin",L}function R(E){if(E.ep)return;E.ep=!0;const L=f(E);fetch(E.href,L)}})();function Kc(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Zi={exports:{}},vo={},ea={exports:{}},fe={};var jc;function xf(){if(jc)return fe;jc=1;var i=Symbol.for("react.element"),h=Symbol.for("react.portal"),f=Symbol.for("react.fragment"),R=Symbol.for("react.strict_mode"),E=Symbol.for("react.profiler"),L=Symbol.for("react.provider"),Q=Symbol.for("react.context"),le=Symbol.for("react.forward_ref"),te=Symbol.for("react.suspense"),z=Symbol.for("react.memo"),Y=Symbol.for("react.lazy"),X=Symbol.iterator;function ee(v){return v===null||typeof v!="object"?null:(v=X&&v[X]||v["@@iterator"],typeof v=="function"?v:null)}var Te={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},ce=Object.assign,de={};function pe(v,w,re){this.props=v,this.context=w,this.refs=de,this.updater=re||Te}pe.prototype.isReactComponent={},pe.prototype.setState=function(v,w){if(typeof v!="object"&&typeof v!="function"&&v!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,v,w,"setState")},pe.prototype.forceUpdate=function(v){this.updater.enqueueForceUpdate(this,v,"forceUpdate")};function Qe(){}Qe.prototype=pe.prototype;function Je(v,w,re){this.props=v,this.context=w,this.refs=de,this.updater=re||Te}var be=Je.prototype=new Qe;be.constructor=Je,ce(be,pe.prototype),be.isPureReactComponent=!0;var Re=Array.isArray,F=Object.prototype.hasOwnProperty,oe={current:null},Ce={key:!0,ref:!0,__self:!0,__source:!0};function $e(v,w,re){var ie,ae={},he=null,xe=null;if(w!=null)for(ie in w.ref!==void 0&&(xe=w.ref),w.key!==void 0&&(he=""+w.key),w)F.call(w,ie)&&!Ce.hasOwnProperty(ie)&&(ae[ie]=w[ie]);var _e=arguments.length-2;if(_e===1)ae.children=re;else if(1<_e){for(var we=Array(_e),lt=0;lt<_e;lt++)we[lt]=arguments[lt+2];ae.children=we}if(v&&v.defaultProps)for(ie in _e=v.defaultProps,_e)ae[ie]===void 0&&(ae[ie]=_e[ie]);return{$$typeof:i,type:v,key:he,ref:xe,props:ae,_owner:oe.current}}function dt(v,w){return{$$typeof:i,type:v.type,key:w,ref:v.ref,props:v.props,_owner:v._owner}}function st(v){return typeof v=="object"&&v!==null&&v.$$typeof===i}function Dt(v){var w={"=":"=0",":":"=2"};return"$"+v.replace(/[=:]/g,function(re){return w[re]})}var ot=/\/+/g;function H(v,w){return typeof v=="object"&&v!==null&&v.key!=null?Dt(""+v.key):w.toString(36)}function Me(v,w,re,ie,ae){var he=typeof v;(he==="undefined"||he==="boolean")&&(v=null);var xe=!1;if(v===null)xe=!0;else switch(he){case"string":case"number":xe=!0;break;case"object":switch(v.$$typeof){case i:case h:xe=!0}}if(xe)return xe=v,ae=ae(xe),v=ie===""?"."+H(xe,0):ie,Re(ae)?(re="",v!=null&&(re=v.replace(ot,"$&/")+"/"),Me(ae,w,re,"",function(lt){return lt})):ae!=null&&(st(ae)&&(ae=dt(ae,re+(!ae.key||xe&&xe.key===ae.key?"":(""+ae.key).replace(ot,"$&/")+"/")+v)),w.push(ae)),1;if(xe=0,ie=ie===""?".":ie+":",Re(v))for(var _e=0;_e>>1,w=M[v];if(0>>1;vE(ae,A))heE(xe,ae)?(M[v]=xe,M[he]=A,v=he):(M[v]=ae,M[ie]=A,v=ie);else if(heE(xe,A))M[v]=xe,M[he]=A,v=he;else break e}}return U}function E(M,U){var A=M.sortIndex-U.sortIndex;return A!==0?A:M.id-U.id}if(typeof performance=="object"&&typeof performance.now=="function"){var L=performance;i.unstable_now=function(){return L.now()}}else{var Q=Date,le=Q.now();i.unstable_now=function(){return Q.now()-le}}var te=[],z=[],Y=1,X=null,ee=3,Te=!1,ce=!1,de=!1,pe=typeof setTimeout=="function"?setTimeout:null,Qe=typeof clearTimeout=="function"?clearTimeout:null,Je=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function be(M){for(var U=f(z);U!==null;){if(U.callback===null)R(z);else if(U.startTime<=M)R(z),U.sortIndex=U.expirationTime,h(te,U);else break;U=f(z)}}function Re(M){if(de=!1,be(M),!ce)if(f(te)!==null)ce=!0,ne(F);else{var U=f(z);U!==null&&Z(Re,U.startTime-M)}}function F(M,U){ce=!1,de&&(de=!1,Qe($e),$e=-1),Te=!0;var A=ee;try{for(be(U),X=f(te);X!==null&&(!(X.expirationTime>U)||M&&!Dt());){var v=X.callback;if(typeof v=="function"){X.callback=null,ee=X.priorityLevel;var w=v(X.expirationTime<=U);U=i.unstable_now(),typeof w=="function"?X.callback=w:X===f(te)&&R(te),be(U)}else R(te);X=f(te)}if(X!==null)var re=!0;else{var ie=f(z);ie!==null&&Z(Re,ie.startTime-U),re=!1}return re}finally{X=null,ee=A,Te=!1}}var oe=!1,Ce=null,$e=-1,dt=5,st=-1;function Dt(){return!(i.unstable_now()-stM||125v?(M.sortIndex=A,h(z,M),f(te)===null&&M===f(z)&&(de?(Qe($e),$e=-1):de=!0,Z(Re,A-v))):(M.sortIndex=w,h(te,M),ce||Te||(ce=!0,ne(F))),M},i.unstable_shouldYield=Dt,i.unstable_wrapCallback=function(M){var U=ee;return function(){var A=ee;ee=U;try{return M.apply(this,arguments)}finally{ee=A}}}})(ra)),ra}var Tc;function jf(){return Tc||(Tc=1,na.exports=kf()),na.exports}var Rc;function Cf(){if(Rc)return It;Rc=1;var i=fa(),h=jf();function f(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),te=Object.prototype.hasOwnProperty,z=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Y={},X={};function ee(e){return te.call(X,e)?!0:te.call(Y,e)?!1:z.test(e)?X[e]=!0:(Y[e]=!0,!1)}function Te(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ce(e,t,n,r){if(t===null||typeof t>"u"||Te(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function de(e,t,n,r,s,o,u){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=o,this.removeEmptyString=u}var pe={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){pe[e]=new de(e,0,!1,e,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];pe[t]=new de(t,1,!1,e[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(e){pe[e]=new de(e,2,!1,e.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){pe[e]=new de(e,2,!1,e,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){pe[e]=new de(e,3,!1,e.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(e){pe[e]=new de(e,3,!0,e,null,!1,!1)}),["capture","download"].forEach(function(e){pe[e]=new de(e,4,!1,e,null,!1,!1)}),["cols","rows","size","span"].forEach(function(e){pe[e]=new de(e,6,!1,e,null,!1,!1)}),["rowSpan","start"].forEach(function(e){pe[e]=new de(e,5,!1,e.toLowerCase(),null,!1,!1)});var Qe=/[\-:]([a-z])/g;function Je(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(Qe,Je);pe[t]=new de(t,1,!1,e,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(Qe,Je);pe[t]=new de(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(Qe,Je);pe[t]=new de(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(e){pe[e]=new de(e,1,!1,e.toLowerCase(),null,!1,!1)}),pe.xlinkHref=new de("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(e){pe[e]=new de(e,1,!1,e.toLowerCase(),null,!0,!0)});function be(e,t,n,r){var s=pe.hasOwnProperty(t)?pe[t]:null;(s!==null?s.type!==0:r||!(2d||s[u]!==o[d]){var m=` -`+s[u].replace(" at new "," at ");return e.displayName&&m.includes("")&&(m=m.replace("",e.displayName)),m}while(1<=u&&0<=d);break}}}finally{re=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?w(e):""}function ae(e){switch(e.tag){case 5:return w(e.type);case 16:return w("Lazy");case 13:return w("Suspense");case 19:return w("SuspenseList");case 0:case 2:case 15:return e=ie(e.type,!1),e;case 11:return e=ie(e.type.render,!1),e;case 1:return e=ie(e.type,!0),e;default:return""}}function he(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ce:return"Fragment";case oe:return"Portal";case dt:return"Profiler";case $e:return"StrictMode";case H:return"Suspense";case Me:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Dt:return(e.displayName||"Context")+".Consumer";case st:return(e._context.displayName||"Context")+".Provider";case ot:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case We:return t=e.displayName||null,t!==null?t:he(e.type)||"Memo";case ne:t=e._payload,e=e._init;try{return he(e(t))}catch{}}return null}function xe(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return he(t);case 8:return t===$e?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function _e(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function we(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function lt(e){var t=we(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(u){r=""+u,o.call(this,u)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(u){r=""+u},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function qt(e){e._valueTracker||(e._valueTracker=lt(e))}function Xn(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=we(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function wn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function nn(e,t){var n=t.checked;return L({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Ee(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=_e(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ot(e,t){t=t.checked,t!=null&&be(e,"checked",t,!1)}function et(e,t){Ot(e,t);var n=_e(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?St(e,t.type,n):t.hasOwnProperty("defaultValue")&&St(e,t.type,_e(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ft(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function St(e,t,n){(t!=="number"||wn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var rn=Array.isArray;function W(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=zt.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function sn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var on={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Zr=["Webkit","ms","Moz","O"];Object.keys(on).forEach(function(e){Zr.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),on[t]=on[e]})});function Nr(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||on.hasOwnProperty(e)&&on[e]?(""+t).trim():t+"px"}function Er(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=Nr(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var es=L({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ln(e,t){if(t){if(es[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(f(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(f(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(f(61))}if(t.style!=null&&typeof t.style!="object")throw Error(f(62))}}function an(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var un=null;function cn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var On=null,me=null,dn=null;function er(e){if(e=to(e)){if(typeof On!="function")throw Error(f(280));var t=e.stateNode;t&&(t=Do(t),On(e.stateNode,e.type,t))}}function Pr(e){me?dn?dn.push(e):dn=[e]:me=e}function Tr(){if(me){var e=me,t=dn;if(dn=me=null,er(e),t)for(e=0;e>>=0,e===0?32:31-(Fn(e)/$t|0)|0}var Et=64,Un=4194304;function Bn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Hn(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,u=n&268435455;if(u!==0){var d=u&~s;d!==0?r=Bn(d):(o&=u,o!==0&&(r=Bn(o)))}else u=n&~s,u!==0?r=Bn(u):o!==0&&(r=Bn(o));if(r===0)return 0;if(t!==0&&t!==r&&(t&s)===0&&(s=r&-r,o=t&-t,s>=o||s===16&&(o&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ne(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ue(t),e[t]=n}function So(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Ws),va=" ",ya=!1;function xa(e,t){switch(e){case"keyup":return dd.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _a(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ds=!1;function md(e,t){switch(e){case"compositionend":return _a(t);case"keypress":return t.which!==32?null:(ya=!0,va);case"textInput":return e=t.data,e===va&&ya?null:e;default:return null}}function pd(e,t){if(ds)return e==="compositionend"||!Al&&xa(e,t)?(e=Co(),ls=ar=Tn=null,ds=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ea(n)}}function Ta(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ta(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ra(){for(var e=window,t=wn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=wn(e.document)}return t}function Ol(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function kd(e){var t=Ra(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ta(n.ownerDocument.documentElement,n)){if(r!==null&&Ol(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=Pa(n,o);var u=Pa(n,r);s&&u&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(u.node,u.offset)):(t.setEnd(u.node,u.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,fs=null,zl=null,Js=null,$l=!1;function Ma(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;$l||fs==null||fs!==wn(r)||(r=fs,"selectionStart"in r&&Ol(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Js&&Gs(Js,r)||(Js=r,r=Lo(zl,"onSelect"),0vs||(e.current=Jl[vs],Jl[vs]=null,vs--)}function Le(e,t){vs++,Jl[vs]=e.current,e.current=t}var hr={},gt=pr(hr),Tt=pr(!1),Hr=hr;function ys(e,t){var n=e.type.contextTypes;if(!n)return hr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in n)s[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Rt(e){return e=e.childContextTypes,e!=null}function Oo(){De(Tt),De(gt)}function Wa(e,t,n){if(gt.current!==hr)throw Error(f(168));Le(gt,t),Le(Tt,n)}function qa(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(f(108,xe(e)||"Unknown",s));return L({},n,r)}function zo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||hr,Hr=gt.current,Le(gt,e),Le(Tt,Tt.current),!0}function Ka(e,t,n){var r=e.stateNode;if(!r)throw Error(f(169));n?(e=qa(e,t,Hr),r.__reactInternalMemoizedMergedChildContext=e,De(Tt),De(gt),Le(gt,e)):De(Tt),Le(Tt,n)}var Vn=null,$o=!1,Yl=!1;function Ga(e){Vn===null?Vn=[e]:Vn.push(e)}function Dd(e){$o=!0,Ga(e)}function gr(){if(!Yl&&Vn!==null){Yl=!0;var e=0,t=ve;try{var n=Vn;for(ve=1;e>=u,s-=u,Wn=1<<32-Ue(t)+s|n<se?(rt=G,G=null):rt=G.sibling;var je=C(x,G,_[se],T);if(je===null){G===null&&(G=rt);break}e&&G&&je.alternate===null&&t(x,G),h=o(je,h,se),K===null?V=je:K.sibling=je,K=je,G=rt}if(se===_.length)return n(x,G),ze&&br(x,se),V;if(G===null){for(;se<_.length;se++)G=P(x,_[se],T),G!==null&&(h=o(G,h,se),K===null?V=G:K.sibling=G,K=G);return ze&&br(x,se),V}for(G=r(x,G);se<_.length;se++)rt=I(G,x,se,_[se],T),rt!==null&&(e&&rt.alternate!==null&&G.delete(rt.key===null?se:rt.key),h=o(rt,h,se),K===null?V=rt:K.sibling=rt,K=rt);return e&&G.forEach(function(Cr){return t(x,Cr)}),ze&&br(x,se),V}function b(x,h,_,T){var V=U(_);if(typeof V!="function")throw Error(f(150));if(_=V.call(_),_==null)throw Error(f(151));for(var K=V=null,G=h,se=h=0,rt=null,je=_.next();G!==null&&!je.done;se++,je=_.next()){G.index>se?(rt=G,G=null):rt=G.sibling;var Cr=C(x,G,je.value,T);if(Cr===null){G===null&&(G=rt);break}e&&G&&Cr.alternate===null&&t(x,G),h=o(Cr,h,se),K===null?V=Cr:K.sibling=Cr,K=Cr,G=rt}if(je.done)return n(x,G),ze&&br(x,se),V;if(G===null){for(;!je.done;se++,je=_.next())je=P(x,je.value,T),je!==null&&(h=o(je,h,se),K===null?V=je:K.sibling=je,K=je);return ze&&br(x,se),V}for(G=r(x,G);!je.done;se++,je=_.next())je=I(G,x,se,je.value,T),je!==null&&(e&&je.alternate!==null&&G.delete(je.key===null?se:je.key),h=o(je,h,se),K===null?V=je:K.sibling=je,K=je);return e&&G.forEach(function(gf){return t(x,gf)}),ze&&br(x,se),V}function Ge(x,h,_,T){if(typeof _=="object"&&_!==null&&_.type===Ce&&_.key===null&&(_=_.props.children),typeof _=="object"&&_!==null){switch(_.$$typeof){case F:e:{for(var V=_.key,K=h;K!==null;){if(K.key===V){if(V=_.type,V===Ce){if(K.tag===7){n(x,K.sibling),h=s(K,_.props.children),h.return=x,x=h;break e}}else if(K.elementType===V||typeof V=="object"&&V!==null&&V.$$typeof===ne&&tu(V)===K.type){n(x,K.sibling),h=s(K,_.props),h.ref=no(x,K,_),h.return=x,x=h;break e}n(x,K);break}else t(x,K);K=K.sibling}_.type===Ce?(h=Xr(_.props.children,x.mode,T,_.key),h.return=x,x=h):(T=fl(_.type,_.key,_.props,null,x.mode,T),T.ref=no(x,h,_),T.return=x,x=T)}return u(x);case oe:e:{for(K=_.key;h!==null;){if(h.key===K)if(h.tag===4&&h.stateNode.containerInfo===_.containerInfo&&h.stateNode.implementation===_.implementation){n(x,h.sibling),h=s(h,_.children||[]),h.return=x,x=h;break e}else{n(x,h);break}else t(x,h);h=h.sibling}h=Ki(_,x.mode,T),h.return=x,x=h}return u(x);case ne:return K=_._init,Ge(x,h,K(_._payload),T)}if(rn(_))return B(x,h,_,T);if(U(_))return b(x,h,_,T);Ho(x,_)}return typeof _=="string"&&_!==""||typeof _=="number"?(_=""+_,h!==null&&h.tag===6?(n(x,h.sibling),h=s(h,_),h.return=x,x=h):(n(x,h),h=qi(_,x.mode,T),h.return=x,x=h),u(x)):n(x,h)}return Ge}var ws=nu(!0),ru=nu(!1),Qo=pr(null),bo=null,ks=null,ri=null;function si(){ri=ks=bo=null}function oi(e){var t=Qo.current;De(Qo),e._currentValue=t}function li(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function js(e,t){bo=e,ri=ks=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Mt=!0),e.firstContext=null)}function Yt(e){var t=e._currentValue;if(ri!==e)if(e={context:e,memoizedValue:t,next:null},ks===null){if(bo===null)throw Error(f(308));ks=e,bo.dependencies={lanes:0,firstContext:e}}else ks=ks.next=e;return t}var Vr=null;function ii(e){Vr===null?Vr=[e]:Vr.push(e)}function su(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ii(t)):(n.next=s.next,s.next=n),t.interleaved=n,Kn(e,r)}function Kn(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var vr=!1;function ai(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ou(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Gn(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function yr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(Se&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Kn(e,n)}return s=r.interleaved,s===null?(t.next=t,ii(r)):(t.next=s.next,s.next=t),r.interleaved=t,Kn(e,n)}function Vo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,zs(e,n)}}function lu(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var u={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?s=o=u:o=o.next=u,n=n.next}while(n!==null);o===null?s=o=t:o=o.next=t}else s=o=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Wo(e,t,n,r){var s=e.updateQueue;vr=!1;var o=s.firstBaseUpdate,u=s.lastBaseUpdate,d=s.shared.pending;if(d!==null){s.shared.pending=null;var m=d,S=m.next;m.next=null,u===null?o=S:u.next=S,u=m;var N=e.alternate;N!==null&&(N=N.updateQueue,d=N.lastBaseUpdate,d!==u&&(d===null?N.firstBaseUpdate=S:d.next=S,N.lastBaseUpdate=m))}if(o!==null){var P=s.baseState;u=0,N=S=m=null,d=o;do{var C=d.lane,I=d.eventTime;if((r&C)===C){N!==null&&(N=N.next={eventTime:I,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var B=e,b=d;switch(C=t,I=n,b.tag){case 1:if(B=b.payload,typeof B=="function"){P=B.call(I,P,C);break e}P=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=b.payload,C=typeof B=="function"?B.call(I,P,C):B,C==null)break e;P=L({},P,C);break e;case 2:vr=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,C=s.effects,C===null?s.effects=[d]:C.push(d))}else I={eventTime:I,lane:C,tag:d.tag,payload:d.payload,callback:d.callback,next:null},N===null?(S=N=I,m=P):N=N.next=I,u|=C;if(d=d.next,d===null){if(d=s.shared.pending,d===null)break;C=d,d=C.next,C.next=null,s.lastBaseUpdate=C,s.shared.pending=null}}while(!0);if(N===null&&(m=P),s.baseState=m,s.firstBaseUpdate=S,s.lastBaseUpdate=N,t=s.shared.interleaved,t!==null){s=t;do u|=s.lane,s=s.next;while(s!==t)}else o===null&&(s.shared.lanes=0);Kr|=u,e.lanes=u,e.memoizedState=P}}function iu(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=mi.transition;mi.transition={};try{e(!1),t()}finally{ve=n,mi.transition=r}}function Nu(){return Xt().memoizedState}function Fd(e,t,n){var r=wr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Eu(e))Pu(t,n);else if(n=su(e,t,n,r),n!==null){var s=Nt();Sn(n,e,r,s),Tu(n,t,r)}}function Ud(e,t,n){var r=wr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Eu(e))Pu(t,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var u=t.lastRenderedState,d=o(u,n);if(s.hasEagerState=!0,s.eagerState=d,gn(d,u)){var m=t.interleaved;m===null?(s.next=s,ii(t)):(s.next=m.next,m.next=s),t.interleaved=s;return}}catch{}n=su(e,t,s,r),n!==null&&(s=Nt(),Sn(n,e,r,s),Tu(n,t,r))}}function Eu(e){var t=e.alternate;return e===He||t!==null&&t===He}function Pu(e,t){lo=Go=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tu(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,zs(e,n)}}var Xo={readContext:Yt,useCallback:vt,useContext:vt,useEffect:vt,useImperativeHandle:vt,useInsertionEffect:vt,useLayoutEffect:vt,useMemo:vt,useReducer:vt,useRef:vt,useState:vt,useDebugValue:vt,useDeferredValue:vt,useTransition:vt,useMutableSource:vt,useSyncExternalStore:vt,useId:vt,unstable_isNewReconciler:!1},Bd={readContext:Yt,useCallback:function(e,t){return Ln().memoizedState=[e,t===void 0?null:t],e},useContext:Yt,useEffect:yu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Jo(4194308,4,Su.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Jo(4194308,4,e,t)},useInsertionEffect:function(e,t){return Jo(4,2,e,t)},useMemo:function(e,t){var n=Ln();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Ln();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Fd.bind(null,He,e),[r.memoizedState,e]},useRef:function(e){var t=Ln();return e={current:e},t.memoizedState=e},useState:gu,useDebugValue:_i,useDeferredValue:function(e){return Ln().memoizedState=e},useTransition:function(){var e=gu(!1),t=e[0];return e=$d.bind(null,e[1]),Ln().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=He,s=Ln();if(ze){if(n===void 0)throw Error(f(407));n=n()}else{if(n=t(),nt===null)throw Error(f(349));(qr&30)!==0||du(r,t,n)}s.memoizedState=n;var o={value:n,getSnapshot:t};return s.queue=o,yu(mu.bind(null,r,o,e),[e]),r.flags|=2048,uo(9,fu.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=Ln(),t=nt.identifierPrefix;if(ze){var n=qn,r=Wn;n=(r&~(1<<32-Ue(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=io++,0")&&(m=m.replace("",e.displayName)),m}while(1<=u&&0<=d);break}}}finally{re=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?w(e):""}function ae(e){switch(e.tag){case 5:return w(e.type);case 16:return w("Lazy");case 13:return w("Suspense");case 19:return w("SuspenseList");case 0:case 2:case 15:return e=ie(e.type,!1),e;case 11:return e=ie(e.type.render,!1),e;case 1:return e=ie(e.type,!0),e;default:return""}}function he(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Ce:return"Fragment";case oe:return"Portal";case dt:return"Profiler";case $e:return"StrictMode";case H:return"Suspense";case Me:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Dt:return(e.displayName||"Context")+".Consumer";case st:return(e._context.displayName||"Context")+".Provider";case ot:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case We:return t=e.displayName||null,t!==null?t:he(e.type)||"Memo";case ne:t=e._payload,e=e._init;try{return he(e(t))}catch{}}return null}function xe(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return he(t);case 8:return t===$e?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function _e(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function we(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function lt(e){var t=we(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,o=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(u){r=""+u,o.call(this,u)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(u){r=""+u},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function qt(e){e._valueTracker||(e._valueTracker=lt(e))}function Xn(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=we(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function wn(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function nn(e,t){var n=t.checked;return A({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Ee(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=_e(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ot(e,t){t=t.checked,t!=null&&be(e,"checked",t,!1)}function et(e,t){Ot(e,t);var n=_e(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?St(e,t.type,n):t.hasOwnProperty("defaultValue")&&St(e,t.type,_e(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function ft(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function St(e,t,n){(t!=="number"||wn(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var rn=Array.isArray;function W(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=zt.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function sn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var on={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Zr=["Webkit","ms","Moz","O"];Object.keys(on).forEach(function(e){Zr.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),on[t]=on[e]})});function Nr(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||on.hasOwnProperty(e)&&on[e]?(""+t).trim():t+"px"}function Er(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=Nr(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var es=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ln(e,t){if(t){if(es[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(f(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(f(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(f(61))}if(t.style!=null&&typeof t.style!="object")throw Error(f(62))}}function an(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var un=null;function cn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var On=null,me=null,dn=null;function er(e){if(e=to(e)){if(typeof On!="function")throw Error(f(280));var t=e.stateNode;t&&(t=Do(t),On(e.stateNode,e.type,t))}}function Pr(e){me?dn?dn.push(e):dn=[e]:me=e}function Tr(){if(me){var e=me,t=dn;if(dn=me=null,er(e),t)for(e=0;e>>=0,e===0?32:31-(Fn(e)/$t|0)|0}var Et=64,Un=4194304;function Bn(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Hn(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,o=e.pingedLanes,u=n&268435455;if(u!==0){var d=u&~s;d!==0?r=Bn(d):(o&=u,o!==0&&(r=Bn(o)))}else u=n&~s,u!==0?r=Bn(u):o!==0&&(r=Bn(o));if(r===0)return 0;if(t!==0&&t!==r&&(t&s)===0&&(s=r&-r,o=t&-t,s>=o||s===16&&(o&4194240)!==0))return t;if((r&4)!==0&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ne(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-Ue(t),e[t]=n}function So(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Ws),va=" ",ya=!1;function xa(e,t){switch(e){case"keyup":return md.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _a(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var ds=!1;function hd(e,t){switch(e){case"compositionend":return _a(t);case"keypress":return t.which!==32?null:(ya=!0,va);case"textInput":return e=t.data,e===va&&ya?null:e;default:return null}}function gd(e,t){if(ds)return e==="compositionend"||!Ll&&xa(e,t)?(e=Co(),ls=ar=Tn=null,ds=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Ea(n)}}function Ta(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ta(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Ra(){for(var e=window,t=wn();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=wn(e.document)}return t}function Ol(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Cd(e){var t=Ra(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Ta(n.ownerDocument.documentElement,n)){if(r!==null&&Ol(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,o=Math.min(r.start,s);r=r.end===void 0?o:Math.min(r.end,s),!e.extend&&o>r&&(s=r,r=o,o=s),s=Pa(n,o);var u=Pa(n,r);s&&u&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==u.node||e.focusOffset!==u.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),o>r?(e.addRange(t),e.extend(u.node,u.offset)):(t.setEnd(u.node,u.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,fs=null,zl=null,Js=null,$l=!1;function Ma(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;$l||fs==null||fs!==wn(r)||(r=fs,"selectionStart"in r&&Ol(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Js&&Gs(Js,r)||(Js=r,r=Ao(zl,"onSelect"),0vs||(e.current=Jl[vs],Jl[vs]=null,vs--)}function Ae(e,t){vs++,Jl[vs]=e.current,e.current=t}var hr={},gt=pr(hr),Tt=pr(!1),Hr=hr;function ys(e,t){var n=e.type.contextTypes;if(!n)return hr;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},o;for(o in n)s[o]=t[o];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Rt(e){return e=e.childContextTypes,e!=null}function Oo(){De(Tt),De(gt)}function Wa(e,t,n){if(gt.current!==hr)throw Error(f(168));Ae(gt,t),Ae(Tt,n)}function qa(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(f(108,xe(e)||"Unknown",s));return A({},n,r)}function zo(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||hr,Hr=gt.current,Ae(gt,e),Ae(Tt,Tt.current),!0}function Ka(e,t,n){var r=e.stateNode;if(!r)throw Error(f(169));n?(e=qa(e,t,Hr),r.__reactInternalMemoizedMergedChildContext=e,De(Tt),De(gt),Ae(gt,e)):De(Tt),Ae(Tt,n)}var Vn=null,$o=!1,Yl=!1;function Ga(e){Vn===null?Vn=[e]:Vn.push(e)}function zd(e){$o=!0,Ga(e)}function gr(){if(!Yl&&Vn!==null){Yl=!0;var e=0,t=ve;try{var n=Vn;for(ve=1;e>=u,s-=u,Wn=1<<32-Ue(t)+s|n<se?(rt=G,G=null):rt=G.sibling;var je=C(x,G,_[se],T);if(je===null){G===null&&(G=rt);break}e&&G&&je.alternate===null&&t(x,G),g=o(je,g,se),K===null?V=je:K.sibling=je,K=je,G=rt}if(se===_.length)return n(x,G),ze&&br(x,se),V;if(G===null){for(;se<_.length;se++)G=P(x,_[se],T),G!==null&&(g=o(G,g,se),K===null?V=G:K.sibling=G,K=G);return ze&&br(x,se),V}for(G=r(x,G);se<_.length;se++)rt=I(G,x,se,_[se],T),rt!==null&&(e&&rt.alternate!==null&&G.delete(rt.key===null?se:rt.key),g=o(rt,g,se),K===null?V=rt:K.sibling=rt,K=rt);return e&&G.forEach(function(Cr){return t(x,Cr)}),ze&&br(x,se),V}function b(x,g,_,T){var V=U(_);if(typeof V!="function")throw Error(f(150));if(_=V.call(_),_==null)throw Error(f(151));for(var K=V=null,G=g,se=g=0,rt=null,je=_.next();G!==null&&!je.done;se++,je=_.next()){G.index>se?(rt=G,G=null):rt=G.sibling;var Cr=C(x,G,je.value,T);if(Cr===null){G===null&&(G=rt);break}e&&G&&Cr.alternate===null&&t(x,G),g=o(Cr,g,se),K===null?V=Cr:K.sibling=Cr,K=Cr,G=rt}if(je.done)return n(x,G),ze&&br(x,se),V;if(G===null){for(;!je.done;se++,je=_.next())je=P(x,je.value,T),je!==null&&(g=o(je,g,se),K===null?V=je:K.sibling=je,K=je);return ze&&br(x,se),V}for(G=r(x,G);!je.done;se++,je=_.next())je=I(G,x,se,je.value,T),je!==null&&(e&&je.alternate!==null&&G.delete(je.key===null?se:je.key),g=o(je,g,se),K===null?V=je:K.sibling=je,K=je);return e&&G.forEach(function(yf){return t(x,yf)}),ze&&br(x,se),V}function Ge(x,g,_,T){if(typeof _=="object"&&_!==null&&_.type===Ce&&_.key===null&&(_=_.props.children),typeof _=="object"&&_!==null){switch(_.$$typeof){case F:e:{for(var V=_.key,K=g;K!==null;){if(K.key===V){if(V=_.type,V===Ce){if(K.tag===7){n(x,K.sibling),g=s(K,_.props.children),g.return=x,x=g;break e}}else if(K.elementType===V||typeof V=="object"&&V!==null&&V.$$typeof===ne&&tu(V)===K.type){n(x,K.sibling),g=s(K,_.props),g.ref=no(x,K,_),g.return=x,x=g;break e}n(x,K);break}else t(x,K);K=K.sibling}_.type===Ce?(g=Xr(_.props.children,x.mode,T,_.key),g.return=x,x=g):(T=fl(_.type,_.key,_.props,null,x.mode,T),T.ref=no(x,g,_),T.return=x,x=T)}return u(x);case oe:e:{for(K=_.key;g!==null;){if(g.key===K)if(g.tag===4&&g.stateNode.containerInfo===_.containerInfo&&g.stateNode.implementation===_.implementation){n(x,g.sibling),g=s(g,_.children||[]),g.return=x,x=g;break e}else{n(x,g);break}else t(x,g);g=g.sibling}g=Ki(_,x.mode,T),g.return=x,x=g}return u(x);case ne:return K=_._init,Ge(x,g,K(_._payload),T)}if(rn(_))return B(x,g,_,T);if(U(_))return b(x,g,_,T);Ho(x,_)}return typeof _=="string"&&_!==""||typeof _=="number"?(_=""+_,g!==null&&g.tag===6?(n(x,g.sibling),g=s(g,_),g.return=x,x=g):(n(x,g),g=qi(_,x.mode,T),g.return=x,x=g),u(x)):n(x,g)}return Ge}var ws=nu(!0),ru=nu(!1),Qo=pr(null),bo=null,ks=null,ri=null;function si(){ri=ks=bo=null}function oi(e){var t=Qo.current;De(Qo),e._currentValue=t}function li(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function js(e,t){bo=e,ri=ks=null,e=e.dependencies,e!==null&&e.firstContext!==null&&((e.lanes&t)!==0&&(Mt=!0),e.firstContext=null)}function Yt(e){var t=e._currentValue;if(ri!==e)if(e={context:e,memoizedValue:t,next:null},ks===null){if(bo===null)throw Error(f(308));ks=e,bo.dependencies={lanes:0,firstContext:e}}else ks=ks.next=e;return t}var Vr=null;function ii(e){Vr===null?Vr=[e]:Vr.push(e)}function su(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,ii(t)):(n.next=s.next,s.next=n),t.interleaved=n,Kn(e,r)}function Kn(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var vr=!1;function ai(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ou(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Gn(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function yr(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,(Se&2)!==0){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Kn(e,n)}return s=r.interleaved,s===null?(t.next=t,ii(r)):(t.next=s.next,s.next=t),r.interleaved=t,Kn(e,n)}function Vo(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,zs(e,n)}}function lu(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,o=null;if(n=n.firstBaseUpdate,n!==null){do{var u={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};o===null?s=o=u:o=o.next=u,n=n.next}while(n!==null);o===null?s=o=t:o=o.next=t}else s=o=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:o,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Wo(e,t,n,r){var s=e.updateQueue;vr=!1;var o=s.firstBaseUpdate,u=s.lastBaseUpdate,d=s.shared.pending;if(d!==null){s.shared.pending=null;var m=d,S=m.next;m.next=null,u===null?o=S:u.next=S,u=m;var N=e.alternate;N!==null&&(N=N.updateQueue,d=N.lastBaseUpdate,d!==u&&(d===null?N.firstBaseUpdate=S:d.next=S,N.lastBaseUpdate=m))}if(o!==null){var P=s.baseState;u=0,N=S=m=null,d=o;do{var C=d.lane,I=d.eventTime;if((r&C)===C){N!==null&&(N=N.next={eventTime:I,lane:0,tag:d.tag,payload:d.payload,callback:d.callback,next:null});e:{var B=e,b=d;switch(C=t,I=n,b.tag){case 1:if(B=b.payload,typeof B=="function"){P=B.call(I,P,C);break e}P=B;break e;case 3:B.flags=B.flags&-65537|128;case 0:if(B=b.payload,C=typeof B=="function"?B.call(I,P,C):B,C==null)break e;P=A({},P,C);break e;case 2:vr=!0}}d.callback!==null&&d.lane!==0&&(e.flags|=64,C=s.effects,C===null?s.effects=[d]:C.push(d))}else I={eventTime:I,lane:C,tag:d.tag,payload:d.payload,callback:d.callback,next:null},N===null?(S=N=I,m=P):N=N.next=I,u|=C;if(d=d.next,d===null){if(d=s.shared.pending,d===null)break;C=d,d=C.next,C.next=null,s.lastBaseUpdate=C,s.shared.pending=null}}while(!0);if(N===null&&(m=P),s.baseState=m,s.firstBaseUpdate=S,s.lastBaseUpdate=N,t=s.shared.interleaved,t!==null){s=t;do u|=s.lane,s=s.next;while(s!==t)}else o===null&&(s.shared.lanes=0);Kr|=u,e.lanes=u,e.memoizedState=P}}function iu(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=mi.transition;mi.transition={};try{e(!1),t()}finally{ve=n,mi.transition=r}}function Nu(){return Xt().memoizedState}function Bd(e,t,n){var r=wr(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Eu(e))Pu(t,n);else if(n=su(e,t,n,r),n!==null){var s=Nt();Sn(n,e,r,s),Tu(n,t,r)}}function Hd(e,t,n){var r=wr(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Eu(e))Pu(t,s);else{var o=e.alternate;if(e.lanes===0&&(o===null||o.lanes===0)&&(o=t.lastRenderedReducer,o!==null))try{var u=t.lastRenderedState,d=o(u,n);if(s.hasEagerState=!0,s.eagerState=d,gn(d,u)){var m=t.interleaved;m===null?(s.next=s,ii(t)):(s.next=m.next,m.next=s),t.interleaved=s;return}}catch{}n=su(e,t,s,r),n!==null&&(s=Nt(),Sn(n,e,r,s),Tu(n,t,r))}}function Eu(e){var t=e.alternate;return e===He||t!==null&&t===He}function Pu(e,t){lo=Go=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Tu(e,t,n){if((n&4194240)!==0){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,zs(e,n)}}var Xo={readContext:Yt,useCallback:vt,useContext:vt,useEffect:vt,useImperativeHandle:vt,useInsertionEffect:vt,useLayoutEffect:vt,useMemo:vt,useReducer:vt,useRef:vt,useState:vt,useDebugValue:vt,useDeferredValue:vt,useTransition:vt,useMutableSource:vt,useSyncExternalStore:vt,useId:vt,unstable_isNewReconciler:!1},Qd={readContext:Yt,useCallback:function(e,t){return An().memoizedState=[e,t===void 0?null:t],e},useContext:Yt,useEffect:yu,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Jo(4194308,4,Su.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Jo(4194308,4,e,t)},useInsertionEffect:function(e,t){return Jo(4,2,e,t)},useMemo:function(e,t){var n=An();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=An();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Bd.bind(null,He,e),[r.memoizedState,e]},useRef:function(e){var t=An();return e={current:e},t.memoizedState=e},useState:gu,useDebugValue:_i,useDeferredValue:function(e){return An().memoizedState=e},useTransition:function(){var e=gu(!1),t=e[0];return e=Ud.bind(null,e[1]),An().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=He,s=An();if(ze){if(n===void 0)throw Error(f(407));n=n()}else{if(n=t(),nt===null)throw Error(f(349));(qr&30)!==0||du(r,t,n)}s.memoizedState=n;var o={value:n,getSnapshot:t};return s.queue=o,yu(mu.bind(null,r,o,e),[e]),r.flags|=2048,uo(9,fu.bind(null,r,o,n,t),void 0,null),n},useId:function(){var e=An(),t=nt.identifierPrefix;if(ze){var n=qn,r=Wn;n=(r&~(1<<32-Ue(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=io++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=u.createElement(n,{is:r.is}):(e=u.createElement(n),n==="select"&&(u=e,r.multiple?u.multiple=!0:r.size&&(u.size=r.size))):e=u.createElementNS(e,n),e[Rn]=t,e[eo]=r,Gu(e,t,!1,!1),t.stateNode=e;e:{switch(u=an(n,r),n){case"dialog":Ie("cancel",e),Ie("close",e),s=r;break;case"iframe":case"object":case"embed":Ie("load",e),s=r;break;case"video":case"audio":for(s=0;sTs&&(t.flags|=128,r=!0,co(o,!1),t.lanes=4194304)}else{if(!r)if(e=qo(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),co(o,!0),o.tail===null&&o.tailMode==="hidden"&&!u.alternate&&!ze)return yt(t),null}else 2*Fe()-o.renderingStartTime>Ts&&n!==1073741824&&(t.flags|=128,r=!0,co(o,!1),t.lanes=4194304);o.isBackwards?(u.sibling=t.child,t.child=u):(n=o.last,n!==null?n.sibling=u:t.child=u,o.last=u)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Fe(),t.sibling=null,n=Be.current,Le(Be,r?n&1|2:n&1),t):(yt(t),null);case 22:case 23:return bi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(Wt&1073741824)!==0&&(yt(t),t.subtreeFlags&6&&(t.flags|=8192)):yt(t),null;case 24:return null;case 25:return null}throw Error(f(156,t.tag))}function Gd(e,t){switch(Zl(t),t.tag){case 1:return Rt(t.type)&&Oo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Cs(),De(Tt),De(gt),fi(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return ci(t),null;case 13:if(De(Be),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(f(340));Ss()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return De(Be),null;case 4:return Cs(),null;case 10:return oi(t.type._context),null;case 22:case 23:return bi(),null;case 24:return null;default:return null}}var nl=!1,xt=!1,Jd=typeof WeakSet=="function"?WeakSet:Set,O=null;function Es(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ve(e,t,r)}else n.current=null}function Li(e,t,n){try{n()}catch(r){Ve(e,t,r)}}var Xu=!1;function Yd(e,t){if(bl=os,e=Ra(),Ol(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var u=0,d=-1,m=-1,S=0,N=0,P=e,C=null;t:for(;;){for(var I;P!==n||s!==0&&P.nodeType!==3||(d=u+s),P!==o||r!==0&&P.nodeType!==3||(m=u+r),P.nodeType===3&&(u+=P.nodeValue.length),(I=P.firstChild)!==null;)C=P,P=I;for(;;){if(P===e)break t;if(C===n&&++S===s&&(d=u),C===o&&++N===r&&(m=u),(I=P.nextSibling)!==null)break;P=C,C=P.parentNode}P=I}n=d===-1||m===-1?null:{start:d,end:m}}else n=null}n=n||{start:0,end:0}}else n=null;for(Vl={focusedElem:e,selectionRange:n},os=!1,O=t;O!==null;)if(t=O,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,O=e;else for(;O!==null;){t=O;try{var B=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(B!==null){var b=B.memoizedProps,Ge=B.memoizedState,x=t.stateNode,h=x.getSnapshotBeforeUpdate(t.elementType===t.type?b:yn(t.type,b),Ge);x.__reactInternalSnapshotBeforeUpdate=h}break;case 3:var _=t.stateNode.containerInfo;_.nodeType===1?_.textContent="":_.nodeType===9&&_.documentElement&&_.removeChild(_.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(f(163))}}catch(T){Ve(t,t.return,T)}if(e=t.sibling,e!==null){e.return=t.return,O=e;break}O=t.return}return B=Xu,Xu=!1,B}function fo(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&Li(t,n,o)}s=s.next}while(s!==r)}}function rl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ai(e){var t=e.ref;if(t!==null){var n=e.stateNode;e.tag,e=n,typeof t=="function"?t(e):t.current=e}}function Zu(e){var t=e.alternate;t!==null&&(e.alternate=null,Zu(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Rn],delete t[eo],delete t[Gl],delete t[Ad],delete t[Id])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ec(e){return e.tag===5||e.tag===3||e.tag===4}function tc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ec(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ii(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Io));else if(r!==4&&(e=e.child,e!==null))for(Ii(e,t,n),e=e.sibling;e!==null;)Ii(e,t,n),e=e.sibling}function Di(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Di(e,t,n),e=e.sibling;e!==null;)Di(e,t,n),e=e.sibling}var ut=null,xn=!1;function xr(e,t,n){for(n=n.child;n!==null;)nc(e,t,n),n=n.sibling}function nc(e,t,n){if(ue&&typeof ue.onCommitFiberUnmount=="function")try{ue.onCommitFiberUnmount(wt,n)}catch{}switch(n.tag){case 5:xt||Es(n,t);case 6:var r=ut,s=xn;ut=null,xr(e,t,n),ut=r,xn=s,ut!==null&&(xn?(e=ut,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ut.removeChild(n.stateNode));break;case 18:ut!==null&&(xn?(e=ut,n=n.stateNode,e.nodeType===8?Kl(e.parentNode,n):e.nodeType===1&&Kl(e,n),ir(e)):Kl(ut,n.stateNode));break;case 4:r=ut,s=xn,ut=n.stateNode.containerInfo,xn=!0,xr(e,t,n),ut=r,xn=s;break;case 0:case 11:case 14:case 15:if(!xt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,u=o.destroy;o=o.tag,u!==void 0&&((o&2)!==0||(o&4)!==0)&&Li(n,t,u),s=s.next}while(s!==r)}xr(e,t,n);break;case 1:if(!xt&&(Es(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(d){Ve(n,t,d)}xr(e,t,n);break;case 21:xr(e,t,n);break;case 22:n.mode&1?(xt=(r=xt)||n.memoizedState!==null,xr(e,t,n),xt=r):xr(e,t,n);break;default:xr(e,t,n)}}function rc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Jd),t.forEach(function(r){var s=lf.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function _n(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~o}if(r=s,r=Fe()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*Zd(r/1960))-r,10e?16:e,Sr===null)var r=!1;else{if(e=Sr,Sr=null,al=0,(Se&6)!==0)throw Error(f(331));var s=Se;for(Se|=4,O=e.current;O!==null;){var o=O,u=o.child;if((O.flags&16)!==0){var d=o.deletions;if(d!==null){for(var m=0;mFe()-$i?Jr(e,0):zi|=n),At(e,t)}function gc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Un,Un<<=1,(Un&130023424)===0&&(Un=4194304)));var n=Nt();e=Kn(e,t),e!==null&&(Ne(e,t,n),At(e,n))}function of(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),gc(e,n)}function lf(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(f(314))}r!==null&&r.delete(t),gc(e,n)}var vc;vc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Tt.current)Mt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Mt=!1,qd(e,t,n);Mt=(e.flags&131072)!==0}else Mt=!1,ze&&(t.flags&1048576)!==0&&Ja(t,Uo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;tl(e,t),e=t.pendingProps;var s=ys(t,gt.current);js(t,n),s=hi(null,t,r,e,s,n);var o=gi();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Rt(r)?(o=!0,zo(t)):o=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ai(t),s.updater=Zo,t.stateNode=s,s._reactInternals=t,wi(t,r,e,n),t=Ni(null,t,r,!0,o,n)):(t.tag=0,ze&&o&&Xl(t),Ct(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(tl(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=uf(r),e=yn(r,e),s){case 0:t=Ci(null,t,r,e,n);break e;case 1:t=Qu(null,t,r,e,n);break e;case 11:t=$u(null,t,r,e,n);break e;case 14:t=Fu(null,t,r,yn(r.type,e),n);break e}throw Error(f(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),Ci(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),Qu(e,t,r,s,n);case 3:e:{if(bu(t),e===null)throw Error(f(387));r=t.pendingProps,o=t.memoizedState,s=o.element,ou(e,t),Wo(t,r,null,n);var u=t.memoizedState;if(r=u.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){s=Ns(Error(f(423)),t),t=Vu(e,t,r,n,s);break e}else if(r!==s){s=Ns(Error(f(424)),t),t=Vu(e,t,r,n,s);break e}else for(Vt=mr(t.stateNode.containerInfo.firstChild),bt=t,ze=!0,vn=null,n=ru(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Ss(),r===s){t=Jn(e,t,n);break e}Ct(e,t,r,n)}t=t.child}return t;case 5:return au(t),e===null&&ti(t),r=t.type,s=t.pendingProps,o=e!==null?e.memoizedProps:null,u=s.children,Wl(r,s)?u=null:o!==null&&Wl(r,o)&&(t.flags|=32),Hu(e,t),Ct(e,t,u,n),t.child;case 6:return e===null&&ti(t),null;case 13:return Wu(e,t,n);case 4:return ui(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ws(t,null,r,n):Ct(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),$u(e,t,r,s,n);case 7:return Ct(e,t,t.pendingProps,n),t.child;case 8:return Ct(e,t,t.pendingProps.children,n),t.child;case 12:return Ct(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,o=t.memoizedProps,u=s.value,Le(Qo,r._currentValue),r._currentValue=u,o!==null)if(gn(o.value,u)){if(o.children===s.children&&!Tt.current){t=Jn(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var d=o.dependencies;if(d!==null){u=o.child;for(var m=d.firstContext;m!==null;){if(m.context===r){if(o.tag===1){m=Gn(-1,n&-n),m.tag=2;var S=o.updateQueue;if(S!==null){S=S.shared;var N=S.pending;N===null?m.next=m:(m.next=N.next,N.next=m),S.pending=m}}o.lanes|=n,m=o.alternate,m!==null&&(m.lanes|=n),li(o.return,n,t),d.lanes|=n;break}m=m.next}}else if(o.tag===10)u=o.type===t.type?null:o.child;else if(o.tag===18){if(u=o.return,u===null)throw Error(f(341));u.lanes|=n,d=u.alternate,d!==null&&(d.lanes|=n),li(u,n,t),u=o.sibling}else u=o.child;if(u!==null)u.return=o;else for(u=o;u!==null;){if(u===t){u=null;break}if(o=u.sibling,o!==null){o.return=u.return,u=o;break}u=u.return}o=u}Ct(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,js(t,n),s=Yt(s),r=r(s),t.flags|=1,Ct(e,t,r,n),t.child;case 14:return r=t.type,s=yn(r,t.pendingProps),s=yn(r.type,s),Fu(e,t,r,s,n);case 15:return Uu(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),tl(e,t),t.tag=1,Rt(r)?(e=!0,zo(t)):e=!1,js(t,n),Mu(t,r,s),wi(t,r,s,n),Ni(null,t,r,!0,e,n);case 19:return Ku(e,t,n);case 22:return Bu(e,t,n)}throw Error(f(156,t.tag))};function yc(e,t){return xo(e,t)}function af(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function en(e,t,n,r){return new af(e,t,n,r)}function Wi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function uf(e){if(typeof e=="function")return Wi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ot)return 11;if(e===We)return 14}return 2}function jr(e,t){var n=e.alternate;return n===null?(n=en(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function fl(e,t,n,r,s,o){var u=2;if(r=e,typeof e=="function")Wi(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Ce:return Xr(n.children,s,o,t);case $e:u=8,s|=8;break;case dt:return e=en(12,n,t,s|2),e.elementType=dt,e.lanes=o,e;case H:return e=en(13,n,t,s),e.elementType=H,e.lanes=o,e;case Me:return e=en(19,n,t,s),e.elementType=Me,e.lanes=o,e;case Z:return ml(n,s,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case st:u=10;break e;case Dt:u=9;break e;case ot:u=11;break e;case We:u=14;break e;case ne:u=16,r=null;break e}throw Error(f(130,e==null?e:typeof e,""))}return t=en(u,n,t,s),t.elementType=e,t.type=r,t.lanes=o,t}function Xr(e,t,n,r){return e=en(7,e,r,t),e.lanes=n,e}function ml(e,t,n,r){return e=en(22,e,r,t),e.elementType=Z,e.lanes=n,e.stateNode={isHidden:!1},e}function qi(e,t,n){return e=en(6,e,null,t),e.lanes=n,e}function Ki(e,t,n){return t=en(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function cf(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=pn(0),this.expirationTimes=pn(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=pn(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Gi(e,t,n,r,s,o,u,d,m){return e=new cf(e,t,n,d,m),t===1?(t=1,o===!0&&(t|=8)):t=0,o=en(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ai(o),e}function df(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(g){console.error(g)}}return i(),ta.exports=kf(),ta.exports}var Lc;function Cf(){if(Lc)return _l;Lc=1;var i=jf();return _l.createRoot=i.createRoot,_l.hydrateRoot=i.hydrateRoot,_l}var Nf=Cf();const Ef=qc(Nf),Pf="/api";async function ye(i,g){const f=await fetch(`${Pf}${i}`,{...g,headers:{"Content-Type":"application/json",...g?.headers??{}}}),R=await f.json();if(!f.ok){const E=R.error?.message??"Ошибка запроса";throw new Error(E)}return R}const Pe={async loadSharedConnectionConfig(){return ye("/llm/shared-connection")},async saveSharedConnectionConfig(i){return ye("/llm/shared-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,model:i.model,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})})},async listModels(i){return ye("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return ye("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return ye("/normalize",{method:"POST",body:JSON.stringify({llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,userQuestion:i.query.userQuestion,context:{period_hint:i.query.periodHint??"",business_context:i.query.businessContext??"",expected_route:i.query.expectedRoute??""},saveAsTestCase:!!i.saveAsTestCase,useMock:!!i.useMock})})},async loadHistory(){return ye("/history")},async loadTrace(i){return ye(`/history/${i}`)},async loadPresets(){return ye("/presets")},async savePreset(i){return ye("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return ye("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,analysis_date:i.analysisDate})})},async startEvalRunAsync(i){return ye("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,questions:i.questions,scenarioQuestions:i.scenarioQuestions,scenarioTitle:i.scenarioTitle,analysis_date:i.analysisDate})})},async loadEvalRunAsyncStatus(i){return ye(`/eval/run-async/${encodeURIComponent(i)}`)},async startRun(){return ye("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return ye("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return ye("/accounting-agent/v1/runs")},async listResults(){return ye("/accounting-agent/v1/results")},async runTrace(i){return ye(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return ye("/assistant/message",{method:"POST",body:JSON.stringify({session_id:i.sessionId??"",mode:"assistant",message:i.userMessage,user_message:i.userMessage,llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion??"address_query_runtime_v1",systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,context:{period_hint:i.context?.periodHint??"",business_context:i.context?.businessContext??""},useMock:!!i.useMock})})},async loadAssistantSession(i){return ye(`/assistant/session/${i}`)},async saveAutoRunAssistantSession(i){return ye("/autoruns/autogen/save-assistant-session",{method:"POST",body:JSON.stringify(i)})},async loadAssistantAnnotations(i){const g=new URLSearchParams;i?.session_id&&g.set("session_id",i.session_id),typeof i?.limit=="number"&&g.set("limit",String(i.limit));const f=g.toString();return ye(`/assistant/annotations${f?`?${f}`:""}`)},async saveAssistantAnnotation(i){return ye("/assistant/annotations",{method:"POST",body:JSON.stringify(i)})},async loadAutoRunsHistory(i){const g=new URLSearchParams;i?.from&&g.set("from",i.from),i?.to&&g.set("to",i.to),i?.target&&g.set("target",i.target),i?.mode&&g.set("mode",i.mode),i?.use_mock&&g.set("use_mock",i.use_mock),i?.prompt_contains&&g.set("prompt_contains",i.prompt_contains),typeof i?.limit=="number"&&g.set("limit",String(i.limit)),typeof i?.scan_limit=="number"&&g.set("scan_limit",String(i.scan_limit));const f=g.toString();return ye(`/autoruns/history${f?`?${f}`:""}`)},async loadAutoRunDetail(i){return ye(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,g){return ye(`/autoruns/history/${encodeURIComponent(i)}/case/${encodeURIComponent(g)}/dialog`)},async loadAutoRunAnnotations(i){const g=new URLSearchParams;i?.run_id&&g.set("run_id",i.run_id),i?.case_id&&g.set("case_id",i.case_id),typeof i?.min_rating=="number"&&g.set("min_rating",String(i.min_rating)),i?.manual_case_decision&&g.set("manual_case_decision",i.manual_case_decision),typeof i?.limit=="number"&&g.set("limit",String(i.limit));const f=g.toString();return ye(`/autoruns/annotations${f?`?${f}`:""}`)},async saveAutoRunAnnotation(i){return ye("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return ye(`/autoruns/annotations/${encodeURIComponent(i.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:i.resolved,resolved_by:i.resolved_by})})},async loadAutoRunPostAnalysis(i){const g=new URLSearchParams;i?.run_id&&g.set("run_id",i.run_id),typeof i?.limit_per_queue=="number"&&g.set("limit_per_queue",String(i.limit_per_queue)),typeof i?.annotation_limit=="number"&&g.set("annotation_limit",String(i.annotation_limit)),typeof i?.scan_limit=="number"&&g.set("scan_limit",String(i.scan_limit)),i?.from&&g.set("from",i.from),i?.to&&g.set("to",i.to),i?.target&&g.set("target",i.target),i?.mode&&g.set("mode",i.mode),i?.use_mock&&g.set("use_mock",i.use_mock),i?.prompt_contains&&g.set("prompt_contains",i.prompt_contains);const f=g.toString();return ye(`/autoruns/post-analysis${f?`?${f}`:""}`)},async loadAutoRunAutogenHistory(i){const g=new URLSearchParams;i?.mode&&g.set("mode",i.mode),typeof i?.limit=="number"&&g.set("limit",String(i.limit));const f=g.toString();return ye(`/autoruns/autogen/history${f?`?${f}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return ye("/autoruns/autogen/personality-catalog")},async updateAutoRunAutogenQuestions(i){return ye(`/autoruns/autogen/history/${encodeURIComponent(i.generation_id)}/questions`,{method:"PATCH",body:JSON.stringify({questions:i.questions})})},async deleteAutoRunAutogenHistoryRecord(i){return ye(`/autoruns/autogen/history/${encodeURIComponent(i)}`,{method:"DELETE"})},async generateAutoRunQuestions(i){return ye("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(i)})}},Tf=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,Rf=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function Mf(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function Lf(i){const g=String(i??""),f=g.match(Tf);return(f?g.slice(0,f.index):g).replace(/###\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)[\s\S]*?(?:```[\s\S]*?```|$)/gi,"").replace(/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)\b[\s\S]*$/gi,"").split(/\r?\n/g).map(Q=>Q.trimEnd()).filter(Q=>Q.trim().length>0).filter(Q=>!Rf.some(le=>le.test(Q))).join(` -`).trim()}function Af(i,g,f="default"){const R=f==="technical",E=[];E.push("# Assistant conversation export"),E.push(`session_id: ${i||"n/a"}`),E.push(`export_mode: ${f}`),E.push(`exported_at: ${new Date().toISOString()}`),E.push("");for(let A=0;A<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=u.createElement(n,{is:r.is}):(e=u.createElement(n),n==="select"&&(u=e,r.multiple?u.multiple=!0:r.size&&(u.size=r.size))):e=u.createElementNS(e,n),e[Rn]=t,e[eo]=r,Gu(e,t,!1,!1),t.stateNode=e;e:{switch(u=an(n,r),n){case"dialog":Ie("cancel",e),Ie("close",e),s=r;break;case"iframe":case"object":case"embed":Ie("load",e),s=r;break;case"video":case"audio":for(s=0;sTs&&(t.flags|=128,r=!0,co(o,!1),t.lanes=4194304)}else{if(!r)if(e=qo(u),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),co(o,!0),o.tail===null&&o.tailMode==="hidden"&&!u.alternate&&!ze)return yt(t),null}else 2*Fe()-o.renderingStartTime>Ts&&n!==1073741824&&(t.flags|=128,r=!0,co(o,!1),t.lanes=4194304);o.isBackwards?(u.sibling=t.child,t.child=u):(n=o.last,n!==null?n.sibling=u:t.child=u,o.last=u)}return o.tail!==null?(t=o.tail,o.rendering=t,o.tail=t.sibling,o.renderingStartTime=Fe(),t.sibling=null,n=Be.current,Ae(Be,r?n&1|2:n&1),t):(yt(t),null);case 22:case 23:return bi(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&(t.mode&1)!==0?(Wt&1073741824)!==0&&(yt(t),t.subtreeFlags&6&&(t.flags|=8192)):yt(t),null;case 24:return null;case 25:return null}throw Error(f(156,t.tag))}function Yd(e,t){switch(Zl(t),t.tag){case 1:return Rt(t.type)&&Oo(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Cs(),De(Tt),De(gt),fi(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 5:return ci(t),null;case 13:if(De(Be),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(f(340));Ss()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return De(Be),null;case 4:return Cs(),null;case 10:return oi(t.type._context),null;case 22:case 23:return bi(),null;case 24:return null;default:return null}}var nl=!1,xt=!1,Xd=typeof WeakSet=="function"?WeakSet:Set,O=null;function Es(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ve(e,t,r)}else n.current=null}function Ai(e,t,n){try{n()}catch(r){Ve(e,t,r)}}var Xu=!1;function Zd(e,t){if(bl=os,e=Ra(),Ol(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break e}var u=0,d=-1,m=-1,S=0,N=0,P=e,C=null;t:for(;;){for(var I;P!==n||s!==0&&P.nodeType!==3||(d=u+s),P!==o||r!==0&&P.nodeType!==3||(m=u+r),P.nodeType===3&&(u+=P.nodeValue.length),(I=P.firstChild)!==null;)C=P,P=I;for(;;){if(P===e)break t;if(C===n&&++S===s&&(d=u),C===o&&++N===r&&(m=u),(I=P.nextSibling)!==null)break;P=C,C=P.parentNode}P=I}n=d===-1||m===-1?null:{start:d,end:m}}else n=null}n=n||{start:0,end:0}}else n=null;for(Vl={focusedElem:e,selectionRange:n},os=!1,O=t;O!==null;)if(t=O,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,O=e;else for(;O!==null;){t=O;try{var B=t.alternate;if((t.flags&1024)!==0)switch(t.tag){case 0:case 11:case 15:break;case 1:if(B!==null){var b=B.memoizedProps,Ge=B.memoizedState,x=t.stateNode,g=x.getSnapshotBeforeUpdate(t.elementType===t.type?b:yn(t.type,b),Ge);x.__reactInternalSnapshotBeforeUpdate=g}break;case 3:var _=t.stateNode.containerInfo;_.nodeType===1?_.textContent="":_.nodeType===9&&_.documentElement&&_.removeChild(_.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(f(163))}}catch(T){Ve(t,t.return,T)}if(e=t.sibling,e!==null){e.return=t.return,O=e;break}O=t.return}return B=Xu,Xu=!1,B}function fo(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var o=s.destroy;s.destroy=void 0,o!==void 0&&Ai(t,n,o)}s=s.next}while(s!==r)}}function rl(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Li(e){var t=e.ref;if(t!==null){var n=e.stateNode;e.tag,e=n,typeof t=="function"?t(e):t.current=e}}function Zu(e){var t=e.alternate;t!==null&&(e.alternate=null,Zu(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Rn],delete t[eo],delete t[Gl],delete t[Dd],delete t[Od])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function ec(e){return e.tag===5||e.tag===3||e.tag===4}function tc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||ec(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ii(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Io));else if(r!==4&&(e=e.child,e!==null))for(Ii(e,t,n),e=e.sibling;e!==null;)Ii(e,t,n),e=e.sibling}function Di(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Di(e,t,n),e=e.sibling;e!==null;)Di(e,t,n),e=e.sibling}var ut=null,xn=!1;function xr(e,t,n){for(n=n.child;n!==null;)nc(e,t,n),n=n.sibling}function nc(e,t,n){if(ue&&typeof ue.onCommitFiberUnmount=="function")try{ue.onCommitFiberUnmount(wt,n)}catch{}switch(n.tag){case 5:xt||Es(n,t);case 6:var r=ut,s=xn;ut=null,xr(e,t,n),ut=r,xn=s,ut!==null&&(xn?(e=ut,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):ut.removeChild(n.stateNode));break;case 18:ut!==null&&(xn?(e=ut,n=n.stateNode,e.nodeType===8?Kl(e.parentNode,n):e.nodeType===1&&Kl(e,n),ir(e)):Kl(ut,n.stateNode));break;case 4:r=ut,s=xn,ut=n.stateNode.containerInfo,xn=!0,xr(e,t,n),ut=r,xn=s;break;case 0:case 11:case 14:case 15:if(!xt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var o=s,u=o.destroy;o=o.tag,u!==void 0&&((o&2)!==0||(o&4)!==0)&&Ai(n,t,u),s=s.next}while(s!==r)}xr(e,t,n);break;case 1:if(!xt&&(Es(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(d){Ve(n,t,d)}xr(e,t,n);break;case 21:xr(e,t,n);break;case 22:n.mode&1?(xt=(r=xt)||n.memoizedState!==null,xr(e,t,n),xt=r):xr(e,t,n);break;default:xr(e,t,n)}}function rc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new Xd),t.forEach(function(r){var s=uf.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function _n(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=u),r&=~o}if(r=s,r=Fe()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*tf(r/1960))-r,10e?16:e,Sr===null)var r=!1;else{if(e=Sr,Sr=null,al=0,(Se&6)!==0)throw Error(f(331));var s=Se;for(Se|=4,O=e.current;O!==null;){var o=O,u=o.child;if((O.flags&16)!==0){var d=o.deletions;if(d!==null){for(var m=0;mFe()-$i?Jr(e,0):zi|=n),Lt(e,t)}function gc(e,t){t===0&&((e.mode&1)===0?t=1:(t=Un,Un<<=1,(Un&130023424)===0&&(Un=4194304)));var n=Nt();e=Kn(e,t),e!==null&&(Ne(e,t,n),Lt(e,n))}function af(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),gc(e,n)}function uf(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(f(314))}r!==null&&r.delete(t),gc(e,n)}var vc;vc=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Tt.current)Mt=!0;else{if((e.lanes&n)===0&&(t.flags&128)===0)return Mt=!1,Gd(e,t,n);Mt=(e.flags&131072)!==0}else Mt=!1,ze&&(t.flags&1048576)!==0&&Ja(t,Uo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;tl(e,t),e=t.pendingProps;var s=ys(t,gt.current);js(t,n),s=hi(null,t,r,e,s,n);var o=gi();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Rt(r)?(o=!0,zo(t)):o=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,ai(t),s.updater=Zo,t.stateNode=s,s._reactInternals=t,wi(t,r,e,n),t=Ni(null,t,r,!0,o,n)):(t.tag=0,ze&&o&&Xl(t),Ct(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(tl(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=df(r),e=yn(r,e),s){case 0:t=Ci(null,t,r,e,n);break e;case 1:t=Qu(null,t,r,e,n);break e;case 11:t=$u(null,t,r,e,n);break e;case 14:t=Fu(null,t,r,yn(r.type,e),n);break e}throw Error(f(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),Ci(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),Qu(e,t,r,s,n);case 3:e:{if(bu(t),e===null)throw Error(f(387));r=t.pendingProps,o=t.memoizedState,s=o.element,ou(e,t),Wo(t,r,null,n);var u=t.memoizedState;if(r=u.element,o.isDehydrated)if(o={element:r,isDehydrated:!1,cache:u.cache,pendingSuspenseBoundaries:u.pendingSuspenseBoundaries,transitions:u.transitions},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){s=Ns(Error(f(423)),t),t=Vu(e,t,r,n,s);break e}else if(r!==s){s=Ns(Error(f(424)),t),t=Vu(e,t,r,n,s);break e}else for(Vt=mr(t.stateNode.containerInfo.firstChild),bt=t,ze=!0,vn=null,n=ru(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Ss(),r===s){t=Jn(e,t,n);break e}Ct(e,t,r,n)}t=t.child}return t;case 5:return au(t),e===null&&ti(t),r=t.type,s=t.pendingProps,o=e!==null?e.memoizedProps:null,u=s.children,Wl(r,s)?u=null:o!==null&&Wl(r,o)&&(t.flags|=32),Hu(e,t),Ct(e,t,u,n),t.child;case 6:return e===null&&ti(t),null;case 13:return Wu(e,t,n);case 4:return ui(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ws(t,null,r,n):Ct(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),$u(e,t,r,s,n);case 7:return Ct(e,t,t.pendingProps,n),t.child;case 8:return Ct(e,t,t.pendingProps.children,n),t.child;case 12:return Ct(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,o=t.memoizedProps,u=s.value,Ae(Qo,r._currentValue),r._currentValue=u,o!==null)if(gn(o.value,u)){if(o.children===s.children&&!Tt.current){t=Jn(e,t,n);break e}}else for(o=t.child,o!==null&&(o.return=t);o!==null;){var d=o.dependencies;if(d!==null){u=o.child;for(var m=d.firstContext;m!==null;){if(m.context===r){if(o.tag===1){m=Gn(-1,n&-n),m.tag=2;var S=o.updateQueue;if(S!==null){S=S.shared;var N=S.pending;N===null?m.next=m:(m.next=N.next,N.next=m),S.pending=m}}o.lanes|=n,m=o.alternate,m!==null&&(m.lanes|=n),li(o.return,n,t),d.lanes|=n;break}m=m.next}}else if(o.tag===10)u=o.type===t.type?null:o.child;else if(o.tag===18){if(u=o.return,u===null)throw Error(f(341));u.lanes|=n,d=u.alternate,d!==null&&(d.lanes|=n),li(u,n,t),u=o.sibling}else u=o.child;if(u!==null)u.return=o;else for(u=o;u!==null;){if(u===t){u=null;break}if(o=u.sibling,o!==null){o.return=u.return,u=o;break}u=u.return}o=u}Ct(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,js(t,n),s=Yt(s),r=r(s),t.flags|=1,Ct(e,t,r,n),t.child;case 14:return r=t.type,s=yn(r,t.pendingProps),s=yn(r.type,s),Fu(e,t,r,s,n);case 15:return Uu(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:yn(r,s),tl(e,t),t.tag=1,Rt(r)?(e=!0,zo(t)):e=!1,js(t,n),Mu(t,r,s),wi(t,r,s,n),Ni(null,t,r,!0,e,n);case 19:return Ku(e,t,n);case 22:return Bu(e,t,n)}throw Error(f(156,t.tag))};function yc(e,t){return xo(e,t)}function cf(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function en(e,t,n,r){return new cf(e,t,n,r)}function Wi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function df(e){if(typeof e=="function")return Wi(e)?1:0;if(e!=null){if(e=e.$$typeof,e===ot)return 11;if(e===We)return 14}return 2}function jr(e,t){var n=e.alternate;return n===null?(n=en(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function fl(e,t,n,r,s,o){var u=2;if(r=e,typeof e=="function")Wi(e)&&(u=1);else if(typeof e=="string")u=5;else e:switch(e){case Ce:return Xr(n.children,s,o,t);case $e:u=8,s|=8;break;case dt:return e=en(12,n,t,s|2),e.elementType=dt,e.lanes=o,e;case H:return e=en(13,n,t,s),e.elementType=H,e.lanes=o,e;case Me:return e=en(19,n,t,s),e.elementType=Me,e.lanes=o,e;case Z:return ml(n,s,o,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case st:u=10;break e;case Dt:u=9;break e;case ot:u=11;break e;case We:u=14;break e;case ne:u=16,r=null;break e}throw Error(f(130,e==null?e:typeof e,""))}return t=en(u,n,t,s),t.elementType=e,t.type=r,t.lanes=o,t}function Xr(e,t,n,r){return e=en(7,e,r,t),e.lanes=n,e}function ml(e,t,n,r){return e=en(22,e,r,t),e.elementType=Z,e.lanes=n,e.stateNode={isHidden:!1},e}function qi(e,t,n){return e=en(6,e,null,t),e.lanes=n,e}function Ki(e,t,n){return t=en(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function ff(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=pn(0),this.expirationTimes=pn(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=pn(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function Gi(e,t,n,r,s,o,u,d,m){return e=new ff(e,t,n,d,m),t===1?(t=1,o===!0&&(t|=8)):t=0,o=en(3,null,null,t),e.current=o,o.stateNode=e,o.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},ai(o),e}function mf(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(h){console.error(h)}}return i(),ta.exports=Cf(),ta.exports}var Ac;function Ef(){if(Ac)return _l;Ac=1;var i=Nf();return _l.createRoot=i.createRoot,_l.hydrateRoot=i.hydrateRoot,_l}var Pf=Ef();const Tf=Kc(Pf),Rf="/api";async function ye(i,h){const f=await fetch(`${Rf}${i}`,{...h,headers:{"Content-Type":"application/json",...h?.headers??{}}}),R=await f.json();if(!f.ok){const E=R.error?.message??"Ошибка запроса";throw new Error(E)}return R}const Pe={async loadSharedConnectionConfig(){return ye("/llm/shared-connection")},async saveSharedConnectionConfig(i){return ye("/llm/shared-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,model:i.model,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})})},async listModels(i){return ye("/llm/models",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async testConnection(i){return ye("/llm/test-connection",{method:"POST",body:JSON.stringify({llmProvider:i.llmProvider,apiKey:i.apiKey,model:i.model,baseUrl:i.baseUrl})})},async normalize(i){return ye("/normalize",{method:"POST",body:JSON.stringify({llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,userQuestion:i.query.userQuestion,context:{period_hint:i.query.periodHint??"",business_context:i.query.businessContext??"",expected_route:i.query.expectedRoute??""},saveAsTestCase:!!i.saveAsTestCase,useMock:!!i.useMock})})},async loadHistory(){return ye("/history")},async loadTrace(i){return ye(`/history/${i}`)},async loadPresets(){return ye("/presets")},async savePreset(i){return ye("/presets/save",{method:"POST",body:JSON.stringify(i)})},async runEval(i){return ye("/eval/run",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,analysis_date:i.analysisDate})})},async startEvalRunAsync(i){return ye("/eval/run-async/start",{method:"POST",body:JSON.stringify({normalizeConfig:{llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion,systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples},caseIds:i.caseIds,useMock:!!i.useMock,mode:i.mode??"standard",caseSetFile:i.caseSetFile,rawQuestions:i.rawQuestions,eval_target:i.evalTarget,compare_with_report_file:i.compareWithReportFile,questions:i.questions,scenarioQuestions:i.scenarioQuestions,scenarioTitle:i.scenarioTitle,analysis_date:i.analysisDate})})},async loadEvalRunAsyncStatus(i){return ye(`/eval/run-async/${encodeURIComponent(i)}`)},async startRun(){return ye("/accounting-agent/v1/runs/start",{method:"POST",body:JSON.stringify({initiator:"ndc_operator",source:"gui"})})},async finishRun(i){return ye("/accounting-agent/v1/runs/finish",{method:"POST",body:JSON.stringify({runId:i,status:"DONE",source:"gui",reason:"Остановлено оператором из GUI"})})},async listRuns(){return ye("/accounting-agent/v1/runs")},async listResults(){return ye("/accounting-agent/v1/results")},async runTrace(i){return ye(`/accounting-agent/v1/trace/run/${i}`)},async sendAssistantMessage(i){return ye("/assistant/message",{method:"POST",body:JSON.stringify({session_id:i.sessionId??"",mode:"assistant",message:i.userMessage,user_message:i.userMessage,llmProvider:i.connection.llmProvider,apiKey:i.connection.apiKey,model:i.connection.model,baseUrl:i.connection.baseUrl,temperature:i.connection.temperature,maxOutputTokens:i.connection.maxOutputTokens,promptVersion:i.promptVersion??"address_query_runtime_v1",systemPrompt:i.prompts.systemPrompt,developerPrompt:i.prompts.developerPrompt,domainPrompt:i.prompts.domainPrompt,fewShotExamples:i.prompts.fewShotExamples,context:{period_hint:i.context?.periodHint??"",business_context:i.context?.businessContext??""},useMock:!!i.useMock})})},async loadAssistantSession(i){return ye(`/assistant/session/${i}`)},async saveAutoRunAssistantSession(i){return ye("/autoruns/autogen/save-assistant-session",{method:"POST",body:JSON.stringify(i)})},async loadAssistantAnnotations(i){const h=new URLSearchParams;i?.session_id&&h.set("session_id",i.session_id),typeof i?.limit=="number"&&h.set("limit",String(i.limit));const f=h.toString();return ye(`/assistant/annotations${f?`?${f}`:""}`)},async saveAssistantAnnotation(i){return ye("/assistant/annotations",{method:"POST",body:JSON.stringify(i)})},async loadAutoRunsHistory(i){const h=new URLSearchParams;i?.from&&h.set("from",i.from),i?.to&&h.set("to",i.to),i?.target&&h.set("target",i.target),i?.mode&&h.set("mode",i.mode),i?.use_mock&&h.set("use_mock",i.use_mock),i?.prompt_contains&&h.set("prompt_contains",i.prompt_contains),typeof i?.limit=="number"&&h.set("limit",String(i.limit)),typeof i?.scan_limit=="number"&&h.set("scan_limit",String(i.scan_limit));const f=h.toString();return ye(`/autoruns/history${f?`?${f}`:""}`)},async loadAutoRunDetail(i){return ye(`/autoruns/history/${encodeURIComponent(i)}`)},async loadAutoRunCaseDialog(i,h){return ye(`/autoruns/history/${encodeURIComponent(i)}/case/${encodeURIComponent(h)}/dialog`)},async loadAutoRunAnnotations(i){const h=new URLSearchParams;i?.run_id&&h.set("run_id",i.run_id),i?.case_id&&h.set("case_id",i.case_id),typeof i?.min_rating=="number"&&h.set("min_rating",String(i.min_rating)),i?.manual_case_decision&&h.set("manual_case_decision",i.manual_case_decision),typeof i?.limit=="number"&&h.set("limit",String(i.limit));const f=h.toString();return ye(`/autoruns/annotations${f?`?${f}`:""}`)},async saveAutoRunAnnotation(i){return ye("/autoruns/annotations",{method:"POST",body:JSON.stringify(i)})},async updateAutoRunAnnotation(i){return ye(`/autoruns/annotations/${encodeURIComponent(i.annotation_id)}`,{method:"PATCH",body:JSON.stringify({resolved:i.resolved,resolved_by:i.resolved_by})})},async loadAutoRunPostAnalysis(i){const h=new URLSearchParams;i?.run_id&&h.set("run_id",i.run_id),typeof i?.limit_per_queue=="number"&&h.set("limit_per_queue",String(i.limit_per_queue)),typeof i?.annotation_limit=="number"&&h.set("annotation_limit",String(i.annotation_limit)),typeof i?.scan_limit=="number"&&h.set("scan_limit",String(i.scan_limit)),i?.from&&h.set("from",i.from),i?.to&&h.set("to",i.to),i?.target&&h.set("target",i.target),i?.mode&&h.set("mode",i.mode),i?.use_mock&&h.set("use_mock",i.use_mock),i?.prompt_contains&&h.set("prompt_contains",i.prompt_contains);const f=h.toString();return ye(`/autoruns/post-analysis${f?`?${f}`:""}`)},async loadAutoRunAutogenHistory(i){const h=new URLSearchParams;i?.mode&&h.set("mode",i.mode),typeof i?.limit=="number"&&h.set("limit",String(i.limit));const f=h.toString();return ye(`/autoruns/autogen/history${f?`?${f}`:""}`)},async loadAutoRunAutogenPersonalityCatalog(){return ye("/autoruns/autogen/personality-catalog")},async updateAutoRunAutogenQuestions(i){return ye(`/autoruns/autogen/history/${encodeURIComponent(i.generation_id)}/questions`,{method:"PATCH",body:JSON.stringify({questions:i.questions})})},async deleteAutoRunAutogenHistoryRecord(i){return ye(`/autoruns/autogen/history/${encodeURIComponent(i)}`,{method:"DELETE"})},async generateAutoRunQuestions(i){return ye("/autoruns/autogen/generate",{method:"POST",body:JSON.stringify(i)})}},Mf=/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json|debug_payload|technical_breakdown)\b/i,Af=[/\b(?:debug_payload_json|technical_breakdown_json)\b/i,/\b(?:route_summary|semantic_profile|domain_scope|relation_patterns|account_scope)\b/i,/\b(?:coverage_report|retrieval_status|problem_unit_state|candidate_evidence)\b/i,/\b(?:graph_domain_scope|graph_runtime|selection_reason|why_included)\b/i];function Lf(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function If(i){const h=String(i??""),f=h.match(Mf);return(f?h.slice(0,f.index):h).replace(/###\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)[\s\S]*?(?:```[\s\S]*?```|$)/gi,"").replace(/(?:^|\n)\s*#{0,6}\s*(?:debug_payload_json|technical_breakdown_json|route_summary_json)\b[\s\S]*$/gi,"").split(/\r?\n/g).map(Q=>Q.trimEnd()).filter(Q=>Q.trim().length>0).filter(Q=>!Af.some(le=>le.test(Q))).join(` +`).trim()}function Df(i,h,f="default"){const R=f==="technical",E=[];E.push("# Assistant conversation export"),E.push(`session_id: ${i||"n/a"}`),E.push(`export_mode: ${f}`),E.push(`exported_at: ${new Date().toISOString()}`),E.push("");for(let L=0;L{E.length!==0&&(R.push(E.join(` -`)),E=[])};for(const Q of f){const le=Q.trimEnd(),te=le.trim();if(!te){A();continue}const z=/^Блок\s+\d+\./i.test(te),Y=/^\d+\.\s/.test(te);(z||Y)&&E.length>0&&A(),E.push(le)}return A(),R.length>0?R:[i]}function Uf(i,g){const f=[],R=/\*\*(.+?)\*\*/g;let E=0,A=0,Q;for(;(Q=R.exec(i))!==null;)Q.index>E&&(f.push(l.jsx("span",{children:i.slice(E,Q.index)},`${g}-t-${A}`)),A+=1),f.push(l.jsx("strong",{children:Q[1]},`${g}-b-${A}`)),A+=1,E=R.lastIndex;return E0?f:[l.jsx("span",{children:i},`${g}-raw`)]}function Bf(i){const g=i.trimStart();return/^Блок\s+\d+\./i.test(g)?"assistant-msg-line heading":/^\d+\.\s/.test(g)?"assistant-msg-line numbered":/^-\s/.test(g)?"assistant-msg-line bullet":"assistant-msg-line"}function Hf(i,g=40){const f=i.replace(/\s+/g," ").trim();if(f.length<=g)return f;const R=f.split(" ").slice(0,3).join(" ").trim();return R.length>=10&&R.length<=g?`${R}…`:`${f.slice(0,g-1).trimEnd()}…`}function Gc(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Qf(i){const g=i.replace(/\r\n?/g,` +$2`)}function Bf(i){const f=Uf(i).split(` +`),R=[];let E=[];const L=()=>{E.length!==0&&(R.push(E.join(` +`)),E=[])};for(const Q of f){const le=Q.trimEnd(),te=le.trim();if(!te){L();continue}const z=/^Блок\s+\d+\./i.test(te),Y=/^\d+\.\s/.test(te);(z||Y)&&E.length>0&&L(),E.push(le)}return L(),R.length>0?R:[i]}function Hf(i,h){const f=[],R=/\*\*(.+?)\*\*/g;let E=0,L=0,Q;for(;(Q=R.exec(i))!==null;)Q.index>E&&(f.push(l.jsx("span",{children:i.slice(E,Q.index)},`${h}-t-${L}`)),L+=1),f.push(l.jsx("strong",{children:Q[1]},`${h}-b-${L}`)),L+=1,E=R.lastIndex;return E0?f:[l.jsx("span",{children:i},`${h}-raw`)]}function Qf(i){const h=i.trimStart();return/^Блок\s+\d+\./i.test(h)?"assistant-msg-line heading":/^\d+\.\s/.test(h)?"assistant-msg-line numbered":/^-\s/.test(h)?"assistant-msg-line bullet":"assistant-msg-line"}function bf(i,h=40){const f=i.replace(/\s+/g," ").trim();if(f.length<=h)return f;const R=f.split(" ").slice(0,3).join(" ").trim();return R.length>=10&&R.length<=h?`${R}…`:`${f.slice(0,h-1).trimEnd()}…`}function Jc(i){return i.replace(/\*\*(.+?)\*\*/g,"$1").replace(/^\d+\.\s*/,"").trim()}function Vf(i){const h=i.replace(/\r\n?/g,` `).split(` -`).map(E=>E.trim()).find(Boolean),f=Gc(g??"");return(f.split("|")[0]?.trim()??f).replace(/\s+/g," ").trim()}function bf(i){const g=i.replace(/\r\n?/g,` +`).map(E=>E.trim()).find(Boolean),f=Jc(h??"");return(f.split("|")[0]?.trim()??f).replace(/\s+/g," ").trim()}function Wf(i){const h=i.replace(/\r\n?/g,` `).split(` -`).map(R=>R.trim()).find(Boolean);return!g||!/^\d+\.\s/.test(g)?!1:Gc(g).includes("|")}function Vf(i,g){const f=g.replace(/\r\n?/g,` +`).map(R=>R.trim()).find(Boolean);return!h||!/^\d+\.\s/.test(h)?!1:Jc(h).includes("|")}function qf(i,h){const f=h.replace(/\r\n?/g,` `).replace(/\*\*(.+?)\*\*/g,"$1").split(` -`).map((E,A)=>{const Q=E.trim();return A===0?Q.replace(/^\d+\.\s*/,""):Q}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!f)return null;const R=Qf(g)||f;return{message_id:i.message_id,source_text:f,anchor_text:R,preview_text:Hf(R)}}function Wf(i,g,f,R){return Ff(i.text).map((A,Q)=>{const le=A.split(` -`),te=i.role==="assistant"&&bf(A),z=te?Vf(i,A):null,Y=!!z&&g?.message_id===z?.message_id&&g?.source_text===z?.source_text,X=le.map((ee,Te)=>l.jsx("p",{className:Bf(ee),children:Uf(ee,`line-${Q}-${Te}`)},`line-${Q}-${Te}`));return!te||!z?l.jsx("div",{className:"assistant-msg-block",children:X},`block-${Q}`):l.jsx("div",{className:Y?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(Y){R();return}f(z)},onKeyDown:ee=>{if(!(ee.key!=="Enter"&&ee.key!==" ")){if(ee.preventDefault(),Y){R();return}f(z)}},children:X},`block-${Q}`)})}function qf({sessionId:i,conversation:g,inputValue:f,onInputChange:R,selectedContextChip:E,onSelectContextChip:A,onClearContextChip:Q,useMock:le,onUseMockChange:te,onSend:z,onClear:Y,onSaveSession:X,busy:ee,saveBusy:Te=!1,saveDisabled:ce=!1,statusText:de,errorMessage:pe,showSaveAction:Qe=!1,showCommentAction:Je=!1,onCommentAssistantMessage:be,isAssistantMessageCommented:Re,canCommentAssistantMessage:F}){const oe=y.useRef(null),Ce=y.useRef(!0),$e=y.useRef(null),[dt,st]=y.useState("idle"),[Dt,ot]=y.useState("чат");function H(ne=!1){oe.current&&(ne&&(Ce.current=!0),oe.current.scrollTop=oe.current.scrollHeight)}y.useEffect(()=>{Ce.current&&H()},[g]),y.useEffect(()=>()=>{$e.current!==null&&window.clearTimeout($e.current)},[]);async function Me(ne){if(g.length===0)return;const Z=Af(i,g,ne),M=await Of(Z);ot(ne==="technical"?"тех":"чат"),st(M?"success":"error"),$e.current!==null&&window.clearTimeout($e.current),$e.current=window.setTimeout(()=>{st("idle")},2200)}function We(){if(!oe.current)return;const ne=oe.current,Z=ne.scrollHeight-ne.scrollTop-ne.clientHeight;Ce.current=Z<16}return l.jsx(Pl,{className:"assistant-panel-frame",title:"Режим ассистента",children:l.jsxs("div",{className:"assistant-live-shell",children:[l.jsxs("div",{className:"assistant-toolbar",children:[l.jsxs("div",{className:"assistant-toolbar-actions",children:[l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Me("default")},disabled:g.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Me("technical")},disabled:g.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),Qe?l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>X?.(),disabled:Te||ce,children:Te?"Сохраняю...":"Сохранить"}):null,l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>Y(),disabled:ee&&g.length===0,children:"Сбросить сессию"})]}),l.jsxs("div",{className:"assistant-toolbar-meta",children:[i?l.jsx("span",{className:"status-chip",children:`session: ${i}`}):null,l.jsxs("div",{className:"assistant-toolbar-meta-right",children:[de?l.jsx("span",{className:"assistant-live-status",children:de}):null,dt==="success"?l.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Dt,")"]}):null,dt==="error"?l.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),pe?l.jsx("p",{className:"error-text assistant-toolbar-error",children:pe}):null]}),l.jsx("div",{ref:oe,className:"assistant-chat-list",onScroll:We,children:g.map((ne,Z)=>{const M=ne.role==="assistant"&&Je&&typeof be=="function"&&(typeof F=="function"?F(ne,Z):!0),U=ne.role==="assistant"&&typeof Re=="function"?Re(ne,Z):!1;return l.jsxs("article",{className:`assistant-msg ${ne.role}`,children:[l.jsxs("header",{className:"assistant-msg-head",children:[l.jsxs("div",{className:"assistant-msg-head-main",children:[l.jsx("strong",{children:If(ne.role)}),l.jsx("span",{children:Df(ne.created_at)})]}),ne.role==="assistant"&&Je?l.jsx("div",{className:"assistant-msg-head-actions",children:l.jsx("button",{type:"button",className:U?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>be?.(ne,Z),disabled:!M,title:M?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":M?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:l.jsx(zf,{commented:U})})}):null]}),l.jsx("div",{className:"assistant-msg-body",children:Wf(ne,E,A,Q)}),ne.role==="assistant"&&ne.debug?l.jsxs("details",{className:"assistant-debug",children:[l.jsx("summary",{children:"Показать технический разбор"}),l.jsx(Kc,{value:ne.debug})]}):null]},ne.message_id)})}),l.jsxs("div",{className:"assistant-compose",children:[E?l.jsxs("div",{className:"assistant-compose-context",children:[l.jsx("span",{className:"assistant-compose-context-label",children:"Выбранный объект"}),l.jsxs("div",{className:"assistant-compose-context-pill",title:E.source_text,children:[l.jsx("span",{className:"assistant-compose-context-pill-text",children:E.preview_text}),l.jsx("button",{type:"button",className:"assistant-compose-context-clear",onClick:Q,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,l.jsxs("label",{className:"full-width",children:["Сообщение",l.jsx("textarea",{className:"assistant-input-textarea",value:f,onChange:ne=>R(ne.target.value),rows:4,placeholder:E?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),l.jsxs("div",{className:"button-row assistant-send-row",children:[l.jsxs("label",{className:"checkbox-row",children:[l.jsx("input",{type:"checkbox",checked:le,onChange:ne=>te(ne.target.checked)}),"Mock-режим"]}),l.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{H(!0),z()},disabled:ee||!f.trim(),children:ee?"Выполняю...":"Отправить"})]})]})]})})}const Sl="http://127.0.0.1:1234/v1",Ac="https://api.openai.com/v1",Nl="qwen2.5-14b-instruct-1m",ma="unsloth/qwen3-30b-a3b-instruct-2507",Kf=[{value:Nl,label:"Qwen2.5 14B Instruct 1M"},{value:ma,label:"Qwen3 30B A3B Instruct 2507"}];function Gf(i){return i.llmProvider!=="local"?"openai":i.model===ma?"local_qwen3":i.model===Nl?"local_qwen25":"local_custom"}function Jf(i,g){const f=new Map;if(g)for(const R of Kf)f.set(R.value,R);for(const R of i)f.has(R)||f.set(R,{value:R,label:R});return Array.from(f.values())}function Yf({value:i,modelOptions:g,modelsBusy:f,onChange:R,onReloadModels:E,onTestConnection:A,onSaveLocalConfig:Q,lastStatus:le,busy:te,embedded:z=!1}){const Y=i.llmProvider==="local",X=Gf(i),ee=Jf(g,Y),Te=ee.some(F=>F.value===i.model),[ce,de]=y.useState(String(i.temperature)),[pe,Qe]=y.useState(String(i.maxOutputTokens));y.useEffect(()=>{de(String(i.temperature))},[i.temperature]),y.useEffect(()=>{Qe(String(i.maxOutputTokens))},[i.maxOutputTokens]);const Je=F=>{const oe=F.replace(",",".").trim();if(!oe){de(String(i.temperature));return}const Ce=Number(oe);if(!Number.isFinite(Ce)){de(String(i.temperature));return}R({...i,temperature:Ce}),de(String(Ce))},be=F=>{const oe=F.trim();if(!oe){Qe(String(i.maxOutputTokens));return}const Ce=Number.parseInt(oe,10);if(!Number.isFinite(Ce)||Ce<=0){Qe(String(i.maxOutputTokens));return}R({...i,maxOutputTokens:Ce}),Qe(String(Ce))},Re=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid-two",children:[l.jsxs("label",{children:["Provider",l.jsxs("select",{value:X,onChange:F=>{const oe=F.target.value;if(oe==="openai"){R({...i,llmProvider:"openai",baseUrl:Ac});return}if(oe==="local_qwen25"){R({...i,llmProvider:"local",model:Nl,baseUrl:Sl});return}if(oe==="local_qwen3"){R({...i,llmProvider:"local",model:ma,baseUrl:Sl});return}R({...i,llmProvider:"local",model:i.llmProvider==="local"?i.model:Nl,baseUrl:Sl})},children:[l.jsx("option",{value:"openai",children:"OpenAI (token)"}),l.jsx("option",{value:"local_qwen25",children:"Qwen2.5 14B Instruct 1M (Local LM Studio)"}),l.jsx("option",{value:"local_qwen3",children:"Qwen3 30B A3B Instruct 2507 (Local LM Studio)"}),l.jsx("option",{value:"local_custom",children:"Local custom (LM Studio / OpenAI-compatible)"})]})]}),l.jsxs("label",{children:["Model",l.jsxs("select",{value:Te?i.model:"__manual__",onChange:F=>{const oe=F.target.value;oe!=="__manual__"&&R({...i,model:oe})},children:[l.jsx("option",{value:"__manual__",children:"Manual input"}),ee.map(F=>l.jsx("option",{value:F.value,children:F.label},F.value))]})]}),l.jsxs("label",{children:["Model ID (manual / current)",l.jsx("input",{value:i.model,onChange:F=>R({...i,model:F.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),Y?null:l.jsxs("label",{className:"full-width",children:["OpenAI API Key",l.jsx("input",{type:"password",value:i.apiKey,onChange:F=>R({...i,apiKey:F.target.value}),placeholder:"sk-..."})]}),l.jsxs("label",{className:Y?"full-width":void 0,children:[Y?"Local server base URL":"Base URL",l.jsx("input",{value:i.baseUrl,onChange:F=>R({...i,baseUrl:F.target.value}),placeholder:Y?Sl:Ac})]}),l.jsxs("label",{children:["Temperature",l.jsx("input",{type:"number",step:"0.1",value:ce,onChange:F=>de(F.target.value),onBlur:F=>Je(F.target.value),onKeyDown:F=>{F.key==="Enter"&&Je(F.target.value)}})]}),l.jsxs("label",{children:["Max output tokens",l.jsx("input",{type:"number",value:pe,onChange:F=>Qe(F.target.value),onBlur:F=>be(F.target.value),onKeyDown:F=>{F.key==="Enter"&&be(F.target.value)}})]})]}),l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>Q(),children:"Save local config"}),l.jsx("button",{type:"button",onClick:()=>E(),disabled:te||f,children:f?"Loading models...":"Load model list"}),l.jsx("button",{type:"button",onClick:()=>A(),disabled:te,children:te?"Checking...":"Test connection"})]})]});return z?l.jsxs("section",{className:"embedded-panel-section",children:[l.jsxs("div",{className:"embedded-panel-section-header",children:[l.jsxs("div",{children:[l.jsx("h4",{children:"LLM Connector"}),l.jsx("p",{children:"Switch between OpenAI cloud and local OpenAI-compatible server."})]}),l.jsx("span",{className:"status-chip",children:le||"Status: not checked"})]}),Re]}):l.jsx(Pl,{title:"LLM Connector",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:l.jsx("span",{className:"status-chip",children:le||"Status: not checked"}),children:Re})}function Xf({value:i,onChange:g,presets:f,selectedPresetId:R,onSelectPreset:E,onLoadPreset:A,onSavePreset:Q,onResetDefaults:le,onDiffPrevious:te,presetName:z,onPresetNameChange:Y,diffSummary:X,embedded:ee=!1}){const Te=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"prompt-manager-grid",children:[l.jsxs("label",{children:["Системный prompt",l.jsx("textarea",{value:i.systemPrompt,onChange:ce=>g({...i,systemPrompt:ce.target.value}),rows:6})]}),l.jsxs("label",{children:["Developer / Instruction prompt",l.jsx("textarea",{value:i.developerPrompt,onChange:ce=>g({...i,developerPrompt:ce.target.value}),rows:6})]}),l.jsxs("label",{children:["Domain prompt",l.jsx("textarea",{value:i.domainPrompt,onChange:ce=>g({...i,domainPrompt:ce.target.value}),rows:6})]}),l.jsxs("label",{children:["Schema notes",l.jsx("textarea",{value:i.schemaNotes,onChange:ce=>g({...i,schemaNotes:ce.target.value}),rows:6})]}),l.jsxs("label",{className:"full-width",children:["Few-shot examples",l.jsx("textarea",{value:i.fewShotExamples,onChange:ce=>g({...i,fewShotExamples:ce.target.value}),rows:8})]})]}),l.jsxs("div",{className:"button-row",children:[l.jsxs("select",{value:R,onChange:ce=>E(ce.target.value),children:[l.jsx("option",{value:"",children:"Выберите preset..."}),f.map(ce=>l.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),l.jsx("button",{type:"button",onClick:()=>A(),children:"Загрузить preset"}),l.jsx("input",{value:z,onChange:ce=>Y(ce.target.value),placeholder:"Имя для сохранения"}),l.jsx("button",{type:"button",onClick:()=>Q(),children:"Сохранить preset"}),l.jsx("button",{type:"button",onClick:()=>te(),children:"Diff с предыдущим"}),l.jsx("button",{type:"button",onClick:()=>le(),children:"Сбросить к default"})]}),X?l.jsx("p",{className:"diff-summary",children:X}):null]});return ee?l.jsxs("section",{className:"embedded-panel-section",children:[l.jsx("div",{className:"embedded-panel-section-header",children:l.jsxs("div",{children:[l.jsx("h4",{children:"Prompt Manager"}),l.jsx("p",{children:"Системный, developer и domain уровни управляются отдельно."})]})}),Te]}):l.jsx(Pl,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:Te})}const sa={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},wl="needs_dialog_policy_fix",_t="__all__",El="__live__:",Ic="ndc_autoruns_ui_config_v1",Dc="ndc-autoruns-save",oa=["Анализ запроса","Получение данных","Подготовка ответа"];function Zf(i,g){const f=i.trim();if(!f)return"";if(!g)return f;const R=f.toLowerCase(),E=g.anchor_text.trim(),A=E.toLowerCase();return A&&R.includes(A)?f:`По выбранному объекту "${E}": ${f}`}const da=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function em(i=da){return i.reduce((g,f)=>(g[f.id]=f.defaultPrompt,g),{})}const Oc={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:em(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function la(i){const g=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(g)?g:""}function zc(i){const g=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,g))}function tm(i){const g=i.getFullYear(),f=String(i.getMonth()+1).padStart(2,"0"),R=String(i.getDate()).padStart(2,"0"),E=String(i.getHours()).padStart(2,"0"),A=String(i.getMinutes()).padStart(2,"0");return`${g}-${f}-${R}T${E}:${A}`}function $c(){const i=new Date;return i.setDate(i.getDate()-14),tm(i)}function kl(i){if(!i.trim())return;const g=Date.parse(i);if(Number.isFinite(g))return new Date(g).toISOString()}function tn(i){if(!i)return"нет данных";const g=Date.parse(i);return Number.isFinite(g)?new Date(g).toLocaleString("ru-RU"):i}function ia(i){return i==="saved_user_sessions"?"Пользовательские сессии":i}function nm(i){const g=i[i.length-1];return`Ручная сессия ${tn(g?.created_at??new Date().toISOString())}`}function rm(i,g){return g<=0?0:Math.max(0,Math.min(100,Number((i/g*100).toFixed(1))))}function jl(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function sm(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function Fc(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function aa(i){const g=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(g)}${"○".repeat(5-g)}`}function Uc(i){return i.length===0?l.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):l.jsx("div",{className:"autoruns-coverage-list",children:i.map(g=>{const f=rm(g.closed_cases,g.total_cases);return l.jsxs("div",{className:"autoruns-coverage-item",children:[l.jsxs("div",{className:"autoruns-coverage-head",children:[l.jsx("strong",{children:g.domain}),l.jsxs("span",{children:[g.closed_cases,"/",g.total_cases," (",f,"%)"]})]}),l.jsx("div",{className:"autoruns-coverage-bar",children:l.jsx("div",{style:{width:`${f}%`}})})]},g.domain)})})}function Cl(i){return`${El}${i}`}function Ms(i){return i.startsWith(El)}function Bc(i){return i.startsWith(El)?i.slice(El.length):""}function Jc(i){const g=i.report_summary?.run_timestamp??i.created_at,f=Math.max(0,i.total_cases-i.completed_cases);return{run_id:Cl(i.job_id),eval_target:i.eval_target,run_timestamp:g,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:i.report_summary?.analysis_date??i.analysis_date??null,prompt_version:null,schema_version:null,suite_id:i.case_set_file,cases_total:i.total_cases,requests_total:null,report_path:`async_job:${i.job_id}`,score_index:i.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:i.completed_cases,open_cases:f,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function yo(i,g){const f=Jc(i),R=i.cases.map(Y=>({case_id:Y.case_id,domain:null,query_class:null,status:Y.status==="completed"?"closed":Y.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${Y.case_id}`,dialog_available:Y.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),A=g!==_t&&R.some(Y=>Y.case_id===g)?g:R.length>0?_t:"",Q={ok:!0,run:f,coverage:{closed_cases:i.completed_cases,open_cases:Math.max(0,i.total_cases-i.completed_cases),domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]},cases:R,annotations_summary:{total:0},report:i.report_summary?{run_id:i.report_summary.run_id,run_timestamp:i.report_summary.run_timestamp,score_index:i.report_summary.score_index,cases_total:i.report_summary.cases_total,analysis_date:i.report_summary.analysis_date??i.analysis_date??null}:{}},le=[];let te=0;if(A===_t)for(const Y of i.cases)for(let X=0;XX.case_id===A)??null;for(let X=0;X<(Y?.messages.length??0);X+=1){const ee=Y?.messages[X];ee&&le.push({...ee,message_index:X,case_id:A,case_message_index:X,commented:!1,annotation:null})}}const z={ok:!0,run_id:f.run_id,case_id:A,source:"assistant_session",session_id:A===_t?`${i.run_id}::__all__`:`${i.run_id}-${A}`,messages:le,decomposition:[],assistant_mode:{status:i.status,completed_cases:i.completed_cases,total_cases:i.total_cases},annotations:[]};return{detail:Q,dialog:z,caseId:A}}function om({commented:i}){const g=i?"comment-icon-svg commented":"comment-icon-svg";return l.jsx("svg",{className:g,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:l.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function Hc({resolved:i}){return l.jsxs("svg",{className:i?"resolve-icon-svg resolved":"resolve-icon-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[l.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),i?l.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function Qc(){return l.jsxs("svg",{className:"autoruns-copy-icon-svg",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[l.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2.2"}),l.jsx("path",{d:"M15 7V5.8a1.8 1.8 0 0 0-1.8-1.8H5.8A1.8 1.8 0 0 0 4 5.8v7.4A1.8 1.8 0 0 0 5.8 15H7"})]})}function lm({connection:i,modelOptions:g,modelsBusy:f,connectionStatus:R,connectionBusy:E,onConnectionChange:A,onReloadModels:Q,onSaveLocalConfig:le,onTestConnection:te,prompts:z,onPromptsChange:Y,promptPresets:X,selectedPresetId:ee,onSelectPreset:Te,onLoadPreset:ce,onSavePreset:de,onResetDefaults:pe,onDiffPrevious:Qe,presetName:Je,onPresetNameChange:be,diffSummary:Re,assistantPromptVersion:F,decompositionPromptVersion:oe,showSettingsMode:Ce,showAutoRunsMode:$e,showAssistantMode:dt,showProgressMode:st,showCommentsMode:Dt,onLog:ot}){const[H,Me]=y.useState({...sa,fromLocal:$c()}),[We,ne]=y.useState(""),[Z,M]=y.useState(null),[U,L]=y.useState(null),[v,w]=y.useState(null),[re,ie]=y.useState([]),[ae,he]=y.useState("all"),[xe,_e]=y.useState(!1),[we,lt]=y.useState(null),[qt,Xn]=y.useState([]),[wn,nn]=y.useState(""),[Ee,Ot]=y.useState(""),[et,ft]=y.useState(""),[St,rn]=y.useState(da),[W,it]=y.useState(Oc),[Zn,In]=y.useState([]),[Dn,kn]=y.useState(""),[mt,zt]=y.useState([]),[qe,sn]=y.useState(null),[on,Zr]=y.useState(null),[Nr,Er]=y.useState(!1),[es,ln]=y.useState(!1),[an,un]=y.useState(!1),[cn,On]=y.useState(!1),[me,dn]=y.useState(!1),[er,Pr]=y.useState(!1),[Tr,Rr]=y.useState(!1),[jn,tr]=y.useState(!1),[Mr,Cn]=y.useState(""),[nr,Oe]=y.useState(""),[k,q]=y.useState(""),[D,ke]=y.useState([]),[Ke,Lr]=y.useState([]),[Ls,As]=y.useState(""),[fn,ts]=y.useState(null),[ns,Tl]=y.useState(!1),[Is,Ds]=y.useState(!1),[xo,rr]=y.useState(""),[Rl,zn]=y.useState(""),[Fe,sr]=y.useState(String(sa.limit)),[Os,$n]=y.useState(String(Oc.count)),[or,_o]=y.useState(160),[ge,wt]=y.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:wl,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[ue,mn]=y.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),[Ue,Fn]=y.useState({open:!1,title:"",saving:!1,error:""}),[$t,Ar]=y.useState({open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""}),[Et,Un]=y.useState({open:!1,generationId:"",title:"",saving:!1,error:""}),Bn=y.useRef(!1),Hn=y.useRef(null),Kt=W.mode==="saved_user_sessions",rs=y.useMemo(()=>St.find(a=>a.id===W.personalityId)??St[0]??da[0],[W.personalityId,St]),pt=y.useMemo(()=>Zn.filter(a=>a.mode===W.mode),[Zn,W.mode]),kt=y.useMemo(()=>pt.find(a=>a.generation_id===Dn)??pt[0]??null,[Dn,pt]),pn=y.useMemo(()=>xe?re.filter(a=>!a.resolved):re,[re,xe]),Ne=pn.find(a=>a.annotation_id===wn)??null,So=v?.messages.find(a=>a.message_index===ge.messageIndex)??null,zs=y.useMemo(()=>{if(!v||ge.messageIndex<0)return null;for(let a=ge.messageIndex-1;a>=0;a-=1){const c=v.messages[a];if(c?.role==="user")return c}return null},[ge.messageIndex,v]),ve=y.useMemo(()=>{const a=new Map;for(const c of Ke)c.message_id&&a.set(c.message_id,c);return a},[Ke]),$s=ue.messageIndex>=0?D[ue.messageIndex]??null:null,Fs=y.useMemo(()=>{if(ue.messageIndex<0)return null;for(let a=ue.messageIndex-1;a>=0;a-=1){const c=D[a];if(c?.role==="user")return c}return null},[ue.messageIndex,D]),Ft=y.useMemo(()=>{const a=pn.map(p=>({source:"autorun",key:`autorun:${p.annotation_id}`,updated_at:p.updated_at,rating:p.rating,autorun:p,assistant:null})),c=Ke.map(p=>({source:"assistant_live",key:`assistant:${p.annotation_id}`,updated_at:p.updated_at,rating:p.rating,autorun:null,assistant:p}));return[...a,...c].sort((p,j)=>Date.parse(j.updated_at)-Date.parse(p.updated_at))},[Ke,pn]),Us=y.useMemo(()=>{if(Ft.length===0)return null;const a=Ft.reduce((c,p)=>c+p.rating,0)/Ft.length;return Number(a.toFixed(2))},[Ft]),ss=y.useMemo(()=>{const a=[...Z?.items??[]];return qe&&a.unshift(Jc(qe)),Ee&&!a.some(c=>c.run_id===Ee)&&U?.run&&a.unshift(U.run),a},[qe,Z?.items,U?.run,Ee]),J=y.useCallback(a=>{ot?.(`[autoruns] ${a}`)},[ot]),lr=y.useCallback(async a=>{const c=String(a??"").trim();if(!c){Lr([]);return}try{const p=await Pe.loadAssistantAnnotations({session_id:c,limit:400});Lr(p.items??[])}catch(p){const j=p instanceof Error?p.message:String(p);J(`Assistant live annotations load error: ${j}`)}},[J]),hn=y.useCallback(a=>{mn(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),Ut=y.useCallback(a=>{Fn(c=>c.saving&&!a?.force?c:{open:!1,title:"",saving:!1,error:""})},[]),Bt=y.useCallback(a=>{Ar(c=>c.saving&&!a?.force?c:{open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""})},[]),Ht=y.useCallback(a=>{Un(c=>c.saving&&!a?.force?c:{open:!1,generationId:"",title:"",saving:!1,error:""})},[]),Nn=y.useCallback(async(a,c,p)=>{a.stopPropagation(),a.preventDefault();const j=String(c??"").trim();if(j)try{if(navigator?.clipboard?.writeText)await navigator.clipboard.writeText(j);else{const $=document.createElement("textarea");$.value=j,$.setAttribute("readonly","true"),$.style.position="fixed",$.style.opacity="0",document.body.appendChild($),$.select(),document.execCommand("copy"),document.body.removeChild($)}J(`${p} copied: ${j}`)}catch($){const Ae=$ instanceof Error?$.message:String($);Oe(`Копирование ${p}: ${Ae}`),J(`copy ${p} error: ${Ae}`)}},[J]);function Ir(){let a=0;rr(oa[0]);const c=window.setInterval(()=>{a=Math.min(a+1,oa.length-1),rr(oa[a])},650);return()=>window.clearInterval(c)}const En=y.useCallback(()=>{q(""),ke([]),Lr([]),As(""),ts(null),rr(""),zn(""),hn({force:!0}),J("Live-чат ассистента в истории автопрогонов сброшен.")},[hn,J]),Ml=y.useCallback(async()=>{const a=Zf(Ls,fn);if(!a)return;Ds(!0),zn(""),As(""),ke(p=>[...p,{message_id:`autoruns-live-${Date.now()}`,session_id:k||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=Ir();try{const p=await Pe.sendAssistantMessage({connection:i,prompts:z,userMessage:a,sessionId:k||void 0,promptVersion:F,useMock:ns});q(p.session_id),ke(p.conversation),await lr(p.session_id),rr("Ответ готов"),J(`Live-ответ ассистента получен: trace=${p.debug.trace_id}`)}catch(p){const j=p instanceof Error?p.message:String(p);zn(j),rr("Ошибка ассистента"),J(`Live-чат ассистента: ошибка отправки сообщения: ${j}`)}finally{c(),Ds(!1)}},[Ls,fn,k,ns,F,i,lr,J,z]),wo=y.useCallback(()=>{if(!k.trim()||D.length===0){zn("Сначала получите хотя бы один ответ в живой сессии ассистента.");return}zn(""),Fn({open:!0,title:nm(D),saving:!1,error:""})},[D,k]),Dr=y.useCallback(async()=>{const a=k.trim(),c=Ue.title.trim();if(!a){Fn(p=>({...p,error:"Активная сессия ассистента не найдена."}));return}if(!c){Fn(p=>({...p,error:"Укажите название сессии."}));return}Fn(p=>({...p,saving:!0,error:""}));try{const p=[z.systemPrompt,z.developerPrompt,z.domainPrompt,z.schemaNotes,z.fewShotExamples].join("||"),j=await Pe.saveAutoRunAssistantSession({session_id:a,title:c,generated_by:W.generatedBy.trim()||void 0,context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:F,decomposition_prompt_version:oe,prompt_fingerprint:p}});In($=>[j.generation,...$.filter(Ae=>Ae.generation_id!==j.generation.generation_id)]),it($=>({...$,mode:"saved_user_sessions"})),kn(j.generation.generation_id),Ut({force:!0}),J(`Живая сессия сохранена в автопрогоны: ${j.generation.generation_id}`)}catch(p){const j=p instanceof Error?p.message:String(p);Fn($=>({...$,saving:!1,error:j})),J(`Assistant live save error: ${j}`)}},[Ue.title,k,F,W.generatedBy,Ut,i.llmProvider,i.model,oe,J,z.developerPrompt,z.domainPrompt,z.fewShotExamples,z.schemaNotes,z.systemPrompt]),ko=y.useCallback(a=>{const c=a.trim();if(!c){sr(String(H.limit));return}if(!/^\d+$/.test(c)){sr(String(H.limit));return}const p=Number.parseInt(c,10);if(!Number.isFinite(p)){sr(String(H.limit));return}const j=Math.max(1,Math.min(500,p));j!==H.limit&&Me($=>({...$,limit:j})),sr(String(j))},[H.limit]),Bs=y.useCallback(a=>{const c=a.trim();if(!c){$n(String(W.count));return}if(!/^\d+$/.test(c)){$n(String(W.count));return}const p=Number.parseInt(c,10);if(!Number.isFinite(p)){$n(String(W.count));return}const j=Math.max(1,Math.min(200,p));j!==W.count&&it($=>({...$,count:j})),$n(String(j))},[W.count]),Or=y.useCallback(a=>{_o(zc(a))},[]),Hs=y.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Or(c)},[Or]),zr=y.useCallback(async()=>{tr(!0);try{const a=await Pe.loadAutoRunAnnotations({limit:800,manual_case_decision:ae});ie(a.items),lt(a.manual_case_decision_schema??null),Xn(a.available_manual_case_decisions??[]),nn(c=>a.items.length===0?"":a.items.some(p=>p.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){J(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{tr(!1)}},[ae,J]),Qt=y.useCallback(async()=>{On(!0);try{const a=await Pe.loadAutoRunAutogenHistory({limit:180});In(a.items)}catch(a){J(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{On(!1)}},[J]),ir=y.useCallback(async()=>{try{const c=(await Pe.loadAutoRunAutogenPersonalityCatalog()).items.map(p=>({id:String(p.id??"").trim(),label:String(p.label??"").trim(),domain:typeof p.domain=="string"?p.domain.trim():"",defaultPrompt:String(p.default_prompt??"").trim()})).filter(p=>p.id.length>0&&p.label.length>0);if(c.length===0)return;rn(c.map(p=>({id:p.id,label:p.label,domain:p.domain||"",defaultPrompt:p.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){J(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[J]),ht=y.useCallback(async()=>{un(!0);try{const a=await Pe.loadAutoRunPostAnalysis({run_id:Ee&&!Ms(Ee)?Ee:void 0,limit_per_queue:30,annotation_limit:1500,from:kl(H.fromLocal),to:kl(H.toLocal),target:H.target,mode:H.mode,use_mock:H.useMock,prompt_contains:H.promptContains.trim()||void 0});Zr(a)}catch(a){J(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),Zr(null)}finally{un(!1)}},[H.fromLocal,H.mode,H.promptContains,H.target,H.toLocal,H.useMock,J,Ee]),os=y.useCallback(async()=>{Er(!0),Oe("");try{if(W.mode==="saved_user_sessions")throw new Error("Пользовательские сессии сохраняются из живого чата, а не генерируются автоматически.");const a=W.personalityPrompts[W.personalityId]??"",c=[z.systemPrompt,z.developerPrompt,z.domainPrompt,z.schemaNotes,z.fewShotExamples].join(` -`).slice(0,900),p=await Pe.generateAutoRunQuestions({mode:W.mode,count:W.count,domain:rs.domain||void 0,persist_to_eval_cases:W.persistToEvalCases,generated_by:W.generatedBy.trim()||void 0,llm:{llm_provider:i.llmProvider,api_key:i.apiKey,model:i.model,base_url:i.baseUrl,temperature:i.temperature,max_output_tokens:i.maxOutputTokens},context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:F,decomposition_prompt_version:oe,prompt_fingerprint:c,autogen_personality_id:rs.id,autogen_personality_prompt:a.trim()||void 0}});J(`Generated ${p.generation.count} questions (${p.generation.mode}) id=${p.generation.generation_id}`+(p.generation.saved_case_set_file?` saved=${p.generation.saved_case_set_file}`:"")),kn(p.generation.generation_id),zt([...p.generation.questions??[]]),await Qt()}catch(a){const c=a instanceof Error?a.message:String(a);Oe(`Автогенерация: ${c}`),J(`Autogen generate error: ${c}`)}finally{Er(!1)}},[F,W.count,W.generatedBy,W.mode,W.personalityId,W.personalityPrompts,W.persistToEvalCases,i.apiKey,i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature,oe,Qt,J,z.developerPrompt,z.domainPrompt,z.fewShotExamples,z.schemaNotes,z.systemPrompt,rs.domain,rs.id]),$r=y.useCallback(async(a,c)=>{if(Ms(a)){const p=Bc(a);if(qe&&qe.job_id===p){const j=yo(qe,c);Ot(a),ft(j.caseId),w(j.dialog);return}w(null);return}Rr(!0);try{const p=await Pe.loadAutoRunCaseDialog(a,c);w(p)}catch(p){const j=p instanceof Error?p.message:String(p);Oe(`Диалог кейса: ${j}`),w(null),J(`Dialog load error for ${a}/${c}: ${j}`)}finally{Rr(!1)}},[qe,J]),Pn=y.useCallback(async(a,c)=>{if(Ms(a)){const p=Bc(a);if(qe&&qe.job_id===p){const j=yo(qe,c??_t);Ot(a),ft(j.caseId),L(j.detail),w(j.dialog);return}Ot(a),ft(""),L(null),w(null);return}Pr(!0);try{const p=await Pe.loadAutoRunDetail(a);L(p);const j=(c&&(c===_t||p.cases.some($=>$.case_id===c))?c:"")||(p.cases.length>0?_t:"")||"";Ot(a),ft(j),j?await $r(a,j):w(null)}catch(p){const j=p instanceof Error?p.message:String(p);Oe(`Детализация прогона: ${j}`),L(null),w(null),J(`Run detail load error for ${a}: ${j}`)}finally{Pr(!1)}},[qe,$r,J]),Qn=y.useCallback(async a=>{dn(!0),Oe("");try{const c=await Pe.loadAutoRunsHistory({from:kl(H.fromLocal),to:kl(H.toLocal),target:H.target,mode:H.mode,use_mock:H.useMock,prompt_contains:H.promptContains.trim()||void 0,limit:H.limit});if(M(c),c.items.length===0){Ot(""),ft(""),L(null),w(null);return}const p=a?.keepSelection??!0,j=a?.preferredRunId??"",$=a?.preferredCaseId??"",Ae=p&&j&&c.items.some(at=>at.run_id===j)?j:c.items[0].run_id;await Pn(Ae,p?$:void 0),ht()}catch(c){const p=c instanceof Error?c.message:String(c);Oe(`История прогонов: ${p}`),J(`History load error: ${p}`)}finally{dn(!1)}},[H.fromLocal,H.limit,H.mode,H.promptContains,H.target,H.toLocal,H.useMock,ht,Pn,J]),Pt=y.useCallback(()=>{Hn.current!==null&&(window.clearTimeout(Hn.current),Hn.current=null)},[]),Fr=y.useCallback(async a=>{try{const c=await Pe.loadEvalRunAsyncStatus(a);sn(c.job);const p=Cl(a);if(Ee===p){const j=yo(c.job,et||_t);L(j.detail),w(j.dialog),ft(j.caseId)}if(c.job.status==="completed"){Pt(),ln(!1);const j=c.job.report_summary?.run_id??c.job.run_id;await Qn({keepSelection:!0,preferredRunId:j||Ee,preferredCaseId:_t}),await Qt(),sn(null);return}if(c.job.status==="failed"){Pt(),ln(!1),Oe(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),J(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}Pt(),Hn.current=window.setTimeout(()=>{Fr(a)},500)}catch(c){Pt(),ln(!1);const p=c instanceof Error?c.message:String(c);Oe(`Запуск прогонов: ${p}`),J(`Autogen async status error: ${p}`)}},[Qt,Qn,J,et,Ee,Pt]),jo=y.useCallback(async()=>{Pt(),ln(!0),Oe("");try{const a=kt;if(!a)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const c=mt.map(Vs=>Vs.trim()).filter(Vs=>Vs.length>0);if(c.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const p=H.useMock==="true",j=la(We),$=a.mode==="saved_user_sessions",at=(await Pe.startEvalRunAsync({connection:i,prompts:z,promptVersion:F,mode:"single-pass-strict",caseSetFile:$?void 0:a.saved_case_set_file??void 0,useMock:p,evalTarget:"assistant_stage1",questions:$?void 0:c,scenarioQuestions:$?c:void 0,scenarioTitle:$?a.title??void 0:void 0,analysisDate:$?void 0:j||void 0})).job;sn(at);const dr=Cl(at.job_id),bs=yo(at,_t);Ot(dr),ft(bs.caseId),L(bs.detail),w(bs.dialog),J(`Запущен async-прогон job=${at.job_id}, run_id=${at.run_id}, вопросов=${c.length}`+(a.saved_case_set_file?`, base_case_set=${a.saved_case_set_file}`:"")+($?", replay_mode=saved_user_session_scenario":j?`, analysis_date=${j}`:", analysis_date=current_state")),Fr(at.job_id)}catch(a){const c=a instanceof Error?a.message:String(a);Oe(`Запуск прогонов: ${c}`),J(`Autogen run error: ${c}`),ln(!1)}},[We,F,i,mt,H.useMock,J,Fr,z,kt,Pt]),Tn=y.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??et,p=a.case_message_index??a.message_index;wt({open:!0,caseId:c,caseMessageIndex:p,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??wl,annotationAuthor:a.annotation?.annotation_author??W.generatedBy,saving:!1,error:""})},[W.generatedBy,et]),ar=y.useCallback(a=>{wt(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:wl,annotationAuthor:W.generatedBy,saving:!1,error:""})},[W.generatedBy]),ls=y.useCallback(async()=>{const a=Ee,c=ge.caseId,p=ge.caseMessageIndex;if(!(!a||!c||p<0)){if(Ms(a)){wt(j=>({...j,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ge.comment.trim()){wt(j=>({...j,error:"Добавьте комментарий."}));return}wt(j=>({...j,saving:!0,error:""}));try{await Pe.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:p,rating:ge.rating,comment:ge.comment.trim(),manual_case_decision:ge.manualCaseDecision,annotation_author:ge.annotationAuthor.trim()||void 0}),ar({force:!0}),Promise.all([Pn(a,et),zr(),ht()]).catch(j=>{const $=j instanceof Error?j.message:String(j);Oe(`Обновление после комментария: ${$}`),J(`Comment refresh error: ${$}`)})}catch(j){wt($=>({...$,saving:!1,error:j instanceof Error?j.message:String(j)}))}}},[ar,ge.annotationAuthor,ge.caseId,ge.caseMessageIndex,ge.comment,ge.manualCaseDecision,ge.rating,zr,ht,Pn,J,et,Ee]),Co=y.useCallback(a=>a.role==="assistant",[]),is=y.useCallback(a=>a.role==="assistant"&&ve.has(a.message_id),[ve]),as=y.useCallback((a,c)=>{if(a.role!=="assistant")return;const p=k.trim(),j=String(a.session_id??"").trim();if(!(p||j)){zn("Сначала получите ответ ассистента в активной сессии.");return}!p&&j&&q(j);const Ae=ve.get(a.message_id)??null;zn(""),mn({open:!0,messageIndex:c,rating:Ae?.rating??3,comment:Ae?.comment??"",annotationAuthor:Ae?.annotation_author??"manual_reviewer",saving:!1,error:""})},[ve,k]),No=y.useCallback(async()=>{if(ue.messageIndex<0)return;if(!ue.comment.trim()){mn(p=>({...p,error:"Добавьте комментарий."}));return}const a=D[ue.messageIndex]??null,c=k.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){mn(p=>({...p,error:"Сессия ассистента не найдена."}));return}mn(p=>({...p,saving:!0,error:""}));try{const p=await Pe.saveAssistantAnnotation({session_id:c,message_index:ue.messageIndex,rating:ue.rating,comment:ue.comment.trim(),annotation_author:ue.annotationAuthor.trim()||void 0});Lr(j=>{const $=[...j],Ae=$.findIndex(at=>at.annotation_id===p.annotation.annotation_id);return Ae>=0?$[Ae]=p.annotation:$.unshift(p.annotation),$.sort((at,dr)=>Date.parse(dr.updated_at)-Date.parse(at.updated_at))}),hn({force:!0})}catch(p){const j=p instanceof Error?p.message:String(p);mn($=>({...$,saving:!1,error:j}))}},[ue.annotationAuthor,ue.comment,ue.messageIndex,ue.rating,D,k,hn]),jt=y.useCallback(a=>{if(!kt||kt.mode!=="saved_user_sessions")return;const c=mt[a]??"";Ar({open:!0,generationId:kt.generation_id,questionIndex:a,questionText:c,saving:!1,error:""})},[mt,kt]),ur=y.useCallback(async()=>{const a=$t.generationId,c=$t.questionIndex;if(!a||c<0)return;const p=mt.filter((j,$)=>$!==c);if(p.length===0){Ar(j=>({...j,error:"Нельзя удалить последний вопрос из сохраненной сессии."}));return}Ar(j=>({...j,saving:!0,error:""}));try{const j=await Pe.updateAutoRunAutogenQuestions({generation_id:a,questions:p});In($=>$.map(Ae=>Ae.generation_id===a?j.generation:Ae)),zt(j.generation.questions),Bt({force:!0}),J(`Обновлена сохраненная сессия: ${a}`)}catch(j){const $=j instanceof Error?j.message:String(j);Ar(Ae=>({...Ae,saving:!1,error:$})),J(`Saved session question delete error: ${$}`)}},[Bt,mt,J,$t.generationId,$t.questionIndex]),Qs=y.useCallback(a=>{Un({open:!0,generationId:a.generation_id,title:a.title??`${ia(a.mode)} ${tn(a.created_at)}`,saving:!1,error:""})},[]),Ur=y.useCallback(async()=>{const a=Et.generationId.trim();if(a){Un(c=>({...c,saving:!0,error:""}));try{const c=await Pe.deleteAutoRunAutogenHistoryRecord(a);In(p=>p.filter(j=>j.generation_id!==c.generation_id)),Ht({force:!0}),J(`Удален набор автопрогона: ${c.generation_id}`+(c.deleted_files.length>0?`, files=${c.deleted_files.length}`:""))}catch(c){const p=c instanceof Error?c.message:String(c);Un(j=>({...j,saving:!1,error:p})),J(`Autogen record delete error: ${p}`)}}},[Et.generationId,Ht,J]),Eo=y.useCallback(a=>{ie(c=>c.map(p=>p.annotation_id===a.annotation_id?{...p,...a}:p)),w(c=>c&&{...c,annotations:c.annotations.map(p=>p.annotation_id===a.annotation_id?a:p),messages:c.messages.map(p=>!p.annotation||p.annotation.annotation_id!==a.annotation_id?p:{...p,commented:!0,annotation:a})})},[]),us=y.useCallback(async(a,c)=>{if(a.annotation_id){if(Ms(a.run_id)){Oe("Статус выполнения можно менять только для завершённых прогонов.");return}Cn(a.annotation_id);try{const p=await Pe.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:W.generatedBy||void 0});Eo(p.annotation),ht()}catch(p){const j=p instanceof Error?p.message:String(p);Oe(`Смена статуса кейса: ${j}`),J(`Annotation resolve toggle error: ${j}`)}finally{Cn("")}}},[Eo,W.generatedBy,ht,J]),cs=y.useCallback(async a=>{nn(a.annotation_id),await Pn(a.run_id,a.case_id),Z?.items.some(c=>c.run_id===a.run_id)||Oe("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[Z?.items,Pn]);y.useEffect(()=>{Bn.current||(Bn.current=!0,Qn({keepSelection:!1}),Qt(),ir(),ht())},[Qt,ir,Qn,ht]),y.useEffect(()=>{Bn.current&&zr()},[ae,zr]),y.useEffect(()=>{nn(a=>pn.length===0?"":pn.some(c=>c.annotation_id===a)?a:pn[0].annotation_id)},[pn]),y.useEffect(()=>{kn(a=>pt.length===0?"":a&&pt.some(c=>c.generation_id===a)?a:pt[0].generation_id)},[pt]),y.useEffect(()=>{if(!kt){zt([]);return}zt([...kt.questions])},[kt]),y.useEffect(()=>{sr(String(H.limit))},[H.limit]),y.useEffect(()=>{$n(String(W.count))},[W.count]),y.useEffect(()=>{if(!k.trim()){Lr([]);return}lr(k)},[k,lr]),y.useEffect(()=>{if(!qe)return;const a=Cl(qe.job_id);if(Ee!==a)return;const c=yo(qe,et||_t);L(c.detail),w(c.dialog),ft(c.caseId)},[qe,et,Ee]),y.useEffect(()=>()=>{Pt()},[Pt]),y.useEffect(()=>{St.length!==0&&it(a=>{let c=!1;const p={...a.personalityPrompts};for(const $ of St)(typeof p[$.id]!="string"||p[$.id].trim().length===0)&&(p[$.id]=$.defaultPrompt,c=!0);let j=a.personalityId;return St.some($=>$.id===a.personalityId)||(j=St[0].id,c=!0),c?{...a,personalityId:j,personalityPrompts:p}:a})},[St]),y.useEffect(()=>{const a=localStorage.getItem(Ic);if(a)try{const c=JSON.parse(a);if(c.filters){const p=c.filters;Me(j=>({...j,...p,limit:typeof p.limit=="number"?Math.max(1,Math.min(500,p.limit)):j.limit}))}typeof c.analysisDate=="string"&&ne(la(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&_o(zc(c.autogenPersonalityPromptHeight)),c.autoGenSettings&&it(p=>{const j={...p.personalityPrompts},$=c.autoGenSettings?.personalityPrompts??{};for(const[at,dr]of Object.entries($))typeof dr=="string"&&at.trim().length>0&&(j[at.trim()]=dr);const Ae=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():p.personalityId;return{...p,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"||c.autoGenSettings?.mode==="saved_user_sessions"?c.autoGenSettings.mode:p.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):p.count,personalityId:Ae,personalityPrompts:j,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:p.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:p.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&he(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&_e(c.hideResolvedAnnotations)}catch{}},[]);const cr=y.useCallback(()=>{const a={filters:H,analysisDate:We,autogenPersonalityPromptHeight:or,autoGenSettings:{mode:W.mode,count:W.count,personalityId:W.personalityId,personalityPrompts:W.personalityPrompts,persistToEvalCases:W.persistToEvalCases,generatedBy:W.generatedBy},annotationDecisionFilter:ae,hideResolvedAnnotations:xe};localStorage.setItem(Ic,JSON.stringify(a))},[We,ae,W,or,H,xe]);return y.useEffect(()=>{const a=()=>{cr(),J("Сохранены настройки панели автопрогонов.")};return window.addEventListener(Dc,a),()=>{window.removeEventListener(Dc,a)}},[J,cr]),l.jsxs(Pl,{className:"autoruns-frame",title:"",hideHeader:!0,children:[l.jsxs("div",{className:"autoruns-columns",children:[Ce?l.jsxs("section",{className:"autoruns-col autoruns-settings-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Настройки"})}),l.jsxs("div",{className:"autoruns-settings-stack",children:[l.jsx(Yf,{embedded:!0,value:i,modelOptions:g,modelsBusy:f,onChange:A,onReloadModels:Q,onSaveLocalConfig:le,onTestConnection:te,lastStatus:R,busy:E}),l.jsx(Xf,{embedded:!0,value:z,onChange:Y,presets:X,selectedPresetId:ee,onSelectPreset:Te,onLoadPreset:ce,onSavePreset:de,onResetDefaults:pe,onDiffPrevious:Qe,presetName:Je,onPresetNameChange:be,diffSummary:Re})]})]}):null,$e?l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Автопрогоны"})}),l.jsx("h4",{children:"Настройки выборки"}),l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Дата с",l.jsx("input",{type:"datetime-local",value:H.fromLocal,onChange:a=>Me(c=>({...c,fromLocal:a.target.value}))})]}),l.jsxs("label",{children:["Дата по",l.jsx("input",{type:"datetime-local",value:H.toLocal,onChange:a=>Me(c=>({...c,toLocal:a.target.value}))})]}),l.jsxs("label",{children:["Целевой контур",l.jsxs("select",{value:H.target,onChange:a=>Me(c=>({...c,target:a.target.value})),children:[l.jsx("option",{value:"all",children:"все"}),(Z?.available.targets??[]).map(a=>l.jsx("option",{value:a,children:a},a))]})]}),l.jsxs("label",{children:["Режим",l.jsxs("select",{value:H.mode,onChange:a=>Me(c=>({...c,mode:a.target.value})),children:[l.jsx("option",{value:"all",children:"все"}),(Z?.available.modes??[]).map(a=>l.jsx("option",{value:a,children:a},a))]})]}),l.jsxs("label",{children:["Использовать mock",l.jsxs("select",{value:H.useMock,onChange:a=>Me(c=>({...c,useMock:a.target.value})),children:[l.jsx("option",{value:"any",children:"любой"}),l.jsx("option",{value:"true",children:"да"}),l.jsx("option",{value:"false",children:"нет"})]})]}),l.jsxs("label",{children:["Лимит",l.jsx("input",{type:"number",min:1,max:500,value:Fe,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&sr(c)},onBlur:a=>ko(a.target.value),onKeyDown:a=>{a.key==="Enter"&&ko(a.target.value)}})]}),l.jsxs("label",{className:"full-width",children:["Версия промпта содержит",l.jsx("input",{value:H.promptContains,onChange:a=>Me(c=>({...c,promptContains:a.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),l.jsx("datalist",{id:"autoruns-prompt-versions",children:(Z?.available.prompt_versions??[]).map(a=>l.jsx("option",{value:a},a))}),l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",disabled:me,onClick:()=>{Qn({keepSelection:!1})},children:me?"Обновляю...":"Применить"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>{Me({...sa,fromLocal:$c()}),Oe("")},children:"Сбросить фильтры"})]}),l.jsx("h4",{children:"Контур генерации"}),l.jsxs("div",{className:"autoruns-meta-list",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Провайдер:"}),l.jsx("strong",{children:i.llmProvider})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Модель:"}),l.jsx("strong",{children:i.model||"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Промпт ассистента:"}),l.jsx("strong",{children:F})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Промпт декомпозиции:"}),l.jsx("strong",{children:oe})]})]}),l.jsx("h4",{children:"Автопрогоны"}),l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Режимы",l.jsxs("select",{value:W.mode,onChange:a=>it(c=>({...c,mode:a.target.value})),children:[l.jsx("option",{value:"codex_creative",children:"codex_creative"}),l.jsx("option",{value:"qwen_seed",children:"qwen_seed"}),l.jsx("option",{value:"saved_user_sessions",children:"Пользовательские сессии"})]})]}),Kt?null:l.jsxs(l.Fragment,{children:[l.jsxs("label",{children:["Кол-во",l.jsx("input",{type:"number",min:1,max:200,value:Os,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&$n(c)},onBlur:a=>Bs(a.target.value),onKeyDown:a=>{a.key==="Enter"&&Bs(a.target.value)}})]}),l.jsxs("label",{children:["Личность автогенерации",l.jsx("select",{value:W.personalityId,onChange:a=>it(c=>({...c,personalityId:a.target.value})),children:St.map(a=>l.jsx("option",{value:a.id,children:a.label},a.id))})]}),l.jsxs("label",{children:["Кто генерирует",l.jsx("input",{value:W.generatedBy,onChange:a=>it(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),l.jsxs("label",{className:"full-width",children:["Промпт личности",l.jsx("textarea",{className:"autoruns-personality-prompt",value:W.personalityPrompts[W.personalityId]??"",onChange:a=>it(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${or}px`},onMouseUp:Hs,onTouchEnd:Hs})]}),l.jsxs("label",{className:"checkbox-row",children:[l.jsx("input",{type:"checkbox",checked:W.persistToEvalCases,onChange:a=>it(c=>({...c,persistToEvalCases:a.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]})]}),Kt?null:l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Дата анализа (срез)",l.jsx("input",{type:"date",value:We,onChange:a=>ne(la(a.target.value))})]}),l.jsx("div",{className:"button-row",children:l.jsx("button",{type:"button",className:"tab",disabled:!We,onClick:()=>ne(""),children:"Сбросить дату среза"})})]}),l.jsxs("div",{className:"button-row",children:[Kt?null:l.jsxs(l.Fragment,{children:[l.jsx("button",{type:"button",disabled:Nr,onClick:()=>{os()},children:Nr?"Генерирую...":"Сгенерировать пачку"}),l.jsx("button",{type:"button",className:"tab",disabled:cn,onClick:()=>{Qt()},children:cn?"Обновляю...":"Обновить историю"})]}),l.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:es||mt.length===0||!kt,onClick:()=>{jo()},children:es?"Запускаю...":"Запустить прогон"})]}),l.jsx("div",{className:"autoruns-form-grid",children:l.jsxs("label",{className:"full-width",children:[Kt?"Сохраненная сессия":"Кейс-сет для запуска",l.jsxs("select",{value:Dn,onChange:a=>kn(a.target.value),disabled:pt.length===0,children:[pt.length===0?l.jsx("option",{value:"",children:Kt?"нет сохраненных сессий":"нет генераций"}):null,pt.map(a=>l.jsxs("option",{value:a.generation_id,children:[tn(a.created_at)," | ",a.title??ia(a.mode)," | ",a.count]},a.generation_id))]})]})}),l.jsxs("div",{className:"autoruns-generated-questions",children:[l.jsxs("div",{className:"autoruns-generated-questions-head",children:[l.jsxs("strong",{children:["Вопросы к запуску: ",mt.length]}),l.jsx("button",{type:"button",className:"tab",onClick:()=>zt([...kt?.questions??[]]),disabled:!kt,children:"Восстановить"})]}),mt.length===0?l.jsx("p",{className:"muted",children:Kt?"Список вопросов пуст. Сначала сохраните живую пользовательскую сессию.":"Список вопросов пуст. Сгенерируйте пачку или восстановите из выбранной генерации."}):l.jsx("div",{className:"autoruns-generated-questions-list",children:mt.map((a,c)=>l.jsxs("div",{className:"autoruns-generated-question-item",children:[l.jsxs("span",{children:[c+1,". ",a]}),l.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onClick:()=>{if(Kt){jt(c);return}zt(p=>p.filter((j,$)=>$!==c))},title:"Удалить вопрос из запуска","aria-label":"Удалить вопрос из запуска",children:"×"})]},`${c}-${a.slice(0,24)}`))})]}),l.jsx("p",{className:"muted",children:Kt?"Запуск воспроизводит сохраненную пользовательскую сессию как один последовательный multi-turn сценарий assistant_stage1.":"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."}),l.jsxs("div",{className:"autoruns-autogen-list",children:[cn?l.jsx("p",{className:"muted",children:Kt?"Загружаю сохраненные пользовательские сессии...":"Загружаю историю автогенераций..."}):null,!cn&&pt.length===0?l.jsx("p",{className:"muted",children:Kt?"Сохраненные пользовательские сессии пока пусты.":"История автогенераций пока пустая."}):null,pt.slice(0,30).map(a=>l.jsxs("article",{className:Dn===a.generation_id?"autoruns-autogen-item selected":"autoruns-autogen-item",onClick:()=>kn(a.generation_id),children:[l.jsxs("header",{children:[l.jsx("strong",{children:a.title??tn(a.created_at)}),l.jsxs("div",{className:"autoruns-autogen-card-actions",children:[l.jsx("span",{children:tn(a.created_at)}),l.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:c=>{c.preventDefault(),c.stopPropagation(),Qs(a)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${a.generation_id}`,children:"×"})]})]}),l.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[l.jsx("span",{children:a.generation_id}),l.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{Nn(c,a.generation_id,"set id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Nn(c,a.generation_id,"set id"))},title:"Скопировать id набора","aria-label":`Скопировать id набора ${a.generation_id}`,children:l.jsx(Qc,{})})]}),l.jsxs("div",{className:"autoruns-run-meta",children:["режим=",ia(a.mode)," | count=",a.count]}),a.domain||a.generated_by?l.jsxs("div",{className:"autoruns-run-meta",children:[a.domain?`домен=${a.domain}`:"домен=общий",a.generated_by?` | автор=${a.generated_by}`:""]}):null,a.saved_case_set_file?l.jsxs("div",{className:"autoruns-run-meta",children:["кейс-сет=",a.saved_case_set_file]}):null,(a.questions??[]).length>0?l.jsx("p",{children:a.questions[0]}):null]},a.generation_id))]}),l.jsxs("details",{className:"autoruns-prompt-details",children:[l.jsx("summary",{children:"Копия активного промпта (только чтение)"}),l.jsxs("label",{children:["Системный",l.jsx("textarea",{readOnly:!0,value:z.systemPrompt})]}),l.jsxs("label",{children:["Разработчика",l.jsx("textarea",{readOnly:!0,value:z.developerPrompt})]}),l.jsxs("label",{children:["Доменный",l.jsx("textarea",{readOnly:!0,value:z.domainPrompt})]}),l.jsxs("label",{children:["Заметки по схеме",l.jsx("textarea",{readOnly:!0,value:z.schemaNotes})]}),l.jsxs("label",{children:["Примеры few-shot",l.jsx("textarea",{readOnly:!0,value:z.fewShotExamples})]})]}),nr?l.jsx("p",{className:"error-text",children:nr}):null]}):null,l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Выдача прогонов"})}),l.jsxs("div",{className:"autoruns-stats-grid",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Всего"}),l.jsx("strong",{children:(Z?.stats.runs_total??0)+(qe?1:0)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Средний score"}),l.jsx("strong",{children:jl(Z?.stats.avg_score_index??null)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Тренд"}),l.jsx("strong",{children:Z?Fc(Z.stats.trend):"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Блокеры"}),l.jsx("strong",{children:Z?.stats.blocking_runs??0})]})]}),l.jsxs("div",{className:"autoruns-run-list",children:[ss.map(a=>l.jsxs("button",{type:"button",className:Ee===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{Pn(a.run_id)},children:[l.jsxs("div",{className:"autoruns-run-head",children:[l.jsx("strong",{children:tn(a.run_timestamp)}),l.jsx("span",{children:sm(a.eval_target)})]}),l.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[l.jsx("span",{children:a.run_id}),l.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{Nn(c,a.run_id,"run id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Nn(c,a.run_id,"run id"))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:l.jsx(Qc,{})})]}),l.jsxs("div",{className:"autoruns-run-meta",children:["режим=",a.mode??"нет данных"," | mock=",String(a.use_mock)]}),l.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",a.analysis_date??"current_state"]}),a.llm_provider||a.model?l.jsxs("div",{className:"autoruns-run-meta",children:["llm=",a.llm_provider??"нет данных"," | модель=",a.model??"нет данных"]}):null,l.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",a.prompt_version??"нет данных"]}),l.jsxs("div",{className:"autoruns-run-foot",children:[l.jsxs("span",{children:["оценка: ",jl(a.score_index)]}),l.jsxs("span",{children:["закрыто/открыто: ",a.closed_cases,"/",a.open_cases]})]}),l.jsxs("div",{className:"autoruns-run-foot",children:[l.jsxs("span",{children:["блокеры: ",a.blocking_failures]}),l.jsxs("span",{children:["качество: ",a.quality_failures]})]})]},a.run_id)),ss.length===0?l.jsx("p",{className:"muted",children:"За выбранный диапазон прогонов нет."}):null]})]}),l.jsxs("section",{className:"autoruns-col",children:[l.jsxs("div",{className:"autoruns-col-header",children:[l.jsx("h3",{children:"Диалог прогона"}),l.jsxs("div",{className:"autoruns-dialog-toolbar",children:[l.jsxs("label",{children:["Прогон",l.jsx("select",{value:Ee,onChange:a=>{const c=a.target.value;Pn(c)},children:ss.map(a=>l.jsxs("option",{value:a.run_id,children:[tn(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),l.jsxs("label",{children:["Кейс",l.jsxs("select",{value:et,onChange:a=>{const c=a.target.value;ft(c),Ee&&c&&$r(Ee,c)},children:[(U?.cases.length??0)>0?l.jsx("option",{value:_t,children:"ВСЕ кейсы подряд"}):null,(U?.cases??[]).map(a=>l.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]})]})]}),l.jsxs("div",{className:"autoruns-case-list",children:[(U?.cases.length??0)>0?l.jsxs("button",{type:"button",className:et===_t?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{ft(_t),Ee&&$r(Ee,_t)},children:[l.jsx("span",{children:"ВСЕ кейсы подряд"}),l.jsx("span",{children:U?.cases.length})]},_t):null,(U?.cases??[]).map(a=>l.jsxs("button",{type:"button",className:et===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{ft(a.case_id),Ee&&$r(Ee,a.case_id)},children:[l.jsx("span",{children:a.case_id}),l.jsxs("span",{children:[a.status,a.commented_count>0?` | комм=${a.commented_count}`:""]})]},a.case_id))]}),l.jsxs("div",{className:"autoruns-dialog-view",children:[Tr||er?l.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!Tr&&!er&&(v?.messages.length??0)===0?l.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(v?.messages??[]).map((a,c)=>{const p=a.role==="assistant"?"assistant":"user";return l.jsxs("article",{className:`autoruns-msg ${p}`,children:[l.jsxs("header",{children:[l.jsx("strong",{children:p==="assistant"?"Система":"Модель/вопрос"}),l.jsxs("div",{className:"autoruns-msg-head-actions",children:[a.case_id?l.jsx("span",{className:"autoruns-msg-case-tag",children:a.case_id}):null,l.jsx("span",{children:a.created_at?tn(a.created_at):"нет данных"}),p==="assistant"&&!Ms(Ee)?l.jsxs(l.Fragment,{children:[l.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>Tn(a),title:"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b","aria-label":"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b",children:l.jsx(om,{commented:a.commented})}),a.annotation?l.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{us(a.annotation,!a.annotation.resolved)},disabled:Mr===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:l.jsx(Hc,{resolved:a.annotation.resolved})}):null]}):null]})]}),l.jsx("p",{children:a.text}),p==="assistant"&&a.annotation?l.jsxs("div",{className:"autoruns-msg-annotation",children:[l.jsx("strong",{children:aa(a.annotation.rating)}),l.jsx("span",{children:a.annotation.comment}),l.jsxs("span",{className:"muted",children:[a.annotation.manual_case_decision,a.annotation.annotation_author?` | ${a.annotation.annotation_author}`:""]})]}):null,(a.trace_id||a.reply_type)&&l.jsxs("footer",{children:[a.trace_id?l.jsxs("span",{children:["trace=",a.trace_id]}):null,a.reply_type?l.jsxs("span",{children:["reply_type=",a.reply_type]}):null]})]},a.message_id??`${p}-${c}`)})]})]}),dt?l.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:l.jsx(qf,{sessionId:k,conversation:D,inputValue:Ls,onInputChange:As,selectedContextChip:fn,onSelectContextChip:ts,onClearContextChip:()=>ts(null),useMock:ns,onUseMockChange:Tl,onSend:Ml,onClear:En,onSaveSession:wo,busy:Is,saveBusy:Ue.saving,saveDisabled:!k.trim()||D.length===0||Is,statusText:xo,errorMessage:Rl,showSaveAction:!0,showCommentAction:!0,onCommentAssistantMessage:as,isAssistantMessageCommented:is,canCommentAssistantMessage:Co})}):null,st?l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Прогресс / регресс"})}),l.jsxs("div",{className:"autoruns-stats-grid",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Последний score"}),l.jsx("strong",{children:jl(Z?.stats.latest_score_index??null)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Предыдущий"}),l.jsx("strong",{children:jl(Z?.stats.previous_score_index??null)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Тренд"}),l.jsx("strong",{children:Z?Fc(Z.stats.trend):"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Пробелы качества"}),l.jsx("strong",{children:Z?.stats.quality_gap_runs??0})]})]}),l.jsx("h4",{children:"Покрытие доменов (история)"}),Uc(Z?.stats.domain_coverage??[]),l.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),Uc(U?.coverage.domain_coverage??[]),l.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),an?l.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,an?null:l.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(on?.post_analysis.stats.by_queue??{}).map(([a,c])=>l.jsxs("div",{children:[l.jsx("span",{children:a}),l.jsx("strong",{children:c})]},a))}),l.jsxs("div",{className:"autoruns-autogen-list",children:[(on?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(a=>l.jsxs("article",{className:"autoruns-autogen-item",children:[l.jsxs("header",{children:[l.jsx("strong",{children:a.manual_case_decision}),l.jsxs("span",{children:[a.rating,"/5"]})]}),l.jsxs("div",{className:"autoruns-run-meta",children:[a.domain??"неизвестно"," / ",a.query_class??"неизвестно"]}),l.jsx("p",{children:a.comment})]},a.annotation_id)),!an&&(on?.post_analysis.recommended_regression_candidates.length??0)===0?l.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Dt?l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Комментарии"})}),l.jsx("h4",{children:"Размеченные ответы"}),l.jsxs("div",{className:"autoruns-comment-filter-row",children:[l.jsxs("label",{children:["Фильтр решений",l.jsxs("select",{value:ae,onChange:a=>he(a.target.value),children:[l.jsx("option",{value:"all",children:"все"}),(qt.length>0?qt:we?.enum??[]).map(a=>l.jsx("option",{value:a,children:String(we?.labels?.[a]??a)},a))]})]}),l.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>_e(a=>!a),children:xe?"Показать выполненные":"Скрыть выполненные"})]}),l.jsxs("div",{className:"autoruns-stats-grid",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Комментариев"}),l.jsx("strong",{children:Ft.length})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Средний рейтинг"}),l.jsx("strong",{children:Us===null?"нет данных":`${Us.toFixed(2)} / 5`})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Последний"}),l.jsx("strong",{children:Ft.length>0?tn(Ft[0].updated_at):"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Статус"}),l.jsx("strong",{children:jn?"обновляю":"готово"})]})]}),l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",disabled:jn,onClick:()=>{zr()},children:jn?"Обновляю...":"Обновить список"}),l.jsx("button",{type:"button",className:"tab",disabled:an,onClick:()=>{ht()},children:an?"Идет пост-анализ...":"Обновить пост-анализ"})]}),l.jsxs("div",{className:"autoruns-comments-list",children:[jn?l.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!jn&&Ft.length===0?l.jsx("p",{className:"muted",children:re.length===0&&Ke.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,Ft.map(a=>{if(a.source==="assistant_live"){const p=a.assistant;return l.jsxs("article",{className:"autoruns-comment-item",children:[l.jsxs("div",{className:"autoruns-comment-head",children:[l.jsx("strong",{children:aa(p.rating)}),l.jsx("div",{className:"autoruns-comment-head-actions",children:l.jsx("span",{children:tn(p.updated_at)})})]}),l.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",p.session_id]}),l.jsxs("div",{className:"autoruns-run-meta",children:["msg=",p.message_index]}),l.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",p.annotation_author?` | author=${p.annotation_author}`:""]}),p.context.question_text?l.jsxs("p",{children:["Q: ",p.context.question_text]}):null,p.context.answer_text?l.jsxs("p",{children:["A: ",p.context.answer_text]}):null,l.jsx("p",{children:p.comment})]},a.key)}const c=a.autorun;return l.jsxs("article",{className:wn===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{cs(c)},role:"button",tabIndex:0,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),cs(c))},children:[l.jsxs("div",{className:"autoruns-comment-head",children:[l.jsx("strong",{children:aa(c.rating)}),l.jsxs("div",{className:"autoruns-comment-head-actions",children:[l.jsx("span",{children:tn(c.updated_at)}),l.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:p=>{p.preventDefault(),p.stopPropagation(),us(c,!c.resolved)},disabled:Mr===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:l.jsx(Hc,{resolved:c.resolved})})]})]}),l.jsx("div",{className:"autoruns-run-meta",children:c.run_id}),l.jsxs("div",{className:"autoruns-run-meta",children:["case=",c.case_id," | msg=",c.message_index]}),l.jsxs("div",{className:"autoruns-run-meta",children:["decision=",c.manual_case_decision,c.annotation_author?` | author=${c.annotation_author}`:""]}),c.resolved_at?l.jsxs("div",{className:"autoruns-run-meta",children:["выполнено",": ",tn(c.resolved_at),c.resolved_by?` | by=${c.resolved_by}`:""]}):null,c.context.question_text?l.jsxs("p",{children:["Q: ",c.context.question_text]}):null,c.context.answer_text?l.jsxs("p",{children:["A: ",c.context.answer_text]}):null,l.jsx("p",{children:c.comment})]},a.key)})]}),Ne?l.jsxs(l.Fragment,{children:[l.jsx("h4",{children:"Тех-контекст брака"}),l.jsxs("div",{className:"autoruns-meta-list",children:[l.jsxs("div",{children:[l.jsx("span",{children:"trace:"}),l.jsx("strong",{children:Ne.technical_context.trace_id??"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"reply_type:"}),l.jsx("strong",{children:Ne.technical_context.reply_type??"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"domain:"}),l.jsx("strong",{children:Ne.technical_context.domain??"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"query_class:"}),l.jsx("strong",{children:Ne.technical_context.query_class??"нет данных"})]})]}),l.jsx("h4",{children:"JSON разбор"}),l.jsx(Kc,{value:{annotation_id:Ne.annotation_id,run_id:Ne.run_id,case_id:Ne.case_id,message_index:Ne.message_index,rating:Ne.rating,comment:Ne.comment,manual_case_decision:Ne.manual_case_decision,annotation_author:Ne.annotation_author,resolved:Ne.resolved,resolved_at:Ne.resolved_at,resolved_by:Ne.resolved_by,context:Ne.context,technical_context:Ne.technical_context,case_summary:Ne.case_summary?{case_id:Ne.case_summary.case_id,domain:Ne.case_summary.domain,query_class:Ne.case_summary.query_class,checks:Ne.case_summary.checks,metric_subscores:Ne.case_summary.metric_subscores}:null}})]}):null]}):null]}),Ue.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Ut()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Сохранить ручную сессию"}),l.jsx("p",{className:"muted",children:"Технический чат будет сохранен в автопрогоны как пользовательская multi-turn сессия."}),l.jsxs("label",{children:["Название",l.jsx("input",{value:Ue.title,onChange:a=>Fn(c=>({...c,title:a.target.value})),placeholder:"Например: НДС и склад на март 2020",disabled:Ue.saving})]}),Ue.error?l.jsx("p",{className:"error-text",children:Ue.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{Dr()},disabled:Ue.saving,children:Ue.saving?"Сохраняю...":"Сохранить"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>Ut(),disabled:Ue.saving,children:"Отмена"})]})]})}):null,$t.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Bt()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Удалить вопрос"}),l.jsx("p",{className:"muted",children:"Действительно удалить вопрос из сохраненной пользовательской сессии?"}),l.jsx("p",{className:"autoruns-comment-quote",children:$t.questionText}),$t.error?l.jsx("p",{className:"error-text",children:$t.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{ur()},disabled:$t.saving,children:$t.saving?"Удаляю...":"Да"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>Bt(),disabled:$t.saving,children:"Нет"})]})]})}):null,Et.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Ht()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Удалить сохраненный набор"}),l.jsx("p",{className:"muted",children:"Будет удалена карточка истории и связанный файл кейс-сета на бэке."}),l.jsx("p",{className:"autoruns-comment-quote",children:Et.title}),Et.error?l.jsx("p",{className:"error-text",children:Et.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{Ur()},disabled:Et.saving,children:Et.saving?"Удаляю...":"Да"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>Ht(),disabled:Et.saving,children:"Нет"})]})]})}):null,ue.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&hn()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Комментарий к ответу ассистента"}),l.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),Fs?l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Вопрос пользователя"}),l.jsx("p",{className:"autoruns-comment-quote",children:Fs.text})]}):null,$s?l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Ответ ассистента"}),l.jsx("p",{className:"autoruns-comment-quote",children:$s.text})]}):null,l.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(a=>l.jsx("button",{type:"button",className:ue.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>mn(c=>({...c,rating:a})),disabled:ue.saving,"aria-label":`Оценка ${a}`,children:ue.rating>=a?"●":"○"},a))}),l.jsx("div",{className:"autoruns-form-grid",children:l.jsxs("label",{children:["Автор комментария",l.jsx("input",{value:ue.annotationAuthor,onChange:a=>mn(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ue.saving})]})}),l.jsxs("label",{children:["Комментарий",l.jsx("textarea",{value:ue.comment,onChange:a=>mn(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:ue.saving})]}),ue.error?l.jsx("p",{className:"error-text",children:ue.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{No()},disabled:ue.saving,children:ue.saving?"Сохраняю...":"Готово"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>hn(),disabled:ue.saving,children:"Отмена"})]})]})}):null,ge.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&ar()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Комментарий к ответу системы"}),l.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),So?l.jsxs(l.Fragment,{children:[l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Вопрос пользователя"}),l.jsx("p",{className:"autoruns-comment-quote",children:zs?.text??"Вопрос в диалоге не найден."})]}),l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Ответ системы"}),l.jsx("p",{className:"autoruns-comment-quote",children:So.text})]})]}):null,l.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(a=>l.jsx("button",{type:"button",className:ge.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>wt(c=>({...c,rating:a})),disabled:ge.saving,"aria-label":`Оценка ${a}`,children:ge.rating>=a?"●":"○"},a))}),l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Решение по кейсу",l.jsx("select",{value:ge.manualCaseDecision,onChange:a=>wt(c=>({...c,manualCaseDecision:a.target.value})),disabled:ge.saving,children:(qt.length>0?qt:we?.enum??[wl]).map(a=>l.jsx("option",{value:a,children:String(we?.labels?.[a]??a)},a))})]}),l.jsxs("label",{children:["Автор комментария",l.jsx("input",{value:ge.annotationAuthor,onChange:a=>wt(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ge.saving})]})]}),l.jsxs("label",{children:["Комментарий",l.jsx("textarea",{value:ge.comment,onChange:a=>wt(c=>({...c,comment:a.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ge.saving})]}),ge.error?l.jsx("p",{className:"error-text",children:ge.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{ls()},disabled:ge.saving,children:ge.saving?"Сохраняю...":"Готово"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>ar(),disabled:ge.saving,children:"Отмена"})]})]})}):null]})}const im={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},bc={systemPrompt:"Ты semantic-normalizer для бухгалтерского ассистента NDC. Возвращай только JSON по схеме normalized_query_v2_0_2.",developerPrompt:"Сначала делай decomposition сообщения на task fragments, затем определяй domain scope и route-critical flags. Для каждого fragment заполняй execution_readiness + route_status + no_route_reason. Если fragment routable, не оставляй его в no_route.",domainPrompt:"Контур: данные текущего предприятия в 1С/NDC. In-scope: документы, проводки, взаиморасчеты, остатки, периодное закрытие, аномалии и контрольные проверки. Out-of-scope: общая теория, законы и оффтоп.",schemaNotes:"schema_version: normalized_query_v2_0_2. Строгий JSON без дополнительных полей.",fewShotExamples:"Q: Проверь по поставщикам хвосты и разложи цепочку документов/оплат. => fragment in_scope, flags: multi_entity + chain_explanation. Q: Как вообще по ФСБУ? => out_of_scope/generic_accounting."},am={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},ua={colors:{backgroundRgb:"18, 18, 18",mainSurfaceRgb:"25, 25, 25",horizontalSurfaceRgb:"30, 30, 30",focusSurfaceRgb:"35, 35, 35",assistantChipRgb:"18, 18, 18",assistantChipHoverRgb:"44, 44, 44",assistantChipSelectedRgb:"167, 59, 255",assistantChipSelectedTextRgb:"240, 240, 240",activeRgb:"167, 59, 255",activeTextRgb:"240, 240, 240",textMainRgb:"240, 240, 240",textMutedRgb:"166, 166, 166",dangerRgb:"126, 126, 126",scrollbarTrackRgb:"20, 20, 20",scrollbarThumbRgb:"30, 30, 30",scrollbarThumbHoverRgb:"30, 50, 30"},layout:{modeColumnWidthPx:406,modeToggleWidthPx:188}},Vc="ndc_normalizer_session_config_v1",Wc="ndc_autoruns_layout_config_v1",um="ndc-autoruns-save",cm="autoruns",ca="normalizer_v2_0_2",dm="address_query_runtime_v1",fm=["normalized","fragments","scope","flags","route","raw","validation","logs"];function mm(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function pm(i,g){if(!g)return"Previous preset is not selected.";const R=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(E=>i[E]!==g[E]).map(E=>`${E}: ${Math.abs(i[E].length-g[E].length)} chars delta`);return R.length===0?"No changes against previous preset.":`Changed fields: ${R.length}. ${R.join(" | ")}`}function hm(){const[i,g]=y.useState(im),[f,R]=y.useState(bc),[E,A]=y.useState(am),[Q,le]=y.useState(null),[te,z]=y.useState([]),[Y,X]=y.useState([]),[ee,Te]=y.useState("normalized"),[ce,de]=y.useState(!1),[pe,Qe]=y.useState(!1),[Je,be]=y.useState([]),[Re,F]=y.useState(""),[oe,Ce]=y.useState([]),[$e,dt]=y.useState(""),[st,Dt]=y.useState("NDC custom preset"),[ot,H]=y.useState(null),[Me,We]=y.useState(""),[ne,Z]=y.useState(!1),[M,U]=y.useState([]),[L,v]=y.useState(""),[w,re]=y.useState([]),[ie,ae]=y.useState(!1),[he,xe]=y.useState(null),[_e,we]=y.useState(""),[lt,qt]=y.useState(cm),[Xn,wn]=y.useState(!0),[nn,Ee]=y.useState(!0),[Ot,et]=y.useState(!0),[ft,St]=y.useState(!0),[rn,W]=y.useState(!0),[it,Zn]=y.useState(!0),[In,Dn]=y.useState(!0),[kn,mt]=y.useState(!0),[zt,qe]=y.useState(!0),[sn,on]=y.useState(!0),[Zr,Nr]=y.useState(!0),[Er,es]=y.useState(!0),[ln,an]=y.useState(!0),un=y.useRef(!1),cn=y.useRef(!1),On=y.useRef(!1);y.useEffect(()=>{const k=document.documentElement,{colors:q}=ua;k.style.setProperty("--rgb-background",q.backgroundRgb),k.style.setProperty("--rgb-surface-main",q.mainSurfaceRgb),k.style.setProperty("--rgb-surface-horizontal",q.horizontalSurfaceRgb),k.style.setProperty("--rgb-surface-focus",q.focusSurfaceRgb),k.style.setProperty("--rgb-assistant-chip",q.assistantChipRgb),k.style.setProperty("--rgb-assistant-chip-hover",q.assistantChipHoverRgb),k.style.setProperty("--rgb-assistant-chip-selected",q.assistantChipSelectedRgb),k.style.setProperty("--rgb-assistant-chip-selected-text",q.assistantChipSelectedTextRgb),k.style.setProperty("--rgb-active",q.activeRgb),k.style.setProperty("--rgb-active-text",q.activeTextRgb),k.style.setProperty("--rgb-text-main",q.textMainRgb),k.style.setProperty("--rgb-text-muted",q.textMutedRgb),k.style.setProperty("--rgb-danger",q.dangerRgb),k.style.setProperty("--rgb-scrollbar-track",q.scrollbarTrackRgb),k.style.setProperty("--rgb-scrollbar-thumb",q.scrollbarThumbRgb),k.style.setProperty("--rgb-scrollbar-thumb-hover",q.scrollbarThumbHoverRgb),k.style.setProperty("--mode-column-width",`${ua.layout.modeColumnWidthPx}px`),k.style.setProperty("--mode-toggle-width",`${ua.layout.modeToggleWidthPx}px`)},[]);const me=k=>{X(q=>[mm(k),...q].slice(0,300))};y.useEffect(()=>{(async()=>{const D=localStorage.getItem(Vc);if(D)try{const ke=JSON.parse(D);g(Ke=>({...Ke,llmProvider:ke.llmProvider==="local"?"local":"openai",model:ke.model??Ke.model,baseUrl:ke.baseUrl??Ke.baseUrl,temperature:ke.temperature??Ke.temperature,maxOutputTokens:ke.maxOutputTokens??Ke.maxOutputTokens}))}catch{}try{const ke=await Pe.loadSharedConnectionConfig();ke.connection&&ke.connection.llmProvider==="local"&&(g(Ke=>({...Ke,llmProvider:"local",model:ke.connection?.model??Ke.model,baseUrl:ke.connection?.baseUrl??Ke.baseUrl,temperature:ke.connection?.temperature??Ke.temperature,maxOutputTokens:ke.connection?.maxOutputTokens??Ke.maxOutputTokens})),me(`Shared local LLM config loaded: ${ke.connection.model}`))}catch(ke){me(`Shared local config load error: ${ke instanceof Error?ke.message:String(ke)}`)}finally{On.current=!0}})();const q=localStorage.getItem(Wc);if(q)try{const D=JSON.parse(q);(D.uiMode==="assistant"||D.uiMode==="autoruns"||D.uiMode==="decomposition")&&qt("autoruns"),D.activeTab&&fm.includes(D.activeTab)&&Te(D.activeTab),typeof D.showAutorunsSettingsMode=="boolean"&&wn(D.showAutorunsSettingsMode),typeof D.showAutorunsAutoRunsMode=="boolean"&&Ee(D.showAutorunsAutoRunsMode),typeof D.showAutorunsAssistantMode=="boolean"&&et(D.showAutorunsAssistantMode),typeof D.showAutorunsDecompositionMode=="boolean"&&St(D.showAutorunsDecompositionMode),typeof D.showAutorunsProgressMode=="boolean"&&W(D.showAutorunsProgressMode),typeof D.showAutorunsCommentsMode=="boolean"&&Zn(D.showAutorunsCommentsMode),typeof D.showDecompositionConnectionMode=="boolean"&&Dn(D.showDecompositionConnectionMode),typeof D.showDecompositionPromptMode=="boolean"&&mt(D.showDecompositionPromptMode),typeof D.showDecompositionQueryMode=="boolean"&&qe(D.showDecompositionQueryMode),typeof D.showDecompositionOutputMode=="boolean"&&on(D.showDecompositionOutputMode),typeof D.showDecompositionMetricsMode=="boolean"&&Nr(D.showDecompositionMetricsMode),typeof D.showDecompositionHistoryMode=="boolean"&&es(D.showDecompositionHistoryMode),typeof D.showDecompositionRuntimeMode=="boolean"&&an(D.showDecompositionRuntimeMode),D.prompts&&(R(ke=>({...ke,...D.prompts})),cn.current=!0)}catch{}dn(),er(),Pr()},[]),y.useEffect(()=>{if(!On.current||i.llmProvider!=="local")return;const k=window.setTimeout(()=>{Pe.saveSharedConnectionConfig(i).catch(q=>me(`Shared local config sync error: ${q instanceof Error?q.message:String(q)}`))},250);return()=>window.clearTimeout(k)},[i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature]);async function dn(){try{const k=await Pe.loadHistory();z(k.items??[])}catch(k){me(`History load error: ${k instanceof Error?k.message:String(k)}`)}}async function er(){try{const q=(await Pe.loadPresets()).presets??[];if(Ce(q),cn.current){un.current=!0;return}if(un.current)return;const D=q.find(ke=>ke.prompt_version===ca)??q.find(ke=>ke.id==="default-normalizer-v2_0_2");if(!D){un.current=!0,me(`Preset autoload skipped: ${ca} not found.`);return}dt(D.id),H(f),R({systemPrompt:D.systemPrompt,developerPrompt:D.developerPrompt,domainPrompt:D.domainPrompt,schemaNotes:D.schemaNotes??"",fewShotExamples:D.fewShotExamples??""}),un.current=!0,me(`Preset autoloaded: ${D.name} (${D.prompt_version}).`)}catch(k){me(`Presets load error: ${k instanceof Error?k.message:String(k)}`)}}async function Pr(){try{const k=await Pe.listRuns();U(k.items??[])}catch(k){me(`Runs load error: ${k instanceof Error?k.message:String(k)}`)}}function Tr(){if(localStorage.setItem(Vc,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),i.llmProvider==="local"){Pe.saveSharedConnectionConfig(i).then(()=>{me("Local config saved and synced to shared agent config (without API key).")}).catch(k=>{me(`Local config saved, but shared sync failed: ${k instanceof Error?k.message:String(k)}`)});return}me("Local config saved (without API key).")}function Rr(){localStorage.setItem(Wc,JSON.stringify({uiMode:lt,activeTab:ee,showAutorunsSettingsMode:Xn,showAutorunsAutoRunsMode:nn,showAutorunsAssistantMode:Ot,showAutorunsDecompositionMode:ft,showAutorunsProgressMode:rn,showAutorunsCommentsMode:it,showDecompositionConnectionMode:In,showDecompositionPromptMode:kn,showDecompositionQueryMode:zt,showDecompositionOutputMode:sn,showDecompositionMetricsMode:Zr,showDecompositionHistoryMode:Er,showDecompositionRuntimeMode:ln,prompts:f})),window.dispatchEvent(new CustomEvent(um)),me("UI layout and prompts saved.")}async function jn(){de(!0),we("");try{const k=await Pe.testConnection(i);k.provider==="local"?k.model_found===!0?(F(`LOCAL OK - ${k.model}`),me(`Local model is available: ${k.model} (catalog size=${k.models_count??"n/a"}).`)):k.model_found===!1?(F(`LOCAL OK, model not loaded - ${k.model}`),me(`Local server is reachable, but model '${k.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(F(`LOCAL OK (model list unavailable) - ${k.model}`),me("Local server is reachable, but model catalog could not be verified.")):(F(`OPENAI OK - ${k.model}`),me(`OpenAI connection ok: ${k.model}`))}catch(k){const q=k instanceof Error?k.message:String(k);F("Connection error"),we(`Test connection: ${q}`),me(`Test connection error: ${q}`)}finally{de(!1)}}async function tr(){Qe(!0);try{const q=(await Pe.listModels(i)).models??[];be(q),q.length>0&&g(D=>D.model&&q.includes(D.model)?D:{...D,model:q[0]}),me(`Model catalog loaded (${i.llmProvider}): ${q.length} items.`)}catch(k){const q=k instanceof Error?k.message:String(k);me(`Load model list error: ${q}`)}finally{Qe(!1)}}y.useEffect(()=>{be([])},[i.llmProvider,i.baseUrl]);function Mr(){const k=oe.find(q=>q.id===$e);if(!k){me("Preset is not selected.");return}H(f),R({systemPrompt:k.systemPrompt,developerPrompt:k.developerPrompt,domainPrompt:k.domainPrompt,schemaNotes:k.schemaNotes??"",fewShotExamples:k.fewShotExamples??""}),me(`Preset loaded: ${k.name}`)}async function Cn(){try{await Pe.savePreset({name:st||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:f.systemPrompt,developerPrompt:f.developerPrompt,domainPrompt:f.domainPrompt,schemaNotes:f.schemaNotes,fewShotExamples:f.fewShotExamples}),me("Preset saved."),await er()}catch(k){me(`Preset save error: ${k instanceof Error?k.message:String(k)}`)}}function nr(){R(bc),me("Prompt panel reset to defaults.")}function Oe(){const k=pm(f,ot);We(k),me(k)}return y.useEffect(()=>{if(!L){re([]);return}Pe.runTrace(L).then(k=>re(k.items)).catch(k=>me(`Run trace error: ${k instanceof Error?k.message:String(k)}`))},[L]),l.jsxs("main",{className:"app-root app-root-autoruns",children:[l.jsxs("header",{className:"app-topbar",children:[l.jsxs("div",{className:"mode-switch-row",children:[l.jsx("button",{type:"button",className:"tab active",onClick:()=>qt("autoruns"),children:"Управление ассистентом"}),l.jsx("button",{type:"button",className:"tab",onClick:Rr,children:"Сохранить"})]}),l.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[l.jsx("button",{type:"button",className:Xn?"tab active":"tab",onClick:()=>wn(k=>!k),children:"Настройки"}),l.jsx("button",{type:"button",className:nn?"tab active":"tab",onClick:()=>Ee(k=>!k),children:"Автопрогоны"}),l.jsx("button",{type:"button",className:Ot?"tab active":"tab",onClick:()=>et(k=>!k),children:"Режим ассистента"}),l.jsx("button",{type:"button",className:rn?"tab active":"tab",onClick:()=>W(k=>!k),children:"Прогресс/регресс"}),l.jsx("button",{type:"button",className:it?"tab active":"tab",onClick:()=>Zn(k=>!k),children:"Комментарии"})]})]}),l.jsx("div",{className:"layout-grid layout-grid-autoruns",children:l.jsx(lm,{connection:i,modelOptions:Je,modelsBusy:pe,connectionStatus:Re,connectionBusy:ce,onConnectionChange:g,onReloadModels:tr,onSaveLocalConfig:Tr,onTestConnection:jn,prompts:f,onPromptsChange:R,promptPresets:oe,selectedPresetId:$e,onSelectPreset:dt,onLoadPreset:Mr,onSavePreset:Cn,onResetDefaults:nr,onDiffPrevious:Oe,presetName:st,onPresetNameChange:Dt,diffSummary:Me,assistantPromptVersion:dm,decompositionPromptVersion:ca,showSettingsMode:Xn,showAutoRunsMode:nn,showAssistantMode:Ot,showProgressMode:rn,showCommentsMode:it,onLog:me})})]})}Ef.createRoot(document.getElementById("root")).render(l.jsx(_f.StrictMode,{children:l.jsx(hm,{})})); +`).map((E,L)=>{const Q=E.trim();return L===0?Q.replace(/^\d+\.\s*/,""):Q}).filter(Boolean).join(" ").replace(/\s+/g," ").trim();if(!f)return null;const R=Vf(h)||f;return{message_id:i.message_id,source_text:f,anchor_text:R,preview_text:bf(R)}}function Kf(i,h,f,R){return Bf(i.text).map((L,Q)=>{const le=L.split(` +`),te=i.role==="assistant"&&Wf(L),z=te?qf(i,L):null,Y=!!z&&h?.message_id===z?.message_id&&h?.source_text===z?.source_text,X=le.map((ee,Te)=>l.jsx("p",{className:Qf(ee),children:Hf(ee,`line-${Q}-${Te}`)},`line-${Q}-${Te}`));return!te||!z?l.jsx("div",{className:"assistant-msg-block",children:X},`block-${Q}`):l.jsx("div",{className:Y?"assistant-msg-block selectable active":"assistant-msg-block selectable",role:"button",tabIndex:0,onClick:()=>{if(Y){R();return}f(z)},onKeyDown:ee=>{if(!(ee.key!=="Enter"&&ee.key!==" ")){if(ee.preventDefault(),Y){R();return}f(z)}},children:X},`block-${Q}`)})}function Gf({sessionId:i,conversation:h,inputValue:f,onInputChange:R,selectedContextChip:E,onSelectContextChip:L,onClearContextChip:Q,useMock:le,onUseMockChange:te,onSend:z,onClear:Y,onSaveSession:X,busy:ee,saveBusy:Te=!1,saveDisabled:ce=!1,statusText:de,errorMessage:pe,showSaveAction:Qe=!1,showCommentAction:Je=!1,onCommentAssistantMessage:be,isAssistantMessageCommented:Re,canCommentAssistantMessage:F}){const oe=y.useRef(null),Ce=y.useRef(!0),$e=y.useRef(null),[dt,st]=y.useState("idle"),[Dt,ot]=y.useState("чат");function H(ne=!1){oe.current&&(ne&&(Ce.current=!0),oe.current.scrollTop=oe.current.scrollHeight)}y.useEffect(()=>{Ce.current&&H()},[h]),y.useEffect(()=>()=>{$e.current!==null&&window.clearTimeout($e.current)},[]);async function Me(ne){if(h.length===0)return;const Z=Df(i,h,ne),M=await $f(Z);ot(ne==="technical"?"тех":"чат"),st(M?"success":"error"),$e.current!==null&&window.clearTimeout($e.current),$e.current=window.setTimeout(()=>{st("idle")},2200)}function We(){if(!oe.current)return;const ne=oe.current,Z=ne.scrollHeight-ne.scrollTop-ne.clientHeight;Ce.current=Z<16}return l.jsx(Pl,{className:"assistant-panel-frame",title:"Режим ассистента",children:l.jsxs("div",{className:"assistant-live-shell",children:[l.jsxs("div",{className:"assistant-toolbar",children:[l.jsxs("div",{className:"assistant-toolbar-actions",children:[l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Me("default")},disabled:h.length===0,title:"Экспорт только user-facing чата",children:"Скопировать чат"}),l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>{Me("technical")},disabled:h.length===0,title:"Технический экспорт с debug payload",children:"Скопировать техчат"}),Qe?l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>X?.(),disabled:Te||ce,children:Te?"Сохраняю...":"Сохранить"}):null,l.jsx("button",{type:"button",className:"assistant-copy-btn",onClick:()=>Y(),disabled:ee&&h.length===0,children:"Сбросить сессию"})]}),l.jsxs("div",{className:"assistant-toolbar-meta",children:[i?l.jsx("span",{className:"status-chip",children:`session: ${i}`}):null,l.jsxs("div",{className:"assistant-toolbar-meta-right",children:[de?l.jsx("span",{className:"assistant-live-status",children:de}):null,dt==="success"?l.jsxs("span",{className:"assistant-copy-feedback success",children:["Скопировано (",Dt,")"]}):null,dt==="error"?l.jsx("span",{className:"assistant-copy-feedback error",children:"Ошибка копирования"}):null]})]}),pe?l.jsx("p",{className:"error-text assistant-toolbar-error",children:pe}):null]}),l.jsx("div",{ref:oe,className:"assistant-chat-list",onScroll:We,children:h.map((ne,Z)=>{const M=ne.role==="assistant"&&Je&&typeof be=="function"&&(typeof F=="function"?F(ne,Z):!0),U=ne.role==="assistant"&&typeof Re=="function"?Re(ne,Z):!1;return l.jsxs("article",{className:`assistant-msg ${ne.role}`,children:[l.jsxs("header",{className:"assistant-msg-head",children:[l.jsxs("div",{className:"assistant-msg-head-main",children:[l.jsx("strong",{children:Of(ne.role)}),l.jsx("span",{children:zf(ne.created_at)})]}),ne.role==="assistant"&&Je?l.jsx("div",{className:"assistant-msg-head-actions",children:l.jsx("button",{type:"button",className:U?"autoruns-comment-icon assistant-comment-btn commented":"autoruns-comment-icon assistant-comment-btn",onClick:()=>be?.(ne,Z),disabled:!M,title:M?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения","aria-label":M?"Комментировать ответ ассистента":"Комментарий недоступен для этого сообщения",children:l.jsx(Ff,{commented:U})})}):null]}),l.jsx("div",{className:"assistant-msg-body",children:Kf(ne,E,L,Q)}),ne.role==="assistant"&&ne.debug?l.jsxs("details",{className:"assistant-debug",children:[l.jsx("summary",{children:"Показать технический разбор"}),l.jsx(Gc,{value:ne.debug})]}):null]},ne.message_id)})}),l.jsxs("div",{className:"assistant-compose",children:[E?l.jsxs("div",{className:"assistant-compose-context",children:[l.jsx("span",{className:"assistant-compose-context-label",children:"Выбранный объект"}),l.jsxs("div",{className:"assistant-compose-context-pill",title:E.source_text,children:[l.jsx("span",{className:"assistant-compose-context-pill-text",children:E.preview_text}),l.jsx("button",{type:"button",className:"assistant-compose-context-clear",onClick:Q,"aria-label":"Убрать выбранный объект",title:"Убрать выбранный объект",children:"×"})]})]}):null,l.jsxs("label",{className:"full-width",children:["Сообщение",l.jsx("textarea",{className:"assistant-input-textarea",value:f,onChange:ne=>R(ne.target.value),rows:4,placeholder:E?"Продолжите вопрос по выбранному объекту...":"Введите вопрос к данным компании..."})]}),l.jsxs("div",{className:"button-row assistant-send-row",children:[l.jsxs("label",{className:"checkbox-row",children:[l.jsx("input",{type:"checkbox",checked:le,onChange:ne=>te(ne.target.checked)}),"Mock-режим"]}),l.jsx("button",{type:"button",className:"assistant-send-btn",onClick:()=>{H(!0),z()},disabled:ee||!f.trim(),children:ee?"Выполняю...":"Отправить"})]})]})]})})}const Sl="http://127.0.0.1:1234/v1",Lc="https://api.openai.com/v1",Nl="qwen2.5-14b-instruct-1m",ma="unsloth/qwen3-30b-a3b-instruct-2507",Jf=[{value:Nl,label:"Qwen2.5 14B Instruct 1M"},{value:ma,label:"Qwen3 30B A3B Instruct 2507"}];function Yf(i){return i.llmProvider!=="local"?"openai":i.model===ma?"local_qwen3":i.model===Nl?"local_qwen25":"local_custom"}function Xf(i,h){const f=new Map;if(h)for(const R of Jf)f.set(R.value,R);for(const R of i)f.has(R)||f.set(R,{value:R,label:R});return Array.from(f.values())}function Zf({value:i,modelOptions:h,modelsBusy:f,onChange:R,onReloadModels:E,onTestConnection:L,onSaveLocalConfig:Q,lastStatus:le,busy:te,embedded:z=!1}){const Y=i.llmProvider==="local",X=Yf(i),ee=Xf(h,Y),Te=ee.some(F=>F.value===i.model),[ce,de]=y.useState(String(i.temperature)),[pe,Qe]=y.useState(String(i.maxOutputTokens));y.useEffect(()=>{de(String(i.temperature))},[i.temperature]),y.useEffect(()=>{Qe(String(i.maxOutputTokens))},[i.maxOutputTokens]);const Je=F=>{const oe=F.replace(",",".").trim();if(!oe){de(String(i.temperature));return}const Ce=Number(oe);if(!Number.isFinite(Ce)){de(String(i.temperature));return}R({...i,temperature:Ce}),de(String(Ce))},be=F=>{const oe=F.trim();if(!oe){Qe(String(i.maxOutputTokens));return}const Ce=Number.parseInt(oe,10);if(!Number.isFinite(Ce)||Ce<=0){Qe(String(i.maxOutputTokens));return}R({...i,maxOutputTokens:Ce}),Qe(String(Ce))},Re=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid-two",children:[l.jsxs("label",{children:["Provider",l.jsxs("select",{value:X,onChange:F=>{const oe=F.target.value;if(oe==="openai"){R({...i,llmProvider:"openai",baseUrl:Lc});return}if(oe==="local_qwen25"){R({...i,llmProvider:"local",model:Nl,baseUrl:Sl});return}if(oe==="local_qwen3"){R({...i,llmProvider:"local",model:ma,baseUrl:Sl});return}R({...i,llmProvider:"local",model:i.llmProvider==="local"?i.model:Nl,baseUrl:Sl})},children:[l.jsx("option",{value:"openai",children:"OpenAI (token)"}),l.jsx("option",{value:"local_qwen25",children:"Qwen2.5 14B Instruct 1M (Local LM Studio)"}),l.jsx("option",{value:"local_qwen3",children:"Qwen3 30B A3B Instruct 2507 (Local LM Studio)"}),l.jsx("option",{value:"local_custom",children:"Local custom (LM Studio / OpenAI-compatible)"})]})]}),l.jsxs("label",{children:["Model",l.jsxs("select",{value:Te?i.model:"__manual__",onChange:F=>{const oe=F.target.value;oe!=="__manual__"&&R({...i,model:oe})},children:[l.jsx("option",{value:"__manual__",children:"Manual input"}),ee.map(F=>l.jsx("option",{value:F.value,children:F.label},F.value))]})]}),l.jsxs("label",{children:["Model ID (manual / current)",l.jsx("input",{value:i.model,onChange:F=>R({...i,model:F.target.value}),placeholder:"qwen2.5-14b-instruct-1m or unsloth/qwen3-30b-a3b-instruct-2507"})]}),Y?null:l.jsxs("label",{className:"full-width",children:["OpenAI API Key",l.jsx("input",{type:"password",value:i.apiKey,onChange:F=>R({...i,apiKey:F.target.value}),placeholder:"sk-..."})]}),l.jsxs("label",{className:Y?"full-width":void 0,children:[Y?"Local server base URL":"Base URL",l.jsx("input",{value:i.baseUrl,onChange:F=>R({...i,baseUrl:F.target.value}),placeholder:Y?Sl:Lc})]}),l.jsxs("label",{children:["Temperature",l.jsx("input",{type:"number",step:"0.1",value:ce,onChange:F=>de(F.target.value),onBlur:F=>Je(F.target.value),onKeyDown:F=>{F.key==="Enter"&&Je(F.target.value)}})]}),l.jsxs("label",{children:["Max output tokens",l.jsx("input",{type:"number",value:pe,onChange:F=>Qe(F.target.value),onBlur:F=>be(F.target.value),onKeyDown:F=>{F.key==="Enter"&&be(F.target.value)}})]})]}),l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>Q(),children:"Save local config"}),l.jsx("button",{type:"button",onClick:()=>E(),disabled:te||f,children:f?"Loading models...":"Load model list"}),l.jsx("button",{type:"button",onClick:()=>L(),disabled:te,children:te?"Checking...":"Test connection"})]})]});return z?l.jsxs("section",{className:"embedded-panel-section",children:[l.jsxs("div",{className:"embedded-panel-section-header",children:[l.jsxs("div",{children:[l.jsx("h4",{children:"LLM Connector"}),l.jsx("p",{children:"Switch between OpenAI cloud and local OpenAI-compatible server."})]}),l.jsx("span",{className:"status-chip",children:le||"Status: not checked"})]}),Re]}):l.jsx(Pl,{title:"LLM Connector",subtitle:"Switch between OpenAI cloud and local OpenAI-compatible server.",actions:l.jsx("span",{className:"status-chip",children:le||"Status: not checked"}),children:Re})}function em({value:i,onChange:h,presets:f,selectedPresetId:R,onSelectPreset:E,onLoadPreset:L,onSavePreset:Q,onResetDefaults:le,onDiffPrevious:te,presetName:z,onPresetNameChange:Y,diffSummary:X,embedded:ee=!1}){const Te=l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"prompt-manager-grid",children:[l.jsxs("label",{children:["Системный prompt",l.jsx("textarea",{value:i.systemPrompt,onChange:ce=>h({...i,systemPrompt:ce.target.value}),rows:6})]}),l.jsxs("label",{children:["Developer / Instruction prompt",l.jsx("textarea",{value:i.developerPrompt,onChange:ce=>h({...i,developerPrompt:ce.target.value}),rows:6})]}),l.jsxs("label",{children:["Domain prompt",l.jsx("textarea",{value:i.domainPrompt,onChange:ce=>h({...i,domainPrompt:ce.target.value}),rows:6})]}),l.jsxs("label",{children:["Schema notes",l.jsx("textarea",{value:i.schemaNotes,onChange:ce=>h({...i,schemaNotes:ce.target.value}),rows:6})]}),l.jsxs("label",{className:"full-width",children:["Few-shot examples",l.jsx("textarea",{value:i.fewShotExamples,onChange:ce=>h({...i,fewShotExamples:ce.target.value}),rows:8})]})]}),l.jsxs("div",{className:"button-row",children:[l.jsxs("select",{value:R,onChange:ce=>E(ce.target.value),children:[l.jsx("option",{value:"",children:"Выберите preset..."}),f.map(ce=>l.jsx("option",{value:ce.id,children:ce.name},ce.id))]}),l.jsx("button",{type:"button",onClick:()=>L(),children:"Загрузить preset"}),l.jsx("input",{value:z,onChange:ce=>Y(ce.target.value),placeholder:"Имя для сохранения"}),l.jsx("button",{type:"button",onClick:()=>Q(),children:"Сохранить preset"}),l.jsx("button",{type:"button",onClick:()=>te(),children:"Diff с предыдущим"}),l.jsx("button",{type:"button",onClick:()=>le(),children:"Сбросить к default"})]}),X?l.jsx("p",{className:"diff-summary",children:X}):null]});return ee?l.jsxs("section",{className:"embedded-panel-section",children:[l.jsx("div",{className:"embedded-panel-section-header",children:l.jsxs("div",{children:[l.jsx("h4",{children:"Prompt Manager"}),l.jsx("p",{children:"Системный, developer и domain уровни управляются отдельно."})]})}),Te]}):l.jsx(Pl,{title:"Prompt Manager",subtitle:"Системный, developer и domain уровни управляются отдельно.",children:Te})}const sa={fromLocal:"",toLocal:"",target:"all",mode:"all",useMock:"any",promptContains:"",limit:120},wl="needs_dialog_policy_fix",_t="__all__",El="__live__:",Ic="ndc_autoruns_ui_config_v1",Dc="ndc-autoruns-save",oa=["Анализ запроса","Получение данных","Подготовка ответа"];function tm(i,h){const f=i.trim();if(!f)return"";if(!h)return f;const R=f.toLowerCase(),E=h.anchor_text.trim(),L=E.toLowerCase();return L&&R.includes(L)?f:`По выбранному объекту "${E}": ${f}`}const da=[{id:"general",label:"Общий контур",domain:"",defaultPrompt:"Генерируй реалистичные живые вопросы бухгалтера по 1С. Добавляй разговорные формулировки и опечатки, но сохраняй бизнес-смысл."}];function nm(i=da){return i.reduce((h,f)=>(h[f.id]=f.defaultPrompt,h),{})}const Oc={mode:"codex_creative",count:24,personalityId:"general",personalityPrompts:nm(),persistToEvalCases:!0,generatedBy:"manual_reviewer"};function la(i){const h=String(i??"").trim();return/^\d{4}-\d{2}-\d{2}$/.test(h)?h:""}function zc(i){const h=typeof i=="number"&&Number.isFinite(i)?Math.trunc(i):160;return Math.max(110,Math.min(520,h))}function rm(i){const h=i.getFullYear(),f=String(i.getMonth()+1).padStart(2,"0"),R=String(i.getDate()).padStart(2,"0"),E=String(i.getHours()).padStart(2,"0"),L=String(i.getMinutes()).padStart(2,"0");return`${h}-${f}-${R}T${E}:${L}`}function $c(){const i=new Date;return i.setDate(i.getDate()-14),rm(i)}function kl(i){if(!i.trim())return;const h=Date.parse(i);if(Number.isFinite(h))return new Date(h).toISOString()}function tn(i){if(!i)return"нет данных";const h=Date.parse(i);return Number.isFinite(h)?new Date(h).toLocaleString("ru-RU"):i}function ia(i){return i==="saved_user_sessions"?"Пользовательские сессии":i}function Yc(i){return i?i.context?.agent_run===!0||i.context?.saved_case_set_kind==="agent_semantic_scenario"?!0:typeof i.title=="string"&&i.title.trim().toUpperCase().startsWith("AGENT"):!1}function Fc(i){const h=i.title??tn(i.created_at);return Yc(i)&&!h.trim().toUpperCase().startsWith("AGENT")?`AGENT | ${h}`:h}function sm(i){const h=i[i.length-1];return`Ручная сессия ${tn(h?.created_at??new Date().toISOString())}`}function om(i,h){return h<=0?0:Math.max(0,Math.min(100,Number((i/h*100).toFixed(1))))}function jl(i){return typeof i!="number"?"нет данных":`${i.toFixed(1)}%`}function lm(i){return i==="assistant_stage1"?"assistant/s1":i==="assistant_stage2"?"assistant/s2":i==="assistant_p0"?"assistant/p0":i}function Uc(i){return i==="up"?"Рост":i==="down"?"Регресс":"Без изменений"}function aa(i){const h=Math.max(1,Math.min(5,Math.round(i)));return`${"●".repeat(h)}${"○".repeat(5-h)}`}function Bc(i){return i.length===0?l.jsx("p",{className:"muted",children:"Покрытие доменов пока не сформировано."}):l.jsx("div",{className:"autoruns-coverage-list",children:i.map(h=>{const f=om(h.closed_cases,h.total_cases);return l.jsxs("div",{className:"autoruns-coverage-item",children:[l.jsxs("div",{className:"autoruns-coverage-head",children:[l.jsx("strong",{children:h.domain}),l.jsxs("span",{children:[h.closed_cases,"/",h.total_cases," (",f,"%)"]})]}),l.jsx("div",{className:"autoruns-coverage-bar",children:l.jsx("div",{style:{width:`${f}%`}})})]},h.domain)})})}function Cl(i){return`${El}${i}`}function Ms(i){return i.startsWith(El)}function Hc(i){return i.startsWith(El)?i.slice(El.length):""}function Xc(i){const h=i.report_summary?.run_timestamp??i.created_at,f=Math.max(0,i.total_cases-i.completed_cases);return{run_id:Cl(i.job_id),eval_target:i.eval_target,run_timestamp:h,mode:"single-pass-strict",llm_provider:null,model:null,use_mock:null,analysis_date:i.report_summary?.analysis_date??i.analysis_date??null,prompt_version:null,schema_version:null,suite_id:i.case_set_file,cases_total:i.total_cases,requests_total:null,report_path:`async_job:${i.job_id}`,score_index:i.report_summary?.score_index??null,blocking_failures:0,quality_failures:0,closed_cases:i.completed_cases,open_cases:f,domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]}}function yo(i,h){const f=Xc(i),R=i.cases.map(Y=>({case_id:Y.case_id,domain:null,query_class:null,status:Y.status==="completed"?"closed":Y.status==="failed"?"open":"unknown",score_index:null,trace_id:null,reply_type:null,session_id:`${i.run_id}-${Y.case_id}`,dialog_available:Y.messages.length>0,commented_count:0,latest_annotation_at:null,avg_rating:null,checks:null,metric_subscores:null})),L=h!==_t&&R.some(Y=>Y.case_id===h)?h:R.length>0?_t:"",Q={ok:!0,run:f,coverage:{closed_cases:i.completed_cases,open_cases:Math.max(0,i.total_cases-i.completed_cases),domain_coverage:[{domain:"runtime",total_cases:i.total_cases,closed_cases:i.completed_cases}]},cases:R,annotations_summary:{total:0},report:i.report_summary?{run_id:i.report_summary.run_id,run_timestamp:i.report_summary.run_timestamp,score_index:i.report_summary.score_index,cases_total:i.report_summary.cases_total,analysis_date:i.report_summary.analysis_date??i.analysis_date??null}:{}},le=[];let te=0;if(L===_t)for(const Y of i.cases)for(let X=0;XX.case_id===L)??null;for(let X=0;X<(Y?.messages.length??0);X+=1){const ee=Y?.messages[X];ee&&le.push({...ee,message_index:X,case_id:L,case_message_index:X,commented:!1,annotation:null})}}const z={ok:!0,run_id:f.run_id,case_id:L,source:"assistant_session",session_id:L===_t?`${i.run_id}::__all__`:`${i.run_id}-${L}`,messages:le,decomposition:[],assistant_mode:{status:i.status,completed_cases:i.completed_cases,total_cases:i.total_cases},annotations:[]};return{detail:Q,dialog:z,caseId:L}}function im({commented:i}){const h=i?"comment-icon-svg commented":"comment-icon-svg";return l.jsx("svg",{className:h,viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:l.jsx("path",{d:"M5 6.5h14v9H11.5l-4.5 3v-3H5z"})})}function Qc({resolved:i}){return l.jsxs("svg",{className:i?"resolve-icon-svg resolved":"resolve-icon-svg",viewBox:"0 0 16 16","aria-hidden":"true",focusable:"false",children:[l.jsx("circle",{cx:"8",cy:"8",r:"6.2"}),i?l.jsx("path",{d:"M5.1 8.2 7.2 10.3 11 6.5"}):null]})}function bc(){return l.jsxs("svg",{className:"autoruns-copy-icon-svg",viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:[l.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2.2"}),l.jsx("path",{d:"M15 7V5.8a1.8 1.8 0 0 0-1.8-1.8H5.8A1.8 1.8 0 0 0 4 5.8v7.4A1.8 1.8 0 0 0 5.8 15H7"})]})}function am({connection:i,modelOptions:h,modelsBusy:f,connectionStatus:R,connectionBusy:E,onConnectionChange:L,onReloadModels:Q,onSaveLocalConfig:le,onTestConnection:te,prompts:z,onPromptsChange:Y,promptPresets:X,selectedPresetId:ee,onSelectPreset:Te,onLoadPreset:ce,onSavePreset:de,onResetDefaults:pe,onDiffPrevious:Qe,presetName:Je,onPresetNameChange:be,diffSummary:Re,assistantPromptVersion:F,decompositionPromptVersion:oe,showSettingsMode:Ce,showAutoRunsMode:$e,showAssistantMode:dt,showProgressMode:st,showCommentsMode:Dt,onLog:ot}){const[H,Me]=y.useState({...sa,fromLocal:$c()}),[We,ne]=y.useState(""),[Z,M]=y.useState(null),[U,A]=y.useState(null),[v,w]=y.useState(null),[re,ie]=y.useState([]),[ae,he]=y.useState("all"),[xe,_e]=y.useState(!1),[we,lt]=y.useState(null),[qt,Xn]=y.useState([]),[wn,nn]=y.useState(""),[Ee,Ot]=y.useState(""),[et,ft]=y.useState(""),[St,rn]=y.useState(da),[W,it]=y.useState(Oc),[Zn,In]=y.useState([]),[Dn,kn]=y.useState(""),[mt,zt]=y.useState([]),[qe,sn]=y.useState(null),[on,Zr]=y.useState(null),[Nr,Er]=y.useState(!1),[es,ln]=y.useState(!1),[an,un]=y.useState(!1),[cn,On]=y.useState(!1),[me,dn]=y.useState(!1),[er,Pr]=y.useState(!1),[Tr,Rr]=y.useState(!1),[jn,tr]=y.useState(!1),[Mr,Cn]=y.useState(""),[nr,Oe]=y.useState(""),[k,q]=y.useState(""),[D,ke]=y.useState([]),[Ke,Ar]=y.useState([]),[As,Ls]=y.useState(""),[fn,ts]=y.useState(null),[ns,Tl]=y.useState(!1),[Is,Ds]=y.useState(!1),[xo,rr]=y.useState(""),[Rl,zn]=y.useState(""),[Fe,sr]=y.useState(String(sa.limit)),[Os,$n]=y.useState(String(Oc.count)),[or,_o]=y.useState(160),[ge,wt]=y.useState({open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:wl,annotationAuthor:"manual_reviewer",saving:!1,error:""}),[ue,mn]=y.useState({open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""}),[Ue,Fn]=y.useState({open:!1,title:"",saving:!1,error:""}),[$t,Lr]=y.useState({open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""}),[Et,Un]=y.useState({open:!1,generationId:"",title:"",saving:!1,error:""}),Bn=y.useRef(!1),Hn=y.useRef(null),Kt=W.mode==="saved_user_sessions",rs=y.useMemo(()=>St.find(a=>a.id===W.personalityId)??St[0]??da[0],[W.personalityId,St]),pt=y.useMemo(()=>Zn.filter(a=>a.mode===W.mode),[Zn,W.mode]),kt=y.useMemo(()=>pt.find(a=>a.generation_id===Dn)??pt[0]??null,[Dn,pt]),pn=y.useMemo(()=>xe?re.filter(a=>!a.resolved):re,[re,xe]),Ne=pn.find(a=>a.annotation_id===wn)??null,So=v?.messages.find(a=>a.message_index===ge.messageIndex)??null,zs=y.useMemo(()=>{if(!v||ge.messageIndex<0)return null;for(let a=ge.messageIndex-1;a>=0;a-=1){const c=v.messages[a];if(c?.role==="user")return c}return null},[ge.messageIndex,v]),ve=y.useMemo(()=>{const a=new Map;for(const c of Ke)c.message_id&&a.set(c.message_id,c);return a},[Ke]),$s=ue.messageIndex>=0?D[ue.messageIndex]??null:null,Fs=y.useMemo(()=>{if(ue.messageIndex<0)return null;for(let a=ue.messageIndex-1;a>=0;a-=1){const c=D[a];if(c?.role==="user")return c}return null},[ue.messageIndex,D]),Ft=y.useMemo(()=>{const a=pn.map(p=>({source:"autorun",key:`autorun:${p.annotation_id}`,updated_at:p.updated_at,rating:p.rating,autorun:p,assistant:null})),c=Ke.map(p=>({source:"assistant_live",key:`assistant:${p.annotation_id}`,updated_at:p.updated_at,rating:p.rating,autorun:null,assistant:p}));return[...a,...c].sort((p,j)=>Date.parse(j.updated_at)-Date.parse(p.updated_at))},[Ke,pn]),Us=y.useMemo(()=>{if(Ft.length===0)return null;const a=Ft.reduce((c,p)=>c+p.rating,0)/Ft.length;return Number(a.toFixed(2))},[Ft]),ss=y.useMemo(()=>{const a=[...Z?.items??[]];return qe&&a.unshift(Xc(qe)),Ee&&!a.some(c=>c.run_id===Ee)&&U?.run&&a.unshift(U.run),a},[qe,Z?.items,U?.run,Ee]),J=y.useCallback(a=>{ot?.(`[autoruns] ${a}`)},[ot]),lr=y.useCallback(async a=>{const c=String(a??"").trim();if(!c){Ar([]);return}try{const p=await Pe.loadAssistantAnnotations({session_id:c,limit:400});Ar(p.items??[])}catch(p){const j=p instanceof Error?p.message:String(p);J(`Assistant live annotations load error: ${j}`)}},[J]),hn=y.useCallback(a=>{mn(c=>c.saving&&!a?.force?c:{open:!1,messageIndex:-1,rating:3,comment:"",annotationAuthor:"manual_reviewer",saving:!1,error:""})},[]),Ut=y.useCallback(a=>{Fn(c=>c.saving&&!a?.force?c:{open:!1,title:"",saving:!1,error:""})},[]),Bt=y.useCallback(a=>{Lr(c=>c.saving&&!a?.force?c:{open:!1,generationId:"",questionIndex:-1,questionText:"",saving:!1,error:""})},[]),Ht=y.useCallback(a=>{Un(c=>c.saving&&!a?.force?c:{open:!1,generationId:"",title:"",saving:!1,error:""})},[]),Nn=y.useCallback(async(a,c,p)=>{a.stopPropagation(),a.preventDefault();const j=String(c??"").trim();if(j)try{if(navigator?.clipboard?.writeText)await navigator.clipboard.writeText(j);else{const $=document.createElement("textarea");$.value=j,$.setAttribute("readonly","true"),$.style.position="fixed",$.style.opacity="0",document.body.appendChild($),$.select(),document.execCommand("copy"),document.body.removeChild($)}J(`${p} copied: ${j}`)}catch($){const Le=$ instanceof Error?$.message:String($);Oe(`Копирование ${p}: ${Le}`),J(`copy ${p} error: ${Le}`)}},[J]);function Ir(){let a=0;rr(oa[0]);const c=window.setInterval(()=>{a=Math.min(a+1,oa.length-1),rr(oa[a])},650);return()=>window.clearInterval(c)}const En=y.useCallback(()=>{q(""),ke([]),Ar([]),Ls(""),ts(null),rr(""),zn(""),hn({force:!0}),J("Live-чат ассистента в истории автопрогонов сброшен.")},[hn,J]),Ml=y.useCallback(async()=>{const a=tm(As,fn);if(!a)return;Ds(!0),zn(""),Ls(""),ke(p=>[...p,{message_id:`autoruns-live-${Date.now()}`,session_id:k||"pending",role:"user",text:a,reply_type:null,created_at:new Date().toISOString(),trace_id:null,debug:null}]);const c=Ir();try{const p=await Pe.sendAssistantMessage({connection:i,prompts:z,userMessage:a,sessionId:k||void 0,promptVersion:F,useMock:ns});q(p.session_id),ke(p.conversation),await lr(p.session_id),rr("Ответ готов"),J(`Live-ответ ассистента получен: trace=${p.debug.trace_id}`)}catch(p){const j=p instanceof Error?p.message:String(p);zn(j),rr("Ошибка ассистента"),J(`Live-чат ассистента: ошибка отправки сообщения: ${j}`)}finally{c(),Ds(!1)}},[As,fn,k,ns,F,i,lr,J,z]),wo=y.useCallback(()=>{if(!k.trim()||D.length===0){zn("Сначала получите хотя бы один ответ в живой сессии ассистента.");return}zn(""),Fn({open:!0,title:sm(D),saving:!1,error:""})},[D,k]),Dr=y.useCallback(async()=>{const a=k.trim(),c=Ue.title.trim();if(!a){Fn(p=>({...p,error:"Активная сессия ассистента не найдена."}));return}if(!c){Fn(p=>({...p,error:"Укажите название сессии."}));return}Fn(p=>({...p,saving:!0,error:""}));try{const p=[z.systemPrompt,z.developerPrompt,z.domainPrompt,z.schemaNotes,z.fewShotExamples].join("||"),j=await Pe.saveAutoRunAssistantSession({session_id:a,title:c,generated_by:W.generatedBy.trim()||void 0,context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:F,decomposition_prompt_version:oe,prompt_fingerprint:p}});In($=>[j.generation,...$.filter(Le=>Le.generation_id!==j.generation.generation_id)]),it($=>({...$,mode:"saved_user_sessions"})),kn(j.generation.generation_id),Ut({force:!0}),J(`Живая сессия сохранена в автопрогоны: ${j.generation.generation_id}`)}catch(p){const j=p instanceof Error?p.message:String(p);Fn($=>({...$,saving:!1,error:j})),J(`Assistant live save error: ${j}`)}},[Ue.title,k,F,W.generatedBy,Ut,i.llmProvider,i.model,oe,J,z.developerPrompt,z.domainPrompt,z.fewShotExamples,z.schemaNotes,z.systemPrompt]),ko=y.useCallback(a=>{const c=a.trim();if(!c){sr(String(H.limit));return}if(!/^\d+$/.test(c)){sr(String(H.limit));return}const p=Number.parseInt(c,10);if(!Number.isFinite(p)){sr(String(H.limit));return}const j=Math.max(1,Math.min(500,p));j!==H.limit&&Me($=>({...$,limit:j})),sr(String(j))},[H.limit]),Bs=y.useCallback(a=>{const c=a.trim();if(!c){$n(String(W.count));return}if(!/^\d+$/.test(c)){$n(String(W.count));return}const p=Number.parseInt(c,10);if(!Number.isFinite(p)){$n(String(W.count));return}const j=Math.max(1,Math.min(200,p));j!==W.count&&it($=>({...$,count:j})),$n(String(j))},[W.count]),Or=y.useCallback(a=>{_o(zc(a))},[]),Hs=y.useCallback(a=>{const c=a.currentTarget.offsetHeight;Number.isFinite(c)&&c>0&&Or(c)},[Or]),zr=y.useCallback(async()=>{tr(!0);try{const a=await Pe.loadAutoRunAnnotations({limit:800,manual_case_decision:ae});ie(a.items),lt(a.manual_case_decision_schema??null),Xn(a.available_manual_case_decisions??[]),nn(c=>a.items.length===0?"":a.items.some(p=>p.annotation_id===c)?c:a.items[0].annotation_id)}catch(a){J(`Annotations load error: ${a instanceof Error?a.message:String(a)}`)}finally{tr(!1)}},[ae,J]),Qt=y.useCallback(async()=>{On(!0);try{const a=await Pe.loadAutoRunAutogenHistory({limit:180});In(a.items)}catch(a){J(`Autogen history load error: ${a instanceof Error?a.message:String(a)}`)}finally{On(!1)}},[J]),ir=y.useCallback(async()=>{try{const c=(await Pe.loadAutoRunAutogenPersonalityCatalog()).items.map(p=>({id:String(p.id??"").trim(),label:String(p.label??"").trim(),domain:typeof p.domain=="string"?p.domain.trim():"",defaultPrompt:String(p.default_prompt??"").trim()})).filter(p=>p.id.length>0&&p.label.length>0);if(c.length===0)return;rn(c.map(p=>({id:p.id,label:p.label,domain:p.domain||"",defaultPrompt:p.defaultPrompt||"Генерируй реалистичные вопросы бухгалтера по выбранному профилю. Не выдумывай непокрытые возможности."})))}catch(a){J(`Autogen personality catalog load error: ${a instanceof Error?a.message:String(a)}`)}},[J]),ht=y.useCallback(async()=>{un(!0);try{const a=await Pe.loadAutoRunPostAnalysis({run_id:Ee&&!Ms(Ee)?Ee:void 0,limit_per_queue:30,annotation_limit:1500,from:kl(H.fromLocal),to:kl(H.toLocal),target:H.target,mode:H.mode,use_mock:H.useMock,prompt_contains:H.promptContains.trim()||void 0});Zr(a)}catch(a){J(`Post-analysis load error: ${a instanceof Error?a.message:String(a)}`),Zr(null)}finally{un(!1)}},[H.fromLocal,H.mode,H.promptContains,H.target,H.toLocal,H.useMock,J,Ee]),os=y.useCallback(async()=>{Er(!0),Oe("");try{if(W.mode==="saved_user_sessions")throw new Error("Пользовательские сессии сохраняются из живого чата, а не генерируются автоматически.");const a=W.personalityPrompts[W.personalityId]??"",c=[z.systemPrompt,z.developerPrompt,z.domainPrompt,z.schemaNotes,z.fewShotExamples].join(` +`).slice(0,900),p=await Pe.generateAutoRunQuestions({mode:W.mode,count:W.count,domain:rs.domain||void 0,persist_to_eval_cases:W.persistToEvalCases,generated_by:W.generatedBy.trim()||void 0,llm:{llm_provider:i.llmProvider,api_key:i.apiKey,model:i.model,base_url:i.baseUrl,temperature:i.temperature,max_output_tokens:i.maxOutputTokens},context:{llm_provider:i.llmProvider,model:i.model,assistant_prompt_version:F,decomposition_prompt_version:oe,prompt_fingerprint:c,autogen_personality_id:rs.id,autogen_personality_prompt:a.trim()||void 0}});J(`Generated ${p.generation.count} questions (${p.generation.mode}) id=${p.generation.generation_id}`+(p.generation.saved_case_set_file?` saved=${p.generation.saved_case_set_file}`:"")),kn(p.generation.generation_id),zt([...p.generation.questions??[]]),await Qt()}catch(a){const c=a instanceof Error?a.message:String(a);Oe(`Автогенерация: ${c}`),J(`Autogen generate error: ${c}`)}finally{Er(!1)}},[F,W.count,W.generatedBy,W.mode,W.personalityId,W.personalityPrompts,W.persistToEvalCases,i.apiKey,i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature,oe,Qt,J,z.developerPrompt,z.domainPrompt,z.fewShotExamples,z.schemaNotes,z.systemPrompt,rs.domain,rs.id]),$r=y.useCallback(async(a,c)=>{if(Ms(a)){const p=Hc(a);if(qe&&qe.job_id===p){const j=yo(qe,c);Ot(a),ft(j.caseId),w(j.dialog);return}w(null);return}Rr(!0);try{const p=await Pe.loadAutoRunCaseDialog(a,c);w(p)}catch(p){const j=p instanceof Error?p.message:String(p);Oe(`Диалог кейса: ${j}`),w(null),J(`Dialog load error for ${a}/${c}: ${j}`)}finally{Rr(!1)}},[qe,J]),Pn=y.useCallback(async(a,c)=>{if(Ms(a)){const p=Hc(a);if(qe&&qe.job_id===p){const j=yo(qe,c??_t);Ot(a),ft(j.caseId),A(j.detail),w(j.dialog);return}Ot(a),ft(""),A(null),w(null);return}Pr(!0);try{const p=await Pe.loadAutoRunDetail(a);A(p);const j=(c&&(c===_t||p.cases.some($=>$.case_id===c))?c:"")||(p.cases.length>0?_t:"")||"";Ot(a),ft(j),j?await $r(a,j):w(null)}catch(p){const j=p instanceof Error?p.message:String(p);Oe(`Детализация прогона: ${j}`),A(null),w(null),J(`Run detail load error for ${a}: ${j}`)}finally{Pr(!1)}},[qe,$r,J]),Qn=y.useCallback(async a=>{dn(!0),Oe("");try{const c=await Pe.loadAutoRunsHistory({from:kl(H.fromLocal),to:kl(H.toLocal),target:H.target,mode:H.mode,use_mock:H.useMock,prompt_contains:H.promptContains.trim()||void 0,limit:H.limit});if(M(c),c.items.length===0){Ot(""),ft(""),A(null),w(null);return}const p=a?.keepSelection??!0,j=a?.preferredRunId??"",$=a?.preferredCaseId??"",Le=p&&j&&c.items.some(at=>at.run_id===j)?j:c.items[0].run_id;await Pn(Le,p?$:void 0),ht()}catch(c){const p=c instanceof Error?c.message:String(c);Oe(`История прогонов: ${p}`),J(`History load error: ${p}`)}finally{dn(!1)}},[H.fromLocal,H.limit,H.mode,H.promptContains,H.target,H.toLocal,H.useMock,ht,Pn,J]),Pt=y.useCallback(()=>{Hn.current!==null&&(window.clearTimeout(Hn.current),Hn.current=null)},[]),Fr=y.useCallback(async a=>{try{const c=await Pe.loadEvalRunAsyncStatus(a);sn(c.job);const p=Cl(a);if(Ee===p){const j=yo(c.job,et||_t);A(j.detail),w(j.dialog),ft(j.caseId)}if(c.job.status==="completed"){Pt(),ln(!1);const j=c.job.report_summary?.run_id??c.job.run_id;await Qn({keepSelection:!0,preferredRunId:j||Ee,preferredCaseId:_t}),await Qt(),sn(null);return}if(c.job.status==="failed"){Pt(),ln(!1),Oe(`Запуск прогонов: ${c.job.error??"неизвестная ошибка"}`),J(`Autogen async run failed: ${c.job.error??"unknown error"}`);return}Pt(),Hn.current=window.setTimeout(()=>{Fr(a)},500)}catch(c){Pt(),ln(!1);const p=c instanceof Error?c.message:String(c);Oe(`Запуск прогонов: ${p}`),J(`Autogen async status error: ${p}`)}},[Qt,Qn,J,et,Ee,Pt]),jo=y.useCallback(async()=>{Pt(),ln(!0),Oe("");try{const a=kt;if(!a)throw new Error("История автогенерации пуста. Сначала сгенерируйте пачку вопросов.");const c=mt.map(Vs=>Vs.trim()).filter(Vs=>Vs.length>0);if(c.length===0)throw new Error("Нет вопросов для запуска: список пустой после ручного редактирования.");const p=H.useMock==="true",j=la(We),$=a.mode==="saved_user_sessions",at=(await Pe.startEvalRunAsync({connection:i,prompts:z,promptVersion:F,mode:"single-pass-strict",caseSetFile:$?void 0:a.saved_case_set_file??void 0,useMock:p,evalTarget:"assistant_stage1",questions:$?void 0:c,scenarioQuestions:$?c:void 0,scenarioTitle:$?a.title??void 0:void 0,analysisDate:$?void 0:j||void 0})).job;sn(at);const dr=Cl(at.job_id),bs=yo(at,_t);Ot(dr),ft(bs.caseId),A(bs.detail),w(bs.dialog),J(`Запущен async-прогон job=${at.job_id}, run_id=${at.run_id}, вопросов=${c.length}`+(a.saved_case_set_file?`, base_case_set=${a.saved_case_set_file}`:"")+($?", replay_mode=saved_user_session_scenario":j?`, analysis_date=${j}`:", analysis_date=current_state")),Fr(at.job_id)}catch(a){const c=a instanceof Error?a.message:String(a);Oe(`Запуск прогонов: ${c}`),J(`Autogen run error: ${c}`),ln(!1)}},[We,F,i,mt,H.useMock,J,Fr,z,kt,Pt]),Tn=y.useCallback(a=>{if(a.role!=="assistant")return;const c=a.case_id??et,p=a.case_message_index??a.message_index;wt({open:!0,caseId:c,caseMessageIndex:p,messageIndex:a.message_index,rating:a.annotation?.rating??3,comment:a.annotation?.comment??"",manualCaseDecision:a.annotation?.manual_case_decision??wl,annotationAuthor:a.annotation?.annotation_author??W.generatedBy,saving:!1,error:""})},[W.generatedBy,et]),ar=y.useCallback(a=>{wt(c=>c.saving&&!a?.force?c:{open:!1,caseId:"",caseMessageIndex:-1,messageIndex:-1,rating:3,comment:"",manualCaseDecision:wl,annotationAuthor:W.generatedBy,saving:!1,error:""})},[W.generatedBy]),ls=y.useCallback(async()=>{const a=Ee,c=ge.caseId,p=ge.caseMessageIndex;if(!(!a||!c||p<0)){if(Ms(a)){wt(j=>({...j,error:"Комментарий можно сохранить после завершения прогона."}));return}if(!ge.comment.trim()){wt(j=>({...j,error:"Добавьте комментарий."}));return}wt(j=>({...j,saving:!0,error:""}));try{await Pe.saveAutoRunAnnotation({run_id:a,case_id:c,message_index:p,rating:ge.rating,comment:ge.comment.trim(),manual_case_decision:ge.manualCaseDecision,annotation_author:ge.annotationAuthor.trim()||void 0}),ar({force:!0}),Promise.all([Pn(a,et),zr(),ht()]).catch(j=>{const $=j instanceof Error?j.message:String(j);Oe(`Обновление после комментария: ${$}`),J(`Comment refresh error: ${$}`)})}catch(j){wt($=>({...$,saving:!1,error:j instanceof Error?j.message:String(j)}))}}},[ar,ge.annotationAuthor,ge.caseId,ge.caseMessageIndex,ge.comment,ge.manualCaseDecision,ge.rating,zr,ht,Pn,J,et,Ee]),Co=y.useCallback(a=>a.role==="assistant",[]),is=y.useCallback(a=>a.role==="assistant"&&ve.has(a.message_id),[ve]),as=y.useCallback((a,c)=>{if(a.role!=="assistant")return;const p=k.trim(),j=String(a.session_id??"").trim();if(!(p||j)){zn("Сначала получите ответ ассистента в активной сессии.");return}!p&&j&&q(j);const Le=ve.get(a.message_id)??null;zn(""),mn({open:!0,messageIndex:c,rating:Le?.rating??3,comment:Le?.comment??"",annotationAuthor:Le?.annotation_author??"manual_reviewer",saving:!1,error:""})},[ve,k]),No=y.useCallback(async()=>{if(ue.messageIndex<0)return;if(!ue.comment.trim()){mn(p=>({...p,error:"Добавьте комментарий."}));return}const a=D[ue.messageIndex]??null,c=k.trim()||(a?.role==="assistant"?String(a.session_id??"").trim():"");if(!c){mn(p=>({...p,error:"Сессия ассистента не найдена."}));return}mn(p=>({...p,saving:!0,error:""}));try{const p=await Pe.saveAssistantAnnotation({session_id:c,message_index:ue.messageIndex,rating:ue.rating,comment:ue.comment.trim(),annotation_author:ue.annotationAuthor.trim()||void 0});Ar(j=>{const $=[...j],Le=$.findIndex(at=>at.annotation_id===p.annotation.annotation_id);return Le>=0?$[Le]=p.annotation:$.unshift(p.annotation),$.sort((at,dr)=>Date.parse(dr.updated_at)-Date.parse(at.updated_at))}),hn({force:!0})}catch(p){const j=p instanceof Error?p.message:String(p);mn($=>({...$,saving:!1,error:j}))}},[ue.annotationAuthor,ue.comment,ue.messageIndex,ue.rating,D,k,hn]),jt=y.useCallback(a=>{if(!kt||kt.mode!=="saved_user_sessions")return;const c=mt[a]??"";Lr({open:!0,generationId:kt.generation_id,questionIndex:a,questionText:c,saving:!1,error:""})},[mt,kt]),ur=y.useCallback(async()=>{const a=$t.generationId,c=$t.questionIndex;if(!a||c<0)return;const p=mt.filter((j,$)=>$!==c);if(p.length===0){Lr(j=>({...j,error:"Нельзя удалить последний вопрос из сохраненной сессии."}));return}Lr(j=>({...j,saving:!0,error:""}));try{const j=await Pe.updateAutoRunAutogenQuestions({generation_id:a,questions:p});In($=>$.map(Le=>Le.generation_id===a?j.generation:Le)),zt(j.generation.questions),Bt({force:!0}),J(`Обновлена сохраненная сессия: ${a}`)}catch(j){const $=j instanceof Error?j.message:String(j);Lr(Le=>({...Le,saving:!1,error:$})),J(`Saved session question delete error: ${$}`)}},[Bt,mt,J,$t.generationId,$t.questionIndex]),Qs=y.useCallback(a=>{Un({open:!0,generationId:a.generation_id,title:a.title??`${ia(a.mode)} ${tn(a.created_at)}`,saving:!1,error:""})},[]),Ur=y.useCallback(async()=>{const a=Et.generationId.trim();if(a){Un(c=>({...c,saving:!0,error:""}));try{const c=await Pe.deleteAutoRunAutogenHistoryRecord(a);In(p=>p.filter(j=>j.generation_id!==c.generation_id)),Ht({force:!0}),J(`Удален набор автопрогона: ${c.generation_id}`+(c.deleted_files.length>0?`, files=${c.deleted_files.length}`:""))}catch(c){const p=c instanceof Error?c.message:String(c);Un(j=>({...j,saving:!1,error:p})),J(`Autogen record delete error: ${p}`)}}},[Et.generationId,Ht,J]),Eo=y.useCallback(a=>{ie(c=>c.map(p=>p.annotation_id===a.annotation_id?{...p,...a}:p)),w(c=>c&&{...c,annotations:c.annotations.map(p=>p.annotation_id===a.annotation_id?a:p),messages:c.messages.map(p=>!p.annotation||p.annotation.annotation_id!==a.annotation_id?p:{...p,commented:!0,annotation:a})})},[]),us=y.useCallback(async(a,c)=>{if(a.annotation_id){if(Ms(a.run_id)){Oe("Статус выполнения можно менять только для завершённых прогонов.");return}Cn(a.annotation_id);try{const p=await Pe.updateAutoRunAnnotation({annotation_id:a.annotation_id,resolved:c,resolved_by:W.generatedBy||void 0});Eo(p.annotation),ht()}catch(p){const j=p instanceof Error?p.message:String(p);Oe(`Смена статуса кейса: ${j}`),J(`Annotation resolve toggle error: ${j}`)}finally{Cn("")}}},[Eo,W.generatedBy,ht,J]),cs=y.useCallback(async a=>{nn(a.annotation_id),await Pn(a.run_id,a.case_id),Z?.items.some(c=>c.run_id===a.run_id)||Oe("Комментарий относится к прогону вне текущего фильтра. Детали загружены напрямую.")},[Z?.items,Pn]);y.useEffect(()=>{Bn.current||(Bn.current=!0,Qn({keepSelection:!1}),Qt(),ir(),ht())},[Qt,ir,Qn,ht]),y.useEffect(()=>{Bn.current&&zr()},[ae,zr]),y.useEffect(()=>{nn(a=>pn.length===0?"":pn.some(c=>c.annotation_id===a)?a:pn[0].annotation_id)},[pn]),y.useEffect(()=>{kn(a=>pt.length===0?"":a&&pt.some(c=>c.generation_id===a)?a:pt[0].generation_id)},[pt]),y.useEffect(()=>{if(!kt){zt([]);return}zt([...kt.questions])},[kt]),y.useEffect(()=>{sr(String(H.limit))},[H.limit]),y.useEffect(()=>{$n(String(W.count))},[W.count]),y.useEffect(()=>{if(!k.trim()){Ar([]);return}lr(k)},[k,lr]),y.useEffect(()=>{if(!qe)return;const a=Cl(qe.job_id);if(Ee!==a)return;const c=yo(qe,et||_t);A(c.detail),w(c.dialog),ft(c.caseId)},[qe,et,Ee]),y.useEffect(()=>()=>{Pt()},[Pt]),y.useEffect(()=>{St.length!==0&&it(a=>{let c=!1;const p={...a.personalityPrompts};for(const $ of St)(typeof p[$.id]!="string"||p[$.id].trim().length===0)&&(p[$.id]=$.defaultPrompt,c=!0);let j=a.personalityId;return St.some($=>$.id===a.personalityId)||(j=St[0].id,c=!0),c?{...a,personalityId:j,personalityPrompts:p}:a})},[St]),y.useEffect(()=>{const a=localStorage.getItem(Ic);if(a)try{const c=JSON.parse(a);if(c.filters){const p=c.filters;Me(j=>({...j,...p,limit:typeof p.limit=="number"?Math.max(1,Math.min(500,p.limit)):j.limit}))}typeof c.analysisDate=="string"&&ne(la(c.analysisDate)),typeof c.autogenPersonalityPromptHeight=="number"&&_o(zc(c.autogenPersonalityPromptHeight)),c.autoGenSettings&&it(p=>{const j={...p.personalityPrompts},$=c.autoGenSettings?.personalityPrompts??{};for(const[at,dr]of Object.entries($))typeof dr=="string"&&at.trim().length>0&&(j[at.trim()]=dr);const Le=typeof c.autoGenSettings?.personalityId=="string"&&c.autoGenSettings.personalityId.trim().length>0?c.autoGenSettings.personalityId.trim():p.personalityId;return{...p,mode:c.autoGenSettings?.mode==="codex_creative"||c.autoGenSettings?.mode==="qwen_seed"||c.autoGenSettings?.mode==="saved_user_sessions"?c.autoGenSettings.mode:p.mode,count:typeof c.autoGenSettings?.count=="number"?Math.max(1,Math.min(200,c.autoGenSettings.count)):p.count,personalityId:Le,personalityPrompts:j,persistToEvalCases:typeof c.autoGenSettings?.persistToEvalCases=="boolean"?c.autoGenSettings.persistToEvalCases:p.persistToEvalCases,generatedBy:typeof c.autoGenSettings?.generatedBy=="string"?c.autoGenSettings.generatedBy:p.generatedBy}}),(c.annotationDecisionFilter==="all"||typeof c.annotationDecisionFilter=="string"&&c.annotationDecisionFilter.length>0)&&he(c.annotationDecisionFilter),typeof c.hideResolvedAnnotations=="boolean"&&_e(c.hideResolvedAnnotations)}catch{}},[]);const cr=y.useCallback(()=>{const a={filters:H,analysisDate:We,autogenPersonalityPromptHeight:or,autoGenSettings:{mode:W.mode,count:W.count,personalityId:W.personalityId,personalityPrompts:W.personalityPrompts,persistToEvalCases:W.persistToEvalCases,generatedBy:W.generatedBy},annotationDecisionFilter:ae,hideResolvedAnnotations:xe};localStorage.setItem(Ic,JSON.stringify(a))},[We,ae,W,or,H,xe]);return y.useEffect(()=>{const a=()=>{cr(),J("Сохранены настройки панели автопрогонов.")};return window.addEventListener(Dc,a),()=>{window.removeEventListener(Dc,a)}},[J,cr]),l.jsxs(Pl,{className:"autoruns-frame",title:"",hideHeader:!0,children:[l.jsxs("div",{className:"autoruns-columns",children:[Ce?l.jsxs("section",{className:"autoruns-col autoruns-settings-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Настройки"})}),l.jsxs("div",{className:"autoruns-settings-stack",children:[l.jsx(Zf,{embedded:!0,value:i,modelOptions:h,modelsBusy:f,onChange:L,onReloadModels:Q,onSaveLocalConfig:le,onTestConnection:te,lastStatus:R,busy:E}),l.jsx(em,{embedded:!0,value:z,onChange:Y,presets:X,selectedPresetId:ee,onSelectPreset:Te,onLoadPreset:ce,onSavePreset:de,onResetDefaults:pe,onDiffPrevious:Qe,presetName:Je,onPresetNameChange:be,diffSummary:Re})]})]}):null,$e?l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Автопрогоны"})}),l.jsx("h4",{children:"Настройки выборки"}),l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Дата с",l.jsx("input",{type:"datetime-local",value:H.fromLocal,onChange:a=>Me(c=>({...c,fromLocal:a.target.value}))})]}),l.jsxs("label",{children:["Дата по",l.jsx("input",{type:"datetime-local",value:H.toLocal,onChange:a=>Me(c=>({...c,toLocal:a.target.value}))})]}),l.jsxs("label",{children:["Целевой контур",l.jsxs("select",{value:H.target,onChange:a=>Me(c=>({...c,target:a.target.value})),children:[l.jsx("option",{value:"all",children:"все"}),(Z?.available.targets??[]).map(a=>l.jsx("option",{value:a,children:a},a))]})]}),l.jsxs("label",{children:["Режим",l.jsxs("select",{value:H.mode,onChange:a=>Me(c=>({...c,mode:a.target.value})),children:[l.jsx("option",{value:"all",children:"все"}),(Z?.available.modes??[]).map(a=>l.jsx("option",{value:a,children:a},a))]})]}),l.jsxs("label",{children:["Использовать mock",l.jsxs("select",{value:H.useMock,onChange:a=>Me(c=>({...c,useMock:a.target.value})),children:[l.jsx("option",{value:"any",children:"любой"}),l.jsx("option",{value:"true",children:"да"}),l.jsx("option",{value:"false",children:"нет"})]})]}),l.jsxs("label",{children:["Лимит",l.jsx("input",{type:"number",min:1,max:500,value:Fe,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&sr(c)},onBlur:a=>ko(a.target.value),onKeyDown:a=>{a.key==="Enter"&&ko(a.target.value)}})]}),l.jsxs("label",{className:"full-width",children:["Версия промпта содержит",l.jsx("input",{value:H.promptContains,onChange:a=>Me(c=>({...c,promptContains:a.target.value})),placeholder:"normalizer_v2_0_2 / address_query_runtime_v1",list:"autoruns-prompt-versions"})]})]}),l.jsx("datalist",{id:"autoruns-prompt-versions",children:(Z?.available.prompt_versions??[]).map(a=>l.jsx("option",{value:a},a))}),l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",disabled:me,onClick:()=>{Qn({keepSelection:!1})},children:me?"Обновляю...":"Применить"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>{Me({...sa,fromLocal:$c()}),Oe("")},children:"Сбросить фильтры"})]}),l.jsx("h4",{children:"Контур генерации"}),l.jsxs("div",{className:"autoruns-meta-list",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Провайдер:"}),l.jsx("strong",{children:i.llmProvider})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Модель:"}),l.jsx("strong",{children:i.model||"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Промпт ассистента:"}),l.jsx("strong",{children:F})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Промпт декомпозиции:"}),l.jsx("strong",{children:oe})]})]}),l.jsx("h4",{children:"Автопрогоны"}),l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Режимы",l.jsxs("select",{value:W.mode,onChange:a=>it(c=>({...c,mode:a.target.value})),children:[l.jsx("option",{value:"codex_creative",children:"codex_creative"}),l.jsx("option",{value:"qwen_seed",children:"qwen_seed"}),l.jsx("option",{value:"saved_user_sessions",children:"Пользовательские сессии"})]})]}),Kt?null:l.jsxs(l.Fragment,{children:[l.jsxs("label",{children:["Кол-во",l.jsx("input",{type:"number",min:1,max:200,value:Os,onChange:a=>{const c=a.target.value;(c===""||/^\d+$/.test(c))&&$n(c)},onBlur:a=>Bs(a.target.value),onKeyDown:a=>{a.key==="Enter"&&Bs(a.target.value)}})]}),l.jsxs("label",{children:["Личность автогенерации",l.jsx("select",{value:W.personalityId,onChange:a=>it(c=>({...c,personalityId:a.target.value})),children:St.map(a=>l.jsx("option",{value:a.id,children:a.label},a.id))})]}),l.jsxs("label",{children:["Кто генерирует",l.jsx("input",{value:W.generatedBy,onChange:a=>it(c=>({...c,generatedBy:a.target.value})),placeholder:"manual_reviewer"})]}),l.jsxs("label",{className:"full-width",children:["Промпт личности",l.jsx("textarea",{className:"autoruns-personality-prompt",value:W.personalityPrompts[W.personalityId]??"",onChange:a=>it(c=>({...c,personalityPrompts:{...c.personalityPrompts,[c.personalityId]:a.target.value}})),placeholder:"Текст промпта для выбранной личности автогенерации",style:{height:`${or}px`},onMouseUp:Hs,onTouchEnd:Hs})]}),l.jsxs("label",{className:"checkbox-row",children:[l.jsx("input",{type:"checkbox",checked:W.persistToEvalCases,onChange:a=>it(c=>({...c,persistToEvalCases:a.target.checked}))}),"Сохранять кейс-сет в `eval_cases`"]})]})]}),Kt?null:l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Дата анализа (срез)",l.jsx("input",{type:"date",value:We,onChange:a=>ne(la(a.target.value))})]}),l.jsx("div",{className:"button-row",children:l.jsx("button",{type:"button",className:"tab",disabled:!We,onClick:()=>ne(""),children:"Сбросить дату среза"})})]}),l.jsxs("div",{className:"button-row",children:[Kt?null:l.jsxs(l.Fragment,{children:[l.jsx("button",{type:"button",disabled:Nr,onClick:()=>{os()},children:Nr?"Генерирую...":"Сгенерировать пачку"}),l.jsx("button",{type:"button",className:"tab",disabled:cn,onClick:()=>{Qt()},children:cn?"Обновляю...":"Обновить историю"})]}),l.jsx("button",{type:"button",className:"autoruns-run-launch-btn",disabled:es||mt.length===0||!kt,onClick:()=>{jo()},children:es?"Запускаю...":"Запустить прогон"})]}),l.jsx("div",{className:"autoruns-form-grid",children:l.jsxs("label",{className:"full-width",children:[Kt?"Сохраненная сессия":"Кейс-сет для запуска",l.jsxs("select",{value:Dn,onChange:a=>kn(a.target.value),disabled:pt.length===0,children:[pt.length===0?l.jsx("option",{value:"",children:Kt?"нет сохраненных сессий":"нет генераций"}):null,pt.map(a=>l.jsxs("option",{value:a.generation_id,children:[tn(a.created_at)," | ",Fc(a)??ia(a.mode)," | ",a.count]},a.generation_id))]})]})}),l.jsxs("div",{className:"autoruns-generated-questions",children:[l.jsxs("div",{className:"autoruns-generated-questions-head",children:[l.jsxs("strong",{children:["Вопросы к запуску: ",mt.length]}),l.jsx("button",{type:"button",className:"tab",onClick:()=>zt([...kt?.questions??[]]),disabled:!kt,children:"Восстановить"})]}),mt.length===0?l.jsx("p",{className:"muted",children:Kt?"Список вопросов пуст. Сначала сохраните живую пользовательскую сессию.":"Список вопросов пуст. Сгенерируйте пачку или восстановите из выбранной генерации."}):l.jsx("div",{className:"autoruns-generated-questions-list",children:mt.map((a,c)=>l.jsxs("div",{className:"autoruns-generated-question-item",children:[l.jsxs("span",{children:[c+1,". ",a]}),l.jsx("button",{type:"button",className:"autoruns-remove-question-btn",onClick:()=>{if(Kt){jt(c);return}zt(p=>p.filter((j,$)=>$!==c))},title:"Удалить вопрос из запуска","aria-label":"Удалить вопрос из запуска",children:"×"})]},`${c}-${a.slice(0,24)}`))})]}),l.jsx("p",{className:"muted",children:Kt?"Запуск воспроизводит сохраненную пользовательскую сессию как один последовательный multi-turn сценарий assistant_stage1.":"Запуск выполняет `assistant_stage1` eval по выбранному кейс-сету."}),l.jsxs("div",{className:"autoruns-autogen-list",children:[cn?l.jsx("p",{className:"muted",children:Kt?"Загружаю сохраненные пользовательские сессии...":"Загружаю историю автогенераций..."}):null,!cn&&pt.length===0?l.jsx("p",{className:"muted",children:Kt?"Сохраненные пользовательские сессии пока пусты.":"История автогенераций пока пустая."}):null,pt.slice(0,30).map(a=>l.jsxs("article",{className:Dn===a.generation_id?"autoruns-autogen-item selected":"autoruns-autogen-item",onClick:()=>kn(a.generation_id),children:[l.jsxs("header",{children:[l.jsx("strong",{children:Fc(a)}),l.jsxs("div",{className:"autoruns-autogen-card-actions",children:[l.jsx("span",{children:tn(a.created_at)}),l.jsx("button",{type:"button",className:"autoruns-autogen-delete-btn",onClick:c=>{c.preventDefault(),c.stopPropagation(),Qs(a)},title:"Удалить сохраненный набор","aria-label":`Удалить набор ${a.generation_id}`,children:"×"})]})]}),l.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[l.jsx("span",{children:a.generation_id}),l.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{Nn(c,a.generation_id,"set id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Nn(c,a.generation_id,"set id"))},title:"Скопировать id набора","aria-label":`Скопировать id набора ${a.generation_id}`,children:l.jsx(bc,{})})]}),l.jsxs("div",{className:"autoruns-run-meta",children:["режим=",ia(a.mode)," | count=",a.count]}),Yc(a)?l.jsxs("div",{className:"autoruns-run-meta",children:["тип=АГЕНТНЫЙ ПРОГОН",a.context?.architecture_phase?` | этап=${a.context.architecture_phase}`:"",a.context?.agent_focus?` | фокус=${a.context.agent_focus}`:""]}):null,a.domain||a.generated_by?l.jsxs("div",{className:"autoruns-run-meta",children:[a.domain?`домен=${a.domain}`:"домен=общий",a.generated_by?` | автор=${a.generated_by}`:""]}):null,a.saved_case_set_file?l.jsxs("div",{className:"autoruns-run-meta",children:["кейс-сет=",a.saved_case_set_file]}):null,(a.questions??[]).length>0?l.jsx("p",{children:a.questions[0]}):null]},a.generation_id))]}),l.jsxs("details",{className:"autoruns-prompt-details",children:[l.jsx("summary",{children:"Копия активного промпта (только чтение)"}),l.jsxs("label",{children:["Системный",l.jsx("textarea",{readOnly:!0,value:z.systemPrompt})]}),l.jsxs("label",{children:["Разработчика",l.jsx("textarea",{readOnly:!0,value:z.developerPrompt})]}),l.jsxs("label",{children:["Доменный",l.jsx("textarea",{readOnly:!0,value:z.domainPrompt})]}),l.jsxs("label",{children:["Заметки по схеме",l.jsx("textarea",{readOnly:!0,value:z.schemaNotes})]}),l.jsxs("label",{children:["Примеры few-shot",l.jsx("textarea",{readOnly:!0,value:z.fewShotExamples})]})]}),nr?l.jsx("p",{className:"error-text",children:nr}):null]}):null,l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Выдача прогонов"})}),l.jsxs("div",{className:"autoruns-stats-grid",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Всего"}),l.jsx("strong",{children:(Z?.stats.runs_total??0)+(qe?1:0)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Средний score"}),l.jsx("strong",{children:jl(Z?.stats.avg_score_index??null)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Тренд"}),l.jsx("strong",{children:Z?Uc(Z.stats.trend):"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Блокеры"}),l.jsx("strong",{children:Z?.stats.blocking_runs??0})]})]}),l.jsxs("div",{className:"autoruns-run-list",children:[ss.map(a=>l.jsxs("button",{type:"button",className:Ee===a.run_id?"autoruns-run-item selected":"autoruns-run-item",onClick:()=>{Pn(a.run_id)},children:[l.jsxs("div",{className:"autoruns-run-head",children:[l.jsx("strong",{children:tn(a.run_timestamp)}),l.jsx("span",{children:lm(a.eval_target)})]}),l.jsxs("div",{className:"autoruns-run-meta autoruns-run-id-row",children:[l.jsx("span",{children:a.run_id}),l.jsx("span",{role:"button",tabIndex:0,className:"autoruns-copy-run-id-btn",onClick:c=>{Nn(c,a.run_id,"run id")},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Nn(c,a.run_id,"run id"))},title:"Скопировать run id","aria-label":`Скопировать run id ${a.run_id}`,children:l.jsx(bc,{})})]}),l.jsxs("div",{className:"autoruns-run-meta",children:["режим=",a.mode??"нет данных"," | mock=",String(a.use_mock)]}),l.jsxs("div",{className:"autoruns-run-meta",children:["analysis_date=",a.analysis_date??"current_state"]}),a.llm_provider||a.model?l.jsxs("div",{className:"autoruns-run-meta",children:["llm=",a.llm_provider??"нет данных"," | модель=",a.model??"нет данных"]}):null,l.jsxs("div",{className:"autoruns-run-meta",children:["промпт=",a.prompt_version??"нет данных"]}),l.jsxs("div",{className:"autoruns-run-foot",children:[l.jsxs("span",{children:["оценка: ",jl(a.score_index)]}),l.jsxs("span",{children:["закрыто/открыто: ",a.closed_cases,"/",a.open_cases]})]}),l.jsxs("div",{className:"autoruns-run-foot",children:[l.jsxs("span",{children:["блокеры: ",a.blocking_failures]}),l.jsxs("span",{children:["качество: ",a.quality_failures]})]})]},a.run_id)),ss.length===0?l.jsx("p",{className:"muted",children:"За выбранный диапазон прогонов нет."}):null]})]}),l.jsxs("section",{className:"autoruns-col",children:[l.jsxs("div",{className:"autoruns-col-header",children:[l.jsx("h3",{children:"Диалог прогона"}),l.jsxs("div",{className:"autoruns-dialog-toolbar",children:[l.jsxs("label",{children:["Прогон",l.jsx("select",{value:Ee,onChange:a=>{const c=a.target.value;Pn(c)},children:ss.map(a=>l.jsxs("option",{value:a.run_id,children:[tn(a.run_timestamp)," | ",a.run_id]},a.run_id))})]}),l.jsxs("label",{children:["Кейс",l.jsxs("select",{value:et,onChange:a=>{const c=a.target.value;ft(c),Ee&&c&&$r(Ee,c)},children:[(U?.cases.length??0)>0?l.jsx("option",{value:_t,children:"ВСЕ кейсы подряд"}):null,(U?.cases??[]).map(a=>l.jsxs("option",{value:a.case_id,children:[a.case_id," | ",a.status]},a.case_id))]})]})]})]}),l.jsxs("div",{className:"autoruns-case-list",children:[(U?.cases.length??0)>0?l.jsxs("button",{type:"button",className:et===_t?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{ft(_t),Ee&&$r(Ee,_t)},children:[l.jsx("span",{children:"ВСЕ кейсы подряд"}),l.jsx("span",{children:U?.cases.length})]},_t):null,(U?.cases??[]).map(a=>l.jsxs("button",{type:"button",className:et===a.case_id?"autoruns-case-item selected":"autoruns-case-item",onClick:()=>{ft(a.case_id),Ee&&$r(Ee,a.case_id)},children:[l.jsx("span",{children:a.case_id}),l.jsxs("span",{children:[a.status,a.commented_count>0?` | комм=${a.commented_count}`:""]})]},a.case_id))]}),l.jsxs("div",{className:"autoruns-dialog-view",children:[Tr||er?l.jsx("p",{className:"muted",children:"Загружаю диалог..."}):null,!Tr&&!er&&(v?.messages.length??0)===0?l.jsx("p",{className:"muted",children:"Диалог для этого прогона не найден."}):null,(v?.messages??[]).map((a,c)=>{const p=a.role==="assistant"?"assistant":"user";return l.jsxs("article",{className:`autoruns-msg ${p}`,children:[l.jsxs("header",{children:[l.jsx("strong",{children:p==="assistant"?"Система":"Модель/вопрос"}),l.jsxs("div",{className:"autoruns-msg-head-actions",children:[a.case_id?l.jsx("span",{className:"autoruns-msg-case-tag",children:a.case_id}):null,l.jsx("span",{children:a.created_at?tn(a.created_at):"нет данных"}),p==="assistant"&&!Ms(Ee)?l.jsxs(l.Fragment,{children:[l.jsx("button",{type:"button",className:a.commented?"autoruns-comment-icon commented":"autoruns-comment-icon",onClick:()=>Tn(a),title:"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b","aria-label":"\\u041a\\u043e\\u043c\\u043c\\u0435\\u043d\\u0442\\u0438\\u0440\\u043e\\u0432\\u0430\\u0442\\u044c \\u043e\\u0442\\u0432\\u0435\\u0442 \\u0441\\u0438\\u0441\\u0442\\u0435\\u043c\\u044b",children:l.jsx(im,{commented:a.commented})}),a.annotation?l.jsx("button",{type:"button",className:a.annotation.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:()=>{us(a.annotation,!a.annotation.resolved)},disabled:Mr===a.annotation.annotation_id,title:a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":a.annotation.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:l.jsx(Qc,{resolved:a.annotation.resolved})}):null]}):null]})]}),l.jsx("p",{children:a.text}),p==="assistant"&&a.annotation?l.jsxs("div",{className:"autoruns-msg-annotation",children:[l.jsx("strong",{children:aa(a.annotation.rating)}),l.jsx("span",{children:a.annotation.comment}),l.jsxs("span",{className:"muted",children:[a.annotation.manual_case_decision,a.annotation.annotation_author?` | ${a.annotation.annotation_author}`:""]})]}):null,(a.trace_id||a.reply_type)&&l.jsxs("footer",{children:[a.trace_id?l.jsxs("span",{children:["trace=",a.trace_id]}):null,a.reply_type?l.jsxs("span",{children:["reply_type=",a.reply_type]}):null]})]},a.message_id??`${p}-${c}`)})]})]}),dt?l.jsx("div",{className:"autoruns-col autoruns-assistant-live-col",children:l.jsx(Gf,{sessionId:k,conversation:D,inputValue:As,onInputChange:Ls,selectedContextChip:fn,onSelectContextChip:ts,onClearContextChip:()=>ts(null),useMock:ns,onUseMockChange:Tl,onSend:Ml,onClear:En,onSaveSession:wo,busy:Is,saveBusy:Ue.saving,saveDisabled:!k.trim()||D.length===0||Is,statusText:xo,errorMessage:Rl,showSaveAction:!0,showCommentAction:!0,onCommentAssistantMessage:as,isAssistantMessageCommented:is,canCommentAssistantMessage:Co})}):null,st?l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Прогресс / регресс"})}),l.jsxs("div",{className:"autoruns-stats-grid",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Последний score"}),l.jsx("strong",{children:jl(Z?.stats.latest_score_index??null)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Предыдущий"}),l.jsx("strong",{children:jl(Z?.stats.previous_score_index??null)})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Тренд"}),l.jsx("strong",{children:Z?Uc(Z.stats.trend):"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Пробелы качества"}),l.jsx("strong",{children:Z?.stats.quality_gap_runs??0})]})]}),l.jsx("h4",{children:"Покрытие доменов (история)"}),Bc(Z?.stats.domain_coverage??[]),l.jsx("h4",{style:{marginTop:14},children:"Покрытие доменов (выбранный прогон)"}),Bc(U?.coverage.domain_coverage??[]),l.jsx("h4",{style:{marginTop:14},children:"Очереди фиксов пост-анализа"}),an?l.jsx("p",{className:"muted",children:"Собираю пост-анализ..."}):null,an?null:l.jsx("div",{className:"autoruns-stats-grid",children:Object.entries(on?.post_analysis.stats.by_queue??{}).map(([a,c])=>l.jsxs("div",{children:[l.jsx("span",{children:a}),l.jsx("strong",{children:c})]},a))}),l.jsxs("div",{className:"autoruns-autogen-list",children:[(on?.post_analysis.recommended_regression_candidates??[]).slice(0,12).map(a=>l.jsxs("article",{className:"autoruns-autogen-item",children:[l.jsxs("header",{children:[l.jsx("strong",{children:a.manual_case_decision}),l.jsxs("span",{children:[a.rating,"/5"]})]}),l.jsxs("div",{className:"autoruns-run-meta",children:[a.domain??"неизвестно"," / ",a.query_class??"неизвестно"]}),l.jsx("p",{children:a.comment})]},a.annotation_id)),!an&&(on?.post_analysis.recommended_regression_candidates.length??0)===0?l.jsx("p",{className:"muted",children:"Рекомендованных кандидатов пока нет."}):null]})]}):null,Dt?l.jsxs("section",{className:"autoruns-col",children:[l.jsx("div",{className:"autoruns-col-header",children:l.jsx("h3",{children:"Комментарии"})}),l.jsx("h4",{children:"Размеченные ответы"}),l.jsxs("div",{className:"autoruns-comment-filter-row",children:[l.jsxs("label",{children:["Фильтр решений",l.jsxs("select",{value:ae,onChange:a=>he(a.target.value),children:[l.jsx("option",{value:"all",children:"все"}),(qt.length>0?qt:we?.enum??[]).map(a=>l.jsx("option",{value:a,children:String(we?.labels?.[a]??a)},a))]})]}),l.jsx("button",{type:"button",className:"tab autoruns-resolved-filter-toggle",onClick:()=>_e(a=>!a),children:xe?"Показать выполненные":"Скрыть выполненные"})]}),l.jsxs("div",{className:"autoruns-stats-grid",children:[l.jsxs("div",{children:[l.jsx("span",{children:"Комментариев"}),l.jsx("strong",{children:Ft.length})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Средний рейтинг"}),l.jsx("strong",{children:Us===null?"нет данных":`${Us.toFixed(2)} / 5`})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Последний"}),l.jsx("strong",{children:Ft.length>0?tn(Ft[0].updated_at):"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"Статус"}),l.jsx("strong",{children:jn?"обновляю":"готово"})]})]}),l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",disabled:jn,onClick:()=>{zr()},children:jn?"Обновляю...":"Обновить список"}),l.jsx("button",{type:"button",className:"tab",disabled:an,onClick:()=>{ht()},children:an?"Идет пост-анализ...":"Обновить пост-анализ"})]}),l.jsxs("div",{className:"autoruns-comments-list",children:[jn?l.jsx("p",{className:"muted",children:"Загружаю комментарии..."}):null,!jn&&Ft.length===0?l.jsx("p",{className:"muted",children:re.length===0&&Ke.length===0?"Пока нет откомментированных ответов.":"Нет открытых кейсов по текущему фильтру."}):null,Ft.map(a=>{if(a.source==="assistant_live"){const p=a.assistant;return l.jsxs("article",{className:"autoruns-comment-item",children:[l.jsxs("div",{className:"autoruns-comment-head",children:[l.jsx("strong",{children:aa(p.rating)}),l.jsx("div",{className:"autoruns-comment-head-actions",children:l.jsx("span",{children:tn(p.updated_at)})})]}),l.jsxs("div",{className:"autoruns-run-meta",children:["live-session: ",p.session_id]}),l.jsxs("div",{className:"autoruns-run-meta",children:["msg=",p.message_index]}),l.jsxs("div",{className:"autoruns-run-meta",children:["source=assistant_live",p.annotation_author?` | author=${p.annotation_author}`:""]}),p.context.question_text?l.jsxs("p",{children:["Q: ",p.context.question_text]}):null,p.context.answer_text?l.jsxs("p",{children:["A: ",p.context.answer_text]}):null,l.jsx("p",{children:p.comment})]},a.key)}const c=a.autorun;return l.jsxs("article",{className:wn===c.annotation_id?"autoruns-comment-item selected":"autoruns-comment-item",onClick:()=>{cs(c)},role:"button",tabIndex:0,onKeyDown:p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),cs(c))},children:[l.jsxs("div",{className:"autoruns-comment-head",children:[l.jsx("strong",{children:aa(c.rating)}),l.jsxs("div",{className:"autoruns-comment-head-actions",children:[l.jsx("span",{children:tn(c.updated_at)}),l.jsx("button",{type:"button",className:c.resolved?"autoruns-resolve-toggle resolved":"autoruns-resolve-toggle",onClick:p=>{p.preventDefault(),p.stopPropagation(),us(c,!c.resolved)},disabled:Mr===c.annotation_id,title:c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный","aria-label":c.resolved?"Отметить кейс как невыполненный":"Отметить кейс как выполненный",children:l.jsx(Qc,{resolved:c.resolved})})]})]}),l.jsx("div",{className:"autoruns-run-meta",children:c.run_id}),l.jsxs("div",{className:"autoruns-run-meta",children:["case=",c.case_id," | msg=",c.message_index]}),l.jsxs("div",{className:"autoruns-run-meta",children:["decision=",c.manual_case_decision,c.annotation_author?` | author=${c.annotation_author}`:""]}),c.resolved_at?l.jsxs("div",{className:"autoruns-run-meta",children:["выполнено",": ",tn(c.resolved_at),c.resolved_by?` | by=${c.resolved_by}`:""]}):null,c.context.question_text?l.jsxs("p",{children:["Q: ",c.context.question_text]}):null,c.context.answer_text?l.jsxs("p",{children:["A: ",c.context.answer_text]}):null,l.jsx("p",{children:c.comment})]},a.key)})]}),Ne?l.jsxs(l.Fragment,{children:[l.jsx("h4",{children:"Тех-контекст брака"}),l.jsxs("div",{className:"autoruns-meta-list",children:[l.jsxs("div",{children:[l.jsx("span",{children:"trace:"}),l.jsx("strong",{children:Ne.technical_context.trace_id??"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"reply_type:"}),l.jsx("strong",{children:Ne.technical_context.reply_type??"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"domain:"}),l.jsx("strong",{children:Ne.technical_context.domain??"нет данных"})]}),l.jsxs("div",{children:[l.jsx("span",{children:"query_class:"}),l.jsx("strong",{children:Ne.technical_context.query_class??"нет данных"})]})]}),l.jsx("h4",{children:"JSON разбор"}),l.jsx(Gc,{value:{annotation_id:Ne.annotation_id,run_id:Ne.run_id,case_id:Ne.case_id,message_index:Ne.message_index,rating:Ne.rating,comment:Ne.comment,manual_case_decision:Ne.manual_case_decision,annotation_author:Ne.annotation_author,resolved:Ne.resolved,resolved_at:Ne.resolved_at,resolved_by:Ne.resolved_by,context:Ne.context,technical_context:Ne.technical_context,case_summary:Ne.case_summary?{case_id:Ne.case_summary.case_id,domain:Ne.case_summary.domain,query_class:Ne.case_summary.query_class,checks:Ne.case_summary.checks,metric_subscores:Ne.case_summary.metric_subscores}:null}})]}):null]}):null]}),Ue.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Ut()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Сохранить ручную сессию"}),l.jsx("p",{className:"muted",children:"Технический чат будет сохранен в автопрогоны как пользовательская multi-turn сессия."}),l.jsxs("label",{children:["Название",l.jsx("input",{value:Ue.title,onChange:a=>Fn(c=>({...c,title:a.target.value})),placeholder:"Например: НДС и склад на март 2020",disabled:Ue.saving})]}),Ue.error?l.jsx("p",{className:"error-text",children:Ue.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{Dr()},disabled:Ue.saving,children:Ue.saving?"Сохраняю...":"Сохранить"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>Ut(),disabled:Ue.saving,children:"Отмена"})]})]})}):null,$t.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Bt()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Удалить вопрос"}),l.jsx("p",{className:"muted",children:"Действительно удалить вопрос из сохраненной пользовательской сессии?"}),l.jsx("p",{className:"autoruns-comment-quote",children:$t.questionText}),$t.error?l.jsx("p",{className:"error-text",children:$t.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{ur()},disabled:$t.saving,children:$t.saving?"Удаляю...":"Да"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>Bt(),disabled:$t.saving,children:"Нет"})]})]})}):null,Et.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&Ht()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Удалить сохраненный набор"}),l.jsx("p",{className:"muted",children:"Будет удалена карточка истории и связанный файл кейс-сета на бэке."}),l.jsx("p",{className:"autoruns-comment-quote",children:Et.title}),Et.error?l.jsx("p",{className:"error-text",children:Et.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{Ur()},disabled:Et.saving,children:Et.saving?"Удаляю...":"Да"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>Ht(),disabled:Et.saving,children:"Нет"})]})]})}):null,ue.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&hn()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Комментарий к ответу ассистента"}),l.jsx("p",{className:"muted",children:"Комментарий будет добавлен в общий список комментариев справа с меткой `assistant_live`."}),Fs?l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Вопрос пользователя"}),l.jsx("p",{className:"autoruns-comment-quote",children:Fs.text})]}):null,$s?l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Ответ ассистента"}),l.jsx("p",{className:"autoruns-comment-quote",children:$s.text})]}):null,l.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа ассистента",children:[1,2,3,4,5].map(a=>l.jsx("button",{type:"button",className:ue.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>mn(c=>({...c,rating:a})),disabled:ue.saving,"aria-label":`Оценка ${a}`,children:ue.rating>=a?"●":"○"},a))}),l.jsx("div",{className:"autoruns-form-grid",children:l.jsxs("label",{children:["Автор комментария",l.jsx("input",{value:ue.annotationAuthor,onChange:a=>mn(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ue.saving})]})}),l.jsxs("label",{children:["Комментарий",l.jsx("textarea",{value:ue.comment,onChange:a=>mn(c=>({...c,comment:a.target.value})),placeholder:"Что именно не так в ответе и что нужно исправить.",rows:4,disabled:ue.saving})]}),ue.error?l.jsx("p",{className:"error-text",children:ue.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{No()},disabled:ue.saving,children:ue.saving?"Сохраняю...":"Готово"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>hn(),disabled:ue.saving,children:"Отмена"})]})]})}):null,ge.open?l.jsx("div",{className:"autoruns-comment-modal-backdrop",onClick:a=>{a.target===a.currentTarget&&ar()},children:l.jsxs("div",{className:"autoruns-comment-modal",children:[l.jsx("h3",{children:"Комментарий к ответу системы"}),l.jsx("p",{className:"muted",children:"Оцените ответ по 5-балльной шкале и добавьте комментарий по браку."}),So?l.jsxs(l.Fragment,{children:[l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Вопрос пользователя"}),l.jsx("p",{className:"autoruns-comment-quote",children:zs?.text??"Вопрос в диалоге не найден."})]}),l.jsxs("details",{className:"autoruns-prompt-details",open:!0,children:[l.jsx("summary",{children:"Ответ системы"}),l.jsx("p",{className:"autoruns-comment-quote",children:So.text})]})]}):null,l.jsx("div",{className:"autoruns-rating-row",role:"group","aria-label":"Рейтинг ответа",children:[1,2,3,4,5].map(a=>l.jsx("button",{type:"button",className:ge.rating>=a?"autoruns-rating-dot active":"autoruns-rating-dot",onClick:()=>wt(c=>({...c,rating:a})),disabled:ge.saving,"aria-label":`Оценка ${a}`,children:ge.rating>=a?"●":"○"},a))}),l.jsxs("div",{className:"autoruns-form-grid",children:[l.jsxs("label",{children:["Решение по кейсу",l.jsx("select",{value:ge.manualCaseDecision,onChange:a=>wt(c=>({...c,manualCaseDecision:a.target.value})),disabled:ge.saving,children:(qt.length>0?qt:we?.enum??[wl]).map(a=>l.jsx("option",{value:a,children:String(we?.labels?.[a]??a)},a))})]}),l.jsxs("label",{children:["Автор комментария",l.jsx("input",{value:ge.annotationAuthor,onChange:a=>wt(c=>({...c,annotationAuthor:a.target.value})),placeholder:"manual_reviewer",disabled:ge.saving})]})]}),l.jsxs("label",{children:["Комментарий",l.jsx("textarea",{value:ge.comment,onChange:a=>wt(c=>({...c,comment:a.target.value})),placeholder:"Почему ответ бракованный, что именно пошло не так, какие технические детали проверить.",rows:4,disabled:ge.saving})]}),ge.error?l.jsx("p",{className:"error-text",children:ge.error}):null,l.jsxs("div",{className:"button-row",children:[l.jsx("button",{type:"button",onClick:()=>{ls()},disabled:ge.saving,children:ge.saving?"Сохраняю...":"Готово"}),l.jsx("button",{type:"button",className:"tab",onClick:()=>ar(),disabled:ge.saving,children:"Отмена"})]})]})}):null]})}const um={llmProvider:"openai",apiKey:"",model:"gpt-4o-mini",baseUrl:"https://api.openai.com/v1",temperature:0,maxOutputTokens:700},Vc={systemPrompt:"Ты semantic-normalizer для бухгалтерского ассистента NDC. Возвращай только JSON по схеме normalized_query_v2_0_2.",developerPrompt:"Сначала делай decomposition сообщения на task fragments, затем определяй domain scope и route-critical flags. Для каждого fragment заполняй execution_readiness + route_status + no_route_reason. Если fragment routable, не оставляй его в no_route.",domainPrompt:"Контур: данные текущего предприятия в 1С/NDC. In-scope: документы, проводки, взаиморасчеты, остатки, периодное закрытие, аномалии и контрольные проверки. Out-of-scope: общая теория, законы и оффтоп.",schemaNotes:"schema_version: normalized_query_v2_0_2. Строгий JSON без дополнительных полей.",fewShotExamples:"Q: Проверь по поставщикам хвосты и разложи цепочку документов/оплат. => fragment in_scope, flags: multi_entity + chain_explanation. Q: Как вообще по ФСБУ? => out_of_scope/generic_accounting."},cm={userQuestion:"",batchQuestionsRaw:"",periodHint:"",businessContext:"",expectedRoute:""},ua={colors:{backgroundRgb:"18, 18, 18",mainSurfaceRgb:"25, 25, 25",horizontalSurfaceRgb:"30, 30, 30",focusSurfaceRgb:"35, 35, 35",assistantChipRgb:"18, 18, 18",assistantChipHoverRgb:"44, 44, 44",assistantChipSelectedRgb:"167, 59, 255",assistantChipSelectedTextRgb:"240, 240, 240",activeRgb:"167, 59, 255",activeTextRgb:"240, 240, 240",textMainRgb:"240, 240, 240",textMutedRgb:"166, 166, 166",dangerRgb:"126, 126, 126",scrollbarTrackRgb:"20, 20, 20",scrollbarThumbRgb:"30, 30, 30",scrollbarThumbHoverRgb:"30, 50, 30"},layout:{modeColumnWidthPx:406,modeToggleWidthPx:188}},Wc="ndc_normalizer_session_config_v1",qc="ndc_autoruns_layout_config_v1",dm="ndc-autoruns-save",fm="autoruns",ca="normalizer_v2_0_2",mm="address_query_runtime_v1",pm=["normalized","fragments","scope","flags","route","raw","validation","logs"];function hm(i){return`[${new Date().toLocaleTimeString("ru-RU")}] ${i}`}function gm(i,h){if(!h)return"Previous preset is not selected.";const R=["systemPrompt","developerPrompt","domainPrompt","schemaNotes","fewShotExamples"].filter(E=>i[E]!==h[E]).map(E=>`${E}: ${Math.abs(i[E].length-h[E].length)} chars delta`);return R.length===0?"No changes against previous preset.":`Changed fields: ${R.length}. ${R.join(" | ")}`}function vm(){const[i,h]=y.useState(um),[f,R]=y.useState(Vc),[E,L]=y.useState(cm),[Q,le]=y.useState(null),[te,z]=y.useState([]),[Y,X]=y.useState([]),[ee,Te]=y.useState("normalized"),[ce,de]=y.useState(!1),[pe,Qe]=y.useState(!1),[Je,be]=y.useState([]),[Re,F]=y.useState(""),[oe,Ce]=y.useState([]),[$e,dt]=y.useState(""),[st,Dt]=y.useState("NDC custom preset"),[ot,H]=y.useState(null),[Me,We]=y.useState(""),[ne,Z]=y.useState(!1),[M,U]=y.useState([]),[A,v]=y.useState(""),[w,re]=y.useState([]),[ie,ae]=y.useState(!1),[he,xe]=y.useState(null),[_e,we]=y.useState(""),[lt,qt]=y.useState(fm),[Xn,wn]=y.useState(!0),[nn,Ee]=y.useState(!0),[Ot,et]=y.useState(!0),[ft,St]=y.useState(!0),[rn,W]=y.useState(!0),[it,Zn]=y.useState(!0),[In,Dn]=y.useState(!0),[kn,mt]=y.useState(!0),[zt,qe]=y.useState(!0),[sn,on]=y.useState(!0),[Zr,Nr]=y.useState(!0),[Er,es]=y.useState(!0),[ln,an]=y.useState(!0),un=y.useRef(!1),cn=y.useRef(!1),On=y.useRef(!1);y.useEffect(()=>{const k=document.documentElement,{colors:q}=ua;k.style.setProperty("--rgb-background",q.backgroundRgb),k.style.setProperty("--rgb-surface-main",q.mainSurfaceRgb),k.style.setProperty("--rgb-surface-horizontal",q.horizontalSurfaceRgb),k.style.setProperty("--rgb-surface-focus",q.focusSurfaceRgb),k.style.setProperty("--rgb-assistant-chip",q.assistantChipRgb),k.style.setProperty("--rgb-assistant-chip-hover",q.assistantChipHoverRgb),k.style.setProperty("--rgb-assistant-chip-selected",q.assistantChipSelectedRgb),k.style.setProperty("--rgb-assistant-chip-selected-text",q.assistantChipSelectedTextRgb),k.style.setProperty("--rgb-active",q.activeRgb),k.style.setProperty("--rgb-active-text",q.activeTextRgb),k.style.setProperty("--rgb-text-main",q.textMainRgb),k.style.setProperty("--rgb-text-muted",q.textMutedRgb),k.style.setProperty("--rgb-danger",q.dangerRgb),k.style.setProperty("--rgb-scrollbar-track",q.scrollbarTrackRgb),k.style.setProperty("--rgb-scrollbar-thumb",q.scrollbarThumbRgb),k.style.setProperty("--rgb-scrollbar-thumb-hover",q.scrollbarThumbHoverRgb),k.style.setProperty("--mode-column-width",`${ua.layout.modeColumnWidthPx}px`),k.style.setProperty("--mode-toggle-width",`${ua.layout.modeToggleWidthPx}px`)},[]);const me=k=>{X(q=>[hm(k),...q].slice(0,300))};y.useEffect(()=>{(async()=>{const D=localStorage.getItem(Wc);if(D)try{const ke=JSON.parse(D);h(Ke=>({...Ke,llmProvider:ke.llmProvider==="local"?"local":"openai",model:ke.model??Ke.model,baseUrl:ke.baseUrl??Ke.baseUrl,temperature:ke.temperature??Ke.temperature,maxOutputTokens:ke.maxOutputTokens??Ke.maxOutputTokens}))}catch{}try{const ke=await Pe.loadSharedConnectionConfig();ke.connection&&ke.connection.llmProvider==="local"&&(h(Ke=>({...Ke,llmProvider:"local",model:ke.connection?.model??Ke.model,baseUrl:ke.connection?.baseUrl??Ke.baseUrl,temperature:ke.connection?.temperature??Ke.temperature,maxOutputTokens:ke.connection?.maxOutputTokens??Ke.maxOutputTokens})),me(`Shared local LLM config loaded: ${ke.connection.model}`))}catch(ke){me(`Shared local config load error: ${ke instanceof Error?ke.message:String(ke)}`)}finally{On.current=!0}})();const q=localStorage.getItem(qc);if(q)try{const D=JSON.parse(q);(D.uiMode==="assistant"||D.uiMode==="autoruns"||D.uiMode==="decomposition")&&qt("autoruns"),D.activeTab&&pm.includes(D.activeTab)&&Te(D.activeTab),typeof D.showAutorunsSettingsMode=="boolean"&&wn(D.showAutorunsSettingsMode),typeof D.showAutorunsAutoRunsMode=="boolean"&&Ee(D.showAutorunsAutoRunsMode),typeof D.showAutorunsAssistantMode=="boolean"&&et(D.showAutorunsAssistantMode),typeof D.showAutorunsDecompositionMode=="boolean"&&St(D.showAutorunsDecompositionMode),typeof D.showAutorunsProgressMode=="boolean"&&W(D.showAutorunsProgressMode),typeof D.showAutorunsCommentsMode=="boolean"&&Zn(D.showAutorunsCommentsMode),typeof D.showDecompositionConnectionMode=="boolean"&&Dn(D.showDecompositionConnectionMode),typeof D.showDecompositionPromptMode=="boolean"&&mt(D.showDecompositionPromptMode),typeof D.showDecompositionQueryMode=="boolean"&&qe(D.showDecompositionQueryMode),typeof D.showDecompositionOutputMode=="boolean"&&on(D.showDecompositionOutputMode),typeof D.showDecompositionMetricsMode=="boolean"&&Nr(D.showDecompositionMetricsMode),typeof D.showDecompositionHistoryMode=="boolean"&&es(D.showDecompositionHistoryMode),typeof D.showDecompositionRuntimeMode=="boolean"&&an(D.showDecompositionRuntimeMode),D.prompts&&(R(ke=>({...ke,...D.prompts})),cn.current=!0)}catch{}dn(),er(),Pr()},[]),y.useEffect(()=>{if(!On.current||i.llmProvider!=="local")return;const k=window.setTimeout(()=>{Pe.saveSharedConnectionConfig(i).catch(q=>me(`Shared local config sync error: ${q instanceof Error?q.message:String(q)}`))},250);return()=>window.clearTimeout(k)},[i.baseUrl,i.llmProvider,i.maxOutputTokens,i.model,i.temperature]);async function dn(){try{const k=await Pe.loadHistory();z(k.items??[])}catch(k){me(`History load error: ${k instanceof Error?k.message:String(k)}`)}}async function er(){try{const q=(await Pe.loadPresets()).presets??[];if(Ce(q),cn.current){un.current=!0;return}if(un.current)return;const D=q.find(ke=>ke.prompt_version===ca)??q.find(ke=>ke.id==="default-normalizer-v2_0_2");if(!D){un.current=!0,me(`Preset autoload skipped: ${ca} not found.`);return}dt(D.id),H(f),R({systemPrompt:D.systemPrompt,developerPrompt:D.developerPrompt,domainPrompt:D.domainPrompt,schemaNotes:D.schemaNotes??"",fewShotExamples:D.fewShotExamples??""}),un.current=!0,me(`Preset autoloaded: ${D.name} (${D.prompt_version}).`)}catch(k){me(`Presets load error: ${k instanceof Error?k.message:String(k)}`)}}async function Pr(){try{const k=await Pe.listRuns();U(k.items??[])}catch(k){me(`Runs load error: ${k instanceof Error?k.message:String(k)}`)}}function Tr(){if(localStorage.setItem(Wc,JSON.stringify({model:i.model,llmProvider:i.llmProvider,baseUrl:i.baseUrl,temperature:i.temperature,maxOutputTokens:i.maxOutputTokens})),i.llmProvider==="local"){Pe.saveSharedConnectionConfig(i).then(()=>{me("Local config saved and synced to shared agent config (without API key).")}).catch(k=>{me(`Local config saved, but shared sync failed: ${k instanceof Error?k.message:String(k)}`)});return}me("Local config saved (without API key).")}function Rr(){localStorage.setItem(qc,JSON.stringify({uiMode:lt,activeTab:ee,showAutorunsSettingsMode:Xn,showAutorunsAutoRunsMode:nn,showAutorunsAssistantMode:Ot,showAutorunsDecompositionMode:ft,showAutorunsProgressMode:rn,showAutorunsCommentsMode:it,showDecompositionConnectionMode:In,showDecompositionPromptMode:kn,showDecompositionQueryMode:zt,showDecompositionOutputMode:sn,showDecompositionMetricsMode:Zr,showDecompositionHistoryMode:Er,showDecompositionRuntimeMode:ln,prompts:f})),window.dispatchEvent(new CustomEvent(dm)),me("UI layout and prompts saved.")}async function jn(){de(!0),we("");try{const k=await Pe.testConnection(i);k.provider==="local"?k.model_found===!0?(F(`LOCAL OK - ${k.model}`),me(`Local model is available: ${k.model} (catalog size=${k.models_count??"n/a"}).`)):k.model_found===!1?(F(`LOCAL OK, model not loaded - ${k.model}`),me(`Local server is reachable, but model '${k.model}' is not in loaded catalog. Use 'Load model list' and select one of loaded models.`)):(F(`LOCAL OK (model list unavailable) - ${k.model}`),me("Local server is reachable, but model catalog could not be verified.")):(F(`OPENAI OK - ${k.model}`),me(`OpenAI connection ok: ${k.model}`))}catch(k){const q=k instanceof Error?k.message:String(k);F("Connection error"),we(`Test connection: ${q}`),me(`Test connection error: ${q}`)}finally{de(!1)}}async function tr(){Qe(!0);try{const q=(await Pe.listModels(i)).models??[];be(q),q.length>0&&h(D=>D.model&&q.includes(D.model)?D:{...D,model:q[0]}),me(`Model catalog loaded (${i.llmProvider}): ${q.length} items.`)}catch(k){const q=k instanceof Error?k.message:String(k);me(`Load model list error: ${q}`)}finally{Qe(!1)}}y.useEffect(()=>{be([])},[i.llmProvider,i.baseUrl]);function Mr(){const k=oe.find(q=>q.id===$e);if(!k){me("Preset is not selected.");return}H(f),R({systemPrompt:k.systemPrompt,developerPrompt:k.developerPrompt,domainPrompt:k.domainPrompt,schemaNotes:k.schemaNotes??"",fewShotExamples:k.fewShotExamples??""}),me(`Preset loaded: ${k.name}`)}async function Cn(){try{await Pe.savePreset({name:st||"NDC preset",prompt_version:"normalizer_v2_0_2",systemPrompt:f.systemPrompt,developerPrompt:f.developerPrompt,domainPrompt:f.domainPrompt,schemaNotes:f.schemaNotes,fewShotExamples:f.fewShotExamples}),me("Preset saved."),await er()}catch(k){me(`Preset save error: ${k instanceof Error?k.message:String(k)}`)}}function nr(){R(Vc),me("Prompt panel reset to defaults.")}function Oe(){const k=gm(f,ot);We(k),me(k)}return y.useEffect(()=>{if(!A){re([]);return}Pe.runTrace(A).then(k=>re(k.items)).catch(k=>me(`Run trace error: ${k instanceof Error?k.message:String(k)}`))},[A]),l.jsxs("main",{className:"app-root app-root-autoruns",children:[l.jsxs("header",{className:"app-topbar",children:[l.jsxs("div",{className:"mode-switch-row",children:[l.jsx("button",{type:"button",className:"tab active",onClick:()=>qt("autoruns"),children:"Управление ассистентом"}),l.jsx("button",{type:"button",className:"tab",onClick:Rr,children:"Сохранить"})]}),l.jsxs("div",{className:"mode-switch-row mode-switch-row-right",children:[l.jsx("button",{type:"button",className:Xn?"tab active":"tab",onClick:()=>wn(k=>!k),children:"Настройки"}),l.jsx("button",{type:"button",className:nn?"tab active":"tab",onClick:()=>Ee(k=>!k),children:"Автопрогоны"}),l.jsx("button",{type:"button",className:Ot?"tab active":"tab",onClick:()=>et(k=>!k),children:"Режим ассистента"}),l.jsx("button",{type:"button",className:rn?"tab active":"tab",onClick:()=>W(k=>!k),children:"Прогресс/регресс"}),l.jsx("button",{type:"button",className:it?"tab active":"tab",onClick:()=>Zn(k=>!k),children:"Комментарии"})]})]}),l.jsx("div",{className:"layout-grid layout-grid-autoruns",children:l.jsx(am,{connection:i,modelOptions:Je,modelsBusy:pe,connectionStatus:Re,connectionBusy:ce,onConnectionChange:h,onReloadModels:tr,onSaveLocalConfig:Tr,onTestConnection:jn,prompts:f,onPromptsChange:R,promptPresets:oe,selectedPresetId:$e,onSelectPreset:dt,onLoadPreset:Mr,onSavePreset:Cn,onResetDefaults:nr,onDiffPrevious:Oe,presetName:st,onPresetNameChange:Dt,diffSummary:Me,assistantPromptVersion:mm,decompositionPromptVersion:ca,showSettingsMode:Xn,showAutoRunsMode:nn,showAssistantMode:Ot,showProgressMode:rn,showCommentsMode:it,onLog:me})})]})}Tf.createRoot(document.getElementById("root")).render(l.jsx(wf.StrictMode,{children:l.jsx(vm,{})})); diff --git a/llm_normalizer/frontend/dist/index.html b/llm_normalizer/frontend/dist/index.html index d2318c0..ebc55bb 100644 --- a/llm_normalizer/frontend/dist/index.html +++ b/llm_normalizer/frontend/dist/index.html @@ -4,7 +4,7 @@ NDC AI Normalizer Playground - + diff --git a/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx b/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx index e63c72c..137a61b 100644 --- a/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx +++ b/llm_normalizer/frontend/src/components/AutoRunsHistoryPanel.tsx @@ -289,6 +289,27 @@ function formatAutoGenModeLabel(mode: AutoGenMode): string { return mode; } +function isAgentSemanticGeneration(item: AutoGenHistoryRecord | null | undefined): boolean { + if (!item) { + return false; + } + if (item.context?.agent_run === true) { + return true; + } + if (item.context?.saved_case_set_kind === "agent_semantic_scenario") { + return true; + } + return typeof item.title === "string" && item.title.trim().toUpperCase().startsWith("AGENT"); +} + +function formatAutoGenGenerationTitle(item: AutoGenHistoryRecord): string { + const fallback = item.title ?? formatDateTime(item.created_at); + if (isAgentSemanticGeneration(item) && !fallback.trim().toUpperCase().startsWith("AGENT")) { + return `AGENT | ${fallback}`; + } + return fallback; +} + function buildSavedSessionDefaultTitle(items: AssistantConversationItem[]): string { const lastMessage = items[items.length - 1]; const timestamp = formatDateTime(lastMessage?.created_at ?? new Date().toISOString()); @@ -2375,7 +2396,7 @@ export function AutoRunsHistoryPanel({ ) : null} {visibleAutoGenHistory.map((item) => ( ))} @@ -2448,7 +2469,7 @@ export function AutoRunsHistoryPanel({ onClick={() => setSelectedAutogenGenerationId(item.generation_id)} >
- {item.title ?? formatDateTime(item.created_at)} + {formatAutoGenGenerationTitle(item)}
{formatDateTime(item.created_at)}
+ {isAgentSemanticGeneration(item) ? ( +
+ тип=АГЕНТНЫЙ ПРОГОН + {item.context?.architecture_phase ? ` | этап=${item.context.architecture_phase}` : ""} + {item.context?.agent_focus ? ` | фокус=${item.context.agent_focus}` : ""} +
+ ) : null} {item.domain || item.generated_by ? (
{item.domain ? `домен=${item.domain}` : "домен=общий"} diff --git a/llm_normalizer/frontend/src/state/types.ts b/llm_normalizer/frontend/src/state/types.ts index e94168d..0c1e1bb 100644 --- a/llm_normalizer/frontend/src/state/types.ts +++ b/llm_normalizer/frontend/src/state/types.ts @@ -334,6 +334,10 @@ export interface AutoGenHistoryRecord { source_session_id?: string | null; saved_session_file?: string | null; saved_case_set_kind?: string | null; + agent_run?: boolean | null; + agent_focus?: string | null; + architecture_phase?: string | null; + source_spec_file?: string | null; } | null; } diff --git a/scripts/save_agent_semantic_run.py b/scripts/save_agent_semantic_run.py new file mode 100644 index 0000000..97ac186 --- /dev/null +++ b/scripts/save_agent_semantic_run.py @@ -0,0 +1,318 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import re +import secrets +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + + +REPO_ROOT = Path(__file__).resolve().parents[1] +HISTORY_FILE = REPO_ROOT / "llm_normalizer" / "data" / "autorun_generators" / "history.json" +SAVED_SESSIONS_DIR = REPO_ROOT / "llm_normalizer" / "data" / "autorun_generators" / "saved_sessions" +EVAL_CASES_DIR = REPO_ROOT / "llm_normalizer" / "data" / "eval_cases" + + +def now_utc() -> datetime: + return datetime.now(timezone.utc).replace(microsecond=0) + + +def utc_stamp(dt: datetime) -> str: + return ( + f"{dt.year:04d}{dt.month:02d}{dt.day:02d}" + f"{dt.hour:02d}{dt.minute:02d}{dt.second:02d}" + ) + + +def generate_id(dt: datetime) -> str: + return f"gen-ag{dt.strftime('%m%d%H%M')}-{secrets.token_hex(3)}" + + +def sanitize_question(value: Any) -> str: + text = str(value or "").replace("\r\n", "\n").replace("\r", "\n") + text = "\n".join(line.strip() for line in text.split("\n")) + text = re.sub(r"[ \t]+", " ", text).strip() + return text + + +def ensure_agent_title(title: str) -> str: + normalized = title.strip() + if not normalized: + raise RuntimeError("Agent semantic run title must not be empty") + return normalized if normalized.upper().startswith("AGENT") else f"AGENT | {normalized}" + + +def load_json(path: Path) -> Any: + return json.loads(path.read_text(encoding="utf-8")) + + +def write_json(path: Path, payload: Any) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +def normalize_questions(raw_questions: list[Any]) -> list[str]: + result: list[str] = [] + seen: set[str] = set() + for item in raw_questions: + question = sanitize_question(item) + if not question or question in seen: + continue + seen.add(question) + result.append(question) + return result + + +def extract_questions_from_spec(spec: dict[str, Any]) -> list[str]: + if isinstance(spec.get("questions"), list): + return normalize_questions(list(spec["questions"])) + steps = spec.get("steps") + if isinstance(steps, list): + return normalize_questions( + [step.get("question") for step in steps if isinstance(step, dict) and step.get("question")] + ) + raise RuntimeError("Spec must define either `questions[]` or `steps[].question`") + + +def build_case_set_payload( + generation_id: str, + title: str, + questions: list[str], + domain: str | None, + scenario_tag: str, +) -> dict[str, Any]: + turns = [{"user_message": question} for question in questions] + case_id = "SAVED-001" + return { + "suite_id": f"assistant_saved_session_{generation_id}", + "suite_version": "0.1.0", + "schema_version": "assistant_saved_session_suite_v0_1", + "generated_at": now_utc().isoformat(), + "generation_id": generation_id, + "mode": "saved_user_sessions", + "title": title, + "domain": domain, + "scenario_count": 1 if turns else 0, + "case_ids": [case_id] if turns else [], + "cases": [ + { + "case_id": case_id, + "scenario_tag": scenario_tag, + "title": title, + "question_type": "followup" if len(turns) > 1 else "direct", + "broadness_level": "medium", + "turns": turns, + } + ] + if turns + else [], + } + + +def build_snapshot_payload( + generation_id: str, + title: str, + questions: list[str], + metadata: dict[str, Any], +) -> dict[str, Any]: + created_at = now_utc().isoformat() + items: list[dict[str, Any]] = [] + for index, question in enumerate(questions, start=1): + items.append( + { + "message_id": f"agent-user-{index:03d}", + "role": "user", + "text": question, + "created_at": created_at, + "reply_type": None, + "trace_id": None, + "debug": None, + } + ) + return { + "saved_at": created_at, + "generation_id": generation_id, + "mode": "saved_user_sessions", + "title": title, + "agent_run": True, + "questions": questions, + "metadata": metadata, + "source_session_id": None, + "session": { + "session_id": None, + "mode": "agent_semantic_run", + "items": items, + "agent_run": True, + "metadata": metadata, + }, + } + + +def read_history() -> list[dict[str, Any]]: + if not HISTORY_FILE.exists(): + return [] + parsed = load_json(HISTORY_FILE) + return parsed if isinstance(parsed, list) else [] + + +def build_history_record( + generation_id: str, + title: str, + questions: list[str], + case_set_file: str, + saved_session_file: str, + domain: str | None, + generated_by: str, + metadata: dict[str, Any], +) -> dict[str, Any]: + context = { + "llm_provider": None, + "model": None, + "assistant_prompt_version": metadata.get("assistant_prompt_version"), + "decomposition_prompt_version": metadata.get("decomposition_prompt_version"), + "prompt_fingerprint": metadata.get("prompt_fingerprint"), + "autogen_personality_id": None, + "autogen_personality_prompt": None, + "source_session_id": None, + "saved_session_file": saved_session_file, + "saved_case_set_kind": "agent_semantic_scenario", + "agent_run": True, + "agent_focus": metadata.get("agent_focus"), + "architecture_phase": metadata.get("architecture_phase"), + "source_spec_file": metadata.get("source_spec_file"), + } + return { + "generation_id": generation_id, + "created_at": now_utc().isoformat(), + "mode": "saved_user_sessions", + "title": title, + "count": len(questions), + "domain": domain, + "questions": questions, + "generated_by": generated_by, + "saved_case_set_file": case_set_file, + "context": context, + } + + +def build_metadata(args: argparse.Namespace, spec: dict[str, Any], spec_path: Path | None) -> dict[str, Any]: + return { + "assistant_prompt_version": args.assistant_prompt_version, + "decomposition_prompt_version": args.decomposition_prompt_version, + "prompt_fingerprint": args.prompt_fingerprint, + "agent_focus": args.agent_focus or spec.get("description") or spec.get("title"), + "architecture_phase": args.architecture_phase, + "source_spec_file": str(spec_path.resolve()) if spec_path else None, + } + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description="Save a targeted AGENT semantic run into autoruns user sessions.") + parser.add_argument("--spec", required=True, help="Path to a truth-harness spec or simple questions spec JSON.") + parser.add_argument("--title", help="Override title for the AGENT run.") + parser.add_argument("--generated-by", default="codex_agent", help="Author label for the generated run.") + parser.add_argument("--architecture-phase", default="turnaround_11", help="Architecture phase / slice being validated.") + parser.add_argument("--agent-focus", help="Short focus label for the targeted fix.") + parser.add_argument("--assistant-prompt-version", help="Optional assistant prompt version metadata.") + parser.add_argument("--decomposition-prompt-version", help="Optional decomposition prompt version metadata.") + parser.add_argument("--prompt-fingerprint", help="Optional prompt fingerprint metadata.") + parser.add_argument("--dry-run", action="store_true", help="Print resulting record metadata without writing files.") + return parser.parse_args() + + +def main() -> int: + args = parse_args() + spec_path = Path(args.spec) + if not spec_path.is_absolute(): + spec_path = (REPO_ROOT / spec_path).resolve() + if not spec_path.exists(): + raise RuntimeError(f"Spec file not found: {spec_path}") + + spec_raw = load_json(spec_path) + if not isinstance(spec_raw, dict): + raise RuntimeError("Spec JSON must be an object") + + questions = extract_questions_from_spec(spec_raw) + if not questions: + raise RuntimeError("Agent semantic run must contain at least one question") + + domain = str(spec_raw.get("domain") or "").strip() or None + source_title = str(args.title or spec_raw.get("title") or spec_path.stem).strip() + title = ensure_agent_title(source_title) + metadata = build_metadata(args, spec_raw, spec_path) + + timestamp = now_utc() + generation_id = generate_id(timestamp) + case_set_file = f"assistant_autogen_saved_user_sessions_{utc_stamp(timestamp)}_{generation_id}.json" + saved_session_file = f"assistant_saved_session_{utc_stamp(timestamp)}_{generation_id}.json" + case_set_payload = build_case_set_payload( + generation_id=generation_id, + title=title, + questions=questions, + domain=domain, + scenario_tag="agent_saved_user_sessions", + ) + snapshot_payload = build_snapshot_payload( + generation_id=generation_id, + title=title, + questions=questions, + metadata=metadata, + ) + record = build_history_record( + generation_id=generation_id, + title=title, + questions=questions, + case_set_file=case_set_file, + saved_session_file=saved_session_file, + domain=domain, + generated_by=str(args.generated_by or "codex_agent").strip() or "codex_agent", + metadata=metadata, + ) + + if args.dry_run: + print( + json.dumps( + { + "ok": True, + "dry_run": True, + "generation_id": generation_id, + "title": title, + "questions_total": len(questions), + "case_set_file": case_set_file, + "saved_session_file": saved_session_file, + "domain": domain, + }, + ensure_ascii=False, + indent=2, + ) + ) + return 0 + + write_json(EVAL_CASES_DIR / case_set_file, case_set_payload) + write_json(SAVED_SESSIONS_DIR / saved_session_file, snapshot_payload) + history = read_history() + history = [record, *[item for item in history if item.get("generation_id") != generation_id]] + write_json(HISTORY_FILE, history[:500]) + + print( + json.dumps( + { + "ok": True, + "generation_id": generation_id, + "title": title, + "questions_total": len(questions), + "case_set_file": case_set_file, + "saved_session_file": saved_session_file, + }, + ensure_ascii=False, + indent=2, + ) + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())