import { stringifyValue } from "./search.js"; import { summarizeObservation, uniqueStrings } from "./summary.js"; import type { LangfuseObservationSummary } from "./types.js"; /** * Deterministic flow reconstruction from cached Langfuse fields. * * Everything here is plain text matching over observation name/input/output/ * metadata — no network, no model calls. Both flows answer "where does this * file or rule show up across the stages", so they share one evidence * collector and differ only in their stage vocabulary and in what they report. * * The stage word lists are bilingual heuristics tuned against real traces; * they are deliberately data, not logic, so tuning them cannot change a code * path. */ export const ATTACHMENT_STAGES = [ "attachment parsing", "image/document understanding", "pre_analysis", "document_parsing", "approval_review" ] as const; export const RULE_FLOW_STAGES = ["rule matching", "document parsing", "final review"] as const; export type AttachmentStage = (typeof ATTACHMENT_STAGES)[number]; export type RuleFlowStage = (typeof RULE_FLOW_STAGES)[number]; export type EvidenceField = "input" | "output" | "metadata"; export interface EvidenceHit { observationId: string; name?: string; type?: string; field: EvidenceField; matched: string; snippet: string; } export type AttachmentSource = | "filename-only" | "file-id-only" | "parsed-text" | "image-ocr" | "model-inferred" | "absent" | "unknown"; const ATTACHMENT_STAGE_TERMS: Record = { "attachment parsing": ["attachment", "附件", "parse_attachment", "attachment_parsing"], "image/document understanding": [ "understanding", "vision", "image", "document_understanding", "文档理解", "图片理解" ], pre_analysis: ["pre_analysis", "pre-analysis", "预分析"], document_parsing: ["document_parsing", "document parsing", "文档解析"], approval_review: ["approval_review", "approval review", "审核"] }; const RULE_STAGE_TERMS: Record = { "rule matching": ["rule", "规则", "policy", "match", "matching", "命中"], "document parsing": ["document", "parse", "parsing", "attachment", "ocr", "文档", "解析", "附件", "提取"], "final review": ["approval_review", "approval review", "review", "审核", "结论", "final"] }; export function stageTerms( stage: AttachmentStage | RuleFlowStage, vocabulary: "attachment" | "rule" ): string[] { return vocabulary === "attachment" ? ATTACHMENT_STAGE_TERMS[stage as AttachmentStage] : RULE_STAGE_TERMS[stage as RuleFlowStage]; } /** Observations whose name mentions any of the stage's terms. */ export function candidatesForStage( observations: LangfuseObservationSummary[], terms: string[] ): LangfuseObservationSummary[] { const lowered = terms.map((term) => term.toLowerCase()); return observations.filter((observation) => { const name = observation.name?.toLowerCase() ?? ""; return lowered.some((term) => name.includes(term)); }); } /** * Scan every field of an observation for each needle and return bounded, * context-padded hits. The cap keeps a pathological trace from ballooning the * response. */ export function collectEvidence( observation: LangfuseObservationSummary, needles: string[], contextChars: number, limit: number ): EvidenceHit[] { const fields = [ ["input", stringifyValue(observation.input)], ["output", stringifyValue(observation.output)], ["metadata", stringifyValue(observation.metadata)] ] as const; const evidence: EvidenceHit[] = []; for (const [field, text] of fields) { const normalized = text.toLowerCase(); for (const needle of needles) { const index = normalized.indexOf(needle.toLowerCase()); if (index < 0) continue; evidence.push({ observationId: observation.id, name: observation.name, type: observation.type, field, matched: text.slice(index, index + needle.length), snippet: text.slice( Math.max(0, index - contextChars), Math.min(text.length, index + needle.length + contextChars) ) }); } } return evidence.slice(0, limit); } /** * Decide where an attachment's presence appears to come from. Labels describe * the text that was found — they never assert that a model understood the file. */ export function classifyAttachmentEvidence( evidence: Array<{ matched: string; snippet: string }>, fileId: string | undefined, fileName: string | undefined ): AttachmentSource { if (evidence.length === 0) return "absent"; const hasFileName = fileName ? evidence.some((item) => item.matched === fileName) : false; const hasFileId = fileId ? evidence.some((item) => item.matched === fileId) : false; const hasOtherHint = evidence.some((item) => item.matched !== fileId && item.matched !== fileName); if (hasOtherHint) { const joined = evidence .map((item) => item.snippet) .join("\n") .toLowerCase(); if (/(ocr|图片|image|vision|视觉|识别)/i.test(joined)) return "image-ocr"; if (/(infer|inferred|推断|模型认为|判断|审核结论)/i.test(joined)) return "model-inferred"; return "parsed-text"; } if (hasFileName) return "filename-only"; if (hasFileId) return "file-id-only"; return "unknown"; } /** Count hits per field, de-duplicating the matched substrings. */ export function summarizeEvidenceFields( evidence: EvidenceHit[] ): Record { const summary: Record = {}; for (const item of evidence) { const entry = summary[item.field]; if (entry) { entry.count += 1; if (!entry.matched.includes(item.matched)) entry.matched.push(item.matched); } else { summary[item.field] = { count: 1, matched: [item.matched] }; } } return summary; } export function buildAttachmentFlow(options: { observations: LangfuseObservationSummary[]; fileId?: string; fileName?: string; needles: string[]; contextChars: number; }) { const { observations, fileId, fileName, needles, contextChars } = options; return ATTACHMENT_STAGES.map((stage) => { const candidates = candidatesForStage(observations, stageTerms(stage, "attachment")); const evidence = candidates.flatMap((observation) => collectEvidence(observation, needles, contextChars, 10) ); const source = classifyAttachmentEvidence(evidence, fileId, fileName); return { stage, source, status: source === "absent" ? ("absent" as const) : ("seen" as const), observations: candidates.map(summarizeObservation), evidence }; }); } export function buildRuleFlow(options: { observations: LangfuseObservationSummary[]; needles: string[]; contextChars: number; }) { const { observations, needles, contextChars } = options; const stages = RULE_FLOW_STAGES.map((stage) => { const candidates = candidatesForStage(observations, stageTerms(stage, "rule")); // Unlike attachment flow, a rule query falls back to every observation: // a rule can be applied inside a generically-named span. const pool = candidates.length ? candidates : observations; const evidence = pool .flatMap((observation) => collectEvidence(observation, needles, contextChars, 20)) .slice(0, 20); return { stage, matched: evidence.length > 0, matchedObservationIds: uniqueStrings(evidence.map((item) => item.observationId)), observations: candidates.map(summarizeObservation), extractedFields: summarizeEvidenceFields(evidence), evidence }; }); const allEvidence = stages.flatMap((stage) => stage.evidence); return { stages: { ruleMatching: stages[0], documentParsing: stages[1], finalReview: stages[2] }, relatedObservationIds: uniqueStrings(allEvidence.map((item) => item.observationId)), evidenceCount: allEvidence.length }; }