Укрепить семантику бизнес-ответов адресного контура

This commit is contained in:
2026-05-09 21:48:17 +03:00
parent f86cb8e886
commit dfbfe26501
48 changed files with 2644 additions and 176 deletions
@@ -356,6 +356,12 @@ function extractMonthPeriod(text) {
}
return {};
}
function isExactHistoricalPeriodWindow(filters) {
return (typeof filters.period_from === "string" &&
filters.period_from.trim().length > 0 &&
typeof filters.period_to === "string" &&
filters.period_to.trim().length > 0);
}
function extractPeriodRange(text) {
const directMatch = text.match(PERIOD_RANGE_PATTERN_1) ?? text.match(PERIOD_RANGE_PATTERN_2);
if (!directMatch) {
@@ -710,6 +716,9 @@ function isLowQualityCounterpartyAnchorValue(rawValue) {
if (meaningfulNonGenericTokens.length === 0 && (hasTemporalCue || paymentCue)) {
return true;
}
if (meaningfulNonGenericTokens.length === 0) {
return true;
}
const meaningfulTokens = tokens.filter((token) => isLikelyCounterpartyToken(token));
return meaningfulTokens.length === 0;
}
@@ -1407,6 +1416,9 @@ function resolveSemanticDateBasisHint(filters, warnings) {
const hasAsOfDate = typeof filters.as_of_date === "string" && filters.as_of_date.trim().length > 0;
const hasPeriodFrom = typeof filters.period_from === "string" && filters.period_from.trim().length > 0;
const hasPeriodTo = typeof filters.period_to === "string" && filters.period_to.trim().length > 0;
if (warnings.includes("as_of_date_derived_from_exact_historical_period") && (hasPeriodFrom || hasPeriodTo)) {
return hasPeriodFrom && hasPeriodTo ? "period_range" : "period_end";
}
if (hasPeriodFrom && hasPeriodTo) {
return "period_range";
}
@@ -1670,6 +1682,14 @@ function extractAddressFilters(userMessage, intent) {
warnings.push("period_derived_from_year_phrase");
}
}
if (isExactHistoricalPeriodWindow(filters) && !warnings.includes("exact_historical_period_window_requested")) {
const derivedFromHistoricalPhrase = warnings.includes("period_derived_from_month_phrase") ||
warnings.includes("period_derived_from_year_range_phrase") ||
warnings.includes("period_derived_from_year_phrase");
if (derivedFromHistoricalPhrase) {
warnings.push("exact_historical_period_window_requested");
}
}
const vatAsOfDate = explicitAsOfDateWithCue ?? explicitAsOfDate;
if (intent === "vat_payable_forecast" && vatAsOfDate && !periodRange.period_from && !periodRange.period_to) {
const quarterWindow = deriveQuarterWindowForDate(vatAsOfDate);
@@ -1685,10 +1705,12 @@ function extractAddressFilters(userMessage, intent) {
}
}
const monthPeriodWasDerived = warnings.includes("period_derived_from_month_phrase");
const yearPeriodWasDerived = warnings.includes("period_derived_from_year_phrase") || warnings.includes("period_derived_from_year_range_phrase");
if (intent === "vat_liability_confirmed_for_tax_period" &&
!periodRange.period_from &&
!periodRange.period_to &&
!monthPeriodWasDerived) {
!monthPeriodWasDerived &&
!yearPeriodWasDerived) {
const periodToForQuarter = filters.period_to ?? vatAsOfDate ?? null;
if (periodToForQuarter) {
const quarterWindow = deriveQuarterWindowForDate(periodToForQuarter);
@@ -1711,7 +1733,12 @@ function extractAddressFilters(userMessage, intent) {
const periodWasDerivedHeuristically = warnings.includes("period_derived_from_month_phrase") ||
warnings.includes("period_derived_from_year_range_phrase") ||
warnings.includes("period_derived_from_year_phrase");
const preserveDerivedPeriodWindow = intent === "inventory_on_hand_as_of_date" || intent === "inventory_supplier_stock_overlap_as_of_date";
const preserveDerivedPeriodWindow = usesAsOfPrimaryWindow(intent) ||
intent === "inventory_on_hand_as_of_date" ||
intent === "inventory_supplier_stock_overlap_as_of_date";
if (periodWasDerivedHeuristically && !warnings.includes("exact_historical_period_window_requested")) {
warnings.push("exact_historical_period_window_requested");
}
if (periodWasDerivedHeuristically && !periodRange.period_from && !periodRange.period_to && !preserveDerivedPeriodWindow) {
delete filters.period_from;
delete filters.period_to;
@@ -1738,6 +1765,14 @@ function extractAddressFilters(userMessage, intent) {
if (filters.period_to) {
filters.as_of_date = filters.period_to;
warnings.push("as_of_date_derived_from_period_to");
if (warnings.includes("period_derived_from_month_phrase") ||
warnings.includes("period_derived_from_year_range_phrase") ||
warnings.includes("period_derived_from_year_phrase")) {
warnings.push("as_of_date_derived_from_exact_historical_period");
if (!warnings.includes("exact_historical_period_window_requested")) {
warnings.push("exact_historical_period_window_requested");
}
}
}
else if (shouldDefaultAsOfDateToToday(intent)) {
filters.as_of_date = new Date().toISOString().slice(0, 10);
@@ -1724,6 +1724,10 @@ function resolveUnicodeAddressIntentBridge(text) {
]).has(byAnchorToken);
const hasMoneyCue = /(?:деньг|денег|выручк|доход|оборот|заработ|прин[её]с|чек|ликвидн|revenue|turnover|money)/iu.test(normalized);
const hasRankingCue = /(?:топ|ранк|сам(?:ый|ая|ое|ые)|больше\s+всего|наибольш|крупн|жирн|max|top|rank)/iu.test(normalized);
const hasInventoryPurchaseToSaleDocumentChainCue = /(?:закупк[а-яё]*[\s\S]{0,80}склад[\s\S]{0,80}продаж|путь\s+товар[а-яё]*[\s\S]{0,80}закуп|purchase\s*->\s*(?:warehouse|stock)\s*->\s*sale|->\s*(?:склад|warehouse|stock)\s*->\s*(?:продаж|sale))/iu.test(normalized) && /(?:товар|позици|номенклатур|sku|item|product)/iu.test(normalized);
if (hasInventoryPurchaseToSaleDocumentChainCue) {
return unicodeBridgeResolution("inventory_purchase_to_sale_chain", "high", "unicode_inventory_purchase_to_sale_chain_bridge_signal_detected");
}
const hasSelectedObjectProfitabilityCue = /(?:\u043f\u043e\s+\u0432\u044b\u0431\u0440\u0430\u043d\u043d(?:\u043e\u043c\u0443|\u043e\u0439)\s+(?:\u043e\u0431\u044a\u0435\u043a\u0442\u0443|\u043f\u043e\u0437\u0438\u0446\u0438\u0438)|selected\s+object)/iu.test(normalized) &&
(/(?:\u0437\u0430\u0440\u0430\u0431\u043e\u0442|\u043f\u0440\u0438\u0431\u044b\u043b|\u043c\u0430\u0440\u0436|profit|margin)/iu.test(normalized) ||
(/(?:\u043f\u0440\u043e\u0434\u0430\u0436|sale)/iu.test(normalized) &&
@@ -1731,10 +1735,6 @@ function resolveUnicodeAddressIntentBridge(text) {
if (hasSelectedObjectProfitabilityCue) {
return unicodeBridgeResolution("inventory_profitability_for_item", "high", "unicode_selected_object_profitability_bridge_signal_detected");
}
const hasInventoryPurchaseToSaleDocumentChainCue = /(?:закупк[а-яё]*[\s\S]{0,80}склад[\s\S]{0,80}продаж|путь\s+товар[а-яё]*[\s\S]{0,80}закуп|purchase\s*->\s*(?:warehouse|stock)\s*->\s*sale|->\s*(?:склад|warehouse|stock)\s*->\s*(?:продаж|sale))/iu.test(normalized) && /(?:товар|позици|номенклатур|sku|item|product)/iu.test(normalized);
if (hasInventoryPurchaseToSaleDocumentChainCue) {
return unicodeBridgeResolution("inventory_purchase_to_sale_chain", "high", "unicode_inventory_purchase_to_sale_chain_bridge_signal_detected");
}
const hasOpenItemsAccountCue = /(?:хвост|долг|незакрыт|вис)/iu.test(normalized) &&
/(?:сч(?:е|ё)т(?:а|у|ом|е|ов)?\s*(?:№|#)?\s*(?:60|62|76)(?:[.,]\d{1,2})?|\b(?:60|62|76)(?:[.,]\d{1,2})?\b\s*сч(?:е|ё)т)/iu.test(normalized);
if (hasOpenItemsAccountCue) {
+13 -7
View File
@@ -1769,7 +1769,7 @@ function enforceStrictAccountScopeForIntent(plan, intent) {
account_scope_mode: "strict"
};
}
function resolveExecutionFiltersForConfirmedBalance(filters, analysisDate) {
function resolveExecutionFiltersForConfirmedBalance(filters, analysisDate, warnings = []) {
const explicitAsOf = normalizeAnalysisDateHint(filters.as_of_date);
const periodTo = normalizeAnalysisDateHint(filters.period_to);
const derivedAsOf = explicitAsOf ?? periodTo ?? analysisDate ?? null;
@@ -1779,8 +1779,10 @@ function resolveExecutionFiltersForConfirmedBalance(filters, analysisDate) {
if (derivedAsOf) {
executionFilters.as_of_date = derivedAsOf;
}
delete executionFilters.period_from;
delete executionFilters.period_to;
if (!warnings.includes("as_of_date_derived_from_exact_historical_period")) {
delete executionFilters.period_from;
delete executionFilters.period_to;
}
const limit = typeof executionFilters.limit === "number" && Number.isFinite(executionFilters.limit)
? Math.max(1, Math.trunc(executionFilters.limit))
: null;
@@ -1952,6 +1954,9 @@ function asksForUnresolvedInventorySupplierLink(userMessage) {
return /(?:\u0431\u0435\u0437\s+\u043f\u043e\u043d\u044f\u0442\u043d[^\s]*\s+\u043f\u0440\u0438\u0432\u044f\u0437\u043a[^\s]*\s+\u043a\s+\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a|\u0431\u0435\u0437\s+(?:\u044f\u0432\u043d[^\s]*\s+)?\u043f\u0440\u0438\u0432\u044f\u0437\u043a[^\s]*\s+\u043a\s+\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a|\u043d\u0435\s+\u0438\u043c\u0435\u044e\u0442\s+\u044f\u0432\u043d[^\s]*\s+\u043f\u0440\u0438\u0432\u044f\u0437\u043a[^\s]*\s+\u043a\s+\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a|\u043d\u0435\u0442\s+\u044f\u0432\u043d[^\s]*\s+\u043f\u0440\u0438\u0432\u044f\u0437\u043a[^\s]*\s+\u043a\s+\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a|unresolved\s+supplier\s+link)/iu.test(String(userMessage ?? ""));
}
function canAutoBroadenPeriodWindow(intent, filters) {
if (Array.isArray(filters.warnings) && filters.warnings?.includes("exact_historical_period_window_requested")) {
return false;
}
const hasRecoverableAsOfOnlyWindow = !hasExplicitPeriodWindow(filters) &&
typeof filters.as_of_date === "string" &&
filters.as_of_date.trim().length > 0 &&
@@ -3001,16 +3006,16 @@ class AddressQueryService {
const confirmedBalanceVatPayableIntent = intent.intent === "vat_payable_confirmed_as_of_date" && requestedResultMode === "confirmed_balance";
const confirmedBalanceInventoryIntent = intent.intent === "inventory_on_hand_as_of_date" && requestedResultMode === "confirmed_balance";
const payablesConfirmedExecution = confirmedBalancePayablesIntent
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate)
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate, filters.warnings)
: null;
const receivablesConfirmedExecution = confirmedBalanceReceivablesIntent
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate)
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate, filters.warnings)
: null;
const vatPayableConfirmedExecution = confirmedBalanceVatPayableIntent
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate)
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate, filters.warnings)
: null;
const inventoryConfirmedExecution = confirmedBalanceInventoryIntent
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate)
? resolveExecutionFiltersForConfirmedBalance(filters.extracted_filters, analysisDate, filters.warnings)
: null;
let executionFilters = inventoryConfirmedExecution?.executionFilters ??
payablesConfirmedExecution?.executionFilters ??
@@ -4219,6 +4224,7 @@ class AddressQueryService {
!counterpartyItemFlowQuery &&
isDocumentOrBankAnchorIntent(intent.intent) &&
!hasExplicitPeriodWindow(filters.extracted_filters) &&
!filters.warnings.some((warning) => warning.startsWith("period_derived_from_")) &&
(anchor.anchor_type === "counterparty" || anchor.anchor_type === "contract")) {
const currentLimit = typeof filters.extracted_filters.limit === "number" && Number.isFinite(filters.extracted_filters.limit)
? Math.max(1, Math.trunc(filters.extracted_filters.limit))
@@ -119,6 +119,10 @@ function truthGateStatusFrom(input) {
return input.truthGateStatusHint;
}
const missingRequiredFilters = input.missingRequiredFilters ?? [];
const reasonCodes = input.reasons ?? [];
const heuristicOpenItemsFallback = Boolean(input.intent === "open_items_by_counterparty_or_contract" &&
(reasonCodes.includes("confirmed_balance_unavailable_fallback_to_heuristic_candidates") ||
reasonCodes.includes("open_items_account_query_override_to_movements")));
if (input.routeExpectationStatus === "mismatch") {
return "blocked_route_expectation_failure";
}
@@ -134,6 +138,9 @@ function truthGateStatusFrom(input) {
if (input.replyType === "factual" && input.limitedReasonCategory === "empty_match") {
return "full_confirmed";
}
if (heuristicOpenItemsFallback) {
return "partial_supported";
}
if (input.limitedReasonCategory === "empty_match" ||
input.limitedReasonCategory === "recipe_visibility_gap" ||
input.limitedReasonCategory === "unsupported" ||
@@ -3281,11 +3281,22 @@ function composeFactualReplyBody(intent, rows, options = {}) {
}
if (intent === "open_items_by_counterparty_or_contract") {
const counterparties = buildCounterpartyRiskAggregate(rows);
const accountLead = typeof options.accountHint === "string" && options.accountHint.trim().length > 0
? `Проверил хвосты по счету ${options.accountHint.trim()}.`
: "Собраны открытые позиции по взаиморасчетам.";
const accountLabel = typeof options.accountHint === "string" && options.accountHint.trim().length > 0
? `по счету ${options.accountHint.trim()}`
: "по взаиморасчетам";
const exactBalanceRequested = options.requestedResultMode === "confirmed_balance";
const periodLabel = options.asOfDate
? `на ${formatDateRu(options.asOfDate)}`
: options.periodFrom || options.periodTo
? `за период ${formatDateRu(options.periodFrom ?? "...")}..${formatDateRu(options.periodTo ?? "...")}`
: null;
const lines = [
accountLead,
exactBalanceRequested
? `Коротко: точный открытый остаток ${accountLabel}${periodLabel ? ` ${periodLabel}` : ""} не подтвержден; ниже только предварительные сигналы по движениям: ${formatNumberWithDots(rows.length)} строк, контрагентов с сигналом: ${formatNumberWithDots(counterparties.length)}.`
: `Коротко: ${accountLabel} найдено ${formatNumberWithDots(rows.length)} строк хвостов/открытых расчетов; контрагентов с сигналом: ${formatNumberWithDots(counterparties.length)}.`,
exactBalanceRequested
? "Это не подтвержденное сальдо и не финальный реестр открытых расчетов: текущий контур видит движения-кандидаты, но не доказывает остаток закрытия."
: "Это shortlist для проверки, а не финальный подтвержденный реестр открытых расчетов.",
`Строк отобрано: ${rows.length}.`,
`Контрагентов с сигналом: ${counterparties.length}.`
];
@@ -3301,7 +3312,12 @@ function composeFactualReplyBody(intent, rows, options = {}) {
}
return {
responseType: "FACTUAL_LIST",
text: lines.join("\n")
text: lines.join("\n"),
semantics: {
result_mode: "heuristic_candidates",
evidence_strength: counterparties.length > 0 || rows.length > 0 ? "medium" : "weak",
balance_confirmed: false
}
};
}
if (intent === "list_contracts_by_counterparty") {
@@ -3366,7 +3382,7 @@ function composeFactualReplyBody(intent, rows, options = {}) {
? `Контрагент: ${counterpartyInline}. Найдено документов: ${rows.length}.`
: `Найдено документов по контрагенту: ${rows.length}.`);
}
if (counterpartyLabel) {
if (counterpartyLabel && itemFlowQuestion) {
lines.push(`Контрагент: ${counterpartyLabel}`);
}
if (itemFlowQuestion) {
@@ -3388,7 +3404,11 @@ function composeFactualReplyBody(intent, rows, options = {}) {
}
}
else {
lines.push(...formatTopRows(rows, rows.length));
const visibleRows = rows.slice(0, 5);
lines.push(...formatTopRows(visibleRows, visibleRows.length));
if (rows.length > visibleRows.length) {
lines.push(`Показаны первые ${visibleRows.length} из ${rows.length} документов; полный список остается в подтвержденном срезе.`);
}
}
return {
responseType: "FACTUAL_LIST",
@@ -165,11 +165,18 @@ const FOLLOWUP_LOW_QUALITY_COUNTERPARTY_TOKENS = new Set([
"сейчас",
"этому",
"этомуже",
"этой",
"этойже",
"тому",
"томуже",
"той",
"тойже",
"нему",
"ней",
"ним",
"цепочка",
"цепочке",
"цепочку",
"неуказанному",
"неуказанный",
"неуказанная",
@@ -93,11 +93,16 @@ function composeInventoryReply(intent, rows, options, deps) {
: `На ${deps.formatDateRu(asOfDate)} подтвержденных товарных остатков по счету 41.01 не найдено.`;
const lines = [directAnswerLine];
if (positions.length > 0) {
(0, inventoryReplyPresentation_1.appendInventorySection)(lines, "Позиции:", positions.slice(0, 20).map((item, index) => (0, inventoryReplyPresentation_1.formatInventorySnapshotPositionLine)(item, index, {
const visiblePositionsLimit = 6;
const visiblePositions = positions.slice(0, visiblePositionsLimit);
(0, inventoryReplyPresentation_1.appendInventorySection)(lines, "Позиции:", visiblePositions.map((item, index) => (0, inventoryReplyPresentation_1.formatInventorySnapshotPositionLine)(item, index, {
formatDateRu: deps.formatDateRu,
formatNumberWithDots: deps.formatNumberWithDots,
formatMoneyRub: deps.formatMoneyRub
})));
if (positions.length > visiblePositions.length) {
lines.push(`Показаны первые ${deps.formatNumberWithDots(visiblePositions.length)} из ${deps.formatNumberWithDots(positions.length)} позиций по сумме; полный список можно раскрыть отдельным запросом.`);
}
}
else {
(0, inventoryReplyPresentation_1.appendInventorySection)(lines, "Позиции:", [
@@ -190,6 +190,7 @@ async function runAssistantLivingChatRuntime(input) {
organization: scopedOrganization,
addressDebug: lastMemoryAddressDebug,
sessionItems: input.sessionItems,
userMessage,
toNonEmptyString: input.toNonEmptyString
});
activeOrganization = scopedOrganization ?? activeOrganization;
@@ -121,7 +121,7 @@ function timeScopeNeedFor(input) {
if (input.explicitDateScope) {
return "explicit_period";
}
if (input.allTimeScopeHint &&
if ((input.allTimeScopeHint || input.subjectScopedBidirectionalAllTime) &&
(input.family === "value_flow" || input.family === "movement_evidence" || input.family === "document_evidence")) {
return "all_time_scope";
}
@@ -396,6 +396,10 @@ function buildAssistantMcpDiscoveryDataNeedGraph(input) {
const comparisonNeed = comparisonNeedFor(action);
const rankingNeed = rankingNeedFromRawUtterance(rawUtterance) ?? seededRankingNeed;
const allTimeScopeHint = hasAllTimeScopeHint(rawUtterance);
const subjectScopedBidirectionalAllTime = businessFactFamily === "value_flow" &&
comparisonNeed === "incoming_vs_outgoing" &&
subjectCandidates.length > 0 &&
!explicitDateScope;
const directBusinessOverviewMoneyAnswerHint = hasBusinessOverviewDirectMoneyAnswerHint({
family: businessFactFamily,
rawUtterance,
@@ -449,7 +453,8 @@ function buildAssistantMcpDiscoveryDataNeedGraph(input) {
const timeScopeNeed = timeScopeNeedFor({
family: businessFactFamily,
explicitDateScope,
allTimeScopeHint
allTimeScopeHint,
subjectScopedBidirectionalAllTime
});
if (timeScopeNeed === "period_required" && !explicitDateScope) {
pushUnique(clarificationGaps, "period");
@@ -492,6 +497,9 @@ function buildAssistantMcpDiscoveryDataNeedGraph(input) {
if (allTimeScopeHint) {
pushReason(reasonCodes, "data_need_graph_all_time_scope_hint");
}
if (subjectScopedBidirectionalAllTime) {
pushReason(reasonCodes, "data_need_graph_subject_bidirectional_value_flow_defaults_to_all_time_scope");
}
if (businessFactFamily === "business_overview" && !explicitDateScope) {
pushReason(reasonCodes, "data_need_graph_business_overview_defaults_to_all_time_scope");
}
@@ -80,6 +80,7 @@ function normalizeTurnMeaning(value) {
const dateScope = toNonEmptyString(value.explicit_date_scope);
const unsupported = toNonEmptyString(value.unsupported_but_understood_family);
const entities = toStringList(value.explicit_entity_candidates);
const businessOverviewSeparateEntities = toStringList(value.business_overview_separate_entity_candidates);
const metadataAmbiguityEntitySets = toStringList(value.metadata_ambiguity_entity_sets);
if (domain) {
result.asked_domain_family = domain;
@@ -96,6 +97,9 @@ function normalizeTurnMeaning(value) {
if (entities.length > 0) {
result.explicit_entity_candidates = entities;
}
if (businessOverviewSeparateEntities.length > 0) {
result.business_overview_separate_entity_candidates = businessOverviewSeparateEntities;
}
if (metadataAmbiguityEntitySets.length > 0) {
result.metadata_ambiguity_entity_sets = metadataAmbiguityEntitySets;
}
@@ -365,18 +365,230 @@ function businessOverviewYearRowsLine(overview) {
const joined = values.join("; ");
return values.length > 0 ? `По годам: ${sentenceAmount(joined) ?? joined}.` : null;
}
function firstOverviewAxisLabel(rows, amountKey = "total_amount_human_ru") {
const first = toRecordObject(Array.isArray(rows) ? rows[0] : null);
const label = toNonEmptyString(first?.axis_value);
const amount = moneyText(first?.[amountKey]);
return label && amount ? `${label} — ${sentenceAmount(amount) ?? amount}` : null;
}
function businessOverviewTaxLine(overview) {
const tax = toRecordObject(overview.tax_position);
if (!tax) {
return null;
}
const salesVat = moneyText(tax.sales_vat_amount_human_ru);
const purchaseVat = moneyText(tax.purchase_vat_amount_human_ru);
const netVat = moneyText(tax.net_vat_amount_human_ru);
if (!salesVat && !purchaseVat && !netVat) {
return null;
}
const direction = tax.net_vat_direction === "vat_to_pay"
? "НДС к уплате"
: tax.net_vat_direction === "vat_to_recover_or_offset"
? "НДС к возмещению/зачету"
: "чистая НДС-позиция";
return `НДС: продажи ${salesVat ?? "0 руб."}, покупки ${purchaseVat ?? "0 руб."}, ${direction} ${sentenceAmount(netVat) ?? netVat ?? "0 руб."}.`;
}
function businessOverviewDebtLine(overview) {
const debt = toRecordObject(overview.debt_position);
if (!debt) {
return null;
}
const receivables = moneyText(toRecordObject(debt.receivables)?.total_amount_human_ru);
const payables = moneyText(toRecordObject(debt.payables)?.total_amount_human_ru);
const net = moneyText(debt.net_debt_position_amount_human_ru);
if (!receivables && !payables && !net) {
return null;
}
const direction = debt.net_debt_position_direction === "net_payable" ? "кредиторка больше дебиторки" : "дебиторка больше кредиторки";
return `Долги: дебиторка ${receivables ?? "0 руб."}, кредиторка ${payables ?? "0 руб."}, нетто ${sentenceAmount(net) ?? net ?? "0 руб."} (${direction}).`;
}
function businessOverviewInventoryLine(overview) {
const inventory = toRecordObject(overview.inventory_position);
if (!inventory) {
return null;
}
const amount = moneyText(inventory.total_amount_human_ru);
const rows = Number(inventory.rows_matched);
const quantity = Number(inventory.total_quantity);
if (!amount && !Number.isFinite(rows)) {
return null;
}
const pieces = [
Number.isFinite(rows) ? `${rows} позиций` : null,
amount ? `на ${sentenceAmount(amount) ?? amount}` : null,
Number.isFinite(quantity) && quantity > 0 ? `количество ${quantity}` : null
].filter((item) => Boolean(item));
return pieces.length > 0 ? `Склад: ${pieces.join(", ")}.` : null;
}
function rowCountText(value) {
const count = Number(value);
return Number.isFinite(count) ? String(count) : null;
}
function sideRowsText(side) {
const rowsWithAmount = rowCountText(side?.rows_with_amount);
const rowsMatched = rowCountText(side?.rows_matched);
if (rowsWithAmount && rowsMatched) {
return `${rowsWithAmount} из ${rowsMatched}`;
}
return rowsWithAmount ?? rowsMatched;
}
function sideDateText(side) {
const first = toNonEmptyString(side?.first_movement_date);
const latest = toNonEmptyString(side?.latest_movement_date);
if (first && latest) {
return first === latest ? `дата ${first}` : `даты ${first}..${latest}`;
}
return first ? `первая дата ${first}` : latest ? `последняя дата ${latest}` : null;
}
function bidirectionalNetLabel(direction) {
if (direction === "net_outgoing") {
return "нетто в сторону контрагента";
}
if (direction === "balanced") {
return "нетто около нуля";
}
return "нетто в нашу сторону";
}
function buildCompactBidirectionalValueFlowReply(entryPoint, draft) {
const bridge = toRecordObject(entryPoint.bridge);
const pilot = toRecordObject(bridge?.pilot);
const flow = toRecordObject(pilot?.derived_bidirectional_value_flow);
if (!flow) {
return null;
}
const incoming = toRecordObject(flow.incoming_customer_revenue);
const outgoing = toRecordObject(flow.outgoing_supplier_payout);
const incomingAmount = moneyText(incoming?.total_amount_human_ru);
const outgoingAmount = moneyText(outgoing?.total_amount_human_ru);
const netAmount = moneyText(flow.net_amount_human_ru);
if (!incomingAmount && !outgoingAmount && !netAmount) {
return null;
}
const counterparty = toNonEmptyString(flow.counterparty) ?? "запрошенному контрагенту";
const period = toNonEmptyString(flow.period_scope);
const periodText = period ? ` за период ${period}` : " в проверенном окне";
const incomingRows = sideRowsText(incoming);
const outgoingRows = sideRowsText(outgoing);
const incomingDates = sideDateText(incoming);
const outgoingDates = sideDateText(outgoing);
const netLabel = bidirectionalNetLabel(flow.net_direction);
const lines = [
`Коротко: по контрагенту ${counterparty}${periodText} по найденным строкам 1С получили ${incomingAmount ?? "0 руб."}, заплатили ${outgoingAmount ?? "0 руб."}; расчетное ${netLabel}: ${sentenceAmount(netAmount) ?? netAmount ?? "0 руб."}.`
];
const basis = [];
if (incomingRows) {
basis.push(`входящих строк с суммой ${incomingRows}${incomingDates ? ` (${incomingDates})` : ""}`);
}
if (outgoingRows) {
basis.push(`исходящих строк с суммой ${outgoingRows}${outgoingDates ? ` (${outgoingDates})` : ""}`);
}
if (basis.length > 0) {
lines.push(`Основа: ${basis.join("; ")}.`);
}
if (flow.coverage_limited_by_probe_limit === true) {
lines.push("Важно: часть проверки уперлась в лимит строк, поэтому это проверенный срез найденных движений, а не гарантия полного периода.");
}
lines.push("Метод: нетто рассчитано как подтвержденные входящие строки 1С минус подтвержденные исходящие строки; это не полное бухгалтерское сальдо вне проверенного окна.");
const fallbackNextStep = toNonEmptyString(draft.next_step_line);
if (fallbackNextStep) {
lines.push(`Следующий шаг: ${localizeLine(fallbackNextStep)}`);
}
const reply = lines.join("\n").trim();
return reply.length > 0 && !hasInternalMechanics(reply) ? reply : null;
}
function compactComparable(value) {
return String(value ?? "")
.toLowerCase()
.replace(/[«»"']/g, "")
.replace(/\s+/g, " ")
.trim();
}
function businessOverviewSeparateSubjectLabel(graph, turnMeaning, organizationScope) {
const candidates = uniqueStrings([
...toStringList(turnMeaning?.business_overview_separate_entity_candidates),
...toStringList(graph?.subject_candidates),
...toStringList(turnMeaning?.explicit_entity_candidates)
]);
const organizationComparable = compactComparable(organizationScope);
for (const candidate of candidates) {
const text = toNonEmptyString(candidate);
if (!text) {
continue;
}
const comparable = compactComparable(text);
if (organizationComparable && comparable === organizationComparable) {
continue;
}
return text;
}
return null;
}
function sameBusinessSubject(left, right) {
const leftComparable = compactComparable(left);
const rightComparable = compactComparable(right);
return Boolean(leftComparable && rightComparable && leftComparable === rightComparable);
}
function previousDocumentSummaryLine(bundle, separateSubject) {
if (!bundle || !sameBusinessSubject(toNonEmptyString(bundle.counterparty), separateSubject)) {
return null;
}
const count = Number(bundle.document_count);
if (!Number.isFinite(count) || count <= 0) {
return null;
}
return `документы по цепочке: найдено ${count}`;
}
function buildPreviousCounterpartyValueFlowSummary(flow, separateSubject, documentBundle) {
if (!flow || !separateSubject || !sameBusinessSubject(toNonEmptyString(flow.counterparty), separateSubject)) {
return null;
}
const incoming = toRecordObject(flow.incoming_customer_revenue);
const outgoing = toRecordObject(flow.outgoing_supplier_payout);
const incomingAmount = moneyText(incoming?.total_amount_human_ru);
const outgoingAmount = moneyText(outgoing?.total_amount_human_ru);
const netAmount = moneyText(flow.net_amount_human_ru);
if (!incomingAmount && !outgoingAmount && !netAmount) {
return null;
}
const counterparty = toNonEmptyString(flow.counterparty) ?? separateSubject;
const netLabel = bidirectionalNetLabel(flow.net_direction);
const lead = `; отдельно по ${counterparty}: получили ${incomingAmount ?? "0 руб."}, заплатили ${outgoingAmount ?? "0 руб."}, ` +
`${netLabel} ${sentenceAmount(netAmount) ?? netAmount ?? "0 руб."}`;
const basis = [];
const incomingRows = sideRowsText(incoming);
const outgoingRows = sideRowsText(outgoing);
const incomingDates = sideDateText(incoming);
const outgoingDates = sideDateText(outgoing);
if (incomingRows) {
basis.push(`входящие строки ${incomingRows}${incomingDates ? ` (${incomingDates})` : ""}`);
}
if (outgoingRows) {
basis.push(`исходящие строки ${outgoingRows}${outgoingDates ? ` (${outgoingDates})` : ""}`);
}
const documents = previousDocumentSummaryLine(documentBundle, counterparty);
if (documents) {
basis.push(documents);
}
const basisText = basis.length > 0 ? ` Основа: ${basis.join("; ")}.` : "";
return {
lead,
line: `Отдельно по контрагенту ${counterparty}: подтверждено получили ${incomingAmount ?? "0 руб."}, ` +
`заплатили ${outgoingAmount ?? "0 руб."}, расчетное ${netLabel} ${sentenceAmount(netAmount) ?? netAmount ?? "0 руб."}.` +
`${basisText} Это не перенос сумм компании на контрагента, а отдельный ранее подтвержденный контрагентский срез.`
};
}
function buildCompactBusinessOverviewReply(entryPoint, draft) {
const turnInput = toRecordObject(entryPoint.turn_input);
const turnMeaning = toRecordObject(turnInput?.turn_meaning_ref);
const graph = toRecordObject(turnInput?.data_need_graph);
const bridge = toRecordObject(entryPoint.bridge);
const pilot = toRecordObject(bridge?.pilot);
const overview = toRecordObject(pilot?.derived_business_overview);
const graphReasons = readStringArray(graph?.reason_codes);
const isBusinessOverview = toNonEmptyString(graph?.business_fact_family) === "business_overview" ||
toNonEmptyString(pilot?.pilot_scope) === "business_overview_route_template_v1";
const rankingNeed = toNonEmptyString(graph?.ranking_need);
const directMoneyAnswer = graphReasons.includes("data_need_graph_business_overview_direct_money_answer");
if (!isBusinessOverview || !overview || (!rankingNeed && !directMoneyAnswer)) {
if (!isBusinessOverview || !overview) {
return null;
}
const incoming = toRecordObject(overview.incoming_customer_revenue);
@@ -387,7 +599,38 @@ function buildCompactBusinessOverviewReply(entryPoint, draft) {
const netDirection = overview.net_direction === "net_outgoing" ? "операционное нетто в минус" : "расчетное операционное нетто";
const period = businessOverviewPeriodText(overview);
const limitLine = businessOverviewCoverageLimitLine(overview);
const organizationScope = toNonEmptyString(turnMeaning?.explicit_organization_scope);
const separateSubject = businessOverviewSeparateSubjectLabel(graph, turnMeaning, organizationScope);
const previousCounterpartySummary = buildPreviousCounterpartyValueFlowSummary(toRecordObject(turnMeaning?.previous_counterparty_value_flow_bundle), separateSubject, toRecordObject(turnMeaning?.previous_counterparty_document_bundle));
const organizationPrefix = organizationScope ? `по компании ${organizationScope} ` : "";
const separateSubjectLead = separateSubject
? previousCounterpartySummary?.lead ??
`; по контрагенту ${separateSubject} суммы компании не переношу, это отдельный контур без подтвержденного итога в этой строке`
: "";
const topCustomer = toRecordObject(Array.isArray(overview.top_customers) ? overview.top_customers[0] : null);
const customerName = toNonEmptyString(topCustomer?.axis_value);
const customerAmount = moneyText(topCustomer?.total_amount_human_ru);
const topCustomerLead = customerName && customerAmount
? `; крупнейший источник входящих денег: ${customerName} — ${sentenceAmount(customerAmount) ?? customerAmount}`
: "";
const topSupplier = firstOverviewAxisLabel(overview.top_suppliers);
const topSupplierLead = topSupplier ? `; крупнейший получатель исходящих денег: ${topSupplier}` : "";
const roleBoundaryLead = topCustomer || topSupplier ? "; клиент/поставщик как бизнес-роли этим денежным срезом не подтверждены" : "";
const graphReasonCodes = toStringList(graph?.reason_codes);
const directMoneyAnswer = graphReasonCodes.includes("data_need_graph_business_overview_direct_money_answer");
const crossScopeExecutiveSummary = Boolean(separateSubject && previousCounterpartySummary);
const lines = [];
if (crossScopeExecutiveSummary && separateSubject && previousCounterpartySummary && (incomingAmount || outgoingAmount || netAmount)) {
lines.push(`Коротко: по компании ${organizationScope ?? "в выбранном контуре"} ${period} подтвержден денежный срез: получили ${incomingAmount ?? "0 руб."}, исходящие платежи/списания ${outgoingAmount ?? "0 руб."}, ${netDirection} ${sentenceAmount(netAmount) ?? netAmount ?? "0 руб."}${previousCounterpartySummary.lead}; можно утверждать только эти подтвержденные срезы, нельзя называть это чистой прибылью, полным оборотом или доказанной ролью главного клиента/поставщика.`);
lines.push(previousCounterpartySummary.line);
lines.push(`Можно утверждать: по компании подтвержден operating-flow proxy по найденным строкам 1С; по ${separateSubject} отдельно подтверждены входящие/исходящие строки, расчетное нетто и документы из предыдущего контрагентского среза.`);
lines.push(`Нельзя утверждать: это не чистая прибыль, не полный бухгалтерский оборот вне проверенного окна и не доказательство, что ${separateSubject} является главным клиентом или поставщиком как бизнес-роль.`);
if (limitLine) {
lines.push(limitLine);
}
const reply = lines.join("\n").trim();
return reply.length > 0 && !hasInternalMechanics(reply) ? reply : null;
}
if (rankingNeed) {
const incomingLeader = strongestIncomingYear(overview);
const netLeader = strongestNetYear(overview);
@@ -397,7 +640,7 @@ function buildCompactBusinessOverviewReply(entryPoint, draft) {
if (!leaderYear || !leaderAmount) {
return null;
}
lines.push(`Коротко: самый доходный год в доступном денежном контуре 1С — ${leaderYear}: ${leaderAmount}${Number.isFinite(leaderRows) && leaderRows > 0 ? ` по ${leaderRows} строкам с суммой` : ""}.`);
lines.push(`Коротко: в доступном проверенном MCP-срезе по входящим денежным строкам лидирует ${leaderYear}: ${leaderAmount}${Number.isFinite(leaderRows) && leaderRows > 0 ? ` по ${leaderRows} строкам с суммой` : ""}; это не полный бухгалтерский рейтинг доходности.`);
const netYear = toNonEmptyString(netLeader?.year_bucket);
const netYearAmount = moneyText(netLeader?.net_amount_human_ru);
if (netYear && netYearAmount) {
@@ -414,18 +657,54 @@ function buildCompactBusinessOverviewReply(entryPoint, draft) {
}
}
else if (incomingAmount || outgoingAmount || netAmount) {
lines.push(`Коротко: ${period} по подтвержденным строкам 1С получили ${incomingAmount ?? "0 руб."}; исходящие платежи/списания ${outgoingAmount ?? "0 руб."}; ${netDirection} ${sentenceAmount(netAmount) ?? netAmount ?? "0 руб"}.`);
lines.push(`Коротко: ${organizationPrefix}${period} по подтвержденным строкам 1С получили ${incomingAmount ?? "0 руб."}; исходящие платежи/списания ${outgoingAmount ?? "0 руб."}; ${netDirection} ${sentenceAmount(netAmount) ?? netAmount ?? "0 руб"}${topCustomerLead}${topSupplierLead}${roleBoundaryLead}${separateSubjectLead}.`);
lines.push('Метод: "заработали" здесь считаю как денежный operating-flow proxy по 1С; это не чистая прибыль и не финрезультат.');
const topCustomer = toRecordObject(Array.isArray(overview.top_customers) ? overview.top_customers[0] : null);
const customerName = toNonEmptyString(topCustomer?.axis_value);
const customerAmount = moneyText(topCustomer?.total_amount_human_ru);
if (customerName && customerAmount) {
if (!directMoneyAnswer && customerName && customerAmount) {
lines.push(`Крупнейший подтвержденный источник входящих денег в этом срезе: ${customerName} — ${sentenceAmount(customerAmount) ?? customerAmount}.`);
}
}
else {
return null;
}
if (separateSubject) {
lines.push(previousCounterpartySummary?.line ??
`Отдельно по контрагенту ${separateSubject}: этот итог не переносит суммы компании на контрагента. Можно утверждать только разделение контура; нельзя делать вывод о выручке, долге или прибыльности ${separateSubject} без отдельного контрагентского среза документов и движений.`);
}
if (!directMoneyAnswer && topSupplier) {
lines.push(`Крупнейший подтвержденный получатель исходящих денег: ${topSupplier}.`);
}
if (!directMoneyAnswer && (topCustomer || topSupplier)) {
lines.push("Важно по ролям: текущий денежный срез подтверждает денежные источники и получателей, но не доказывает, что это главный клиент или главный поставщик как бизнес-роль.");
}
if (!directMoneyAnswer) {
lines.push(`Что подтверждено: денежный срез по компании${organizationScope ? ` ${organizationScope}` : ""}${period ? ` ${period}` : ""}${topCustomer ? ", крупнейший источник входящих денег" : ""}${topSupplier ? ", крупнейший получатель исходящих денег" : ""}.`);
const taxLine = businessOverviewTaxLine(overview);
if (taxLine) {
lines.push(taxLine);
}
const debtLine = businessOverviewDebtLine(overview);
if (debtLine) {
lines.push(debtLine);
}
const inventoryLine = businessOverviewInventoryLine(overview);
if (inventoryLine) {
lines.push(inventoryLine);
}
const missingOverviewFamilies = [];
if (!taxLine) {
missingOverviewFamilies.push("общая НДС/налоговая позиция без отдельного точного расчета");
}
if (!debtLine) {
missingOverviewFamilies.push("долги без даты среза");
}
if (!inventoryLine) {
missingOverviewFamilies.push("склад без даты среза");
}
if (missingOverviewFamilies.length > 0) {
lines.push(`Что не подтверждено в этом срезе: ${missingOverviewFamilies.join(", ")}.`);
}
lines.push("Что нельзя утверждать: чистую прибыль, полноценный финрезультат, юридические бизнес-роли клиентов/поставщиков и общую налоговую позицию без отдельного точного расчета.");
}
if (limitLine) {
lines.push(limitLine);
}
@@ -476,6 +755,10 @@ function buildReplyText(entryPoint, status) {
}
return null;
}
const compactBidirectionalValueFlowReply = buildCompactBidirectionalValueFlowReply(entryPoint, draft);
if (compactBidirectionalValueFlowReply) {
return compactBidirectionalValueFlowReply;
}
const compactBusinessOverviewReply = buildCompactBusinessOverviewReply(entryPoint, draft);
if (compactBusinessOverviewReply) {
return compactBusinessOverviewReply;
@@ -233,6 +233,18 @@ function readStateTransitionReasonCodes(input) {
.map((item) => toNonEmptyString(item))
.filter((item) => Boolean(item));
}
function hasFullConfirmedTruth(input) {
const truthGateStatus = toNonEmptyString(input.addressRuntimeMeta?.truth_gate_contract_status);
if (truthGateStatus === "full_confirmed") {
return true;
}
const truthAnswerPolicy = toRecordObject(input.addressRuntimeMeta?.assistant_truth_answer_policy_v1);
const truthGate = toRecordObject(truthAnswerPolicy?.truth_gate);
const sourceTruthGateStatus = toNonEmptyString(truthGate?.source_truth_gate_status);
const coverageStatus = toNonEmptyString(truthGate?.coverage_status);
const groundingStatus = toNonEmptyString(truthGate?.grounding_status);
return sourceTruthGateStatus === "full_confirmed" || (coverageStatus === "full" && groundingStatus === "grounded");
}
function readStringArray(value) {
return Array.isArray(value)
? value.map((item) => toNonEmptyString(item)).filter((item) => Boolean(item))
@@ -299,6 +311,12 @@ function hasExactMatchedFactualAddressReply(input, entryPoint) {
if (hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
return false;
}
if (hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
if (!(isMetadataDiscoveryTurn(entryPoint) && isInventoryExactAddressIntent(detectedIntent))) {
return false;
}
}
const mcpCallStatus = toNonEmptyString(input.addressRuntimeMeta?.mcp_call_status);
const truthMode = toNonEmptyString(input.addressRuntimeMeta?.truth_mode);
const selectedRecipe = toNonEmptyString(input.addressRuntimeMeta?.selected_recipe);
@@ -335,16 +353,7 @@ function hasRuntimeAdjustedExactReply(input, entryPoint) {
if (hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
return false;
}
const truthGateStatus = toNonEmptyString(input.addressRuntimeMeta?.truth_gate_contract_status);
const truthAnswerPolicy = toRecordObject(input.addressRuntimeMeta?.assistant_truth_answer_policy_v1);
const truthGate = toRecordObject(truthAnswerPolicy?.truth_gate);
const sourceTruthGateStatus = toNonEmptyString(truthGate?.source_truth_gate_status);
const coverageStatus = toNonEmptyString(truthGate?.coverage_status);
const groundingStatus = toNonEmptyString(truthGate?.grounding_status);
const hasFullConfirmedTruth = truthGateStatus === "full_confirmed" ||
sourceTruthGateStatus === "full_confirmed" ||
(coverageStatus === "full" && groundingStatus === "grounded");
if (!hasFullConfirmedTruth) {
if (!hasFullConfirmedTruth(input)) {
return false;
}
const truthAnswerShape = readTruthAnswerShape(input);
@@ -354,6 +363,26 @@ function hasRuntimeAdjustedExactReply(input, entryPoint) {
}
return readStateTransitionReasonCodes(input).some((reason) => /^intent_adjusted_to_.+_followup_context$/i.test(reason));
}
function hasRuntimeMatchedExactReply(input, entryPoint) {
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
return false;
}
if (!hasEffectivelyFactualAddressReply(input)) {
return false;
}
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
return false;
}
if (hasEvidenceLaneConflictWithDiscoveryTurnMeaning(input, entryPoint)) {
return false;
}
if (!hasFullConfirmedTruth(input)) {
return false;
}
const reasonCodes = readStateTransitionReasonCodes(input);
return (reasonCodes.some((reason) => reason === "route_expectation_matched") &&
reasonCodes.some((reason) => /(?:confirmed_balance_exact|exact_.+_intent|vat_period_inspection_bridge_signal_detected)/iu.test(reason)));
}
function hasAlignedFactualAddressReply(input, entryPoint) {
if (!isDiscoveryReadyAddressCandidate(input, entryPoint)) {
return false;
@@ -380,6 +409,9 @@ function hasSemanticConflictWithDiscoveryTurnMeaning(input, entryPoint) {
if (hasRuntimeAdjustedExactReply(input, entryPoint)) {
return false;
}
if (hasRuntimeMatchedExactReply(input, entryPoint)) {
return false;
}
const detectedIntent = toNonEmptyString(input.addressRuntimeMeta?.detected_intent);
const turnMeaning = readDiscoveryTurnMeaning(entryPoint);
const askedDomain = toNonEmptyString(turnMeaning?.asked_domain_family);
@@ -453,16 +485,7 @@ function hasFullConfirmedFactualAddressReply(input, entryPoint) {
if (hasMetadataDiscoveryPriority(input, entryPoint)) {
return false;
}
const truthGateStatus = toNonEmptyString(input.addressRuntimeMeta?.truth_gate_contract_status);
if (truthGateStatus === "full_confirmed") {
return true;
}
const truthAnswerPolicy = toRecordObject(input.addressRuntimeMeta?.assistant_truth_answer_policy_v1);
const truthGate = toRecordObject(truthAnswerPolicy?.truth_gate);
const sourceTruthGateStatus = toNonEmptyString(truthGate?.source_truth_gate_status);
const coverageStatus = toNonEmptyString(truthGate?.coverage_status);
const groundingStatus = toNonEmptyString(truthGate?.grounding_status);
return sourceTruthGateStatus === "full_confirmed" || (coverageStatus === "full" && groundingStatus === "grounded");
return hasFullConfirmedTruth(input);
}
function applyAssistantMcpDiscoveryResponsePolicy(input) {
const currentReply = String(input.currentReply ?? "");
@@ -482,6 +505,7 @@ function applyAssistantMcpDiscoveryResponsePolicy(input) {
const fullConfirmedFactualAddressReply = hasFullConfirmedFactualAddressReply(input, entryPoint);
const exactMatchedFactualAddressReply = hasExactMatchedFactualAddressReply(input, entryPoint);
const runtimeAdjustedExactReply = hasRuntimeAdjustedExactReply(input, entryPoint);
const runtimeMatchedExactReply = hasRuntimeMatchedExactReply(input, entryPoint);
const openScopeValueFlowDiscoveryPriority = hasOpenScopeValueFlowDiscoveryPriority(input, entryPoint);
const metadataDiscoveryPriority = hasMetadataDiscoveryPriority(input, entryPoint);
const valueFlowActionConflictWithDiscoveryTurnMeaning = hasValueFlowActionConflictWithDiscoveryTurnMeaning(input, entryPoint);
@@ -534,6 +558,9 @@ function applyAssistantMcpDiscoveryResponsePolicy(input) {
if (runtimeAdjustedExactReply) {
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_runtime_adjusted_exact_reply_over_stale_discovery_turn_meaning");
}
if (runtimeMatchedExactReply) {
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_runtime_matched_exact_reply_over_stale_discovery_turn_meaning");
}
if (deterministicBroadBusinessEvaluationReply && candidate.candidate_status === "clarification_candidate") {
pushReason(reasonCodes, "mcp_discovery_response_policy_keep_broad_business_summary_over_clarification_candidate");
}
@@ -557,6 +584,7 @@ function applyAssistantMcpDiscoveryResponsePolicy(input) {
!fullConfirmedFactualAddressReply &&
!exactMatchedFactualAddressReply &&
!runtimeAdjustedExactReply &&
!runtimeMatchedExactReply &&
!(deterministicBroadBusinessEvaluationReply && candidate.candidate_status === "clarification_candidate") &&
ALLOWED_CANDIDATE_STATUSES.has(candidate.candidate_status) &&
candidate.eligible_for_future_hot_runtime &&
@@ -193,6 +193,9 @@ function pushScopedEntityCandidate(target, value, groundedFollowupEntity) {
isValueFlowPredicateEntityCandidate(text)) {
return;
}
if (target.some((existing) => sameScopedName(existing, text))) {
return;
}
pushUnique(target, text);
}
function canonicalizeEntityResolutionCandidate(value) {
@@ -220,6 +223,19 @@ function compactLower(value) {
function sameScopedName(left, right) {
return Boolean(left && right && compactLower(left) === compactLower(right));
}
function preferredScopedDisplayName(value, candidates) {
const anchor = toNonEmptyString(value);
if (!anchor) {
return null;
}
for (const candidate of candidates) {
const text = candidateValue(candidate);
if (sameScopedName(text, anchor)) {
return text;
}
}
return anchor;
}
function candidateValue(value) {
const direct = toNonEmptyString(value);
if (direct && direct !== "[object Object]") {
@@ -553,7 +569,9 @@ function collectFollowupDiscoverySeed(followupContext) {
metadataSelectedSurfaceObjects: collectEntityCandidates(followupContext?.previous_discovery_metadata_selected_surface_objects),
metadataRecommendedNextPrimitive: normalizeMetadataRecommendedPrimitive(followupContext?.previous_discovery_metadata_recommended_next_primitive),
metadataAmbiguityDetected: followupContext?.previous_discovery_metadata_ambiguity_detected === true,
metadataAmbiguityEntitySets: collectEntityCandidates(followupContext?.previous_discovery_metadata_ambiguity_entity_sets)
metadataAmbiguityEntitySets: collectEntityCandidates(followupContext?.previous_discovery_metadata_ambiguity_entity_sets),
previousBidirectionalValueFlow: toRecordObject(followupContext?.previous_discovery_bidirectional_value_flow),
previousDocumentSummary: toRecordObject(followupContext?.previous_discovery_document_summary)
};
}
function buildMetadataSurfaceRef(followupSeed) {
@@ -652,8 +670,15 @@ function hasOrganizationLevelSupplierQualityOverviewSignal(text) {
const hasCompanyScopeCue = /(?:\u0443\s+\u043d\u0430\u0441|\u043d\u0430\u0448\w*|\u043f\u043e\s+\u043a\u043e\u043c\u043f\u0430\u043d|\u043a\u043e\u043c\u043f\u0430\u043d|\u043e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446|\u0431\u0438\u0437\u043d\u0435\u0441|\u0432\s+\u0446\u0435\u043b\u043e\u043c|\u043e\u0431\u0449\w*|\u043a\u0430\u043a\w*|\u043f\u043e\u043a\u0430\u0436|\u0434\u0430\u0439|\u0441\u0440\u0435\u0437|\u0430\u043d\u0430\u043b\u0438\u0437|(?:19|20)\d{2}|company|business|organization|overall|our|we|us|show|give|analysis)/iu.test(text);
return hasSupplierScopeCue && hasSupplierQualityCue && hasCompanyScopeCue;
}
function hasCrossScopeExecutiveSummarySignal(text) {
return (/(?:\u0441\u043e\u0431\u0435\u0440\p{L}*\s+(?:\u043a\u043e\u0440\u043e\u0442\u043a\p{L}*\s+)?\u0438\u0442\u043e\u0433|\u044d\u043a\u0437\u0435\u043a\u044c\u044e\u0442\u0438\u0432\p{L}*\s+\u0441\u0430\u043c\u043c\u0430\u0440\u0438|executive\s+summary|final\s+summary)/iu.test(text) &&
/(?:\u0447\u0442\u043e\s+(?:\u043c\u044b\s+)?\u043f\u043e\u0434\u0442\u0432\u0435\u0440\p{L}*|\u043f\u043e\s+\u043a\u043e\u043c\u043f\u0430\u043d\p{L}*|\u043f\u043e\s+\u043e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446\p{L}*|confirmed|company|organization)/iu.test(text) &&
/(?:\u043e\u0442\u0434\u0435\u043b\u044c\u043d\p{L}*\s+\u043f\u043e|\u043f\u043e\s+\u043a\u043e\u043d\u0442\u0440\u0430\u0433\u0435\u043d\u0442\p{L}*|\u043a\u043e\u043d\u0442\u0440\u0430\u0433\u0435\u043d\u0442\p{L}*|\u0433\u0440\u0443\u043f\u043f\p{L}*\s+\u0441\u0432\u043a|\u0441\u0432\u043a|counterpart(?:y|ies)?)/iu.test(text) &&
/(?:\u0447\u0442\u043e\s+\u043c\u043e\u0436\u043d\p{L}*|\u0447\u0442\u043e\s+\u043d\u0435\u043b\u044c\u0437\p{L}*|\u0432\u044b\u0432\u043e\u0434\p{L}*|allowed|forbidden|cannot|can\s+say)/iu.test(text));
}
function hasBusinessOverviewSignal(text) {
if (hasOrganizationLevelEarningsOverviewSignal(text) ||
if (hasCrossScopeExecutiveSummarySignal(text) ||
hasOrganizationLevelEarningsOverviewSignal(text) ||
hasOrganizationLevelDebtPositionOverviewSignal(text) ||
hasOrganizationLevelDebtDueDateOverviewSignal(text) ||
hasOrganizationLevelInventoryReserveLiquidationOverviewSignal(text) ||
@@ -679,6 +704,34 @@ function hasBusinessOverviewContinuationSignal(text) {
hasFinalSummaryCue ||
hasMoneyBreakdownCue);
}
function hasExplicitVatQuestionSignal(text) {
if (!text) {
return false;
}
return (/(?:\u043d\u0434\u0441|vat)/iu.test(text) &&
/(?:\u0437\u0430|\u043d\u0430|\u043f\u0435\u0440\u0438\u043e\u0434|\u043f\u043e\u0437\u0438\u0446|\u043a\s+\u0443\u043f\u043b\u0430\u0442|\u043a\s+\u0432\u043e\u0437\u043c\u0435\u0449|\u043e\u0441\u043d\u043e\u0432\u0430\u043d|\u043d\u0430\u043b\u043e\u0433\u043e\u0432\p{L}*\s+\u0432\u044b\u0432\u043e\u0434|tax\s+period|tax\s+position)/iu.test(text));
}
function hasBusinessOverviewSeparateCounterpartySignal(text) {
if (!text) {
return false;
}
return (/(?:\u043e\u0442\u0434\u0435\u043b\u044c\u043d\p{L}*\s+\u043f\u043e|\u043f\u043e\s+\u043a\u043e\u043d\u0442\u0440\u0430\u0433\u0435\u043d\u0442\p{L}*|\u043a\u043e\u043d\u0442\u0440\u0430\u0433\u0435\u043d\u0442\p{L}*|counterpart(?:y|ies)?)/iu.test(text) &&
/(?:\u043a\u043e\u043c\u043f\u0430\u043d\p{L}*|\u043e\u0440\u0433\u0430\u043d\u0438\u0437\u0430\u0446\p{L}*|company|organization|\u0438\u0442\u043e\u0433|summary|\u0432\u044b\u0432\u043e\u0434\p{L}*)/iu.test(text));
}
function businessOverviewSeparateCounterpartyCandidateFromText(text) {
const source = (0, addressTextRepair_1.repairAddressMojibakeText)(String(text ?? ""));
const patterns = [
/(?:\u043e\u0442\u0434\u0435\u043b\u044c\u043d\p{L}*\s+\u043f\u043e|\u043f\u043e\s+\u043a\u043e\u043d\u0442\u0440\u0430\u0433\u0435\u043d\u0442\p{L}*)\s+(.+?)(?:[,.;:!?]|\s+\u043a\u0430\u043a\u0438\p{L}*\b|\s+\u0447\u0442\u043e\b|$)/iu,
/(?:\u0434\u043b\u044f|for)\s+([\p{L}\d._-]+(?:\s+[\p{L}\d._-]+){0,3})(?:[,.;:!?]|\s+\u043a\u0430\u043a\u0438\p{L}*\b|\s+\u0447\u0442\u043e\b|$)/iu
];
for (const pattern of patterns) {
const candidate = normalizeFollowupCounterpartyCandidate(source.match(pattern)?.[1]);
if (candidate && !isInvalidEntityCandidate(candidate)) {
return candidate;
}
}
return null;
}
function hasExplicitTopicSwitchSignal(text) {
return /(?:^|\s)(?:\u0442\u0435\u043f\u0435\u0440\u044c|\u0430\s+\u0442\u0435\u043f\u0435\u0440\u044c|\u0434\u0430\u043b\u044c\u0448\u0435|\u043e\u0442\u0434\u0435\u043b\u044c\u043d\u043e|\u043f\u0435\u0440\u0435\u0439\u0434[\u0451\u0435]\u043c|\u0441\u043c\u0435\u043d\u0438\u043c\s+\u0442\u0435\u043c\u0443|\u0432\u0435\u0440\u043d[\u0451\u0435]\u043c\u0441\u044f\s+\u043a|now|next|switch\s+to)(?:\s|$)/iu.test(text);
}
@@ -1047,8 +1100,13 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
const rawEntitySourceText = repairedUserText ?? rawUserText ?? repairedEffectiveText ?? rawEffectiveText ?? rawSignalSourceText;
const rawText = compactLower(rawSignalSourceText);
const rawReferentialDocumentExclusionSignal = hasReferentialDocumentExclusionFollowupSignal(repairedUserText ?? rawUserText ?? "");
const businessOverviewContinuationSignal = hasBusinessOverviewFollowupSeed(followupSeed) && hasBusinessOverviewContinuationSignal(rawText);
const rawBusinessOverviewSignal = hasBusinessOverviewSignal(rawText) || businessOverviewContinuationSignal;
const rawPrimaryBusinessOverviewSignal = hasBusinessOverviewSignal(rawText);
const explicitVatQuestionSignal = hasExplicitVatQuestionSignal(rawText);
const explicitVatSuppressesBusinessOverviewContinuation = Boolean(explicitVatQuestionSignal && !rawPrimaryBusinessOverviewSignal);
const businessOverviewContinuationSignal = hasBusinessOverviewFollowupSeed(followupSeed) &&
hasBusinessOverviewContinuationSignal(rawText) &&
!explicitVatSuppressesBusinessOverviewContinuation;
const rawBusinessOverviewSignal = rawPrimaryBusinessOverviewSignal || businessOverviewContinuationSignal;
const rawLifecycleSignal = !rawBusinessOverviewSignal && hasLifecycleSignal(rawText);
const rawBidirectionalValueFlowSignal = !rawBusinessOverviewSignal && !rawLifecycleSignal && hasBidirectionalValueFlowSignal(rawText);
const rawValueFlowSignal = !rawBusinessOverviewSignal &&
@@ -1094,6 +1152,10 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
rawDomain === "business_summary" ||
rawDomain === "business_overview" ||
rawAction === "broad_evaluation";
const businessOverviewSeparateCounterpartySignal = Boolean(businessOverviewSignal && hasBusinessOverviewSeparateCounterpartySignal(rawText));
const businessOverviewSeparateCounterpartyCandidate = businessOverviewSeparateCounterpartySignal
? businessOverviewSeparateCounterpartyCandidateFromText(rawText)
: null;
const explicitIntentCandidate = toNonEmptyString(assistantTurnMeaning?.explicit_intent_candidate);
const currentTurnDocumentLaneSignal = rawAction === "list_documents";
const currentTurnMovementLaneSignal = rawAction === "list_movements";
@@ -1125,6 +1187,7 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
sameScopedName(followupSeed.counterparty, followupSeed.organization) ||
sameScopedName(followupSeed.counterparty, currentTurnOrganizationScope)));
const businessOverviewSuppressesFollowupCounterparty = Boolean(businessOverviewSignal &&
!businessOverviewSeparateCounterpartySignal &&
(rawBusinessOverviewSignal ||
businessOverviewContinuationSignal ||
broadBusinessEvaluationUnsupported ||
@@ -1161,7 +1224,9 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
? null
: normalizeFollowupCounterpartyCandidate(predecomposeEntities.counterparty);
const predecomposeDateScope = collectDateScope(predecomposeContract);
const suppressFollowupBusinessOverviewSeed = Boolean(explicitVatSuppressesBusinessOverviewContinuation && hasBusinessOverviewFollowupSeed(followupSeed));
const periodClarificationFollowupApplicable = Boolean(followupSeed.domain &&
!suppressFollowupBusinessOverviewSeed &&
followupSeed.loopStatus === "awaiting_clarification" &&
followupSeed.loopPendingAxes.includes("period") &&
!rawLifecycleSignal &&
@@ -1172,6 +1237,7 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
relativeCurrentDateHintDetected ||
(predecomposeDateScope && !isImplicitCurrentDateScope(predecomposeDateScope))));
const followupDiscoverySeedApplicable = Boolean(followupSeed.domain &&
!suppressFollowupBusinessOverviewSeed &&
!rawLifecycleSignal &&
!rawMetadataSignal &&
(periodClarificationFollowupApplicable ||
@@ -1499,6 +1565,7 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
for (const candidate of collectEntityCandidates(assistantTurnMeaning?.explicit_entity_candidates)) {
pushScopedEntityCandidate(entityCandidates, candidate, groundedFollowupEntity);
}
pushScopedEntityCandidate(entityCandidates, businessOverviewSeparateCounterpartyCandidate, groundedFollowupEntity);
pushScopedEntityCandidate(entityCandidates, normalizedPredecomposeCounterparty, groundedFollowupEntity);
pushScopedEntityCandidate(entityCandidates, rawScopedEntityCandidate, groundedFollowupEntity);
if (!groundedFollowupEntity) {
@@ -1511,6 +1578,20 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
}
pushScopedEntityCandidate(entityCandidates, rawEntityCandidate, groundedFollowupEntity);
}
const businessOverviewSeparateCounterpartyDisplayCandidate = businessOverviewSeparateCounterpartySignal
? preferredScopedDisplayName(businessOverviewSeparateCounterpartyCandidate, [
groundedFollowupEntity,
effectiveFollowupCounterparty,
followupSeed.discoveryEntity,
normalizedPredecomposeCounterparty,
rawScopedEntityCandidate,
rawEntityCandidate,
...entityCandidates
])
: null;
const businessOverviewSeparateEntityCandidates = businessOverviewSeparateCounterpartyDisplayCandidate
? [businessOverviewSeparateCounterpartyDisplayCandidate]
: [];
if ((rawMetadataSignal || metadataFollowupSeedApplicable) &&
!groundedFollowupEntity &&
!metadataScopedLaneWithoutSubject) {
@@ -1579,6 +1660,8 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
(clarificationLoopStillNeedsPeriod ||
businessOverviewSignal ||
openScopeValueFlowWithoutResolvedCounterparty ||
valueFlowGroundedDocumentFollowupApplicable ||
valueFlowGroundedMovementFollowupApplicable ||
(valueFlowOrganizationStaysScope && (Boolean(followupSeed.rankingNeed) || bidirectionalValueFlowSignal))));
const suppressNegatedTaxOnlyDateScope = Boolean(businessOverviewSignal && negatedTaxDateScopeOnlySignal);
const topicSwitchSuppressesFollowupScope = Boolean(rawTopicSwitchSignal &&
@@ -1604,10 +1687,15 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
(suppressImplicitCurrentDateScope && isImplicitCurrentDateScope(followupSeed.dateScope))
? null
: followupSeed.dateScope;
const businessOverviewRawYearOverridesPredecomposeAsOf = Boolean(businessOverviewSignal &&
rawDateScope &&
/^\d{4}$/.test(rawDateScope) &&
normalizedPredecomposeDateScope &&
normalizedPredecomposeDateScope.startsWith(`${rawDateScope}-`));
const explicitDateScope = rawAllTimeScopeSignal
? null
: normalizedAssistantTurnMeaningDateScope ??
normalizedPredecomposeDateScope ??
(businessOverviewRawYearOverridesPredecomposeAsOf ? rawDateScope : normalizedPredecomposeDateScope) ??
rawDateScope ??
normalizedFollowupDateScope;
const followupDateScopeApplied = Boolean(!rawAllTimeScopeSignal &&
@@ -1656,6 +1744,11 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
? followupSeed.rankingNeed
: undefined,
explicit_entity_candidates: businessOverviewSignal ? [] : entityCandidates,
business_overview_separate_entity_candidates: businessOverviewSeparateEntityCandidates,
previous_counterparty_value_flow_bundle: businessOverviewSignal && followupSeed.previousBidirectionalValueFlow
? followupSeed.previousBidirectionalValueFlow
: undefined,
previous_counterparty_document_bundle: businessOverviewSignal && followupSeed.previousDocumentSummary ? followupSeed.previousDocumentSummary : undefined,
metadata_ambiguity_entity_sets: metadataAmbiguityLaneClarificationApplicable && followupSeed.metadataAmbiguityEntitySets.length > 0
? followupSeed.metadataAmbiguityEntitySets
: undefined,
@@ -1716,6 +1809,15 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
if ((turnMeaning.explicit_entity_candidates?.length ?? 0) > 0) {
cleanTurnMeaning.explicit_entity_candidates = turnMeaning.explicit_entity_candidates;
}
if ((turnMeaning.business_overview_separate_entity_candidates?.length ?? 0) > 0) {
cleanTurnMeaning.business_overview_separate_entity_candidates = turnMeaning.business_overview_separate_entity_candidates;
}
if (toRecordObject(turnMeaning.previous_counterparty_value_flow_bundle)) {
cleanTurnMeaning.previous_counterparty_value_flow_bundle = turnMeaning.previous_counterparty_value_flow_bundle;
}
if (toRecordObject(turnMeaning.previous_counterparty_document_bundle)) {
cleanTurnMeaning.previous_counterparty_document_bundle = turnMeaning.previous_counterparty_document_bundle;
}
if ((turnMeaning.metadata_ambiguity_entity_sets?.length ?? 0) > 0) {
cleanTurnMeaning.metadata_ambiguity_entity_sets = turnMeaning.metadata_ambiguity_entity_sets;
}
@@ -1924,9 +2026,21 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
if (businessOverviewContinuationSignal) {
pushReason(reasonCodes, "mcp_discovery_business_overview_continuation_from_followup_context");
}
if (explicitVatSuppressesBusinessOverviewContinuation) {
pushReason(reasonCodes, "mcp_discovery_business_overview_continuation_suppressed_by_explicit_vat_question");
}
if (businessOverviewSuppressesFollowupCounterparty) {
pushReason(reasonCodes, "mcp_discovery_business_overview_suppressed_stale_counterparty");
}
if (businessOverviewSeparateCounterpartySignal) {
pushReason(reasonCodes, "mcp_discovery_business_overview_preserved_explicit_counterparty_summary_scope");
}
if (businessOverviewSeparateCounterpartyCandidate) {
pushReason(reasonCodes, "mcp_discovery_business_overview_counterparty_from_summary_text");
}
if (businessOverviewRawYearOverridesPredecomposeAsOf) {
pushReason(reasonCodes, "mcp_discovery_business_overview_raw_year_overrode_predecompose_as_of_scope");
}
if (!(valueFlowOrganizationStaysScope && normalizedPredecomposeCounterparty === explicitOrganizationScope) &&
normalizedPredecomposeCounterparty) {
pushReason(reasonCodes, "mcp_discovery_counterparty_from_predecompose");
@@ -1957,11 +2071,17 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
if (runDiscovery && !hasTurnMeaning) {
pushReason(reasonCodes, "mcp_discovery_turn_meaning_missing");
}
const dataNeedGraphTurnMeaning = businessOverviewSeparateCounterpartySignal && cleanTurnMeaning.explicit_entity_candidates
? {
...cleanTurnMeaning,
explicit_entity_candidates: []
}
: cleanTurnMeaning;
const dataNeedGraph = runDiscovery && hasTurnMeaning
? (0, assistantMcpDiscoveryDataNeedGraph_1.buildAssistantMcpDiscoveryDataNeedGraph)({
semanticDataNeed,
rawUtterance: rawSignalSourceText,
turnMeaning: cleanTurnMeaning
turnMeaning: dataNeedGraphTurnMeaning
})
: null;
if (dataNeedGraph) {
@@ -171,6 +171,30 @@ function hasSignalAcrossSamples(samples, detector) {
function hasExplicitRecapPromptSignal(samples) {
return samples.some((sample) => /(?:что\s+мы\s+.*(?:обсуждали|выяснили)|что\s+уже\s+выяснили|что\s+уже\s+поняли|напомни\s+что\s+мы|executive\s+summary|финальн\w*\s+собери|итогов\w*\s+(?:резюм|summary|вывод)|по\s+всему\s+диалогу|где\s+ответы\s+были\s+подтвержден|где\s+proxy|где\s+прокси|не\s+хватил\w*\s+доказательств|ручн\w*\s+(?:смотр|провер|контрол))/iu.test(sample));
}
function normalizeMemoryCheckpointSample(value) {
return String(value ?? "")
.trim()
.toLowerCase()
.replace(/ё/g, "е")
.replace(/[«»"'`]/g, "")
.replace(/\s+/g, " ");
}
function hasMemoryCheckpointPromptSignal(samples) {
return samples.some((sample) => {
const text = normalizeMemoryCheckpointSample(sample);
if (!text) {
return false;
}
if (/(?:стартов\w*\s+чек\s+контекст|чек\s+контекста|context\s+check|memory\s+check)/iu.test(text)) {
return true;
}
const hasSelectedStateCue = /(?:выбранн\w*\s+(?:компан|организац|контрагент|объект)|активн\w*\s+(?:компан|организац|контрагент|объект)|selected\s+(?:company|organization|counterparty|object)|active\s+(?:company|organization|counterparty|object))/iu.test(text);
const hasDialogStateCue = /(?:в\s+текущ\w*\s+диалог|в\s+этом\s+диалог|в\s+сессии|контекст(?:е|а)?\s+диалог|current\s+(?:dialog|session|conversation))/iu.test(text);
const hasHonestyCue = /(?:не\s+выдумывай\s+памят|не\s+придумывай\s+памят|скажи\s+честно|если\s+нет|no\s+fabricat|do\s+not\s+invent\s+memory)/iu.test(text);
const asksCurrentSelection = /(?:есть\s+ли\s+уже|есть\s+ли\s+сейчас|что\s+выбрано|кто\s+выбран|какая\s+компан\w*\s+выбран)/iu.test(text);
return (hasSelectedStateCue && hasDialogStateCue) || (hasDialogStateCue && hasHonestyCue) || (asksCurrentSelection && hasHonestyCue);
});
}
function buildInventoryHistoryCapabilityFollowupReply(input) {
const contextFacts = (0, assistantContinuityPolicy_1.resolveAddressDebugContextFacts)(input.addressDebug, input.toNonEmptyString);
const organization = input.organization ?? contextFacts.organization;
@@ -545,6 +569,26 @@ function extractBuyerFromSaleTraceAnswer(answerText, itemLabel) {
}
return null;
}
function extractRequestedMemorySubject(userMessage) {
const text = String(userMessage ?? "").trim();
if (!text) {
return null;
}
const patterns = [
/памят[ьи]\s+про\s+([^.;!?]+)/iu,
/memory\s+about\s+([^.;!?]+)/iu
];
for (const pattern of patterns) {
const match = text.match(pattern);
const subject = match?.[1]
? match[1].replace(/[«»"'`]/g, "").replace(/\s+/g, " ").trim()
: "";
if (subject.length >= 2 && subject.length <= 80) {
return subject;
}
}
return null;
}
function buildAddressMemoryRecapReply(input) {
const contextFacts = (0, assistantContinuityPolicy_1.resolveAddressDebugContextFacts)(input.addressDebug, input.toNonEmptyString);
const item = contextFacts.item;
@@ -604,7 +648,14 @@ function buildAddressMemoryRecapReply(input) {
"Могу кратко напомнить контекст или сразу продолжить следующий шаг по этому же сценарию."
].join(" ");
}
return "Да, помню предыдущий адресный контур. Могу кратко напомнить, что мы уже подтвердили, или сразу продолжить следующий шаг.";
const requestedMemorySubject = extractRequestedMemorySubject(input.userMessage);
const subjectLine = requestedMemorySubject
? ` Память про «${requestedMemorySubject}» в этом диалоге не подтверждена.`
: " Память про конкретную компанию или контрагента в этом диалоге не подтверждена.";
return [
`Коротко: в текущем диалоге я не вижу выбранной компании, контрагента или позиции.${subjectLine}`,
"Чтобы продолжить без выдуманной памяти, назови компанию, контрагента или объект, и я начну новый проверенный контур."
].join(" ");
}
function buildBroadBusinessEvaluationReply(input) {
const contextFacts = (0, assistantContinuityPolicy_1.resolveAddressDebugContextFacts)(input.addressDebug, input.toNonEmptyString);
@@ -820,6 +871,7 @@ function createAssistantMemoryRecapPolicy(deps) {
const historicalCapabilitySignal = hasSignalAcrossSamples(samples, deps.hasHistoricalCapabilityFollowupSignal);
const memoryRecapSignal = hasSignalAcrossSamples(samples, deps.hasConversationMemoryRecallFollowupSignal);
const explicitRecapPromptSignal = hasExplicitRecapPromptSignal(samples);
const memoryCheckpointPromptSignal = hasMemoryCheckpointPromptSignal(samples);
return {
contextualHistoricalCapabilityFollowupDetected: Boolean(input.capabilityMetaQuery &&
!input.dataScopeMetaQuery &&
@@ -829,9 +881,10 @@ function createAssistantMemoryRecapPolicy(deps) {
contextualMemoryRecapFollowupDetected: Boolean(!input.dataScopeMetaQuery &&
!input.capabilityMetaQuery &&
!input.aggregateBusinessAnalyticsSignal &&
memoryRecapSignal &&
(explicitRecapPromptSignal || (!input.dataRetrievalSignal && !input.strongDataSignal)) &&
continuity.hasGroundedAddressContext)
(memoryCheckpointPromptSignal ||
(memoryRecapSignal &&
(explicitRecapPromptSignal || (!input.dataRetrievalSignal && !input.strongDataSignal)) &&
continuity.hasGroundedAddressContext)))
};
}
return {
@@ -116,6 +116,10 @@ function createAssistantTransitionPolicy(deps) {
}
return null;
}
function hasExplicitSummaryBundleReuseSignal(userMessage, alternateMessage = null) {
const samples = [userMessage, alternateMessage].map((item) => normalizeFollowupText(item)).filter(Boolean);
return samples.some((sample) => /(?:итог|summary|резюм|вывод|что\s+(?:мы\s+)?подтверд|что\s+понят|что\s+можно|что\s+нельзя|собери\s+коротк)/iu.test(sample) && /(?:контрагент|группа\s+свк|свк|отдельн)/iu.test(sample));
}
function parseDmyDateToIso(value) {
const match = String(value ?? "").trim().match(/^(\d{2})\.(\d{2})\.(\d{4})$/);
if (!match) {
@@ -244,6 +248,57 @@ function createAssistantTransitionPolicy(deps) {
}
return null;
}
function readMcpDiscoveryBidirectionalValueFlow(debug) {
const entryPoint = debug?.assistant_mcp_discovery_entry_point_v1;
const flow = entryPoint?.bridge?.pilot?.derived_bidirectional_value_flow;
if (!flow || typeof flow !== "object" || Array.isArray(flow)) {
return null;
}
return flow;
}
function readCounterpartyDocumentSummaryFromItem(item) {
const text = deps.toNonEmptyString(item?.text);
if (!text) {
return null;
}
const firstLine = text.split(/\r?\n/).map((line) => line.trim()).find(Boolean) ?? "";
const match = firstLine.match(/Контрагент:\s*([^.\n]+)\.\s*Найдено документов:\s*(\d+)/iu);
if (!match?.[1] || !match?.[2]) {
return null;
}
return {
counterparty: deps.toNonEmptyString(match[1]),
document_count: Number(match[2]),
direct_answer: firstLine
};
}
function findRecentDiscoveryValueFlowBundle(items) {
for (let index = Array.isArray(items) ? items.length - 1 : -1; index >= 0; index -= 1) {
const item = items[index];
const debug = item?.debug;
if (!item || item.role !== "assistant" || !debug || typeof debug !== "object") {
continue;
}
const flow = readMcpDiscoveryBidirectionalValueFlow(debug);
if (flow) {
return flow;
}
}
return null;
}
function findRecentCounterpartyDocumentBundle(items) {
for (let index = Array.isArray(items) ? items.length - 1 : -1; index >= 0; index -= 1) {
const item = items[index];
if (!item || item.role !== "assistant" || !item.debug || typeof item.debug !== "object") {
continue;
}
const summary = readCounterpartyDocumentSummaryFromItem(item);
if (summary) {
return summary;
}
}
return null;
}
function hasInventoryPurchaseDateVatBridgeSignal(userMessage, alternateMessage, sourceIntentHint, hasInventoryItemFocusHint) {
if (sourceIntentHint !== "inventory_purchase_provenance_for_item" &&
!hasInventoryItemFocusHint &&
@@ -388,7 +443,8 @@ function createAssistantTransitionPolicy(deps) {
llmPreDecomposeMeta
})
: null;
if (assistantTurnMeaning?.stale_replay_forbidden === true) {
if (assistantTurnMeaning?.stale_replay_forbidden === true &&
!hasExplicitSummaryBundleReuseSignal(userMessage, alternateMessage)) {
return null;
}
const latestAddressItem = deps.findLastAddressAssistantItem(items);
@@ -465,17 +521,20 @@ function createAssistantTransitionPolicy(deps) {
const shortValueFlowRetargetAlternate = hasValueFlowCarryoverSourceHint && deps.toNonEmptyString(alternateMessage)
? hasShortValueFlowRetargetCue(String(alternateMessage ?? ""))
: false;
const explicitSummaryBundleReuseSignal = hasExplicitSummaryBundleReuseSignal(userMessage, alternateMessage);
let hasPrimaryFollowupSignal = deps.hasAddressFollowupContextSignal(userMessage) ||
Boolean(debtRoleSwapPrimary) ||
shortValueFlowRetargetPrimary ||
inventoryShortFollowupPrimary ||
inventoryPurchaseDateVatBridge;
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal;
let hasAlternateFollowupSignal = deps.toNonEmptyString(alternateMessage)
? deps.hasAddressFollowupContextSignal(alternateMessage) ||
Boolean(debtRoleSwapAlternate) ||
shortValueFlowRetargetAlternate ||
inventoryShortFollowupAlternate ||
inventoryPurchaseDateVatBridge
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal
: false;
const hasPrimaryIndexReferenceSignal = deps.extractDisplayedEntityIndexMention(userMessage) !== null;
const hasAlternateIndexReferenceSignal = deps.toNonEmptyString(alternateMessage)
@@ -507,6 +566,7 @@ function createAssistantTransitionPolicy(deps) {
hasInventoryRootRestatementPrimary ||
hasInventoryRootRestatementAlternate ||
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal ||
Boolean(debtRoleSwapIntent) ||
shortValueFlowRetargetPrimary ||
shortValueFlowRetargetAlternate ||
@@ -526,6 +586,7 @@ function createAssistantTransitionPolicy(deps) {
hasInventoryRootRestatementPrimary ||
hasInventoryRootRestatementAlternate ||
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal ||
Boolean(debtRoleSwapIntent) ||
shortValueFlowRetargetPrimary ||
shortValueFlowRetargetAlternate ||
@@ -556,7 +617,8 @@ function createAssistantTransitionPolicy(deps) {
!hasImplicitContinuationSignal &&
!hasSuggestedIntentPivotSignal &&
!hasOrganizationClarificationContinuation &&
!hasIndexReferenceSignal) {
!hasIndexReferenceSignal &&
!explicitSummaryBundleReuseSignal) {
return null;
}
if (!hasPrimaryFollowupSignal &&
@@ -570,7 +632,8 @@ function createAssistantTransitionPolicy(deps) {
!hasImplicitContinuationSignal &&
!hasSuggestedIntentPivotSignal &&
!hasOrganizationClarificationContinuation &&
!hasIndexReferenceSignal) {
!hasIndexReferenceSignal &&
!explicitSummaryBundleReuseSignal) {
return null;
}
if (!carryoverSourceDebug) {
@@ -598,6 +661,8 @@ function createAssistantTransitionPolicy(deps) {
const sourceDiscoveryLoopSubjectResolutionOptional = (0, assistantContinuityPolicy_1.readAssistantMcpDiscoveryLoopSubjectResolutionOptional)(carryoverSourceDebug);
const sourceDiscoveryRankingNeed = (0, assistantContinuityPolicy_1.readAssistantMcpDiscoveryRankingNeed)(carryoverSourceDebug, deps.toNonEmptyString);
const sourceDiscoveryEntityAmbiguityCandidates = (0, assistantContinuityPolicy_1.readAssistantMcpDiscoveryEntityAmbiguityCandidates)(carryoverSourceDebug, deps.toNonEmptyString);
const sourceDiscoveryBidirectionalValueFlow = readMcpDiscoveryBidirectionalValueFlow(carryoverSourceDebug) ?? findRecentDiscoveryValueFlowBundle(items);
const sourceDiscoveryDocumentSummary = findRecentCounterpartyDocumentBundle(items);
const llmExplicitIntent = deps.toNonEmptyString(llmPreDecomposeMeta?.predecomposeContract?.intent);
const llmSelectedObjectScopeDetected = llmPreDecomposeMeta?.predecomposeContract?.semantics?.selected_object_scope_detected === true;
const resolvedPrimaryIntent = deps.resolveAddressIntent(deps.repairAddressMojibake(String(userMessage ?? ""))).intent;
@@ -690,6 +755,7 @@ function createAssistantTransitionPolicy(deps) {
shortValueFlowRetargetPrimary ||
inventoryShortFollowupPrimary ||
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal ||
hasInventoryRootTemporalFollowupPrimary;
hasAlternateFollowupSignal = deps.toNonEmptyString(alternateMessage)
? deps.hasAddressFollowupContextSignal(alternateMessage) ||
@@ -698,6 +764,7 @@ function createAssistantTransitionPolicy(deps) {
shortValueFlowRetargetAlternate ||
inventoryShortFollowupAlternate ||
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal ||
hasInventoryRootTemporalFollowupAlternate
: false;
hasStrongFollowupReference =
@@ -711,6 +778,7 @@ function createAssistantTransitionPolicy(deps) {
hasInventoryRootTemporalFollowupPrimary ||
hasInventoryRootTemporalFollowupAlternate ||
inventoryPurchaseDateVatBridge ||
explicitSummaryBundleReuseSignal ||
Boolean(debtRoleSwapIntent) ||
shortValueFlowRetargetPrimary ||
shortValueFlowRetargetAlternate ||
@@ -859,6 +927,8 @@ function createAssistantTransitionPolicy(deps) {
previous_discovery_metadata_recommended_next_primitive: sourceDiscoveryMetadataRecommendedNextPrimitive ?? undefined,
previous_discovery_metadata_ambiguity_detected: sourceDiscoveryMetadataAmbiguityDetected || undefined,
previous_discovery_metadata_ambiguity_entity_sets: sourceDiscoveryMetadataAmbiguityEntitySets.length > 0 ? sourceDiscoveryMetadataAmbiguityEntitySets : undefined,
previous_discovery_bidirectional_value_flow: sourceDiscoveryBidirectionalValueFlow ?? undefined,
previous_discovery_document_summary: sourceDiscoveryDocumentSummary ?? undefined,
resolved_counterparty_from_display: resolvedCounterpartyFromDisplay || undefined,
root_context_only: rootScopedPivot || undefined,
root_intent: shouldAttachInventoryRootFrame ? inventoryRootFrame?.intent ?? undefined : undefined,
@@ -80,21 +80,24 @@ function groundingStatusFrom(debug, input, truthGateStatus) {
}
function coverageStatusFrom(debug, input, truthGateStatus, groundingStatus) {
const explicitCoverageEvidence = (0, addressCoverageEvidencePolicy_1.toAddressCoverageEvidenceContract)(debug.address_coverage_evidence_v1);
if (truthGateStatus === "full_confirmed") {
return "full";
}
if (truthGateStatus === "partial_supported" || truthGateStatus === "limited_temporal_or_contextual") {
return "partial";
}
if (truthGateStatus.startsWith("blocked")) {
return "blocked";
}
if (toStringList(debug.missing_required_filters).length > 0 || groundingStatus === "route_mismatch_blocked" || groundingStatus === "no_grounded_answer") {
return "blocked";
}
if (truthGateStatus === "partial_supported" || truthGateStatus === "limited_temporal_or_contextual") {
return "partial";
}
if (explicitCoverageEvidence) {
return explicitCoverageEvidence.coverage_status;
}
if (debug.balance_confirmed === false || toNonEmptyString(debug.result_mode) === "heuristic_candidates") {
return "partial";
}
if (truthGateStatus === "full_confirmed") {
return "full";
}
const coverageReport = toRecordObject(input.coverageReport) ?? toRecordObject(debug.coverage_report);
if (coverageReport) {
const total = asNumber(coverageReport.requirements_total);
@@ -123,10 +126,16 @@ function truthModeFrom(input) {
if (input.truthGateStatus === "blocked_missing_anchor" || toStringList(input.debug.missing_required_filters).length > 0) {
return "clarification_required";
}
if (input.truthGateStatus === "full_confirmed" || (input.coverageStatus === "full" && input.groundingStatus === "grounded")) {
if (input.coverageStatus === "partial") {
return "limited";
}
if (input.truthGateStatus === "full_confirmed" && input.coverageStatus === "full") {
return "confirmed";
}
if (input.truthGateStatus === "partial_supported" || input.truthGateStatus === "limited_temporal_or_contextual" || input.coverageStatus === "partial") {
if (input.coverageStatus === "full" && input.groundingStatus === "grounded") {
return "confirmed";
}
if (input.truthGateStatus === "partial_supported" || input.truthGateStatus === "limited_temporal_or_contextual") {
return "limited";
}
return "unsupported";
@@ -140,6 +149,9 @@ function evidenceGradeFrom(debug, coverageStatus, groundingStatus, truthGateStat
if (isEvidenceGrade(explicit)) {
return explicit;
}
if (debug.balance_confirmed === false || toNonEmptyString(debug.result_mode) === "heuristic_candidates") {
return coverageStatus === "partial" ? "medium" : "weak";
}
if (coverageStatus === "blocked") {
return "none";
}