Stage 3: улучшена логика жизненного цикла и очищены ответы ассистента

This commit is contained in:
2026-03-26 20:21:51 +03:00
parent d0b842adb0
commit 914843a8ba
81 changed files with 18051 additions and 654 deletions
@@ -1,4 +1,4 @@
import type { CandidateEvidenceItem, ProblemConfidence, ProblemUnit, ProblemUnitType } from "../types/stage2ProblemUnits";
import type { CandidateEvidenceItem, ProblemConfidence, ProblemUnit, ProblemUnitType } from "../types/stage2ProblemUnits";
import {
LIFECYCLE_MODEL_SCHEMA_VERSION,
STAGE3_LIFECYCLE_DOMAINS,
@@ -47,13 +47,99 @@ function hasToken(values: string[], pattern: RegExp): boolean {
return values.some((value) => pattern.test(value));
}
function defaultExpectedState(domain: LifecycleDomain): string {
if (domain === "bank_settlement") return "settlement_closed";
if (domain === "customer_settlement") return "receivable_closed";
if (domain === "deferred_expense") return "fully_written_off";
if (domain === "fixed_asset") return "depreciation_active";
if (domain === "vat_flow") return "vat_deducted";
return "close_completed";
function normalizeStateToken(value: string): string {
return value.trim().toLowerCase();
}
function resolveStateCode(model: LifecycleDomainModel, stateCode: string | null | undefined): string | null {
if (!stateCode || typeof stateCode !== "string") {
return null;
}
const normalized = normalizeStateToken(stateCode);
const matched = model.states.find((state) => normalizeStateToken(state.state_code) === normalized);
return matched?.state_code ?? null;
}
function defaultInitialState(model: LifecycleDomainModel): string {
const initial = model.states.find((state) => state.state_class === "initial");
if (initial) {
return initial.state_code;
}
return model.states[0]?.state_code ?? "unknown_state";
}
function defaultExpectedState(model: LifecycleDomainModel): string {
const terminal = model.states.find((state) => state.is_terminal || state.state_class === "terminal");
if (terminal) {
return terminal.state_code;
}
const active = model.states.find((state) => state.state_class === "active");
if (active) {
return active.state_code;
}
return defaultInitialState(model);
}
function expectedTransitionAdjacency(model: LifecycleDomainModel): Map<string, string[]> {
const graph = new Map<string, string[]>();
for (const transition of model.transitions) {
if (transition.transition_type !== "expected") {
continue;
}
const from = transition.from_state;
const to = transition.to_state;
const current = graph.get(from) ?? [];
if (!current.includes(to)) {
current.push(to);
}
graph.set(from, current);
}
return graph;
}
function shortestExpectedPath(model: LifecycleDomainModel, fromState: string, toState: string): string[] | null {
if (fromState === toState) {
return [fromState];
}
const graph = expectedTransitionAdjacency(model);
const queue: string[][] = [[fromState]];
const visited = new Set<string>([fromState]);
while (queue.length > 0) {
const path = queue.shift();
if (!path) {
continue;
}
const tail = path[path.length - 1];
const nextStates = graph.get(tail) ?? [];
for (const nextState of nextStates) {
if (visited.has(nextState)) {
continue;
}
const nextPath = [...path, nextState];
if (nextState === toState) {
return nextPath;
}
visited.add(nextState);
queue.push(nextPath);
}
}
return null;
}
function transitionEdgeLabel(fromState: string, toState: string): string {
return `${fromState}->${toState}`;
}
function resolvePreviousStates(model: LifecycleDomainModel, currentState: string): string[] {
const initialState = defaultInitialState(model);
if (initialState === currentState) {
return [];
}
const path = shortestExpectedPath(model, initialState, currentState);
if (!path || path.length <= 1) {
return [];
}
return path.slice(0, -1);
}
const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
@@ -64,53 +150,53 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
states: [
{
state_code: "initiated_payment",
state_label: "Платеж инициирован",
state_label: "Платеж инициирован",
state_class: "initial",
entry_conditions: ["payment_order_created"],
exit_conditions: ["bank_recorded"],
is_terminal: false,
is_problematic: false,
business_meaning: "Есть инициирование платежа."
business_meaning: "Есть инициирование платежа."
},
{
state_code: "bank_recorded",
state_label: "Платеж отражен банком",
state_label: "Платеж отражен банком",
state_class: "active",
entry_conditions: ["bank_statement_recorded"],
exit_conditions: ["settlement_linked"],
is_terminal: false,
is_problematic: false,
business_meaning: "Движение денег зафиксировано, ожидается расчетное закрытие."
business_meaning: "Движение денег зафиксировано, ожидается расчетное закрытие."
},
{
state_code: "settlement_closed",
state_label: "Расчет закрыт",
state_label: "Расчет закрыт",
state_class: "terminal",
entry_conditions: ["payment_to_settlement_linked"],
exit_conditions: [],
is_terminal: true,
is_problematic: false,
business_meaning: "Платеж доведен до расчетного результата."
business_meaning: "Платеж доведен до расчетного результата."
},
{
state_code: "stale_unlinked_payment",
state_label: "Платеж завис без закрытия",
state_label: "Платеж завис без закрытия",
state_class: "problematic",
entry_conditions: ["bank_recorded", "missing_link"],
exit_conditions: ["settlement_closed"],
is_terminal: false,
is_problematic: true,
business_meaning: "Платеж отражен, но ожидаемая связь по расчету не завершена."
business_meaning: "Платеж отражен, но ожидаемая связь по расчету не завершена."
},
{
state_code: "misclosed_payment",
state_label: "Платеж закрыт некорректно",
state_label: "Платеж закрыт некорректно",
state_class: "problematic",
entry_conditions: ["wrong_document_type_or_posting_mismatch"],
exit_conditions: ["settlement_closed"],
is_terminal: false,
is_problematic: true,
business_meaning: "Формальное закрытие есть, но путь закрытия неверный."
business_meaning: "Формальное закрытие есть, но путь закрытия неверный."
}
],
transitions: [
@@ -121,7 +207,7 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
required_evidence: ["bank_statement_recorded"],
optional_evidence: ["payment_order"],
forbidden_conditions: [],
business_meaning: "Платеж должен появиться во выписке."
business_meaning: "Платеж должен появиться во выписке."
},
{
from_state: "bank_recorded",
@@ -130,7 +216,7 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
required_evidence: ["payment_to_settlement_link"],
optional_evidence: ["document_to_posting"],
forbidden_conditions: ["wrong_document_type"],
business_meaning: "После выписки должен закрываться расчет."
business_meaning: "После выписки должен закрываться расчет."
}
],
defects: []
@@ -142,43 +228,43 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
states: [
{
state_code: "invoice_issued",
state_label: "Реализация отражена",
state_label: "Реализация отражена",
state_class: "initial",
entry_conditions: ["realization_document_exists"],
exit_conditions: ["payment_recorded"],
is_terminal: false,
is_problematic: false,
business_meaning: "Возникла дебиторская позиция."
business_meaning: "Возникла дебиторская позиция."
},
{
state_code: "payment_recorded",
state_label: "Оплата отражена",
state_label: "Оплата отражена",
state_class: "active",
entry_conditions: ["payment_document_exists"],
exit_conditions: ["receivable_closed"],
is_terminal: false,
is_problematic: false,
business_meaning: "Оплата есть, ожидается корректное закрытие."
business_meaning: "Оплата есть, ожидается корректное закрытие."
},
{
state_code: "receivable_closed",
state_label: "Дебиторка закрыта",
state_label: "Дебиторка закрыта",
state_class: "terminal",
entry_conditions: ["closing_document_linked"],
exit_conditions: [],
is_terminal: true,
is_problematic: false,
business_meaning: "Дебиторская позиция закрыта корректно."
business_meaning: "Дебиторская позиция закрыта корректно."
},
{
state_code: "stale_receivable",
state_label: "Дебиторка зависла",
state_label: "Дебиторка зависла",
state_class: "problematic",
entry_conditions: ["unresolved_settlement"],
exit_conditions: ["receivable_closed"],
is_terminal: false,
is_problematic: true,
business_meaning: "Позиция остается незавершенной дольше ожидаемого."
business_meaning: "Позиция остается незавершенной дольше ожидаемого."
}
],
transitions: [
@@ -189,7 +275,7 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
required_evidence: ["payment_document_exists"],
optional_evidence: [],
forbidden_conditions: [],
business_meaning: "После реализации ожидается оплата/зачет."
business_meaning: "После реализации ожидается оплата/зачет."
},
{
from_state: "payment_recorded",
@@ -198,7 +284,7 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
required_evidence: ["closing_document_linked"],
optional_evidence: ["register_movement_exists"],
forbidden_conditions: ["cross_branch_inconsistency"],
business_meaning: "Оплата должна завершаться корректным закрытием расчета."
business_meaning: "Оплата должна завершаться корректным закрытием расчета."
}
],
defects: []
@@ -210,43 +296,43 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
states: [
{
state_code: "recognized",
state_label: "РБП признан",
state_label: "РБП признан",
state_class: "initial",
entry_conditions: ["deferred_expense_created"],
exit_conditions: ["writeoff_started"],
is_terminal: false,
is_problematic: false,
business_meaning: "РБП поставлен на учет."
business_meaning: "РБП поставлен на учет."
},
{
state_code: "partially_written_off",
state_label: "Частичное списание",
state_label: "Частичное списание",
state_class: "active",
entry_conditions: ["partial_writeoff_exists"],
exit_conditions: ["fully_written_off"],
is_terminal: false,
is_problematic: false,
business_meaning: "Списание идет по графику."
business_meaning: "Списание идет по графику."
},
{
state_code: "fully_written_off",
state_label: "РБП полностью списан",
state_label: "РБП полностью списан",
state_class: "terminal",
entry_conditions: ["full_writeoff_exists"],
exit_conditions: [],
is_terminal: true,
is_problematic: false,
business_meaning: "РБП завершил lifecycle."
business_meaning: "РБП завершил lifecycle."
},
{
state_code: "overdue_writeoff",
state_label: "Просроченное списание",
state_label: "Просроченное списание",
state_class: "problematic",
entry_conditions: ["period_boundary", "missing_link"],
exit_conditions: ["fully_written_off"],
is_terminal: false,
is_problematic: true,
business_meaning: "РБП живет дольше допустимого окна."
business_meaning: "РБП живет дольше допустимого окна."
}
],
transitions: [],
@@ -259,53 +345,53 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
states: [
{
state_code: "capitalized",
state_label: "Капвложения отражены",
state_label: "Капвложения отражены",
state_class: "initial",
entry_conditions: ["capitalization_document_exists"],
exit_conditions: ["accepted_for_accounting"],
is_terminal: false,
is_problematic: false,
business_meaning: "Объект зафиксирован как вложение."
business_meaning: "Объект зафиксирован как вложение."
},
{
state_code: "accepted_for_accounting",
state_label: "Принят к учету",
state_label: "Принят к учету",
state_class: "active",
entry_conditions: ["acceptance_document_exists"],
exit_conditions: ["depreciation_active"],
is_terminal: false,
is_problematic: false,
business_meaning: "Объект переведен в основной контур учета."
business_meaning: "Объект переведен в основной контур учета."
},
{
state_code: "depreciation_active",
state_label: "Амортизация активна",
state_label: "Амортизация активна",
state_class: "active",
entry_conditions: ["depreciation_register_movement"],
exit_conditions: ["disposed"],
is_terminal: false,
is_problematic: false,
business_meaning: "Жизненный цикл ОС идет штатно."
business_meaning: "Жизненный цикл ОС идет штатно."
},
{
state_code: "contradictory_asset_state",
state_label: "Противоречивый статус ОС",
state_label: "Противоречивый статус ОС",
state_class: "problematic",
entry_conditions: ["posting_mismatch_or_wrong_path"],
exit_conditions: ["depreciation_active"],
is_terminal: false,
is_problematic: true,
business_meaning: "Статус ОС формально есть, но смыслово противоречив."
business_meaning: "Статус ОС формально есть, но смыслово противоречив."
},
{
state_code: "disposed",
state_label: "Выбыл",
state_label: "Выбыл",
state_class: "terminal",
entry_conditions: ["disposal_document_exists"],
exit_conditions: [],
is_terminal: true,
is_problematic: false,
business_meaning: "Жизненный цикл ОС завершен."
business_meaning: "Жизненный цикл ОС завершен."
}
],
transitions: [],
@@ -318,43 +404,43 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
states: [
{
state_code: "vat_registered",
state_label: "НДС отражен документно",
state_label: "НДС отражен документно",
state_class: "initial",
entry_conditions: ["invoice_registered"],
exit_conditions: ["vat_reflected"],
is_terminal: false,
is_problematic: false,
business_meaning: "Сформирован первичный документный слой НДС."
business_meaning: "Сформирован первичный документный слой НДС."
},
{
state_code: "vat_reflected",
state_label: "НДС отражен в учете",
state_label: "НДС отражен в учете",
state_class: "active",
entry_conditions: ["vat_register_movement"],
exit_conditions: ["vat_deducted"],
is_terminal: false,
is_problematic: false,
business_meaning: "НДС проходит штатную стадию отражения."
business_meaning: "НДС проходит штатную стадию отражения."
},
{
state_code: "vat_deducted",
state_label: "НДС принят к вычету",
state_label: "НДС принят к вычету",
state_class: "terminal",
entry_conditions: ["deduction_confirmed"],
exit_conditions: [],
is_terminal: true,
is_problematic: false,
business_meaning: "НДС-цепочка завершена корректно."
business_meaning: "НДС-цепочка завершена корректно."
},
{
state_code: "vat_conflict",
state_label: "Конфликт НДС-цепочки",
state_label: "Конфликт НДС-цепочки",
state_class: "problematic",
entry_conditions: ["cross_branch_inconsistency"],
exit_conditions: ["vat_reflected"],
is_terminal: false,
is_problematic: true,
business_meaning: "Бухгалтерская и налоговая ветки расходятся."
business_meaning: "Бухгалтерская и налоговая ветки расходятся."
}
],
transitions: [],
@@ -367,53 +453,53 @@ const LIFECYCLE_DOMAIN_MODELS: Record<LifecycleDomain, LifecycleDomainModel> = {
states: [
{
state_code: "preclose_checks",
state_label: "Предзакрытие",
state_label: "Предзакрытие",
state_class: "active",
entry_conditions: ["period_scope_detected"],
exit_conditions: ["close_ready"],
is_terminal: false,
is_problematic: false,
business_meaning: "Идет проверка готовности периода."
business_meaning: "Идет проверка готовности периода."
},
{
state_code: "close_ready",
state_label: "Готов к закрытию",
state_label: "Готов к закрытию",
state_class: "active",
entry_conditions: ["no_blockers_detected"],
exit_conditions: ["close_completed"],
is_terminal: false,
is_problematic: false,
business_meaning: "Период может быть закрыт."
business_meaning: "Период может быть закрыт."
},
{
state_code: "close_completed",
state_label: "Закрытие завершено",
state_label: "Закрытие завершено",
state_class: "terminal",
entry_conditions: ["close_operation_done"],
exit_conditions: [],
is_terminal: true,
is_problematic: false,
business_meaning: "Период закрыт."
business_meaning: "Период закрыт."
},
{
state_code: "close_blocked",
state_label: "Закрытие заблокировано",
state_label: "Закрытие заблокировано",
state_class: "problematic",
entry_conditions: ["period_close_risk_or_stale_state"],
exit_conditions: ["close_ready"],
is_terminal: false,
is_problematic: true,
business_meaning: "Есть lifecycle-дефекты, влияющие на закрытие."
business_meaning: "Есть lifecycle-дефекты, влияющие на закрытие."
},
{
state_code: "close_contradicted",
state_label: "Закрыт формально, но с противоречием",
state_label: "Закрыт формально, но с противоречием",
state_class: "problematic",
entry_conditions: ["misclosed_or_cross_branch_conflict"],
exit_conditions: ["close_completed"],
is_terminal: false,
is_problematic: true,
business_meaning: "Формальное закрытие не согласовано с фактическими ветками."
business_meaning: "Формальное закрытие не согласовано с фактическими ветками."
}
],
transitions: [],
@@ -426,7 +512,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "missing_expected_transition",
defect_class: "path",
severity_hint: "medium",
business_meaning: "Ожидаемый переход не произошел.",
business_meaning: "Ожидаемый переход не произошел.",
evidence_requirements: ["expected_state", "missing_transition_signal"],
period_impact_potential: "indirect"
},
@@ -434,7 +520,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "invalid_transition",
defect_class: "path",
severity_hint: "high",
business_meaning: "Переход произошел по некорректному пути.",
business_meaning: "Переход произошел по некорректному пути.",
evidence_requirements: ["invalid_transition_signal"],
period_impact_potential: "indirect"
},
@@ -442,7 +528,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "stale_active_state",
defect_class: "timing",
severity_hint: "high",
business_meaning: "Объект завис в активном состоянии.",
business_meaning: "Объект завис в активном состоянии.",
evidence_requirements: ["stale_marker", "missing_transition_signal"],
period_impact_potential: "direct"
},
@@ -450,7 +536,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "contradictory_state",
defect_class: "consistency",
severity_hint: "high",
business_meaning: "Статусы объекта противоречат друг другу.",
business_meaning: "Статусы объекта противоречат друг другу.",
evidence_requirements: ["contradiction_signal"],
period_impact_potential: "direct"
},
@@ -458,7 +544,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "premature_terminal_state",
defect_class: "closure",
severity_hint: "medium",
business_meaning: "Терминальное состояние наступило преждевременно.",
business_meaning: "Терминальное состояние наступило преждевременно.",
evidence_requirements: ["terminal_state", "missing_required_previous_state"],
period_impact_potential: "indirect"
},
@@ -466,7 +552,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "misclosed_state",
defect_class: "closure",
severity_hint: "high",
business_meaning: "Контур формально закрыт, но закрыт неверно.",
business_meaning: "Контур формально закрыт, но закрыт неверно.",
evidence_requirements: ["wrong_closure_path"],
period_impact_potential: "direct"
},
@@ -474,7 +560,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "orphan_intermediate_state",
defect_class: "path",
severity_hint: "medium",
business_meaning: "Промежуточная стадия осталась без корректного продолжения.",
business_meaning: "Промежуточная стадия осталась без корректного продолжения.",
evidence_requirements: ["intermediate_state_without_next"],
period_impact_potential: "indirect"
},
@@ -482,7 +568,7 @@ const SHARED_DEFECTS: LifecycleDefectDefinition[] = [
defect_code: "cross_branch_state_conflict",
defect_class: "consistency",
severity_hint: "high",
business_meaning: "Состояния соседних веток учета противоречат друг другу.",
business_meaning: "Состояния соседних веток учета противоречат друг другу.",
evidence_requirements: ["cross_branch_conflict_signal"],
period_impact_potential: "direct"
}
@@ -502,6 +588,23 @@ class LifecycleRegistryImpl {
public getDomain(domain: LifecycleDomain): LifecycleDomainModel {
return this.models[domain];
}
public hasState(domain: LifecycleDomain, stateCode: string | null | undefined): boolean {
const model = this.getDomain(domain);
return Boolean(resolveStateCode(model, stateCode));
}
public resolveDefaultExpectedState(domain: LifecycleDomain): string {
return defaultExpectedState(this.getDomain(domain));
}
public resolveInitialState(domain: LifecycleDomain): string {
return defaultInitialState(this.getDomain(domain));
}
public findExpectedPath(domain: LifecycleDomain, fromState: string, toState: string): string[] | null {
return shortestExpectedPath(this.getDomain(domain), fromState, toState);
}
}
export const LifecycleRegistry = new LifecycleRegistryImpl(LIFECYCLE_DOMAIN_MODELS);
@@ -524,30 +627,88 @@ function inferLifecycleDomain(input: LifecycleResolverInput): LifecycleDomain {
.join(" ")
.toLowerCase();
if (includesAny(unitTokens, [/\bnds\b/, /\bvat\b/, /\btax\b/, /cross[_\s-]?branch/, /\b19\b/, /\b68\b/])) {
return "vat_flow";
}
if (includesAny(unitTokens, [/\bperiod\b/, /\bclose\b/, /закрыт/, /reporting/]) || input.unit.problem_unit_type === "period_risk_cluster") {
return "period_close";
}
if (includesAny(unitTokens, [/deferred/, /writeoff/, /рбп/, /\b97\b/])) {
const hasVatMarkers = includesAny(unitTokens, [
/domain_hint:vat_flow/,
/\binvoice_to_vat\b/,
/\bvat_chain_conflict\b/,
/(^|[^a-z0-9])nds([^a-z0-9]|$)/,
/(^|[^a-z0-9])vat([^a-z0-9]|$)/,
/(^|[^a-z0-9])tax(?:es)?([^a-z0-9]|$)/,
/\baccount[_:\s-]?(19|68)\b/
]);
const hasDeferredMarkers = includesAny(unitTokens, [
/domain_hint:deferred_expense/,
/\bdeferred(?:_expense)?\b/,
/\bdeferred_expense_to_writeoff\b/,
/\bwriteoff\b/,
/\bpartially_written_off\b/,
/\bfully_written_off\b/,
/\baccount[_:\s-]?97\b/
]);
const hasFixedAssetMarkers = includesAny(unitTokens, [
/domain_hint:fixed_asset/,
/\bfixed[_\s-]?asset(?:s)?\b/,
/\basset_card_to_depreciation\b/,
/\bdepreciation(?:_active)?\b/,
/\baccepted_for_accounting\b/,
/\bcapitalized\b/,
/\baccount[_:\s-]?(01|02|08)\b/
]);
const hasPeriodCloseMarkers = includesAny(unitTokens, [
/domain_hint:period_close/,
/\bperiod[_\s-]?close\b/,
/\bperiod_close_risk\b/,
/\bclose[_\s-]?risk\b/,
/\bclosure[_\s-]?risk\b/,
/\bpreclose\b/,
/\bmonth[_\s-]?close\b/,
/\bperiod_risk\b/
]);
if (hasDeferredMarkers) {
return "deferred_expense";
}
if (includesAny(unitTokens, [/fixed[_\s-]?asset/, /амортиз/, /ос\b/, /\b01\b/, /\b02\b/, /\b08\b/])) {
if (hasFixedAssetMarkers) {
return "fixed_asset";
}
if (includesAny(unitTokens, [/buyer/, /customer/, /дебитор/, /\b62\b/])) {
if (hasVatMarkers) {
return "vat_flow";
}
if (
hasPeriodCloseMarkers ||
input.unit.problem_unit_type === "period_risk_cluster" ||
input.unit.period_impact?.impact_class === "close_risk"
) {
return "period_close";
}
if (includesAny(unitTokens, [/buyer/, /customer/, /\b62\b/])) {
return "customer_settlement";
}
if (
includesAny(unitTokens, [
/domain_hint:bank_settlement/,
/\bpayment_to_settlement\b/,
/\bstatement_to_document\b/,
/\bbank_recorded\b/,
/\binitiated_payment\b/,
/\bsettlement(?:_closed)?\b/
]) ||
input.unit.problem_unit_type === "unresolved_settlement_cluster" ||
input.unit.problem_unit_type === "broken_chain_segment"
) {
return "bank_settlement";
}
if (input.unit.problem_unit_type === "cross_branch_inconsistency_cluster") {
return "vat_flow";
}
if (input.unit.problem_unit_type === "lifecycle_anomaly_node") {
return "deferred_expense";
}
return "bank_settlement";
}
function inferCurrentState(domain: LifecycleDomain, input: LifecycleResolverInput): string {
const explicitActual = input.unit.actual_state?.trim();
if (explicitActual) {
return explicitActual;
}
const anomalies = input.candidates.flatMap((item) => item.anomaly_patterns).map((item) => item.toLowerCase());
const relations = input.candidates.flatMap((item) => item.relation_pattern_hits).map((item) => item.toLowerCase());
@@ -573,7 +734,7 @@ function inferCurrentState(domain: LifecycleDomain, input: LifecycleResolverInpu
if (domain === "fixed_asset") {
if (hasInvalid) return "contradictory_asset_state";
if (hasToken(relations, /depreciation|amort/)) return "depreciation_active";
if (hasToken(relations, /accept|учет/)) return "accepted_for_accounting";
if (hasToken(relations, /accept|account/)) return "accepted_for_accounting";
return "capitalized";
}
if (domain === "vat_flow") {
@@ -587,27 +748,51 @@ function inferCurrentState(domain: LifecycleDomain, input: LifecycleResolverInpu
return "preclose_checks";
}
function inferExpectedState(domain: LifecycleDomain, input: LifecycleResolverInput): string {
function inferExpectedState(domain: LifecycleDomain, input: LifecycleResolverInput, model: LifecycleDomainModel): string {
const explicitExpected = input.unit.expected_state?.trim();
if (explicitExpected) {
return explicitExpected;
}
return defaultExpectedState(domain);
return defaultExpectedState(model);
}
function inferMissingTransition(input: LifecycleResolverInput): string | null {
function inferMissingTransition(
input: LifecycleResolverInput,
model: LifecycleDomainModel,
currentState: string,
expectedState: string
): string | null {
if (typeof input.unit.failed_expected_edge === "string" && input.unit.failed_expected_edge.trim().length > 0) {
return input.unit.failed_expected_edge.trim();
}
const anomalies = input.candidates.flatMap((item) => item.anomaly_patterns).join(" ").toLowerCase();
if (/(missing_link|no_continuation|broken_lifecycle|tail|unresolved)/.test(anomalies)) {
return "expected_transition_not_observed";
if (!/(missing_link|no_continuation|broken_lifecycle|tail|unresolved)/.test(anomalies)) {
return null;
}
return null;
if (currentState !== expectedState) {
const path = shortestExpectedPath(model, currentState, expectedState);
if (path && path.length >= 2) {
return transitionEdgeLabel(path[0], path[1]);
}
}
const directExpected = model.transitions.find(
(transition) => transition.transition_type === "expected" && transition.from_state === currentState
);
if (directExpected) {
return transitionEdgeLabel(directExpected.from_state, directExpected.to_state);
}
return "expected_transition_not_observed";
}
function inferInvalidTransition(input: LifecycleResolverInput): string | null {
function inferInvalidTransition(input: LifecycleResolverInput, model: LifecycleDomainModel): string | null {
const anomalies = input.candidates.flatMap((item) => item.anomaly_patterns).join(" ").toLowerCase();
for (const transition of model.transitions) {
for (const forbiddenCondition of transition.forbidden_conditions) {
if (anomalies.includes(forbiddenCondition.toLowerCase())) {
return `${transitionEdgeLabel(transition.from_state, transition.to_state)}:forbidden:${forbiddenCondition}`;
}
}
}
if (/(cross_branch|cross_domain_inconsistency)/.test(anomalies)) {
return "cross_branch_conflict_transition";
}
@@ -653,6 +838,14 @@ export function classifyLifecycleDefect(input: {
return null;
}
function registryBackedDefect(domain: LifecycleDomain, defect: LifecycleDefectType | null): LifecycleDefectType | null {
if (!defect) {
return null;
}
const model = LifecycleRegistry.getDomain(domain);
return model.defects.some((definition) => definition.defect_code === defect) ? defect : null;
}
function resolutionConfidence(unitConfidence: ProblemConfidence, input: {
hasExplicitStates: boolean;
hasDefectSignal: boolean;
@@ -690,32 +883,47 @@ function lifecycleInterpretation(input: {
missingTransition: string | null;
invalidTransition: string | null;
}): string {
const base = `Текущая стадия: ${input.currentState}; ожидаемая стадия: ${input.expectedState}.`;
const base = `Текущая стадия: ${input.currentState}; ожидаемая стадия: ${input.expectedState}.`;
if (input.defect === "stale_active_state") {
return `${base} Объект завис во времени и не дошел до ожидаемого перехода.`;
return `${base} Объект завис во времени и не дошел до ожидаемого перехода.`;
}
if (input.defect === "misclosed_state") {
return `${base} Контур закрыт формально, но путь закрытия противоречит бухгалтерской логике.`;
return `${base} Контур закрыт формально, но путь закрытия противоречит бухгалтерской логике.`;
}
if (input.defect === "cross_branch_state_conflict") {
return `${base} Между ветками домена ${input.domain} обнаружено противоречие состояний.`;
return `${base} Между ветками домена ${input.domain} обнаружено противоречие состояний.`;
}
if (input.defect === "missing_expected_transition") {
return `${base} Не зафиксирован ожидаемый переход (${input.missingTransition ?? "unknown_transition"}).`;
return `${base} Не зафиксирован ожидаемый переход (${input.missingTransition ?? "unknown_transition"}).`;
}
if (input.defect === "invalid_transition") {
return `${base} Зафиксирован некорректный переход (${input.invalidTransition ?? "invalid_transition"}).`;
return `${base} Зафиксирован некорректный переход (${input.invalidTransition ?? "invalid_transition"}).`;
}
return `${base} Lifecycle-разрешение не выявило критичный дефект, но состояние требует наблюдения.`;
return `${base} Lifecycle-разрешение не выявило критичный дефект, но состояние требует наблюдения.`;
}
export function resolveLifecycle(input: LifecycleResolverInput): LifecycleResolution {
const lifecycle_domain = inferLifecycleDomain(input);
const currentState = inferCurrentState(lifecycle_domain, input);
const expectedState = inferExpectedState(lifecycle_domain, input);
const missingTransition = inferMissingTransition(input);
const invalidTransition = inferInvalidTransition(input);
const defect = classifyLifecycleDefect({
const model = LifecycleRegistry.getDomain(lifecycle_domain);
const inferredCurrentState = inferCurrentState(lifecycle_domain, input);
const inferredExpectedState = inferExpectedState(lifecycle_domain, input, model);
const explicitActualState = input.unit.actual_state?.trim() ?? null;
const explicitExpectedState = input.unit.expected_state?.trim() ?? null;
const explicitCurrentState = resolveStateCode(model, explicitActualState);
const explicitExpectedResolved = resolveStateCode(model, explicitExpectedState);
const inferredCurrentResolved = resolveStateCode(model, inferredCurrentState);
const inferredExpectedResolved = resolveStateCode(model, inferredExpectedState);
const currentState = explicitCurrentState ?? inferredCurrentResolved ?? defaultInitialState(model);
const expectedState = explicitExpectedResolved ?? inferredExpectedResolved ?? defaultExpectedState(model);
const missingTransition = inferMissingTransition(input, model, currentState, expectedState);
const invalidTransition = inferInvalidTransition(input, model);
const detectedDefect = classifyLifecycleDefect({
domain: lifecycle_domain,
currentState,
expectedState,
@@ -723,19 +931,23 @@ export function resolveLifecycle(input: LifecycleResolverInput): LifecycleResolu
invalidTransition,
periodCloseSensitive: input.unit.period_impact?.impact_class === "close_risk"
});
const defect = registryBackedDefect(lifecycle_domain, detectedDefect);
const evidenceIds = uniqueStrings(input.unit.evidence_pack, 8);
const previousStates = resolvePreviousStates(model, currentState);
const limitations = uniqueStrings(
[
...input.unit.snapshot_limitations,
...(input.candidates.some((item) => item.confidence_hint === "low") ? ["low_confidence_candidates_present"] : []),
...(input.unit.actual_state ? [] : ["actual_state_inferred"]),
...(input.unit.expected_state ? [] : ["expected_state_inferred"])
...(explicitActualState && !explicitCurrentState ? ["actual_state_not_in_registry_normalized"] : []),
...(explicitExpectedState && !explicitExpectedResolved ? ["expected_state_not_in_registry_normalized"] : []),
...(explicitCurrentState ? [] : ["actual_state_inferred"]),
...(explicitExpectedResolved ? [] : ["expected_state_inferred"])
],
8
);
const confidence = resolutionConfidence(input.unit.confidence, {
hasExplicitStates: Boolean(input.unit.actual_state || input.unit.expected_state),
hasExplicitStates: Boolean(explicitCurrentState || explicitExpectedResolved),
hasDefectSignal: Boolean(defect || missingTransition || invalidTransition),
candidateCount: input.candidates.length,
hasSnapshotLimitations: limitations.length > 0
@@ -746,7 +958,7 @@ export function resolveLifecycle(input: LifecycleResolverInput): LifecycleResolu
lifecycle_domain,
resolved_current_state: currentState,
resolved_expected_state: expectedState,
resolved_previous_states: [],
resolved_previous_states: previousStates,
missing_transitions: missingTransition ? [missingTransition] : [],
invalid_transitions: invalidTransition ? [invalidTransition] : [],
detected_defects: defect ? [defect] : [],