Semantic Gate: закрепить контрагентский value-flow и денежный разбор

This commit is contained in:
2026-05-05 20:19:47 +03:00
parent 9be3fb29b7
commit ba23b056b8
19 changed files with 614 additions and 48 deletions
@@ -1116,6 +1116,20 @@ function buildWhereClause(filters: AddressFilterSet, fieldPath: string, extraCon
return "";
}
function buildBankDocumentWhereClause(
filters: AddressFilterSet,
dateFieldPath: string,
counterpartyFieldPath: string
): string {
return buildWhereClause(
filters,
dateFieldPath,
[buildCounterpartyReferenceCondition(filters, [counterpartyFieldPath])].filter((item): item is string =>
Boolean(item)
)
);
}
function buildManagementWhereClause(filters: AddressFilterSet, fieldPath: string): string {
return buildWhereClause(filters, fieldPath);
}
@@ -1538,8 +1552,14 @@ export function buildAddressRecipePlan(
recipe.query_template === "bank_docs"
? BANK_DOCS_QUERY_TEMPLATE
.replaceAll("__LIMIT__", String(resolvedLimit))
.replace("__WHERE_OUT__", buildWhereClause(filters, "БанкСписание.Дата"))
.replace("__WHERE_IN__", buildWhereClause(filters, "БанкПоступление.Дата"))
.replace(
"__WHERE_OUT__",
buildBankDocumentWhereClause(filters, "БанкСписание.Дата", "БанкСписание.Контрагент")
)
.replace(
"__WHERE_IN__",
buildBankDocumentWhereClause(filters, "БанкПоступление.Дата", "БанкПоступление.Контрагент")
)
.replaceAll("__ORDER_DIRECTION__", resolveOrderDirection(filters.sort))
: recipe.query_template === "period_profile"
? PERIOD_COVERAGE_PROFILE_QUERY_TEMPLATE.replaceAll(
@@ -1553,12 +1573,18 @@ export function buildAddressRecipePlan(
)
: recipe.query_template === "counterparty_roles_profile"
? COUNTERPARTY_POPULATION_AND_ROLES_QUERY_TEMPLATE
.replaceAll("__WHERE_OUT__", buildWhereClause(filters, "БанкСписание.Дата"))
.replaceAll("__WHERE_IN__", buildWhereClause(filters, "БанкПоступление.Дата"))
.replaceAll(
"__WHERE_OUT__",
buildBankDocumentWhereClause(filters, "БанкСписание.Дата", "БанкСписание.Контрагент")
)
.replaceAll(
"__WHERE_IN__",
buildBankDocumentWhereClause(filters, "БанкПоступление.Дата", "БанкПоступление.Контрагент")
)
: recipe.query_template === "counterparty_lifecycle_profile"
? COUNTERPARTY_ACTIVITY_LIFECYCLE_QUERY_TEMPLATE.replaceAll(
"__WHERE_IN__",
buildWhereClause(filters, "БанкПоступление.Дата")
buildBankDocumentWhereClause(filters, "БанкПоступление.Дата", "БанкПоступление.Контрагент")
)
: recipe.query_template === "contract_usage_profile"
? CONTRACT_USAGE_OVERVIEW_QUERY_TEMPLATE
@@ -1573,12 +1599,18 @@ export function buildAddressRecipePlan(
: recipe.query_template === "customer_revenue_profile"
? CUSTOMER_REVENUE_PROFILE_QUERY_TEMPLATE
.replaceAll("__LIMIT__", String(resolvedLimit))
.replaceAll("__WHERE_IN__", buildWhereClause(filters, "БанкПоступление.Дата"))
.replaceAll(
"__WHERE_IN__",
buildBankDocumentWhereClause(filters, "БанкПоступление.Дата", "БанкПоступление.Контрагент")
)
.replaceAll("__ORDER_DIRECTION__", resolveOrderDirection(filters.sort))
: recipe.query_template === "supplier_payout_profile"
? SUPPLIER_PAYOUT_PROFILE_QUERY_TEMPLATE
.replaceAll("__LIMIT__", String(resolvedLimit))
.replaceAll("__WHERE_OUT__", buildWhereClause(filters, "БанкСписание.Дата"))
.replaceAll(
"__WHERE_OUT__",
buildBankDocumentWhereClause(filters, "БанкСписание.Дата", "БанкСписание.Контрагент")
)
.replaceAll("__ORDER_DIRECTION__", resolveOrderDirection(filters.sort))
: recipe.query_template === "contract_value_profile"
? CONTRACT_VALUE_PROFILE_QUERY_TEMPLATE
@@ -76,6 +76,60 @@ function toRecordObject(value: unknown): Record<string, unknown> | null {
return value as Record<string, unknown>;
}
function sessionOrganizationName(
sessionOrganizationScope: BuildAssistantAddressOrchestrationRuntimeInput["sessionOrganizationScope"],
toNonEmptyString: BuildAssistantAddressOrchestrationRuntimeInput["toNonEmptyString"]
): string | null {
const scope = toRecordObject(sessionOrganizationScope);
return toNonEmptyString(scope?.selectedOrganization) ?? toNonEmptyString(scope?.activeOrganization);
}
function predecomposeOrganizationName(
predecomposeContract: Record<string, unknown> | null,
toNonEmptyString: BuildAssistantAddressOrchestrationRuntimeInput["toNonEmptyString"]
): string | null {
const entities = toRecordObject(predecomposeContract?.entities);
return (
toNonEmptyString(entities?.organization) ??
toNonEmptyString(predecomposeContract?.organization)
);
}
function mergeOrganizationIntoDiscoveryFollowupContext(
followupContext: Record<string, unknown> | null,
organization: string | null
): Record<string, unknown> | null {
if (!organization) {
return followupContext;
}
const base = followupContext ? { ...followupContext } : {};
const previousFilters = toRecordObject(base.previous_filters)
? { ...(base.previous_filters as Record<string, unknown>) }
: {};
if (!previousFilters.organization) {
previousFilters.organization = organization;
}
base.previous_filters = previousFilters;
const rootFilters = toRecordObject(base.root_filters)
? { ...(base.root_filters as Record<string, unknown>) }
: {};
if (!rootFilters.organization) {
rootFilters.organization = organization;
}
base.root_filters = rootFilters;
if (!base.previous_anchor_type) {
base.previous_anchor_type = "organization";
}
if (!base.previous_anchor_value) {
base.previous_anchor_value = organization;
}
return base;
}
function hasSelectedObjectInventorySignal(text: string | null): boolean {
return /(?:по\s+выбранному\s+объекту|по\s+выбранной\s+позиции|по\s+этой\s+позиции|по\s+этому\s+товару|по\s+ним|selected\s+object)/iu.test(
String(text ?? "")
@@ -308,6 +362,13 @@ export async function buildAssistantAddressOrchestrationRuntime(
const orchestrationDecision = routePolicyRuntime.orchestrationDecision;
const orchestrationContract = toRecordObject(orchestrationDecision.orchestrationContract);
const predecomposeContract = toRecordObject(addressPreDecompose.predecomposeContract);
const explicitPredecomposeOrganization = predecomposeOrganizationName(predecomposeContract, input.toNonEmptyString);
const discoveryFollowupContext = mergeOrganizationIntoDiscoveryFollowupContext(
followupContext,
explicitPredecomposeOrganization
? null
: sessionOrganizationName(input.sessionOrganizationScope ?? null, input.toNonEmptyString)
);
const dialogContinuationContract = input.buildAddressDialogContinuationContractV2(
input.userMessage,
addressInputMessage,
@@ -323,7 +384,7 @@ export async function buildAssistantAddressOrchestrationRuntime(
effectiveMessage: addressInputMessage,
assistantTurnMeaning: toRecordObject(orchestrationContract?.assistant_turn_meaning),
predecomposeContract,
followupContext
followupContext: discoveryFollowupContext
})) as Record<string, unknown>;
} catch (error) {
mcpDiscoveryRuntimeEntryPointError = String(error instanceof Error ? error.message : error ?? "unknown_error").slice(0, 280);
@@ -160,6 +160,13 @@ function isValueFlowPilot(pilot: AssistantMcpDiscoveryPilotExecutionContract): b
);
}
function isSingleDirectionValueFlowPilot(pilot: AssistantMcpDiscoveryPilotExecutionContract): boolean {
return (
pilot.pilot_scope === "counterparty_value_flow_query_movements_v1" ||
pilot.pilot_scope === "counterparty_supplier_payout_query_movements_v1"
);
}
function isBusinessOverviewPilot(pilot: AssistantMcpDiscoveryPilotExecutionContract): boolean {
return pilot.pilot_scope === "business_overview_route_template_v1";
}
@@ -251,6 +258,61 @@ function explicitOrganizationScope(pilot: AssistantMcpDiscoveryPilotExecutionCon
return normalized.length > 0 ? normalized : null;
}
function hasExecutedZeroValueFlowRows(pilot: AssistantMcpDiscoveryPilotExecutionContract): boolean {
const summary = pilot.source_rows_summary ?? "";
return (
pilot.mcp_execution_performed &&
isSingleDirectionValueFlowPilot(pilot) &&
!pilot.derived_value_flow &&
(/0\s+MCP\s+value-flow\s+rows\s+fetched/i.test(summary) ||
/\b0\s+matched\s+value-flow\s+scope\b/i.test(summary))
);
}
function valueFlowDirectionLabelRu(pilot: AssistantMcpDiscoveryPilotExecutionContract): string {
return pilot.pilot_scope === "counterparty_supplier_payout_query_movements_v1"
? "исходящих платежей/списаний"
: "входящих денежных поступлений";
}
function valueFlowZeroResultConfirmedLine(pilot: AssistantMcpDiscoveryPilotExecutionContract): string | null {
if (!hasExecutedZeroValueFlowRows(pilot)) {
return null;
}
const counterparty = firstEntityCandidate(pilot);
if (!counterparty) {
return null;
}
const organization = explicitOrganizationScope(pilot);
const period = explicitDateScope(pilot);
const organizationPart = organization ? ` по организации ${organization}` : "";
const periodPart = period ? ` за период ${period}` : " в проверенном окне";
return `В проверенном срезе 1С по контрагенту ${counterparty}${organizationPart}${periodPart} ${valueFlowDirectionLabelRu(
pilot
)} не найдено.`;
}
function valueFlowZeroResultUnknownLine(pilot: AssistantMcpDiscoveryPilotExecutionContract): string | null {
if (!hasExecutedZeroValueFlowRows(pilot)) {
return null;
}
const counterparty = firstEntityCandidate(pilot);
if (!counterparty) {
return null;
}
const period = explicitDateScope(pilot);
const periodPart = period ? ` вне периода ${period}` : " вне проверенного окна";
return `Это не доказывает отсутствие операций с контрагентом ${counterparty}${periodPart} или вне доступного банковского контура.`;
}
function valueFlowZeroResultHeadline(pilot: AssistantMcpDiscoveryPilotExecutionContract): string | null {
const confirmedLine = valueFlowZeroResultConfirmedLine(pilot);
if (!confirmedLine) {
return null;
}
return confirmedLine;
}
function hasAllTimeScope(pilot: AssistantMcpDiscoveryPilotExecutionContract): boolean {
return (
dryRunHasAxis(pilot, "all_time_scope") ||
@@ -600,6 +662,10 @@ function headlineFor(mode: AssistantMcpDiscoveryAnswerMode, pilot: AssistantMcpD
}
return "По данным 1С найдены строки входящих денежных поступлений; сумму можно называть только в рамках проверенного периода и найденных строк.";
}
const zeroValueFlowHeadline = valueFlowZeroResultHeadline(pilot);
if (mode === "checked_sources_only" && zeroValueFlowHeadline) {
return zeroValueFlowHeadline;
}
if (isDocumentPilot(pilot) && mode === "confirmed_with_bounded_inference") {
return `По документам${documentOrMovementScopeRu(pilot)} в 1С найдены подтвержденные строки; ответ ограничен проверенным окном и найденными строками.`;
}
@@ -1487,6 +1553,11 @@ function businessOverviewUnknownLines(pilot: AssistantMcpDiscoveryPilotExecution
return userFacingUnknowns(pilot.evidence.unknown_facts);
}
function appendValueFlowZeroResultUnknown(lines: string[], pilot: AssistantMcpDiscoveryPilotExecutionContract): string[] {
const zeroLine = valueFlowZeroResultUnknownLine(pilot);
return zeroLine ? uniqueStrings([zeroLine, ...lines]) : lines;
}
export function buildAssistantMcpDiscoveryAnswerDraft(
pilot: AssistantMcpDiscoveryPilotExecutionContract
): AssistantMcpDiscoveryAnswerDraftContract {
@@ -1581,6 +1652,8 @@ export function buildAssistantMcpDiscoveryAnswerDraft(
? [derivedValueLine]
: derivedValueLine
? [...pilot.evidence.confirmed_facts, derivedValueLine, ...monthlyConfirmedLines]
: valueFlowZeroResultConfirmedLine(pilot)
? [valueFlowZeroResultConfirmedLine(pilot)!]
: derivedEntityResolutionLine
? [...pilot.evidence.confirmed_facts, derivedEntityResolutionLine]
: derivedMetadataLine
@@ -1592,7 +1665,7 @@ export function buildAssistantMcpDiscoveryAnswerDraft(
? pilot.derived_metadata_surface.available_fields.length > 0
? userFacingUnknowns(pilot.evidence.unknown_facts)
: ["Детальный список полей этих объектов этим шагом не получен."]
: rankedValueFlowUnknownLines(pilot);
: appendValueFlowZeroResultUnknown(rankedValueFlowUnknownLines(pilot), pilot);
return {
schema_version: ASSISTANT_MCP_DISCOVERY_ANSWER_DRAFT_SCHEMA_VERSION,
@@ -235,7 +235,11 @@ function pushScopedEntityCandidate(
if (!text) {
return;
}
if ((groundedFollowupEntity && isReferentialEntityPlaceholder(text)) || isValueFlowPredicateEntityCandidate(text)) {
if (
isInvalidEntityCandidate(text) ||
(groundedFollowupEntity && isReferentialEntityPlaceholder(text)) ||
isValueFlowPredicateEntityCandidate(text)
) {
return;
}
pushUnique(target, text);
@@ -911,7 +915,20 @@ function hasBusinessOverviewContinuationSignal(text: string): boolean {
/(?:\u0447\u0442\u043e\s+\u043c\u044b\s+\u0437\u043d\u0430\u0435\u043c|\u0447\u0442\u043e\s+\u043f\u043e\u043d\u044f\u0442\u043d\u043e|\u0447\u0442\u043e\s+\u043f\u0440\u043e\u0432\u0435\u0440\w*\s+\u0434\u0430\u043b\u044c\u0448\u0435|\u0441\u043b\u0435\u0434\u0443\u044e\u0449\w*\s+\u0448\u0430\u0433|\u0438\u0442\u043e\u0433\w*\s+\u0432\u044b\u0432\u043e\u0434|\u043a\u0430\u043a\u043e\u0439\s+\u0432\u044b\u0432\u043e\u0434|\u0447\u0442\u043e\s+\u0441\s+\u044d\u0442\u0438\u043c\s+\u0434\u0435\u043b\u0430\u0442\u044c|what\s+do\s+we\s+know|what\s+is\s+missing|next\s+step|final\s+summary)/iu.test(
normalized
);
return hasEvidenceContinuationCue || hasAnalystContinuationCue || hasTaxContinuationCue || hasFinalSummaryCue;
const hasMoneyBreakdownCue =
/(?:\u0440\u0430\u0441\u043a\u0440\u043e\p{L}*\s+\u0434\u0435\u043d\p{L}*|\u0441\u043a\u043e\u043b\u044c\u043a\u043e\s+\u0432\u0441\u0435\u0433\u043e\s+\u043f\u043e\u043b\u0443\u0447|\u0441\u043a\u043e\u043b\u044c\u043a\u043e\s+(?:\u0432\u0441\u0435\u0433\u043e\s+)?\u0437\u0430\u043f\u043b\u0430\u0442|\u0447\u0438\u0441\u0442\p{L}*\s+\u0434\u0435\u043d\u0435\u0436\u043d\p{L}*\s+\u043f\u043e\u0442\u043e\u043a|\u0433\u043b\u0430\u0432\u043d\p{L}*\s+(?:\u043a\u043b\u0438\u0435\u043d\u0442|\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a)|top\s+(?:customer|supplier)|cash\s+breakdown)/iu.test(
normalized
) &&
/(?:\u043f\u043e\u043b\u0443\u0447|\u0437\u0430\u043f\u043b\u0430\u0442|\u043d\u0435\u0442\u0442\u043e|\u0434\u0435\u043d\p{L}*|\u043a\u043b\u0438\u0435\u043d\u0442|\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a|received|paid|net|cash|customer|supplier)/iu.test(
normalized
);
return (
hasEvidenceContinuationCue ||
hasAnalystContinuationCue ||
hasTaxContinuationCue ||
hasFinalSummaryCue ||
hasMoneyBreakdownCue
);
}
function hasExplicitTopicSwitchSignal(text: string): boolean {
@@ -1568,7 +1585,7 @@ export function buildAssistantMcpDiscoveryTurnInput(
);
const normalizedPredecomposeCounterparty = organizationMirrorsPredecomposeCounterparty
? null
: predecomposeEntities.counterparty;
: normalizeFollowupCounterpartyCandidate(predecomposeEntities.counterparty);
const predecomposeDateScope = collectDateScope(predecomposeContract);
const periodClarificationFollowupApplicable = Boolean(
followupSeed.domain &&
@@ -223,6 +223,29 @@ function hasOrganizationLevelSupplierQualityOverviewSignal(text) {
return hasSupplierScopeCue && hasSupplierQualityCue && hasCompanyScopeCue;
}
function hasOrganizationLevelMoneyBreakdownSignal(text) {
const normalized = String(text ?? "");
if (!normalized) {
return false;
}
const hasIncomingCue = /(?:\u043f\u043e\u043b\u0443\u0447|\u0432\u0445\u043e\u0434\u044f\u0449|\u043f\u043e\u0441\u0442\u0443\u043f|\u043a\u043b\u0438\u0435\u043d\u0442|received|incoming|customer)/iu.test(
normalized
);
const hasOutgoingCue = /(?:\u0437\u0430\u043f\u043b\u0430\u0442|\u0438\u0441\u0445\u043e\u0434\u044f\u0449|\u0441\u043f\u0438\u0441\u0430\u043d|\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a|paid|outgoing|supplier)/iu.test(
normalized
);
const hasNetCue = /(?:\u043d\u0435\u0442\u0442\u043e|\u0447\u0438\u0441\u0442\p{L}*\s+\u0434\u0435\u043d\u0435\u0436\u043d\p{L}*\s+\u043f\u043e\u0442\u043e\u043a|net\s+(?:cash|flow)|cash\s+flow)/iu.test(
normalized
);
const hasRankingCue = /(?:\u0433\u043b\u0430\u0432\u043d\p{L}*\s+(?:\u043a\u043b\u0438\u0435\u043d\u0442|\u043f\u043e\u0441\u0442\u0430\u0432\u0449\u0438\u043a)|top\s+(?:customer|supplier))/iu.test(
normalized
);
const hasBreakdownCue = /(?:\u0440\u0430\u0441\u043a\u0440\u043e\p{L}*|\u043f\u043e\u0434\u0440\u043e\u0431\u043d|\u0441\u043a\u043e\u043b\u044c\u043a\u043e\s+\u0432\u0441\u0435\u0433\u043e|\u0441\u0432\u043e\u0434\p{L}*|breakdown|detail)/iu.test(
normalized
);
return hasBreakdownCue && hasIncomingCue && hasOutgoingCue && (hasNetCue || hasRankingCue);
}
function detectBroadBusinessEvaluation(text) {
const normalized = String(text ?? "");
if (!normalized) {
@@ -264,6 +287,11 @@ function detectBroadBusinessEvaluation(text) {
family: "broad_business_evaluation"
};
}
if (hasOrganizationLevelMoneyBreakdownSignal(normalized)) {
return {
family: "broad_business_evaluation"
};
}
return null;
}