ARCH: добавить двусторонний MCP discovery для нетто-потока
This commit is contained in:
@@ -26,6 +26,7 @@ exports.buildInventoryRootFrameFromAddressDebug = buildInventoryRootFrameFromAdd
|
||||
exports.isGroundedAddressDebug = isGroundedAddressDebug;
|
||||
exports.resolveAssistantContinuitySnapshot = resolveAssistantContinuitySnapshot;
|
||||
exports.resolveAssistantOrganizationAuthority = resolveAssistantOrganizationAuthority;
|
||||
exports.resolveOrganizationClarificationContinuation = resolveOrganizationClarificationContinuation;
|
||||
const assistantOrganizationMatcher_1 = require("./assistantOrganizationMatcher");
|
||||
function fallbackToNonEmptyString(value) {
|
||||
if (value === null || value === undefined) {
|
||||
@@ -685,3 +686,36 @@ function resolveAssistantOrganizationAuthority(input) {
|
||||
organizationClarificationSelectionFromScope
|
||||
};
|
||||
}
|
||||
function resolveOrganizationClarificationContinuation(input) {
|
||||
const toNonEmptyString = input.toNonEmptyString ?? fallbackToNonEmptyString;
|
||||
const normalizeOrganizationScopeValue = input.normalizeOrganizationScopeValue ?? normalizeOrganizationScopeDefault;
|
||||
const candidates = Array.isArray(input.organizationClarificationCandidates)
|
||||
? input.organizationClarificationCandidates
|
||||
: [];
|
||||
const resolveOrganizationSelectionFromMessage = input.resolveOrganizationSelectionFromMessage;
|
||||
const messages = Array.isArray(input.rawMessages) ? input.rawMessages : [];
|
||||
let explicitSelection = null;
|
||||
if (typeof resolveOrganizationSelectionFromMessage === "function") {
|
||||
for (const message of messages) {
|
||||
const normalizedMessage = toNonEmptyString(message);
|
||||
if (!normalizedMessage) {
|
||||
continue;
|
||||
}
|
||||
explicitSelection = resolveOrganizationSelectionFromMessage(normalizedMessage, candidates);
|
||||
if (explicitSelection) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const normalizedScopeSelection = normalizeOrganizationScopeValue(input.organizationClarificationSelectionFromScope);
|
||||
const selection = explicitSelection ??
|
||||
(normalizedScopeSelection &&
|
||||
candidates.some((candidate) => normalizeOrganizationScopeValue(candidate) === normalizedScopeSelection)
|
||||
? normalizedScopeSelection
|
||||
: null);
|
||||
return {
|
||||
explicitSelection,
|
||||
selection,
|
||||
hasContinuation: Boolean(input.lastOrganizationClarificationDebug && selection)
|
||||
};
|
||||
}
|
||||
|
||||
+40
-2
@@ -61,9 +61,13 @@ function modeFor(pilot) {
|
||||
}
|
||||
function isValueFlowPilot(pilot) {
|
||||
return (pilot.pilot_scope === "counterparty_value_flow_query_movements_v1" ||
|
||||
pilot.pilot_scope === "counterparty_supplier_payout_query_movements_v1");
|
||||
pilot.pilot_scope === "counterparty_supplier_payout_query_movements_v1" ||
|
||||
pilot.pilot_scope === "counterparty_bidirectional_value_flow_query_movements_v1");
|
||||
}
|
||||
function headlineFor(mode, pilot) {
|
||||
if (pilot.derived_bidirectional_value_flow && mode === "confirmed_with_bounded_inference") {
|
||||
return "По данным 1С найдены строки входящих и исходящих денежных движений; нетто можно называть только как расчет по найденным строкам и проверенному периоду.";
|
||||
}
|
||||
if (pilot.derived_value_flow && mode === "confirmed_with_bounded_inference") {
|
||||
if (pilot.derived_value_flow.value_flow_direction === "outgoing_supplier_payout") {
|
||||
return "По данным 1С найдены строки исходящих платежей/списаний; сумму можно называть только в рамках проверенного периода и найденных строк.";
|
||||
@@ -147,6 +151,40 @@ function derivedValueFlowConfirmedLine(pilot) {
|
||||
: "";
|
||||
return `По найденным строкам ${movementLabel} в 1С${counterparty}${period} ${totalLabel} ${flow.total_amount_human_ru} Учтено строк с суммой: ${flow.rows_with_amount} из ${flow.rows_matched}.${dates}${limitCaveat} ${caveat}`;
|
||||
}
|
||||
function sideDateRange(first, latest) {
|
||||
if (first && latest) {
|
||||
return ` первая дата ${first}, последняя ${latest}`;
|
||||
}
|
||||
return " даты движения не выделены";
|
||||
}
|
||||
function derivedBidirectionalValueFlowConfirmedLine(pilot) {
|
||||
const flow = pilot.derived_bidirectional_value_flow;
|
||||
if (!flow) {
|
||||
return null;
|
||||
}
|
||||
const counterparty = flow.counterparty ? ` по контрагенту ${flow.counterparty}` : "";
|
||||
const period = flow.period_scope ? ` за период ${flow.period_scope}` : " в проверенном окне";
|
||||
const incoming = flow.incoming_customer_revenue;
|
||||
const outgoing = flow.outgoing_supplier_payout;
|
||||
const netLabel = flow.net_direction === "net_incoming"
|
||||
? "нетто в нашу сторону"
|
||||
: flow.net_direction === "net_outgoing"
|
||||
? "нетто исходящий"
|
||||
: "нетто нулевое";
|
||||
const limitCaveat = flow.coverage_limited_by_probe_limit
|
||||
? " Лимит строк проверки достигнут хотя бы по одной стороне; полный запрошенный период может быть покрыт не полностью."
|
||||
: "";
|
||||
return [
|
||||
`По найденным строкам 1С${counterparty}${period}: получили ${incoming.total_amount_human_ru} по входящим движениям, заплатили ${outgoing.total_amount_human_ru} по исходящим платежам/списаниям.`,
|
||||
`Расчетное ${netLabel}: ${flow.net_amount_human_ru}`,
|
||||
`Входящие строки с суммой: ${incoming.rows_with_amount} из ${incoming.rows_matched};${sideDateRange(incoming.first_movement_date, incoming.latest_movement_date)}.`,
|
||||
`Исходящие строки с суммой: ${outgoing.rows_with_amount} из ${outgoing.rows_matched};${sideDateRange(outgoing.first_movement_date, outgoing.latest_movement_date)}.`,
|
||||
`${limitCaveat} Это расчет по найденным строкам 1С, а не подтверждение полного сальдо вне проверенного окна.`
|
||||
]
|
||||
.join(" ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
function buildAssistantMcpDiscoveryAnswerDraft(pilot) {
|
||||
const mode = modeFor(pilot);
|
||||
const reasonCodes = [...pilot.reason_codes, ...pilot.evidence.reason_codes];
|
||||
@@ -161,7 +199,7 @@ function buildAssistantMcpDiscoveryAnswerDraft(pilot) {
|
||||
const inferenceLines = derivedInferenceLine
|
||||
? [derivedInferenceLine]
|
||||
: pilot.evidence.inferred_facts;
|
||||
const derivedValueLine = derivedValueFlowConfirmedLine(pilot);
|
||||
const derivedValueLine = derivedBidirectionalValueFlowConfirmedLine(pilot) ?? derivedValueFlowConfirmedLine(pilot);
|
||||
const confirmedLines = derivedValueLine
|
||||
? [...pilot.evidence.confirmed_facts, derivedValueLine]
|
||||
: pilot.evidence.confirmed_facts;
|
||||
|
||||
+219
-1
@@ -120,6 +120,16 @@ function valueFlowPilotProfile(planner) {
|
||||
const action = String(meaning?.asked_action_family ?? "").toLowerCase();
|
||||
const unsupported = String(meaning?.unsupported_but_understood_family ?? "").toLowerCase();
|
||||
const combined = `${action} ${unsupported}`;
|
||||
if (combined.includes("net_value_flow") ||
|
||||
combined.includes("bidirectional") ||
|
||||
combined.includes("netting") ||
|
||||
combined.includes("net")) {
|
||||
return {
|
||||
scope: "counterparty_bidirectional_value_flow_query_movements_v1",
|
||||
recipe_intent: null,
|
||||
direction: "bidirectional_net_value_flow"
|
||||
};
|
||||
}
|
||||
if (combined.includes("payout") ||
|
||||
combined.includes("outflow") ||
|
||||
combined.includes("supplier") ||
|
||||
@@ -314,6 +324,74 @@ function deriveValueFlow(result, counterparty, periodScope, direction, probeLimi
|
||||
inference_basis: "sum_of_confirmed_1c_value_flow_rows"
|
||||
};
|
||||
}
|
||||
function deriveValueFlowSideSummary(result, probeLimit) {
|
||||
if (!result || result.error || result.matched_rows <= 0) {
|
||||
return {
|
||||
rows_matched: 0,
|
||||
rows_with_amount: 0,
|
||||
total_amount: 0,
|
||||
total_amount_human_ru: formatAmountHumanRu(0),
|
||||
first_movement_date: null,
|
||||
latest_movement_date: null,
|
||||
coverage_limited_by_probe_limit: false
|
||||
};
|
||||
}
|
||||
let totalAmount = 0;
|
||||
let rowsWithAmount = 0;
|
||||
for (const row of result.rows) {
|
||||
const amount = rowAmountValue(row);
|
||||
if (amount !== null) {
|
||||
totalAmount += amount;
|
||||
rowsWithAmount += 1;
|
||||
}
|
||||
}
|
||||
const dates = result.rows
|
||||
.map((row) => rowDateValue(row))
|
||||
.filter((value) => Boolean(value))
|
||||
.sort();
|
||||
return {
|
||||
rows_matched: result.matched_rows,
|
||||
rows_with_amount: rowsWithAmount,
|
||||
total_amount: totalAmount,
|
||||
total_amount_human_ru: formatAmountHumanRu(totalAmount),
|
||||
first_movement_date: dates[0] ?? null,
|
||||
latest_movement_date: dates[dates.length - 1] ?? null,
|
||||
coverage_limited_by_probe_limit: result.matched_rows >= probeLimit
|
||||
};
|
||||
}
|
||||
function deriveBidirectionalValueFlow(input) {
|
||||
const incoming = deriveValueFlowSideSummary(input.incomingResult, input.probeLimit);
|
||||
const outgoing = deriveValueFlowSideSummary(input.outgoingResult, input.probeLimit);
|
||||
if (incoming.rows_with_amount <= 0 && outgoing.rows_with_amount <= 0) {
|
||||
return null;
|
||||
}
|
||||
const netAmount = incoming.total_amount - outgoing.total_amount;
|
||||
return {
|
||||
counterparty: input.counterparty,
|
||||
period_scope: input.periodScope,
|
||||
incoming_customer_revenue: incoming,
|
||||
outgoing_supplier_payout: outgoing,
|
||||
net_amount: netAmount,
|
||||
net_amount_human_ru: formatAmountHumanRu(Math.abs(netAmount)),
|
||||
net_direction: netAmount > 0 ? "net_incoming" : netAmount < 0 ? "net_outgoing" : "balanced",
|
||||
coverage_limited_by_probe_limit: incoming.coverage_limited_by_probe_limit || outgoing.coverage_limited_by_probe_limit,
|
||||
inference_basis: "incoming_minus_outgoing_confirmed_1c_value_flow_rows"
|
||||
};
|
||||
}
|
||||
function summarizeBidirectionalValueFlowRows(input) {
|
||||
const incoming = input.incomingResult;
|
||||
const outgoing = input.outgoingResult;
|
||||
if (!incoming && !outgoing) {
|
||||
return null;
|
||||
}
|
||||
const incomingSummary = incoming?.error
|
||||
? "incoming value-flow query failed"
|
||||
: `${incoming?.fetched_rows ?? 0} incoming value-flow rows fetched, ${incoming?.matched_rows ?? 0} matched`;
|
||||
const outgoingSummary = outgoing?.error
|
||||
? "outgoing supplier-payout query failed"
|
||||
: `${outgoing?.fetched_rows ?? 0} outgoing supplier-payout rows fetched, ${outgoing?.matched_rows ?? 0} matched`;
|
||||
return `${incomingSummary}; ${outgoingSummary}`;
|
||||
}
|
||||
function buildLifecycleConfirmedFacts(result, counterparty) {
|
||||
if (result.error || result.matched_rows <= 0) {
|
||||
return [];
|
||||
@@ -341,6 +419,21 @@ function buildValueFlowConfirmedFacts(result, counterparty, direction) {
|
||||
: "1C value-flow rows were found for the requested counterparty scope"
|
||||
];
|
||||
}
|
||||
function buildBidirectionalValueFlowConfirmedFacts(derived) {
|
||||
if (!derived) {
|
||||
return [];
|
||||
}
|
||||
const hasIncoming = derived.incoming_customer_revenue.rows_matched > 0;
|
||||
const hasOutgoing = derived.outgoing_supplier_payout.rows_matched > 0;
|
||||
if (derived.counterparty) {
|
||||
return [
|
||||
`1C bidirectional value-flow rows were checked for counterparty ${derived.counterparty}: incoming=${hasIncoming ? "found" : "not_found"}, outgoing=${hasOutgoing ? "found" : "not_found"}`
|
||||
];
|
||||
}
|
||||
return [
|
||||
`1C bidirectional value-flow rows were checked for the requested counterparty scope: incoming=${hasIncoming ? "found" : "not_found"}, outgoing=${hasOutgoing ? "found" : "not_found"}`
|
||||
];
|
||||
}
|
||||
function buildLifecycleInferredFacts(result) {
|
||||
if (result.error || result.fetched_rows <= 0) {
|
||||
return [];
|
||||
@@ -356,6 +449,12 @@ function buildValueFlowInferredFacts(derived) {
|
||||
}
|
||||
return ["Counterparty value-flow total was calculated from confirmed 1C movement rows"];
|
||||
}
|
||||
function buildBidirectionalValueFlowInferredFacts(derived) {
|
||||
if (!derived) {
|
||||
return [];
|
||||
}
|
||||
return ["Counterparty net value-flow was calculated as incoming confirmed 1C rows minus outgoing confirmed 1C rows"];
|
||||
}
|
||||
function buildLifecycleUnknownFacts() {
|
||||
return ["Legal registration date is not proven by this MCP discovery pilot"];
|
||||
}
|
||||
@@ -375,6 +474,16 @@ function buildValueFlowUnknownFacts(periodScope, direction, derived) {
|
||||
: "Full all-time turnover is not proven without an explicit checked period");
|
||||
return unknownFacts;
|
||||
}
|
||||
function buildBidirectionalValueFlowUnknownFacts(periodScope, derived) {
|
||||
const unknownFacts = [];
|
||||
if (derived?.coverage_limited_by_probe_limit) {
|
||||
unknownFacts.push("Complete requested-period coverage for bidirectional value-flow is not proven because at least one MCP discovery probe row limit was reached");
|
||||
}
|
||||
unknownFacts.push(periodScope
|
||||
? "Full bidirectional value-flow outside the checked period is not proven by this MCP discovery pilot"
|
||||
: "Full all-time bidirectional value-flow is not proven without an explicit checked period");
|
||||
return unknownFacts;
|
||||
}
|
||||
function buildEmptyEvidence(planner, dryRun, probeResults, reason) {
|
||||
return (0, assistantMcpDiscoveryPolicy_1.resolveAssistantMcpDiscoveryEvidence)({
|
||||
plan: planner.discovery_plan,
|
||||
@@ -408,6 +517,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: null,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: ["MCP discovery pilot was blocked before execution"],
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
@@ -429,6 +539,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: null,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: ["MCP discovery pilot needs more scope before execution"],
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
@@ -456,6 +567,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: null,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: ["MCP discovery pilot scope is not implemented yet"],
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
@@ -466,7 +578,109 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
let queryResult = null;
|
||||
const filters = buildValueFlowFilters(planner);
|
||||
const valueFlowProfile = valueFlowPilotProfile(planner);
|
||||
const selection = (0, addressRecipeCatalog_1.selectAddressRecipe)(valueFlowProfile.recipe_intent, filters);
|
||||
if (valueFlowProfile.direction === "bidirectional_net_value_flow") {
|
||||
let incomingResult = null;
|
||||
let outgoingResult = null;
|
||||
const incomingSelection = (0, addressRecipeCatalog_1.selectAddressRecipe)("customer_revenue_and_payments", filters);
|
||||
const outgoingSelection = (0, addressRecipeCatalog_1.selectAddressRecipe)("supplier_payouts_profile", filters);
|
||||
if (!incomingSelection.selected_recipe || !outgoingSelection.selected_recipe) {
|
||||
pushReason(reasonCodes, "pilot_bidirectional_value_flow_recipe_not_available");
|
||||
const evidence = buildEmptyEvidence(planner, dryRun, probeResults, "Bidirectional value-flow recipes are not available");
|
||||
return {
|
||||
schema_version: exports.ASSISTANT_MCP_DISCOVERY_PILOT_EXECUTOR_SCHEMA_VERSION,
|
||||
policy_owner: "assistantMcpDiscoveryPilotExecutor",
|
||||
pilot_status: "unsupported",
|
||||
pilot_scope: valueFlowProfile.scope,
|
||||
dry_run: dryRun,
|
||||
mcp_execution_performed: false,
|
||||
executed_primitives: executedPrimitives,
|
||||
skipped_primitives: skippedPrimitives,
|
||||
probe_results: probeResults,
|
||||
evidence,
|
||||
source_rows_summary: null,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: ["Bidirectional value-flow recipes are not available"],
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
}
|
||||
pushReason(reasonCodes, "pilot_bidirectional_value_flow_recipes_selected");
|
||||
const incomingRecipePlan = (0, addressRecipeCatalog_1.buildAddressRecipePlan)(incomingSelection.selected_recipe, filters);
|
||||
const outgoingRecipePlan = (0, addressRecipeCatalog_1.buildAddressRecipePlan)(outgoingSelection.selected_recipe, filters);
|
||||
for (const step of dryRun.execution_steps) {
|
||||
if (step.primitive_id !== "query_movements") {
|
||||
skippedPrimitives.push(step.primitive_id);
|
||||
probeResults.push(skippedProbeResult(step, "pilot_bidirectional_value_flow_uses_two_query_movements_and_derives_net"));
|
||||
continue;
|
||||
}
|
||||
incomingResult = await deps.executeAddressMcpQuery({
|
||||
query: incomingRecipePlan.query,
|
||||
limit: incomingRecipePlan.limit,
|
||||
account_scope: incomingRecipePlan.account_scope
|
||||
});
|
||||
outgoingResult = await deps.executeAddressMcpQuery({
|
||||
query: outgoingRecipePlan.query,
|
||||
limit: outgoingRecipePlan.limit,
|
||||
account_scope: outgoingRecipePlan.account_scope
|
||||
});
|
||||
pushUnique(executedPrimitives, step.primitive_id);
|
||||
probeResults.push(queryResultToProbeResult(step.primitive_id, incomingResult));
|
||||
probeResults.push(queryResultToProbeResult(step.primitive_id, outgoingResult));
|
||||
if (incomingResult.error) {
|
||||
pushUnique(queryLimitations, incomingResult.error);
|
||||
pushReason(reasonCodes, "pilot_bidirectional_incoming_query_movements_mcp_error");
|
||||
}
|
||||
if (outgoingResult.error) {
|
||||
pushUnique(queryLimitations, outgoingResult.error);
|
||||
pushReason(reasonCodes, "pilot_bidirectional_outgoing_query_movements_mcp_error");
|
||||
}
|
||||
if (!incomingResult.error || !outgoingResult.error) {
|
||||
pushReason(reasonCodes, "pilot_bidirectional_query_movements_mcp_executed");
|
||||
}
|
||||
}
|
||||
const sourceRowsSummary = summarizeBidirectionalValueFlowRows({ incomingResult, outgoingResult });
|
||||
const derivedBidirectionalValueFlow = deriveBidirectionalValueFlow({
|
||||
incomingResult,
|
||||
outgoingResult,
|
||||
counterparty,
|
||||
periodScope: dateScope,
|
||||
probeLimit: planner.discovery_plan.execution_budget.max_rows_per_probe
|
||||
});
|
||||
if (derivedBidirectionalValueFlow) {
|
||||
pushReason(reasonCodes, "pilot_derived_bidirectional_value_flow_from_confirmed_rows");
|
||||
}
|
||||
const evidence = (0, assistantMcpDiscoveryPolicy_1.resolveAssistantMcpDiscoveryEvidence)({
|
||||
plan: planner.discovery_plan,
|
||||
probeResults,
|
||||
confirmedFacts: buildBidirectionalValueFlowConfirmedFacts(derivedBidirectionalValueFlow),
|
||||
inferredFacts: buildBidirectionalValueFlowInferredFacts(derivedBidirectionalValueFlow),
|
||||
unknownFacts: buildBidirectionalValueFlowUnknownFacts(dateScope, derivedBidirectionalValueFlow),
|
||||
sourceRowsSummary,
|
||||
queryLimitations,
|
||||
recommendedNextProbe: "explain_evidence_basis"
|
||||
});
|
||||
return {
|
||||
schema_version: exports.ASSISTANT_MCP_DISCOVERY_PILOT_EXECUTOR_SCHEMA_VERSION,
|
||||
policy_owner: "assistantMcpDiscoveryPilotExecutor",
|
||||
pilot_status: "executed",
|
||||
pilot_scope: valueFlowProfile.scope,
|
||||
dry_run: dryRun,
|
||||
mcp_execution_performed: executedPrimitives.length > 0,
|
||||
executed_primitives: executedPrimitives,
|
||||
skipped_primitives: skippedPrimitives,
|
||||
probe_results: probeResults,
|
||||
evidence,
|
||||
source_rows_summary: sourceRowsSummary,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: derivedBidirectionalValueFlow,
|
||||
query_limitations: queryLimitations,
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
}
|
||||
const recipeIntent = valueFlowProfile.recipe_intent;
|
||||
const selection = recipeIntent ? (0, addressRecipeCatalog_1.selectAddressRecipe)(recipeIntent, filters) : { selected_recipe: null };
|
||||
if (!selection.selected_recipe) {
|
||||
pushReason(reasonCodes, "pilot_value_flow_recipe_not_available");
|
||||
const evidence = buildEmptyEvidence(planner, dryRun, probeResults, "Value-flow recipe is not available");
|
||||
@@ -484,6 +698,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: null,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: ["Value-flow recipe is not available"],
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
@@ -542,6 +757,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: sourceRowsSummary,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: derivedValueFlow,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: queryLimitations,
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
@@ -566,6 +782,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: null,
|
||||
derived_activity_period: null,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: ["Lifecycle recipe is not available"],
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
@@ -621,6 +838,7 @@ async function executeAssistantMcpDiscoveryPilot(planner, deps = DEFAULT_DEPS) {
|
||||
source_rows_summary: sourceRowsSummary,
|
||||
derived_activity_period: derivedActivityPeriod,
|
||||
derived_value_flow: null,
|
||||
derived_bidirectional_value_flow: null,
|
||||
query_limitations: queryLimitations,
|
||||
reason_codes: reasonCodes
|
||||
};
|
||||
|
||||
@@ -60,7 +60,7 @@ function recipeFor(input) {
|
||||
const combined = `${domain} ${action} ${unsupported}`.trim();
|
||||
const axes = [];
|
||||
addScopeAxes(axes, meaning);
|
||||
if (includesAny(combined, ["turnover", "revenue", "payment", "payout", "value"])) {
|
||||
if (includesAny(combined, ["turnover", "revenue", "payment", "payout", "value", "net", "netting", "balance", "cashflow"])) {
|
||||
pushUnique(axes, "aggregate_axis");
|
||||
pushUnique(axes, "amount");
|
||||
pushUnique(axes, "coverage_target");
|
||||
|
||||
+24
@@ -82,6 +82,18 @@ function localizeLine(value) {
|
||||
if (/^1C supplier-payout rows were found for the requested counterparty scope$/i.test(value)) {
|
||||
return "В 1С найдены строки исходящих платежей/списаний по запрошенному контрагентскому контуру.";
|
||||
}
|
||||
const bidirectionalMatch = value.match(/^1C bidirectional value-flow rows were checked for counterparty\s+(.+): incoming=(found|not_found), outgoing=(found|not_found)$/i);
|
||||
if (bidirectionalMatch) {
|
||||
const incoming = bidirectionalMatch[2] === "found" ? "входящие строки найдены" : "входящие строки не найдены";
|
||||
const outgoing = bidirectionalMatch[3] === "found" ? "исходящие строки найдены" : "исходящие строки не найдены";
|
||||
return `В 1С проверены входящие и исходящие денежные строки по контрагенту ${bidirectionalMatch[1]}: ${incoming}, ${outgoing}.`;
|
||||
}
|
||||
const bidirectionalScopeMatch = value.match(/^1C bidirectional value-flow rows were checked for the requested counterparty scope: incoming=(found|not_found), outgoing=(found|not_found)$/i);
|
||||
if (bidirectionalScopeMatch) {
|
||||
const incoming = bidirectionalScopeMatch[1] === "found" ? "входящие строки найдены" : "входящие строки не найдены";
|
||||
const outgoing = bidirectionalScopeMatch[2] === "found" ? "исходящие строки найдены" : "исходящие строки не найдены";
|
||||
return `В 1С проверены входящие и исходящие денежные строки по запрошенному контрагентскому контуру: ${incoming}, ${outgoing}.`;
|
||||
}
|
||||
if (/^Business activity duration may be inferred from first and latest confirmed 1C activity rows$/i.test(value)) {
|
||||
return "Длительность деловой активности можно оценивать только как вывод по первой и последней подтвержденной строке активности в 1С.";
|
||||
}
|
||||
@@ -91,12 +103,18 @@ function localizeLine(value) {
|
||||
if (/^Counterparty supplier-payout total was calculated from confirmed 1C outgoing payment rows$/i.test(value)) {
|
||||
return "Сумма исходящих платежей рассчитана только по подтвержденным строкам списаний в 1С.";
|
||||
}
|
||||
if (/^Counterparty net value-flow was calculated as incoming confirmed 1C rows minus outgoing confirmed 1C rows$/i.test(value)) {
|
||||
return "Нетто денежного потока рассчитано только как входящие подтвержденные строки 1С минус исходящие подтвержденные строки 1С.";
|
||||
}
|
||||
if (/^Legal registration date is not proven by this MCP discovery pilot$/i.test(value)) {
|
||||
return "Юридическая дата регистрации этим поиском не подтверждена.";
|
||||
}
|
||||
if (/^Complete requested-period coverage is not proven because the MCP discovery probe row limit was reached$/i.test(value)) {
|
||||
return "Полное покрытие запрошенного периода не подтверждено: проверка достигла лимита найденных строк.";
|
||||
}
|
||||
if (/^Complete requested-period coverage for bidirectional value-flow is not proven because at least one MCP discovery probe row limit was reached$/i.test(value)) {
|
||||
return "Полное покрытие запрошенного периода по двустороннему денежному потоку не подтверждено: хотя бы одна сторона проверки достигла лимита найденных строк.";
|
||||
}
|
||||
if (/^Full turnover outside the checked period is not proven by this MCP discovery pilot$/i.test(value)) {
|
||||
return "Полный оборот вне проверенного периода этим поиском не подтвержден.";
|
||||
}
|
||||
@@ -109,6 +127,12 @@ function localizeLine(value) {
|
||||
if (/^Full all-time supplier-payout amount is not proven without an explicit checked period$/i.test(value)) {
|
||||
return "Полный объем исходящих платежей за все время без явно проверенного периода не подтвержден.";
|
||||
}
|
||||
if (/^Full bidirectional value-flow outside the checked period is not proven by this MCP discovery pilot$/i.test(value)) {
|
||||
return "Полный двусторонний денежный поток вне проверенного периода этим поиском не подтвержден.";
|
||||
}
|
||||
if (/^Full all-time bidirectional value-flow is not proven without an explicit checked period$/i.test(value)) {
|
||||
return "Полный двусторонний денежный поток за все время без явно проверенного периода не подтвержден.";
|
||||
}
|
||||
return value;
|
||||
}
|
||||
function section(title, lines) {
|
||||
|
||||
+29
-5
@@ -101,12 +101,15 @@ function hasValueFlowSignal(text) {
|
||||
function hasPayoutSignal(text) {
|
||||
return /(?:\bмы\s+(?:за)?плат|(?:за)?платил|оплатил|перечисл|списан|расход|поставщик|исходящ|supplier|payout|outflow|paid\s+to|payment\s+to)/iu.test(text);
|
||||
}
|
||||
function hasBidirectionalValueFlowSignal(text) {
|
||||
return /(?:нетто|сальдо|баланс\s+(?:плат|денег|денеж)|взаиморасч[её]т|получил[иа]?.*(?:за)?платил|(?:за)?платил[иа]?.*получил|входящ.*исходящ|исходящ.*входящ|дебет.*кредит|кредит.*дебет|net\s+(?:flow|cash|payment)|cash\s+net|incoming\s+and\s+outgoing|received\s+and\s+paid|paid\s+and\s+received)/iu.test(text);
|
||||
}
|
||||
function semanticNeedFor(input) {
|
||||
const combined = compactLower(`${input.domain ?? ""} ${input.action ?? ""} ${input.unsupported ?? ""}`);
|
||||
if (input.lifecycleSignal || /(?:lifecycle|activity|duration|age)/iu.test(combined)) {
|
||||
return "counterparty lifecycle evidence";
|
||||
}
|
||||
if (input.valueFlowSignal || /(?:turnover|revenue|payment|payout|value)/iu.test(combined)) {
|
||||
if (input.valueFlowSignal || /(?:turnover|revenue|payment|payout|value|net|netting|balance|cashflow)/iu.test(combined)) {
|
||||
return "counterparty value-flow evidence";
|
||||
}
|
||||
if (/(?:document|documents|list_documents)/iu.test(combined)) {
|
||||
@@ -136,8 +139,9 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
|
||||
const reasonCodes = [];
|
||||
const rawText = compactLower(`${input.userMessage ?? ""} ${input.effectiveMessage ?? ""}`);
|
||||
const lifecycleSignal = hasLifecycleSignal(rawText);
|
||||
const valueFlowSignal = !lifecycleSignal && hasValueFlowSignal(rawText);
|
||||
const payoutSignal = valueFlowSignal && hasPayoutSignal(rawText);
|
||||
const bidirectionalValueFlowSignal = !lifecycleSignal && hasBidirectionalValueFlowSignal(rawText);
|
||||
const valueFlowSignal = !lifecycleSignal && (hasValueFlowSignal(rawText) || bidirectionalValueFlowSignal);
|
||||
const payoutSignal = valueFlowSignal && !bidirectionalValueFlowSignal && hasPayoutSignal(rawText);
|
||||
const rawDomain = toNonEmptyString(assistantTurnMeaning?.asked_domain_family);
|
||||
const rawAction = toNonEmptyString(assistantTurnMeaning?.asked_action_family);
|
||||
const unsupported = toNonEmptyString(assistantTurnMeaning?.unsupported_but_understood_family);
|
||||
@@ -157,11 +161,28 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
|
||||
const explicitOrganizationScope = valueFlowSignal && !predecomposeEntities.counterparty ? null : predecomposeEntities.organization;
|
||||
const turnMeaning = {
|
||||
asked_domain_family: lifecycleSignal ? "counterparty_lifecycle" : valueFlowSignal ? "counterparty_value" : rawDomain,
|
||||
asked_action_family: lifecycleSignal ? "activity_duration" : valueFlowSignal ? (payoutSignal ? "payout" : "turnover") : rawAction,
|
||||
asked_action_family: lifecycleSignal
|
||||
? "activity_duration"
|
||||
: valueFlowSignal
|
||||
? bidirectionalValueFlowSignal
|
||||
? "net_value_flow"
|
||||
: payoutSignal
|
||||
? "payout"
|
||||
: "turnover"
|
||||
: rawAction,
|
||||
explicit_entity_candidates: entityCandidates,
|
||||
explicit_organization_scope: explicitOrganizationScope,
|
||||
explicit_date_scope: collectDateScope(predecomposeContract),
|
||||
unsupported_but_understood_family: unsupported ?? (lifecycleSignal ? "counterparty_lifecycle" : valueFlowSignal ? (payoutSignal ? "counterparty_payouts_or_outflow" : "counterparty_value_or_turnover") : null),
|
||||
unsupported_but_understood_family: unsupported ??
|
||||
(lifecycleSignal
|
||||
? "counterparty_lifecycle"
|
||||
: valueFlowSignal
|
||||
? bidirectionalValueFlowSignal
|
||||
? "counterparty_bidirectional_value_flow_or_netting"
|
||||
: payoutSignal
|
||||
? "counterparty_payouts_or_outflow"
|
||||
: "counterparty_value_or_turnover"
|
||||
: null),
|
||||
stale_replay_forbidden: Boolean(assistantTurnMeaning?.stale_replay_forbidden || unsupported || lifecycleSignal || valueFlowSignal)
|
||||
};
|
||||
const cleanTurnMeaning = {};
|
||||
@@ -212,6 +233,9 @@ function buildAssistantMcpDiscoveryTurnInput(input) {
|
||||
if (payoutSignal) {
|
||||
pushReason(reasonCodes, "mcp_discovery_payout_signal_detected");
|
||||
}
|
||||
if (bidirectionalValueFlowSignal) {
|
||||
pushReason(reasonCodes, "mcp_discovery_bidirectional_value_flow_signal_detected");
|
||||
}
|
||||
if (unsupported) {
|
||||
pushReason(reasonCodes, "mcp_discovery_unsupported_but_understood_turn");
|
||||
}
|
||||
|
||||
+16
-11
@@ -328,17 +328,22 @@ function createAssistantRoutePolicy(deps) {
|
||||
continuitySnapshot.lastGroundedAddressDebug;
|
||||
const lastOrganizationClarificationDebug = findLastOrganizationClarificationAddressDebug(sessionItems);
|
||||
const organizationClarificationCandidates = organizationAuthority.organizationClarificationCandidates;
|
||||
const organizationClarificationSelectionFromScope = organizationAuthority.organizationClarificationSelectionFromScope;
|
||||
const explicitOrganizationClarificationSelection = resolveOrganizationSelectionFromMessage(rawUserMessage, organizationClarificationCandidates) ??
|
||||
resolveOrganizationSelectionFromMessage(repairedRawUserMessage, organizationClarificationCandidates) ??
|
||||
resolveOrganizationSelectionFromMessage(effectiveAddressUserMessage, organizationClarificationCandidates) ??
|
||||
resolveOrganizationSelectionFromMessage(repairedEffectiveAddressUserMessage, organizationClarificationCandidates) ??
|
||||
null;
|
||||
const organizationClarificationSelection = explicitOrganizationClarificationSelection ??
|
||||
(organizationClarificationSelectionFromScope &&
|
||||
organizationClarificationCandidates.some((candidate) => normalizeOrganizationScopeValue(candidate) === organizationClarificationSelectionFromScope)
|
||||
? organizationClarificationSelectionFromScope
|
||||
: null);
|
||||
const organizationClarificationContinuation = (0, assistantContinuityPolicy_1.resolveOrganizationClarificationContinuation)({
|
||||
rawMessages: [
|
||||
rawUserMessage,
|
||||
repairedRawUserMessage,
|
||||
effectiveAddressUserMessage,
|
||||
repairedEffectiveAddressUserMessage
|
||||
],
|
||||
organizationClarificationCandidates,
|
||||
organizationClarificationSelectionFromScope: organizationAuthority.organizationClarificationSelectionFromScope,
|
||||
lastOrganizationClarificationDebug,
|
||||
resolveOrganizationSelectionFromMessage,
|
||||
toNonEmptyString,
|
||||
normalizeOrganizationScopeValue
|
||||
});
|
||||
const explicitOrganizationClarificationSelection = organizationClarificationContinuation.explicitSelection;
|
||||
const organizationClarificationSelection = organizationClarificationContinuation.selection;
|
||||
const metaSignals = resolveMetaSignalSet({
|
||||
rawUserMessage,
|
||||
repairedRawUserMessage,
|
||||
|
||||
@@ -316,13 +316,18 @@ function createAssistantTransitionPolicy(deps) {
|
||||
const organizationClarificationCandidates = Array.isArray(organizationAuthority.organizationClarificationCandidates)
|
||||
? organizationAuthority.organizationClarificationCandidates
|
||||
: [];
|
||||
const explicitOrganizationClarificationSelection = deps.resolveOrganizationSelectionFromMessage(userMessage, organizationClarificationCandidates) ??
|
||||
(deps.toNonEmptyString(alternateMessage)
|
||||
? deps.resolveOrganizationSelectionFromMessage(String(alternateMessage ?? ""), organizationClarificationCandidates)
|
||||
: null);
|
||||
const organizationClarificationSelection = explicitOrganizationClarificationSelection ??
|
||||
deps.normalizeOrganizationScopeValue(organizationAuthority.organizationClarificationSelectionFromScope);
|
||||
const hasOrganizationClarificationContinuation = Boolean(lastOrganizationClarificationDebug && organizationClarificationSelection);
|
||||
const organizationClarificationContinuation = (0, assistantContinuityPolicy_1.resolveOrganizationClarificationContinuation)({
|
||||
rawMessages: [userMessage, alternateMessage],
|
||||
organizationClarificationCandidates,
|
||||
organizationClarificationSelectionFromScope: organizationAuthority.organizationClarificationSelectionFromScope,
|
||||
lastOrganizationClarificationDebug,
|
||||
resolveOrganizationSelectionFromMessage: deps.resolveOrganizationSelectionFromMessage,
|
||||
toNonEmptyString: deps.toNonEmptyString,
|
||||
normalizeOrganizationScopeValue: deps.normalizeOrganizationScopeValue
|
||||
});
|
||||
const explicitOrganizationClarificationSelection = organizationClarificationContinuation.explicitSelection;
|
||||
const organizationClarificationSelection = organizationClarificationContinuation.selection;
|
||||
const hasOrganizationClarificationContinuation = organizationClarificationContinuation.hasContinuation;
|
||||
const carryoverSourceDebug = previousAddressDebug ??
|
||||
(hasOrganizationClarificationContinuation ? lastOrganizationClarificationDebug : null);
|
||||
const followupOffer = carryoverSourceDebug ? deps.buildAddressFollowupOffer(carryoverSourceDebug) : null;
|
||||
|
||||
Reference in New Issue
Block a user