Open-World: добавить профиль документов в бизнес-обзор

This commit is contained in:
2026-05-05 13:09:42 +03:00
parent e803942472
commit 466b3b66e5
9 changed files with 479 additions and 26 deletions
@@ -498,6 +498,9 @@ function headlineFor(mode: AssistantMcpDiscoveryAnswerMode, pilot: AssistantMcpD
if (overview.activity_period) {
families.push("активность");
}
if (overview.document_activity_profile) {
families.push("профиль типов документов и разделов учета");
}
if (overview.tax_position) {
families.push("НДС-позиция");
}
@@ -730,6 +733,7 @@ function buildMustNotClaim(pilot: AssistantMcpDiscoveryPilotExecutionContract):
claims.push("Do not present business overview yearly operating-flow breakdown as profit, financial result, or a complete annual P&L.");
claims.push("Do not present business overview trading-margin proxy as clean profit, accounting financial result, or exact cost-of-sales margin.");
claims.push("Do not present business overview supplier concentration as vendor-risk audit, procurement quality, or full expense structure.");
claims.push("Do not present business overview document/account-section activity profile as process quality, accounting correctness, or completeness of all 1C activity.");
claims.push("Do not claim debt quality, VAT position, inventory health, or company health unless those contours were separately checked.");
claims.push("Do not present a debt-position snapshot as debt aging, overdue debt, or credit-quality analysis.");
claims.push("Do not present open-settlement concentration as contractual due-date aging or confirmed overdue debt.");
@@ -1141,6 +1145,25 @@ function derivedBusinessOverviewConfirmedLines(pilot: AssistantMcpDiscoveryPilot
`Окно подтвержденной активности в 1С: ${overview.activity_period.first_activity_date}${overview.activity_period.latest_activity_date}; ориентировочно ${overview.activity_period.duration_human_ru}.`
);
}
if (overview.document_activity_profile) {
const profile = overview.document_activity_profile;
const topDocument = profile.top_document_types[0];
const topSection = profile.top_account_sections[0];
const parts: string[] = [];
if (topDocument) {
const shareText = topDocument.share_pct === null ? "" : ` (${topDocument.share_pct}%)`;
parts.push(`ведущий тип документов ${topDocument.document_type}${topDocument.count} документов${shareText}`);
}
if (topSection) {
const shareText = topSection.share_pct === null ? "" : ` (${topSection.share_pct}%)`;
parts.push(`ведущий раздел учета ${topSection.account_section}${topSection.operation_count} операций${shareText}`);
}
if (parts.length > 0) {
lines.push(
`Профиль операционной активности${organization}${period}: ${parts.join("; ")}. Это activity mix по найденным строкам 1С, а не аудит качества учета или полноты процессов.`
);
}
}
if (overview.tax_position) {
const taxDirection =
overview.tax_position.net_vat_direction === "vat_to_pay"
@@ -1333,6 +1356,17 @@ function businessOverviewRiskSynthesisLine(overview: BusinessOverview): string |
`staleness risk proxy открытых расчетов: ${debtStalenessRiskBandRu(overview.debt_staleness_risk_proxy.risk_band)}, возраст ${overview.debt_staleness_risk_proxy.max_contract_age_days} дн., концентрация старейшего крупного договора ${overview.debt_staleness_risk_proxy.top_contract_share_pct}%`
);
}
if (overview.document_activity_profile) {
const topDocument = overview.document_activity_profile.top_document_types[0];
const topSection = overview.document_activity_profile.top_account_sections[0];
const parts = [
topDocument ? `ведущий тип документов ${topDocument.document_type}` : null,
topSection ? `ведущий раздел учета ${topSection.account_section}` : null
].filter((item): item is string => Boolean(item));
if (parts.length > 0) {
signals.push(`операционный activity mix: ${parts.join(", ")}`);
}
}
if (overview.inventory_position) {
signals.push(`складской остаток на дату ${overview.inventory_position.total_amount_human_ru}`);
if (overview.inventory_position.aging_signal?.max_age_days !== null && overview.inventory_position.aging_signal?.max_age_days !== undefined) {
@@ -1357,7 +1391,7 @@ function businessOverviewRiskSynthesisLine(overview: BusinessOverview): string |
function businessOverviewExecutiveVerdictLine(overview: BusinessOverview): string | null {
const hasCash = overview.incoming_customer_revenue.rows_with_amount > 0 || overview.outgoing_supplier_payout.rows_with_amount > 0;
const hasExtraSignals = Boolean(
const hasTaxDebtInventorySignals = Boolean(
overview.tax_position ||
overview.trading_margin_proxy ||
overview.debt_position ||
@@ -1367,6 +1401,8 @@ function businessOverviewExecutiveVerdictLine(overview: BusinessOverview): strin
overview.inventory_turnover_proxy ||
overview.inventory_staleness_risk_proxy
);
const hasDocumentActivitySignal = Boolean(overview.document_activity_profile);
const hasExtraSignals = hasTaxDebtInventorySignals || hasDocumentActivitySignal;
if (!hasCash && !hasExtraSignals) {
return null;
}
@@ -1376,9 +1412,11 @@ function businessOverviewExecutiveVerdictLine(overview: BusinessOverview): strin
: overview.net_direction === "net_outgoing"
? "операционно исходящий поток сильнее входящего, это зона внимания к расходам/закупкам"
: "операционный поток выглядит сбалансированным";
const evidenceTone = hasExtraSignals
const evidenceTone = hasTaxDebtInventorySignals
? "часть налоговых, долговых или складских контуров уже отдельно проверена"
: "налоги, долги и склад еще не дают проверенного управленческого контекста";
: hasDocumentActivitySignal
? "операционный activity mix по типам документов и разделам учета уже отдельно проверен"
: "налоги, долги и склад еще не дают проверенного управленческого контекста";
return `Сводный LLM-аудит по подтвержденному: ${cashTone}; ${evidenceTone}. Это полезный управленческий срез по найденным строкам 1С, но не финальный вывод о прибыльности, марже или здоровье компании.`;
}
@@ -1460,6 +1498,9 @@ export function buildAssistantMcpDiscoveryAnswerDraft(
if (pilot.derived_business_overview?.yearly_breakdown?.length) {
pushReason(reasonCodes, "answer_contains_business_overview_yearly_operating_breakdown");
}
if (pilot.derived_business_overview?.document_activity_profile) {
pushReason(reasonCodes, "answer_contains_business_overview_document_activity_profile");
}
if (pilot.derived_business_overview?.debt_position) {
pushReason(reasonCodes, "answer_contains_business_overview_debt_position");
}
@@ -138,6 +138,28 @@ export interface AssistantMcpDiscoveryBusinessOverviewYearBucket {
net_direction: AssistantMcpDiscoveryNetDirection;
}
export interface AssistantMcpDiscoveryBusinessOverviewDocumentTypeBucket {
document_type: string;
count: number;
share_pct: number | null;
}
export interface AssistantMcpDiscoveryBusinessOverviewAccountSectionBucket {
account_section: string;
operation_count: number;
share_pct: number | null;
}
export interface AssistantMcpDiscoveryDerivedBusinessOverviewDocumentActivityProfile {
period_scope: string | null;
rows_matched: number;
total_document_type_count: number;
total_account_section_operations: number;
top_document_types: AssistantMcpDiscoveryBusinessOverviewDocumentTypeBucket[];
top_account_sections: AssistantMcpDiscoveryBusinessOverviewAccountSectionBucket[];
inference_basis: "document_type_and_account_section_profile_confirmed_1c_rows";
}
export interface AssistantMcpDiscoveryDerivedBidirectionalValueFlow {
counterparty: string | null;
period_scope: string | null;
@@ -174,6 +196,7 @@ export interface AssistantMcpDiscoveryDerivedBusinessOverview {
inventory_position: AssistantMcpDiscoveryDerivedBusinessOverviewInventoryPosition | null;
inventory_turnover_proxy: AssistantMcpDiscoveryDerivedBusinessOverviewInventoryTurnoverProxy | null;
inventory_staleness_risk_proxy: AssistantMcpDiscoveryDerivedBusinessOverviewInventoryStalenessRiskProxy | null;
document_activity_profile: AssistantMcpDiscoveryDerivedBusinessOverviewDocumentActivityProfile | null;
coverage_limited_by_probe_limit: boolean;
checked_signal_count: number;
missing_signal_families: string[];
@@ -615,6 +638,18 @@ function buildValueFlowFilters(planner: AssistantMcpDiscoveryPlannerContract): A
};
}
function buildBusinessOverviewDocumentActivityFilters(planner: AssistantMcpDiscoveryPlannerContract): AddressFilterSet {
const meaning = planner.discovery_plan.turn_meaning_ref;
const organization = toNonEmptyString(meaning?.explicit_organization_scope);
const dateScope = toNonEmptyString(meaning?.explicit_date_scope);
return {
...dateScopeToFilters(dateScope),
...(organization ? { organization } : {}),
limit: planner.discovery_plan.execution_budget.max_rows_per_probe,
sort: "period_asc"
};
}
function buildBusinessOverviewTaxFilters(planner: AssistantMcpDiscoveryPlannerContract): AddressFilterSet | null {
const meaning = planner.discovery_plan.turn_meaning_ref;
const organization = toNonEmptyString(meaning?.explicit_organization_scope);
@@ -2603,6 +2638,85 @@ function deriveBusinessOverviewYearlyBreakdown(input: {
});
}
function normalizeBusinessOverviewActivityMarker(row: Record<string, unknown>): string | null {
const marker = toNonEmptyString(rowDocumentValue(row));
return marker ? marker.trim().toUpperCase() : null;
}
function normalizeBusinessOverviewAccountSection(value: string | null): string | null {
const normalized = String(value ?? "").replace(/\s+/g, "").trim();
if (!normalized) {
return null;
}
const sectionMatch = normalized.match(/^(\d{2})(?:[.\-_/]|$)/);
return sectionMatch?.[1] ?? normalized;
}
function deriveBusinessOverviewDocumentActivityProfile(
result: AddressMcpQueryExecutorResult | null,
periodScope: string | null
): AssistantMcpDiscoveryDerivedBusinessOverviewDocumentActivityProfile | null {
if (!result || result.error || result.matched_rows <= 0) {
return null;
}
const documentTypeBuckets = new Map<string, number>();
const accountSectionBuckets = new Map<string, number>();
for (const row of result.rows) {
const marker = normalizeBusinessOverviewActivityMarker(row);
const count = rowAmountValue(row);
if (!marker || count === null || count <= 0) {
continue;
}
if (marker === "DOC_TYPE_DOCS") {
const documentType = rowDebitAccountValue(row) ?? rowAccountValue(row);
if (documentType) {
documentTypeBuckets.set(documentType, (documentTypeBuckets.get(documentType) ?? 0) + count);
}
continue;
}
if (marker === "SECTION_DT_OPS" || marker === "SECTION_KT_OPS") {
const section = normalizeBusinessOverviewAccountSection(rowDebitAccountValue(row) ?? rowAccountValue(row));
if (section) {
accountSectionBuckets.set(section, (accountSectionBuckets.get(section) ?? 0) + count);
}
}
}
const totalDocumentTypeCount = Array.from(documentTypeBuckets.values()).reduce((sum, count) => sum + count, 0);
const totalAccountSectionOperations = Array.from(accountSectionBuckets.values()).reduce((sum, count) => sum + count, 0);
const topDocumentTypes = Array.from(documentTypeBuckets.entries())
.map(([documentType, count]) => ({
document_type: documentType,
count,
share_pct: percentageOfTotal(count, totalDocumentTypeCount)
}))
.sort((left, right) => right.count - left.count || left.document_type.localeCompare(right.document_type, "ru"))
.slice(0, 5);
const topAccountSections = Array.from(accountSectionBuckets.entries())
.map(([accountSection, operationCount]) => ({
account_section: accountSection,
operation_count: operationCount,
share_pct: percentageOfTotal(operationCount, totalAccountSectionOperations)
}))
.sort((left, right) => right.operation_count - left.operation_count || left.account_section.localeCompare(right.account_section, "ru"))
.slice(0, 5);
if (topDocumentTypes.length <= 0 && topAccountSections.length <= 0) {
return null;
}
return {
period_scope: periodScope,
rows_matched: result.matched_rows,
total_document_type_count: totalDocumentTypeCount,
total_account_section_operations: totalAccountSectionOperations,
top_document_types: topDocumentTypes,
top_account_sections: topAccountSections,
inference_basis: "document_type_and_account_section_profile_confirmed_1c_rows"
};
}
function deriveValueFlow(
result: AssistantMcpDiscoveryCoverageAwareQueryResult | null,
counterparty: string | null,
@@ -3521,6 +3635,7 @@ function deriveBusinessOverview(input: {
receivablesResult: AddressMcpQueryExecutorResult | null;
payablesResult: AddressMcpQueryExecutorResult | null;
openContractsResult: AddressMcpQueryExecutorResult | null;
documentActivityProfileResult: AddressMcpQueryExecutorResult | null;
debtAsOfDate: string | null;
inventoryOnHandResult: AddressMcpQueryExecutorResult | null;
inventoryAgingResult: AddressMcpQueryExecutorResult | null;
@@ -3558,6 +3673,10 @@ function deriveBusinessOverview(input: {
openContractsResult: input.openContractsResult,
debtAsOfDate: input.debtAsOfDate
});
const documentActivityProfile = deriveBusinessOverviewDocumentActivityProfile(
input.documentActivityProfileResult,
input.periodScope
);
const debtStalenessRiskProxy = deriveBusinessOverviewDebtStalenessRiskProxy(debtOpenSettlementQuality);
const inventoryPosition = deriveBusinessOverviewInventoryPosition({
inventoryOnHandResult: input.inventoryOnHandResult,
@@ -3581,6 +3700,7 @@ function deriveBusinessOverview(input: {
Boolean(debtPosition),
Boolean(debtOpenSettlementQuality),
Boolean(debtStalenessRiskProxy),
Boolean(documentActivityProfile),
Boolean(inventoryPosition),
Boolean(inventoryTurnoverProxy),
Boolean(inventoryStalenessRiskProxy)
@@ -3610,6 +3730,7 @@ function deriveBusinessOverview(input: {
inventory_position: inventoryPosition,
inventory_turnover_proxy: inventoryTurnoverProxy,
inventory_staleness_risk_proxy: inventoryStalenessRiskProxy,
document_activity_profile: documentActivityProfile,
coverage_limited_by_probe_limit:
incoming.coverage_limited_by_probe_limit || outgoing.coverage_limited_by_probe_limit,
checked_signal_count: checkedSignalCount,
@@ -3628,7 +3749,9 @@ function deriveBusinessOverview(input: {
inventoryPosition?.aging_signal ? null : "inventory_aging_quality"
].filter((item): item is string => Boolean(item)),
inference_basis:
inventoryPosition
documentActivityProfile
? "business_overview_from_confirmed_1c_multi_family_rows"
: inventoryPosition
? "business_overview_from_confirmed_1c_multi_family_rows"
: debtOpenSettlementQuality
? "business_overview_from_confirmed_1c_multi_family_rows"
@@ -3651,6 +3774,7 @@ function summarizeBusinessOverviewRows(input: {
receivablesResult: AddressMcpQueryExecutorResult | null;
payablesResult: AddressMcpQueryExecutorResult | null;
openContractsResult: AddressMcpQueryExecutorResult | null;
documentActivityProfileResult: AddressMcpQueryExecutorResult | null;
inventoryOnHandResult: AddressMcpQueryExecutorResult | null;
inventoryAgingResult: AddressMcpQueryExecutorResult | null;
}): string | null {
@@ -3679,6 +3803,9 @@ function summarizeBusinessOverviewRows(input: {
if (input.openContractsResult && !input.openContractsResult.error) {
parts.push(`${input.openContractsResult.fetched_rows} open-contract rows fetched, ${input.openContractsResult.matched_rows} matched`);
}
if (input.documentActivityProfileResult && !input.documentActivityProfileResult.error) {
parts.push(`${input.documentActivityProfileResult.fetched_rows} document/account-section profile rows fetched, ${input.documentActivityProfileResult.matched_rows} matched`);
}
if (input.inventoryOnHandResult && !input.inventoryOnHandResult.error) {
parts.push(`${input.inventoryOnHandResult.fetched_rows} inventory on-hand rows fetched, ${input.inventoryOnHandResult.matched_rows} matched`);
}
@@ -3727,6 +3854,25 @@ function buildBusinessOverviewConfirmedFacts(derived: AssistantMcpDiscoveryDeriv
`Подтвержденное окно активности в 1С: ${derived.activity_period.first_activity_date}${derived.activity_period.latest_activity_date}.`
);
}
if (derived.document_activity_profile) {
const profile = derived.document_activity_profile;
const topDocument = profile.top_document_types[0];
const topSection = profile.top_account_sections[0];
const parts: string[] = [];
if (topDocument) {
const shareText = topDocument.share_pct === null ? "" : ` (${topDocument.share_pct}%)`;
parts.push(`ведущий тип документов ${topDocument.document_type}${topDocument.count} документов${shareText}`);
}
if (topSection) {
const shareText = topSection.share_pct === null ? "" : ` (${topSection.share_pct}%)`;
parts.push(`ведущий раздел учета ${topSection.account_section}${topSection.operation_count} операций${shareText}`);
}
if (parts.length > 0) {
facts.push(
`Профиль операционной активности${organization}${period} подтвержден по типам документов и разделам учета 1С: ${parts.join("; ")}. Это activity mix, а не аудит качества учета или полноты бизнес-процессов.`
);
}
}
if (derived.tax_position) {
const taxDirection =
derived.tax_position.net_vat_direction === "vat_to_pay"
@@ -4641,10 +4787,12 @@ export async function executeAssistantMcpDiscoveryPilot(
let receivablesResult: AddressMcpQueryExecutorResult | null = null;
let payablesResult: AddressMcpQueryExecutorResult | null = null;
let openContractsResult: AddressMcpQueryExecutorResult | null = null;
let documentActivityProfileResult: AddressMcpQueryExecutorResult | null = null;
let inventoryOnHandResult: AddressMcpQueryExecutorResult | null = null;
let inventoryAgingResult: AddressMcpQueryExecutorResult | null = null;
const valueFilters = buildValueFlowFilters(planner);
const lifecycleFilters = buildLifecycleFilters(planner);
const documentActivityFilters = buildBusinessOverviewDocumentActivityFilters(planner);
const taxFilters = buildBusinessOverviewTaxFilters(planner);
const tradingMarginFilters = buildBusinessOverviewTradingMarginFilters(planner);
const debtFilters = buildBusinessOverviewDebtFilters(planner);
@@ -4654,6 +4802,7 @@ export async function executeAssistantMcpDiscoveryPilot(
const incomingSelection = selectAddressRecipe("customer_revenue_and_payments", valueFilters);
const outgoingSelection = selectAddressRecipe("supplier_payouts_profile", valueFilters);
const lifecycleSelection = selectAddressRecipe("counterparty_activity_lifecycle", lifecycleFilters);
const documentActivitySelection = selectAddressRecipe("document_type_and_account_section_profile", documentActivityFilters);
const taxSelection = taxFilters
? selectAddressRecipe("vat_liability_confirmed_for_tax_period", taxFilters)
: null;
@@ -4707,6 +4856,12 @@ export async function executeAssistantMcpDiscoveryPilot(
}
pushReason(reasonCodes, "pilot_business_overview_recipes_selected");
if (documentActivitySelection.selected_recipe) {
pushReason(reasonCodes, "pilot_business_overview_document_activity_profile_recipe_selected");
} else {
pushReason(reasonCodes, "pilot_business_overview_document_activity_profile_recipe_not_available");
pushUnique(queryLimitations, "Business overview document/account-section profile requires an executable document-section profile recipe");
}
if (taxSelection?.selected_recipe) {
pushReason(reasonCodes, "pilot_business_overview_tax_recipe_selected");
} else if (!taxFilters) {
@@ -4919,6 +5074,18 @@ export async function executeAssistantMcpDiscoveryPilot(
});
probeResults.push(queryResultToProbeResult(step.primitive_id, tradingMarginResult));
}
if (documentActivitySelection.selected_recipe) {
const documentActivityPlan = buildAddressRecipePlan(
documentActivitySelection.selected_recipe,
documentActivityFilters
);
documentActivityProfileResult = await runtimeDeps.executeAddressMcpQuery({
query: documentActivityPlan.query,
limit: documentActivityPlan.limit,
account_scope: documentActivityPlan.account_scope
});
probeResults.push(queryResultToProbeResult(step.primitive_id, documentActivityProfileResult));
}
if (lifecycleResult.error) {
pushUnique(queryLimitations, lifecycleResult.error);
pushReason(reasonCodes, "pilot_business_overview_query_documents_mcp_error");
@@ -4931,6 +5098,12 @@ export async function executeAssistantMcpDiscoveryPilot(
} else if (tradingMarginResult) {
pushReason(reasonCodes, "pilot_business_overview_trading_margin_query_mcp_executed");
}
if (documentActivityProfileResult?.error) {
pushUnique(queryLimitations, documentActivityProfileResult.error);
pushReason(reasonCodes, "pilot_business_overview_document_activity_profile_query_mcp_error");
} else if (documentActivityProfileResult) {
pushReason(reasonCodes, "pilot_business_overview_document_activity_profile_query_mcp_executed");
}
continue;
}
@@ -4947,6 +5120,7 @@ export async function executeAssistantMcpDiscoveryPilot(
receivablesResult,
payablesResult,
openContractsResult,
documentActivityProfileResult,
debtAsOfDate,
inventoryOnHandResult,
inventoryAgingResult,
@@ -4968,6 +5142,9 @@ export async function executeAssistantMcpDiscoveryPilot(
if (derivedBusinessOverview.activity_period) {
pushReason(reasonCodes, "pilot_derived_business_overview_activity_window_from_confirmed_rows");
}
if (derivedBusinessOverview.document_activity_profile) {
pushReason(reasonCodes, "pilot_derived_business_overview_document_activity_profile_from_confirmed_rows");
}
if (derivedBusinessOverview.tax_position) {
pushReason(reasonCodes, "pilot_derived_business_overview_tax_position_from_confirmed_rows");
}
@@ -5005,6 +5182,7 @@ export async function executeAssistantMcpDiscoveryPilot(
receivablesResult,
payablesResult,
openContractsResult,
documentActivityProfileResult,
inventoryOnHandResult,
inventoryAgingResult
});