ГЛОБАЛЬНЫЙ РЕФАКТОРИНГ АРХИТЕКТУРЫ - Рефакторинг этапов 2.562.60 Deep-turn attempt input builder \ Deep-turn analysis-attempt input builder \ Deep-turn response-runtime input builder:

This commit is contained in:
2026-04-11 09:46:42 +03:00
parent c849eb5f5b
commit 6c9b94ef34
16 changed files with 1234 additions and 393 deletions
@@ -0,0 +1,135 @@
import { describe, expect, it, vi } from "vitest";
import { buildAssistantDeepTurnAnalysisRuntimeInput } from "../src/services/assistantDeepTurnAnalysisAttemptInputBuilder";
function buildInput(overrides: Record<string, unknown> = {}) {
return {
userMessage: "why debt not closed",
normalizedPayload: { fragments: [] },
routeSummary: { mode: "deterministic_v2", decisions: [] },
runtimeAnalysisContext: {
active: true,
as_of_date: "2020-07-31",
period_from: null,
period_to: null,
source: "analysis_context"
},
followupUsage: { applied: true },
investigationState: { session_id: "asst-1" },
featureAnswerPolicyV11: true,
featureProblemCentricAnswerV1: true,
featureLifecycleAnswerV1: true,
resolveBusinessScopeAlignment: vi.fn(() => ({ route_summary_resolved: { mode: "deterministic_v2", decisions: [] } })),
inferP0DomainFromMessage: vi.fn(() => "settlements_60_62"),
resolveBusinessScopeFromLiveContext: vi.fn(({ current }) => current),
extractRequirements: vi.fn(() => ({ requirements: [{ id: "R1" }], byFragment: new Map([["F1", ["R1"]]]) })),
toExecutionPlan: vi.fn(() => [{ fragment_id: "F1", requirement_ids: ["R1"], route: "store_canonical", should_execute: true }]),
enforceRbpLiveRoutePlan: vi.fn(({ executionPlan }) => ({ executionPlan, audit: { rbp: true } })),
enforceFaLiveRoutePlan: vi.fn(({ executionPlan }) => ({ executionPlan, audit: { fa: true } })),
executeRouteRuntime: vi.fn(async () => ({})),
mapNoRouteReason: vi.fn(() => "skipped"),
buildSkippedResult: vi.fn(() => ({ status: "skipped" })),
evaluateCoverage: vi.fn(() => ({ requirements: [{ id: "R1" }], coverage: {} })),
checkGrounding: vi.fn(() => ({ status: "grounded", reasons: [] })),
collectRbpLiveRouteAudit: vi.fn(() => ({ routed: 1 })),
collectFaLiveRouteAudit: vi.fn(() => ({ routed: 1 })),
hasExplicitPeriodAnchor: vi.fn(() => false),
runDeepTurnContextRuntimeSafe: vi.fn(() => ({ context: true })),
runDeepTurnPlanRuntimeSafe: vi.fn(() => ({ plan: true })),
runDeepTurnRetrievalRuntimeSafe: vi.fn(async () => ({ retrieval: true })),
runDeepTurnGuardRuntimeSafe: vi.fn(() => ({ guard: true })),
runDeepTurnGroundingRuntimeSafe: vi.fn(() => ({ grounding: true })),
runDeepTurnCompositionRuntimeSafe: vi.fn(() => ({ composition: true })),
...overrides
} as any;
}
describe("assistant deep turn analysis attempt input builder", () => {
it("builds analysis runtime callbacks and delegates stage payload mapping", async () => {
const input = buildInput();
const runtimeInput = buildAssistantDeepTurnAnalysisRuntimeInput(input);
runtimeInput.runContextRuntime();
runtimeInput.runExecutionPlanRuntime({
resolvedRouteSummary: { mode: "deterministic_v2", decisions: [] } as any,
claimAnchorAudit: { claim_type: "prove_settlement_closure_state" } as any,
temporalGuard: { primary_period_window: {} },
domainPolarityGuardInitial: { polarity: "supplier_payable" }
});
await runtimeInput.runRetrievalRuntime({
executionPlan: [{ fragment_id: "F1", route: "store_canonical" }],
liveTemporalHint: { as_of_date: "2020-07-31", period_from: null, period_to: null, source: "analysis_context" }
} as any);
runtimeInput.runGuardRuntime({
retrievalResults: [],
domainPolarityGuardInitial: { polarity: "supplier_payable" },
claimAnchorAudit: { claim_type: "prove_settlement_closure_state" },
temporalGuard: { primary_period_window: {} },
focusDomainForGuards: "settlements_60_62",
companyAnchors: { accounts: ["60.01"] },
userMessage: "runtime-user-message"
} as any);
runtimeInput.runGroundingRuntime({
claimType: "prove_settlement_closure_state",
retrievalResults: [],
rbpPlanAudit: { rbp: true },
faPlanAudit: { fa: true },
routeSummary: { mode: "deterministic_v2", decisions: [] },
requirementExtraction: { requirements: [{ id: "R1" }], byFragment: new Map([["F1", ["R1"]]]) },
temporalGuard: { primary_period_window: {} },
polarityAudit: { polarity: "supplier_payable" },
evidenceAudit: { admissible_evidence_count: 1 },
claimAnchorAudit: { claim_type: "prove_settlement_closure_state" },
targetedEvidenceHitRate: 1,
businessScopeResolved: ["company_specific_accounting"]
} as any);
runtimeInput.runCompositionRuntime({
resolvedRouteSummary: { mode: "deterministic_v2", decisions: [] },
retrievalResults: [],
requirements: [{ id: "R1" }],
coverageReport: { requirements_total: 1, requirements_covered: 1 },
groundingCheck: { status: "grounded", reasons: [] },
companyAnchors: { accounts: ["60.01"] }
} as any);
expect(input.runDeepTurnContextRuntimeSafe).toHaveBeenCalledWith(
expect.objectContaining({
userMessage: "why debt not closed",
runtimeAnalysisContext: expect.objectContaining({ as_of_date: "2020-07-31" }),
resolveCompanyAnchors: expect.any(Function)
})
);
expect(input.runDeepTurnPlanRuntimeSafe).toHaveBeenCalledWith(
expect.objectContaining({
claimType: "prove_settlement_closure_state",
userMessage: "why debt not closed"
})
);
expect(input.runDeepTurnRetrievalRuntimeSafe).toHaveBeenCalledWith(
expect.objectContaining({
executeRouteRuntime: input.executeRouteRuntime,
mapNoRouteReason: input.mapNoRouteReason
})
);
expect(input.runDeepTurnGuardRuntimeSafe).toHaveBeenCalledWith(
expect.objectContaining({
userMessage: "runtime-user-message",
focusDomainForGuards: "settlements_60_62"
})
);
expect(input.runDeepTurnGroundingRuntimeSafe).toHaveBeenCalledWith(
expect.objectContaining({
normalizedPayload: { fragments: [] },
userMessage: "why debt not closed",
targetedEvidenceHitRate: 1
})
);
expect(input.runDeepTurnCompositionRuntimeSafe).toHaveBeenCalledWith(
expect.objectContaining({
userMessage: "why debt not closed",
featureAnswerPolicyV11: true,
featureProblemCentricAnswerV1: true,
featureLifecycleAnswerV1: true
})
);
});
});
@@ -0,0 +1,114 @@
import { describe, expect, it, vi } from "vitest";
import {
buildAssistantDeepTurnAnalysisAttemptRuntimeInput,
buildAssistantDeepTurnNormalizationRuntimeInput,
buildAssistantDeepTurnResponseAttemptRuntimeInput
} from "../src/services/assistantDeepTurnAttemptInputBuilder";
function buildNormalizationRuntime(overrides: Record<string, unknown> = {}) {
return {
followupBinding: {
normalizedQuestion: "normalized-question",
mergedContext: {},
usage: { applied: true }
},
normalizePayload: {
userQuestion: "normalized-question"
},
normalized: {
trace_id: "trace-1",
prompt_version: "normalizer_v2_0_2",
schema_version: "normalized_query_v2_0_2",
normalized: { fragments: [] },
route_hint_summary: { mode: "deterministic_v2", decisions: [] }
},
...overrides
} as any;
}
describe("assistant deep turn attempt input builder", () => {
it("builds normalization runtime input from turn fields", () => {
const normalize = vi.fn(async () => ({}));
const runtimeInput = buildAssistantDeepTurnNormalizationRuntimeInput({
userMessage: "why debt not closed",
payload: { llmProvider: "openai", context: {} } as any,
featureInvestigationStateV1: true,
featureStateFollowupBindingV1: true,
sessionInvestigationState: { session_id: "asst-1" },
buildFollowupStateBinding: vi.fn(() => ({
normalizedQuestion: "normalized",
mergedContext: {},
usage: null
})),
normalize
});
expect(runtimeInput.userMessage).toBe("why debt not closed");
expect(runtimeInput.normalize).toBe(normalize);
expect(runtimeInput.featureInvestigationStateV1).toBe(true);
expect(runtimeInput.featureStateFollowupBindingV1).toBe(true);
});
it("builds analysis and response attempt inputs from normalization runtime", () => {
const normalizationRuntime = buildNormalizationRuntime();
const deepTurnAnalysisRuntime = {
composition: { reply_type: "partial_coverage" }
} as any;
const analysisInput = buildAssistantDeepTurnAnalysisAttemptRuntimeInput({
userMessage: "why debt not closed",
runtimeAnalysisContext: { active: true, as_of_date: "2020-07-31", period_from: null, period_to: null, source: "analysis_context" },
sessionInvestigationState: { session_id: "asst-1" } as any,
featureAnswerPolicyV11: true,
featureProblemCentricAnswerV1: true,
featureLifecycleAnswerV1: true,
resolveBusinessScopeAlignment: vi.fn(),
inferP0DomainFromMessage: vi.fn(),
resolveBusinessScopeFromLiveContext: vi.fn(),
extractRequirements: vi.fn(),
toExecutionPlan: vi.fn(),
enforceRbpLiveRoutePlan: vi.fn(),
enforceFaLiveRoutePlan: vi.fn(),
executeRouteRuntime: vi.fn(),
mapNoRouteReason: vi.fn(),
buildSkippedResult: vi.fn(),
evaluateCoverage: vi.fn(),
checkGrounding: vi.fn(),
collectRbpLiveRouteAudit: vi.fn(),
collectFaLiveRouteAudit: vi.fn(),
hasExplicitPeriodAnchor: vi.fn(),
normalizationRuntime
});
const responseInput = buildAssistantDeepTurnResponseAttemptRuntimeInput({
featureInvestigationStateV1: true,
featureContractsV11: true,
featureAnswerPolicyV11: true,
sessionId: "asst-1",
questionId: "msg-q1",
userMessage: "why debt not closed",
runtimeAnalysisContext: { as_of_date: "2020-07-31" } as any,
sessionInvestigationState: { session_id: "asst-1" } as any,
addressRuntimeMetaForDeep: null,
extractDroppedIntentSegments: vi.fn(() => []),
buildDebugRoutes: vi.fn(() => []),
extractExecutionState: vi.fn(() => []),
sanitizeReply: vi.fn((value: string) => value),
persistInvestigationState: vi.fn(),
messageIdFactory: vi.fn(() => "msg-a1"),
appendItem: vi.fn(),
getSession: vi.fn(),
persistSession: vi.fn(),
cloneConversation: vi.fn((items: unknown[]) => items),
logEvent: vi.fn(),
normalizationRuntime,
deepTurnAnalysisRuntime
});
expect(analysisInput.normalizedPayload).toEqual({ fragments: [] });
expect(analysisInput.routeSummary).toEqual({ mode: "deterministic_v2", decisions: [] });
expect(analysisInput.followupUsage).toEqual({ applied: true });
expect(responseInput.normalizedQuestion).toBe("normalized-question");
expect(responseInput.normalized.trace_id).toBe("trace-1");
expect(responseInput.followupApplied).toBe(true);
});
});
@@ -0,0 +1,78 @@
import { describe, expect, it, vi } from "vitest";
import { buildAssistantDeepTurnResponseRuntimeInput } from "../src/services/assistantDeepTurnResponseRuntimeInputBuilder";
function buildDeepRuntime() {
return {
companyAnchors: { accounts: ["60.01"] },
temporalGuard: { primary_period_window: { from: "2020-07-01", to: "2020-07-31" } },
claimAnchorAudit: { claim_type: "prove_settlement_closure_state" },
businessScopeResolution: { business_scope_resolved: ["company_specific_accounting"] },
resolvedRouteSummary: { mode: "deterministic_v2", decisions: [] as any[] },
requirementExtraction: {
requirements: [{ id: "R1" }],
byFragment: new Map<string, string[]>([["F1", ["R1"]]])
},
executionPlan: [{ fragment_id: "F1", route: "store_canonical" }],
retrievalCalls: [{ fragment_id: "F1", route: "store_canonical" }],
retrievalResultsRaw: [{ fragment_id: "F1", route: "store_canonical", raw_result: {} }],
retrievalResults: [{ fragment_id: "F1", requirement_ids: ["R1"] }],
polarityGuardResult: { audit: { polarity: "supplier_payable" } },
targetedEvidenceResult: { audit: { targeted_evidence_hit_rate: 1 } },
evidenceGateResult: { audit: { admissible_evidence_count: 2 } },
rbpLiveRouteAudit: { routed: 1 },
faLiveRouteAudit: { routed: 1 },
coverageEvaluation: {
requirements: [{ id: "R1" }],
coverage: { requirements_total: 1, requirements_covered: 1 }
},
groundedAnswerEligibilityGuard: { eligible: true },
groundingCheck: { status: "grounded", reasons: [] },
questionTypeClass: "causal_trace",
composition: { reply_type: "factual_with_explanation", assistant_reply: "ok" }
} as any;
}
describe("assistant deep turn response runtime input builder", () => {
it("maps analysis runtime into response runtime contract", () => {
const runtimeInput = buildAssistantDeepTurnResponseRuntimeInput({
featureInvestigationStateV1: true,
featureContractsV11: true,
featureAnswerPolicyV11: true,
sessionId: "asst-1",
questionId: "msg-q1",
userMessage: "why debt not closed",
normalized: {
trace_id: "trace-1",
prompt_version: "normalizer_v2_0_2",
schema_version: "normalized_query_v2_0_2",
normalized: { fragments: [] }
},
normalizedQuestion: "normalized-question",
deepTurnAnalysisRuntime: buildDeepRuntime(),
runtimeAnalysisContext: { as_of_date: "2020-07-31" },
followupStateUsage: { applied: true },
followupApplied: true,
previousInvestigationState: null,
addressRuntimeMetaForDeep: null,
extractDroppedIntentSegments: vi.fn(() => []),
buildDebugRoutes: vi.fn(() => []),
extractExecutionState: vi.fn(() => []),
sanitizeReply: vi.fn((value: string) => value),
persistInvestigationState: vi.fn(),
messageIdFactory: vi.fn(() => "msg-a1"),
appendItem: vi.fn(),
getSession: vi.fn(),
persistSession: vi.fn(),
cloneConversation: vi.fn((items: unknown[]) => items),
logEvent: vi.fn()
});
expect(runtimeInput.routeSummary).toEqual({ mode: "deterministic_v2", decisions: [] });
expect(runtimeInput.requirementExtractionRequirements).toEqual([{ id: "R1" }]);
expect(runtimeInput.coverageEvaluationRequirements).toEqual([{ id: "R1" }]);
expect(runtimeInput.questionTypeClass).toBe("causal_trace");
expect(runtimeInput.polarityAudit).toEqual({ polarity: "supplier_payable" });
expect(runtimeInput.targetedEvidenceAudit).toEqual({ targeted_evidence_hit_rate: 1 });
expect(runtimeInput.evidenceAdmissibilityGateAudit).toEqual({ admissible_evidence_count: 2 });
});
});