From a96b7a6c0858864f56a8426cc9903e3d83764472 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Thu, 8 Oct 2026 11:00:00 +0800 Subject: [PATCH 1/6] =?UTF-8?q?refactor(core):=20=E5=B0=86=E5=9B=9E?= =?UTF-8?q?=E7=AD=94=E5=88=86=E6=AE=B5=E8=A7=A3=E6=9E=90=E4=B8=8B=E6=B2=89?= =?UTF-8?q?=E5=88=B0=20core=20=E4=BE=9B=E6=BA=AF=E6=BA=90=E5=A4=8D?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 引用溯源与渲染器必须共用同一套 folio-block 围栏规则,避免把代码块里的示例当成引用。UI 改为从 core 重导出,渲染行为不变。 --- packages/core/src/answer-segments.ts | 81 ++++++++++++++++++ packages/core/src/index.ts | 1 + .../chat/blocks/parseAnswerSegments.ts | 82 +------------------ 3 files changed, 83 insertions(+), 81 deletions(-) create mode 100644 packages/core/src/answer-segments.ts diff --git a/packages/core/src/answer-segments.ts b/packages/core/src/answer-segments.ts new file mode 100644 index 00000000..973ffbc3 --- /dev/null +++ b/packages/core/src/answer-segments.ts @@ -0,0 +1,81 @@ +import { ANSWER_BLOCK_FENCE_LANG } from './answer-blocks.ts'; + +/** + * One segment of a Copilot answer: either Markdown text or a typed + * `folio-block` fence body. Untyped fences stay in text segments so ordinary + * code blocks keep rendering through Markdown. + */ +export type AnswerSegment = + | { kind: 'text'; text: string } + | { kind: 'block'; body: string; closed: boolean }; + +const FENCE_OPEN = /^[ \t]{0,3}(`{3,}|~{3,})(.*)$/; +const FENCE_CLOSE = /^[ \t]{0,3}(`{3,}|~{3,})[ \t]*$/; + +// `split('\n')` leaves the carriage return on CRLF lines. Strip it only for +// delimiter detection so the ordinary Markdown and typed JSON bytes remain +// unchanged in the returned segments. +const fenceLine = (line: string): string => (line.endsWith('\r') ? line.slice(0, -1) : line); + +/** + * Split an answer string into text and typed-block segments. + * + * Every fence is opaque until a bare closing fence with the same marker and + * at least the opening length arrives. This keeps `folio-block` examples + * inside ordinary Markdown code fences as literal text. + * + * An unclosed `folio-block` fence produces a `closed: false` block segment for + * streaming; unclosed ordinary fences remain verbatim Markdown. + */ +export function parseAnswerSegments(content: string): AnswerSegment[] { + const lines = content.split('\n'); + const segments: AnswerSegment[] = []; + let textLines: string[] = []; + + const flushText = () => { + if (textLines.length > 0) { + segments.push({ kind: 'text', text: textLines.join('\n') }); + textLines = []; + } + }; + + let index = 0; + while (index < lines.length) { + const line = lines[index] ?? ''; + const open = fenceLine(line).match(FENCE_OPEN); + const marker = open?.[1]; + const info = open?.[2] ?? ''; + + // Backtick info strings cannot contain another backtick. Such a line is + // prose rather than a fence and must not swallow later answer blocks. + if (!marker || (marker[0] === '`' && info.includes('`'))) { + textLines.push(line); + index += 1; + continue; + } + + const typed = info.trim() === ANSWER_BLOCK_FENCE_LANG; + if (typed) flushText(); + else textLines.push(line); + + const bodyLines: string[] = []; + let closed = false; + index += 1; + while (index < lines.length) { + const bodyLine = lines[index] ?? ''; + const close = fenceLine(bodyLine).match(FENCE_CLOSE)?.[1]; + if (close && close[0] === marker[0] && close.length >= marker.length) { + if (!typed) textLines.push(bodyLine); + closed = true; + index += 1; + break; + } + if (typed) bodyLines.push(bodyLine); + else textLines.push(bodyLine); + index += 1; + } + if (typed) segments.push({ kind: 'block', body: bodyLines.join('\n'), closed }); + } + flushText(); + return segments; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 9028575e..ee6934c4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -578,6 +578,7 @@ export interface Skill { // ── Folio V3 domains ─────────────────────────────────────────────────────── export * from './answer-blocks.ts'; +export * from './answer-segments.ts'; export * from './citations.ts'; export * from './capability.ts'; export * from './research.ts'; diff --git a/packages/ui/src/components/chat/blocks/parseAnswerSegments.ts b/packages/ui/src/components/chat/blocks/parseAnswerSegments.ts index 5602b6e2..458289ea 100644 --- a/packages/ui/src/components/chat/blocks/parseAnswerSegments.ts +++ b/packages/ui/src/components/chat/blocks/parseAnswerSegments.ts @@ -1,81 +1 @@ -import { ANSWER_BLOCK_FENCE_LANG } from '@finagent/core'; - -/** - * One segment of a Copilot answer: either Markdown text or a typed - * `folio-block` fence body. Untyped fences stay in text segments so ordinary - * code blocks keep rendering through Markdown. - */ -export type AnswerSegment = - | { kind: 'text'; text: string } - | { kind: 'block'; body: string; closed: boolean }; - -const FENCE_OPEN = /^[ \t]{0,3}(`{3,}|~{3,})(.*)$/; -const FENCE_CLOSE = /^[ \t]{0,3}(`{3,}|~{3,})[ \t]*$/; - -// `split('\n')` leaves the carriage return on CRLF lines. Strip it only for -// delimiter detection so the ordinary Markdown and typed JSON bytes remain -// unchanged in the returned segments. -const fenceLine = (line: string): string => (line.endsWith('\r') ? line.slice(0, -1) : line); - -/** - * Split an answer string into text and typed-block segments. - * - * Every fence is opaque until a bare closing fence with the same marker and - * at least the opening length arrives. This keeps `folio-block` examples - * inside ordinary Markdown code fences as literal text. - * - * An unclosed `folio-block` fence produces a `closed: false` block segment for - * streaming; unclosed ordinary fences remain verbatim Markdown. - */ -export function parseAnswerSegments(content: string): AnswerSegment[] { - const lines = content.split('\n'); - const segments: AnswerSegment[] = []; - let textLines: string[] = []; - - const flushText = () => { - if (textLines.length > 0) { - segments.push({ kind: 'text', text: textLines.join('\n') }); - textLines = []; - } - }; - - let index = 0; - while (index < lines.length) { - const line = lines[index] ?? ''; - const open = fenceLine(line).match(FENCE_OPEN); - const marker = open?.[1]; - const info = open?.[2] ?? ''; - - // Backtick info strings cannot contain another backtick. Such a line is - // prose rather than a fence and must not swallow later answer blocks. - if (!marker || (marker[0] === '`' && info.includes('`'))) { - textLines.push(line); - index += 1; - continue; - } - - const typed = info.trim() === ANSWER_BLOCK_FENCE_LANG; - if (typed) flushText(); - else textLines.push(line); - - const bodyLines: string[] = []; - let closed = false; - index += 1; - while (index < lines.length) { - const bodyLine = lines[index] ?? ''; - const close = fenceLine(bodyLine).match(FENCE_CLOSE)?.[1]; - if (close && close[0] === marker[0] && close.length >= marker.length) { - if (!typed) textLines.push(bodyLine); - closed = true; - index += 1; - break; - } - if (typed) bodyLines.push(bodyLine); - else textLines.push(bodyLine); - index += 1; - } - if (typed) segments.push({ kind: 'block', body: bodyLines.join('\n'), closed }); - } - flushText(); - return segments; -} +export { parseAnswerSegments, type AnswerSegment } from '@finagent/core'; From dae7a7b9b3a9fffbe688a27d9a0738ca59c04df2 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Sat, 10 Oct 2026 14:20:00 +0800 Subject: [PATCH 2/6] =?UTF-8?q?feat(evidence):=20=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E5=8C=96=E5=AF=B9=E8=B4=A6=E5=86=B2=E7=AA=81=E5=B9=B6=E4=BF=9D?= =?UTF-8?q?=E7=95=99=E5=85=A8=E9=83=A8=E5=80=99=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 ReconciliationResult 规范进金融证据信封。实质冲突保留双方候选与选中来源,不把价格平均成一个数。仅含 providers/method 的旧记录保持原样。 --- packages/core/src/financial-evidence.ts | 24 +++++- .../src/evidence/financial-evidence.test.ts | 60 +++++++++++++++ .../shared/src/evidence/financial-evidence.ts | 76 ++++++++++++++++++- 3 files changed, 157 insertions(+), 3 deletions(-) diff --git a/packages/core/src/financial-evidence.ts b/packages/core/src/financial-evidence.ts index 41ff822d..3b04d6db 100644 --- a/packages/core/src/financial-evidence.ts +++ b/packages/core/src/financial-evidence.ts @@ -1,3 +1,5 @@ +import type { FinancialFactCandidate, ReconciliationState } from './reconciliation.ts'; + /** Machine-readable lineage for structured financial facts used by Copilot. */ export const FINANCIAL_EVIDENCE_SCHEMA_VERSION = 'financial-evidence/v1' as const; @@ -34,7 +36,25 @@ export interface FinancialEvidenceMetadata { dataset?: string; cacheHit?: boolean; fallback?: FinancialEvidenceEnvelope['fallback']; - reconciliation?: FinancialEvidenceEnvelope['reconciliation']; + reconciliation?: FinancialEvidenceReconciliation; +} + +/** + * Provider disagreement recorded on a persisted fact. + * + * `providers` + `method` is the original shape. `state` and `candidates` are + * additive: a material conflict keeps every candidate and never replaces them + * with an average. Older records that only stored providers/method stay valid. + */ +export interface FinancialEvidenceReconciliation { + providers: string[]; + method: string; + state?: ReconciliationState; + candidates?: FinancialFactCandidate[]; + discrepancy?: number; + selectedProvider?: string; + /** Verbatim reconciler explanation, when the producer supplied one. */ + reason?: string; } export interface FinancialEvidenceEnvelope { @@ -59,7 +79,7 @@ export interface FinancialEvidenceEnvelope { delayed?: boolean; cacheHit: boolean; fallback?: { from: string; to: string; reason?: string }; - reconciliation?: { providers: string[]; method: string }; + reconciliation?: FinancialEvidenceReconciliation; resultSnapshot: unknown; resultHash: string; lineage: FinancialEvidenceLineageStep[]; diff --git a/packages/shared/src/evidence/financial-evidence.test.ts b/packages/shared/src/evidence/financial-evidence.test.ts index 002a0ea7..fbf2e69e 100644 --- a/packages/shared/src/evidence/financial-evidence.test.ts +++ b/packages/shared/src/evidence/financial-evidence.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'bun:test'; import type { ToolCall } from '@finagent/core'; +import { reconcileFinancialFacts } from '@finagent/core'; import { buildFinancialEvidence, computeEnvelopeId, @@ -154,3 +155,62 @@ describe('asOf unit normalization (issue #181)', () => { expect(envelope.asOf).toBe(110); }); }); + +describe('reconciliation persistence', () => { + it('keeps a historical providers/method record without inventing a conflict', () => { + const [record] = buildFinancialEvidence({ + sessionId: 's', + runId: 'r', + toolCalls: [call({ + result: { + data: { symbol: 'AAPL.US', lastPrice: 210.5 }, + provenance: { providerId: 'longbridge', fetchedAt: 120, stale: false }, + evidence: { reconciliation: { providers: ['longbridge', 'massive'], method: 'priority' } }, + }, + })], + }); + expect(record.reconciliation).toEqual({ providers: ['longbridge', 'massive'], method: 'priority' }); + expect(record.values.find((value) => value.metric === 'lastPrice')?.normalizedValue).toBe(210.5); + }); + + it('stores a material conflict with both candidates and does not average the selected price', () => { + const reconciliation = reconcileFinancialFacts( + [ + { provider: 'longbridge', value: 100, currency: 'USD', unit: 'price' }, + { provider: 'massive', value: 300, currency: 'USD', unit: 'price' }, + ], + { version: 'financial-facts.v1', relativeTolerance: 0.01, providerPriority: ['massive'] } + ); + const [record] = buildFinancialEvidence({ + sessionId: 's', + runId: 'r', + toolCalls: [call({ + result: { + data: { symbol: 'AAPL.US', lastPrice: 210, currency: 'USD' }, + provenance: { providerId: 'massive', fetchedAt: 120, marketTime: 100, stale: false, delayed: true }, + evidence: { + currencies: { lastPrice: 'USD' }, + units: { lastPrice: 'price' }, + reconciliation, + }, + }, + })], + }); + const lastPrice = record.values.find((value) => value.metric === 'lastPrice'); + expect(lastPrice?.normalizedValue).toBe(210); + expect(lastPrice?.normalizedValue).not.toBe(200); + expect(record.reconciliation).toMatchObject({ + state: 'material-conflict', + method: 'financial-facts.v1', + selectedProvider: 'massive', + discrepancy: 200, + providers: ['longbridge', 'massive'], + }); + expect(record.reconciliation?.candidates).toEqual([ + { provider: 'longbridge', value: 100, currency: 'USD', unit: 'price' }, + { provider: 'massive', value: 300, currency: 'USD', unit: 'price' }, + ]); + expect(record.reconciliation?.reason).toContain('never averaged'); + expect(JSON.stringify(record.reconciliation)).not.toContain('apiKey'); + }); +}); diff --git a/packages/shared/src/evidence/financial-evidence.ts b/packages/shared/src/evidence/financial-evidence.ts index dbe0f77a..3cb463bf 100644 --- a/packages/shared/src/evidence/financial-evidence.ts +++ b/packages/shared/src/evidence/financial-evidence.ts @@ -4,7 +4,10 @@ import type { FinancialEvidenceKind, FinancialEvidenceLineageStep, FinancialEvidenceMetadata, + FinancialEvidenceReconciliation, FinancialEvidenceValue, + FinancialFactCandidate, + ReconciliationState, ToolCall, } from '@finagent/core'; import { @@ -56,6 +59,7 @@ export function buildFinancialEvidence(input: BuildFinancialEvidenceInput): Fina const values = collectValues(result.data, result.evidence); const snapshot = redact(result.data); const resultHash = hashJson(snapshot); + const reconciliation = normalizeReconciliation(result.evidence?.reconciliation); const lineage: FinancialEvidenceLineageStep[] = [ { kind: 'provider', description: `Retrieved ${mapping.capabilityId} from ${provider}.` }, ...(result.evidence?.lineage ?? []), @@ -86,7 +90,7 @@ export function buildFinancialEvidence(input: BuildFinancialEvidenceInput): Fina ...(provenance.delayed === true ? { delayed: true } : {}), cacheHit: result.evidence?.cacheHit === true, ...(result.evidence?.fallback ? { fallback: result.evidence.fallback } : {}), - ...(result.evidence?.reconciliation ? { reconciliation: result.evidence.reconciliation } : {}), + ...(reconciliation ? { reconciliation } : {}), resultSnapshot: snapshot, resultHash, lineage, @@ -120,6 +124,76 @@ export function financialEvidenceToJson(evidence: FinancialEvidenceEnvelope[]): }, null, 2)}\n`; } +const RECONCILIATION_STATES = new Set([ + 'agreement', + 'within-tolerance', + 'material-conflict', + 'incomparable', + 'insufficient-sources', +]); + +/** + * Keep a reconciler result on the persisted fact without collapsing candidates + * into one number. Accepts both the historical `{ providers, method }` shape + * and a full `ReconciliationResult`. + */ +function normalizeReconciliation(value: unknown): FinancialEvidenceReconciliation | undefined { + const record = asRecord(value); + if (Object.keys(record).length === 0) return undefined; + + const state = typeof record.state === 'string' && RECONCILIATION_STATES.has(record.state as ReconciliationState) + ? record.state as ReconciliationState + : undefined; + const candidates = readCandidates(record.candidates); + const providers = readProviders(record.providers); + const candidateProviders = (candidates ?? []).map((candidate) => candidate.provider); + const resolvedProviders = providers.length > 0 ? providers : candidateProviders; + const method = stringValue(record.method) ?? stringValue(record.policyVersion) ?? state; + if (!method || (resolvedProviders.length === 0 && !state)) return undefined; + + const selected = asRecord(record.selected); + const selectedProvider = stringValue(record.selectedProvider) ?? stringValue(selected.provider); + const discrepancy = numberValue(record.discrepancy); + const reason = stringValue(record.reason); + + return { + providers: resolvedProviders, + method, + ...(state ? { state } : {}), + ...(candidates && candidates.length > 0 ? { candidates } : {}), + ...(discrepancy !== undefined ? { discrepancy } : {}), + ...(selectedProvider ? { selectedProvider } : {}), + ...(reason ? { reason } : {}), + }; +} + +function readProviders(value: unknown): string[] { + if (!Array.isArray(value)) return []; + return value.filter((provider): provider is string => typeof provider === 'string' && provider.length > 0); +} + +function readCandidates(value: unknown): FinancialFactCandidate[] | undefined { + if (!Array.isArray(value)) return undefined; + const candidates: FinancialFactCandidate[] = []; + for (const candidate of value) { + const item = asRecord(candidate); + const provider = stringValue(item.provider); + const amount = numberValue(item.value); + if (!provider || amount === undefined) continue; + candidates.push({ + provider, + value: amount, + ...(stringValue(item.instrument) ? { instrument: stringValue(item.instrument) } : {}), + ...(numberValue(item.asOf) !== undefined ? { asOf: numberValue(item.asOf) } : {}), + ...(stringValue(item.period) ? { period: stringValue(item.period) } : {}), + ...(stringValue(item.currency) ? { currency: stringValue(item.currency) } : {}), + ...(stringValue(item.unit) ? { unit: stringValue(item.unit) } : {}), + ...(stringValue(item.adjustment) ? { adjustment: stringValue(item.adjustment) } : {}), + }); + } + return candidates; +} + function readStructuredResult(value: unknown): StructuredResult { const record = asRecord(value); if ('data' in record) { From 749b4c2614373ac1fa167489953f1504108f05a1 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Mon, 12 Oct 2026 10:35:00 +0800 Subject: [PATCH 3/6] =?UTF-8?q?feat(evidence):=20=E7=BB=9F=E4=B8=80?= =?UTF-8?q?=E5=A5=91=E7=BA=A6=E6=A0=87=E5=87=BA=E5=BB=B6=E8=BF=9F=E4=B8=8E?= =?UTF-8?q?=E5=86=B2=E7=AA=81=E5=8F=AF=E7=94=A8=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实质冲突或口径不可比时将 availability 标为 conflicted,并在提供者声明延迟时写入 freshness.delayed。provenance.envelopeId 保留 fe_ id。选中数值仍是规范化原值。 --- packages/core/src/evidence-contract.ts | 10 ++++ packages/shared/src/evidence/contract.test.ts | 48 +++++++++++++++++++ packages/shared/src/evidence/contract.ts | 14 +++++- 3 files changed, 71 insertions(+), 1 deletion(-) diff --git a/packages/core/src/evidence-contract.ts b/packages/core/src/evidence-contract.ts index c102f6c4..73206573 100644 --- a/packages/core/src/evidence-contract.ts +++ b/packages/core/src/evidence-contract.ts @@ -92,6 +92,11 @@ export interface EvidenceFreshness { /** Market-time of the fact itself, when known. */ asOf?: number; stale: boolean; + /** + * True when the producing provider reported a delayed or end-of-day value. + * Omitted when the provider did not say so — absence is not "live". + */ + delayed?: boolean; } export interface EvidenceItem { @@ -116,6 +121,11 @@ export interface EvidenceItem { provider?: string; /** Scoping instrument for non-financial evidence (news about a listing). */ instrumentId?: string; + /** + * Persisted `fe_*` envelope id. Copilot answers cite either this id or the + * tool-call id; both must join back to the same observation. + */ + envelopeId?: string; }; } diff --git a/packages/shared/src/evidence/contract.test.ts b/packages/shared/src/evidence/contract.test.ts index 877e332b..8745069f 100644 --- a/packages/shared/src/evidence/contract.test.ts +++ b/packages/shared/src/evidence/contract.test.ts @@ -162,6 +162,54 @@ describe('evidence contract projections', () => { expect(evidence[0]!.freshness.asOf).toBe(999); }); + it('marks material conflicts without averaging the selected value', () => { + const { sources, evidence } = projectFinancialEvidence([envelope({ + delayed: true, + values: [{ metric: 'lastPrice', originalValue: '210.00', normalizedValue: 210, currency: 'USD', unit: 'price' }], + reconciliation: { + providers: ['longbridge', 'massive'], + method: 'financial-facts.v1', + state: 'material-conflict', + selectedProvider: 'massive', + discrepancy: 200, + reason: 'Material disagreement; candidates are preserved and never averaged.', + candidates: [ + { provider: 'longbridge', value: 100, currency: 'USD', unit: 'price' }, + { provider: 'massive', value: 300, currency: 'USD', unit: 'price' }, + ], + }, + })]); + expect(evidence[0]!.availability).toBe('conflicted'); + expect(evidence[0]!.financial?.value).toBe(210); + expect(evidence[0]!.financial?.value).not.toBe(200); + expect(evidence[0]!.freshness.delayed).toBe(true); + expect(evidence[0]!.provenance.envelopeId).toBe('fe_abc123'); + expect(sources[0]!.providerMeta?.reconciliation).toMatchObject({ + state: 'material-conflict', + candidates: [ + { provider: 'longbridge', value: 100 }, + { provider: 'massive', value: 300 }, + ], + }); + }); + + it('keeps agreement and legacy reconciliation records available', () => { + const agreed = projectFinancialEvidence([envelope({ + reconciliation: { + providers: ['longbridge', 'massive'], + method: 'financial-facts.v1', + state: 'agreement', + }, + })]); + expect(agreed.evidence[0]!.availability).toBe('available'); + expect(agreed.evidence[0]!.freshness.delayed).toBeUndefined(); + + const legacy = projectFinancialEvidence([envelope({ + reconciliation: { providers: ['longbridge'], method: 'priority' }, + })]); + expect(legacy.evidence[0]!.availability).toBe('available'); + }); + it('never fabricates canonical URLs for structured finance sources', () => { const { sources } = projectFinancialEvidence([envelope()]); expect(sources[0]!.canonicalUrl).toBeUndefined(); diff --git a/packages/shared/src/evidence/contract.ts b/packages/shared/src/evidence/contract.ts index e4739713..d8889f7e 100644 --- a/packages/shared/src/evidence/contract.ts +++ b/packages/shared/src/evidence/contract.ts @@ -1,5 +1,6 @@ import { createHash } from 'node:crypto'; import type { + EvidenceAvailability, EvidenceBundle, EvidenceClaim, EvidenceItem, @@ -92,14 +93,19 @@ export function projectFinancialEvidence( retrievedAt: envelope.retrievedAt, ...(resolvedAsOf !== undefined ? { asOf: resolvedAsOf } : {}), stale: envelope.stale, + ...(envelope.delayed === true ? { delayed: true } : {}), }, - availability: 'available', + // Conflict is a property of the observation. The selected normalized + // value is kept as reported; candidates stay on the source and are + // never averaged into `financial.value`. + availability: availabilityForEnvelope(envelope), provenance: { runId: envelope.runId, toolCallId: envelope.toolCallId, toolName: envelope.toolName, ...(envelope.capabilityId ? { capabilityId: envelope.capabilityId } : {}), provider: envelope.provider, + envelopeId: envelope.id, }, }); } @@ -344,6 +350,12 @@ export function parseEvidenceBundle(json: string): EvidenceBundle | undefined { } } +function availabilityForEnvelope(envelope: FinancialEvidenceEnvelope): EvidenceAvailability { + const state = envelope.reconciliation?.state; + if (state === 'material-conflict' || state === 'incomparable') return 'conflicted'; + return 'available'; +} + function deriveSourceId( kind: EvidenceSourceKind, origin: Record From aa17e8d6c3acd4aebebc29f2413e6df3a29c0f99 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:05:00 +0800 Subject: [PATCH 4/6] =?UTF-8?q?feat(evidence):=20=E4=BB=8E=20Copilot=20?= =?UTF-8?q?=E5=BC=95=E7=94=A8=E8=A7=A3=E6=9E=90=E5=88=B0=E5=B7=B2=E6=8C=81?= =?UTF-8?q?=E4=B9=85=E5=8C=96=E4=BA=8B=E5=AE=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 行内工具调用 id 与已闭合 folio-block 的 evidenceIds(工具调用 id 或 fe_)都加入同一条事实,带上提供者、标的、货币、asOf、retrievedAt、延迟、回退和冲突候选。无法解析的引用显式为 unmapped,重载后结果不变。 --- .../src/evidence/citation-trace.test.ts | 167 +++++++++++++ .../shared/src/evidence/citation-trace.ts | 220 ++++++++++++++++++ packages/shared/src/evidence/index.ts | 8 + 3 files changed, 395 insertions(+) create mode 100644 packages/shared/src/evidence/citation-trace.test.ts create mode 100644 packages/shared/src/evidence/citation-trace.ts diff --git a/packages/shared/src/evidence/citation-trace.test.ts b/packages/shared/src/evidence/citation-trace.test.ts new file mode 100644 index 00000000..30b4aab4 --- /dev/null +++ b/packages/shared/src/evidence/citation-trace.test.ts @@ -0,0 +1,167 @@ +import { describe, expect, it } from 'bun:test'; +import { renderCitationMarker } from '@finagent/core'; +import { appendBlocksToAnswer, renderBlockFence } from '../agent/answer-block-emitter.ts'; +import { buildFinancialEvidence } from './financial-evidence.ts'; +import { resolveCopilotCitationTrace } from './citation-trace.ts'; +import type { ToolCall } from '@finagent/core'; + +function quoteCall(overrides: Partial = {}): ToolCall { + return { + id: 'quote-1', + toolName: 'get_quote', + args: { symbol: 'AAPL.US' }, + startedAt: 1_710_000_000_000, + completedAt: 1_710_000_000_123, + status: 'success', + result: { + data: { symbol: 'AAPL.US', instrumentId: 'XNAS:AAPL', lastPrice: 210, currency: 'USD' }, + provenance: { + providerId: 'massive', + provider: 'massive', + instrumentId: 'XNAS:AAPL', + fetchedAt: 1_710_000_000_123, + marketTime: 1_710_000_000_456, + delayed: true, + stale: false, + }, + evidence: { + currencies: { lastPrice: 'USD' }, + units: { lastPrice: 'price' }, + fallback: { from: 'longbridge', to: 'massive', reason: 'TIMEOUT' }, + reconciliation: { + state: 'material-conflict', + policyVersion: 'financial-facts.v1', + candidates: [ + { provider: 'longbridge', value: 100, currency: 'USD', unit: 'price' }, + { provider: 'massive', value: 300, currency: 'USD', unit: 'price' }, + ], + selected: { provider: 'massive', value: 300, currency: 'USD', unit: 'price' }, + discrepancy: 200, + reason: 'Material disagreement; candidates are preserved and never averaged.', + }, + }, + }, + ...overrides, + }; +} + +describe('resolveCopilotCitationTrace', () => { + it('joins a tool-call citation and an fe_ citation to the same persisted fact', () => { + const evidence = buildFinancialEvidence({ + sessionId: 'session-1', + runId: 'run-1', + toolCalls: [quoteCall()], + }); + const envelope = evidence[0]!; + const block = renderBlockFence({ + version: 1, + type: 'metric_grid', + title: 'AAPL', + evidenceIds: [envelope.id], + metrics: [{ + label: 'Last', + value: 210, + unit: 'price', + currency: 'USD', + evidenceIds: ['quote-1'], + }], + }); + const answer = appendBlocksToAnswer( + `Apple last traded at 210 USD. ${renderCitationMarker('quote-1')} ${renderCitationMarker('missing-tool')}`, + [JSON.parse(block.slice(block.indexOf('\n') + 1, block.lastIndexOf('\n```')))] + ); + const trace = resolveCopilotCitationTrace({ + question: "What is Apple's current price, and where did it come from?", + answer, + financialEvidence: evidence, + }); + + expect(trace.schemaVersion).toBe('folio-citation-trace/v1'); + expect(trace.citations.map((citation) => citation.citationId)).toEqual(['quote-1', 'missing-tool', envelope.id]); + + const byTool = trace.citations[0]!; + const gap = trace.citations[1]!; + const byEnvelope = trace.citations[2]!; + + expect(byTool).toMatchObject({ + origin: 'inline', + resolution: 'tool_call', + envelopeId: envelope.id, + toolCallId: 'quote-1', + toolName: 'get_quote', + runId: 'run-1', + provider: 'massive', + instrumentId: 'XNAS:AAPL', + metric: 'lastPrice', + value: 210, + currency: 'USD', + unit: 'price', + asOf: 1_710_000_000_456, + retrievedAt: 1_710_000_000_123, + delayed: true, + stale: false, + fallback: { from: 'longbridge', to: 'massive', reason: 'TIMEOUT' }, + availability: 'conflicted', + }); + expect(byTool.asOf).not.toBe(byTool.retrievedAt); + expect(byTool.value).not.toBe(200); + expect(byTool.reconciliation?.candidates).toEqual([ + { provider: 'longbridge', value: 100, currency: 'USD', unit: 'price' }, + { provider: 'massive', value: 300, currency: 'USD', unit: 'price' }, + ]); + expect(byTool.values.find((value) => value.metric === 'lastPrice')?.evidenceId).toMatch(/^ev_/); + + expect(gap).toMatchObject({ resolution: 'unmapped', availability: 'unmapped', values: [] }); + expect(gap.provider).toBeUndefined(); + expect(gap.value).toBeUndefined(); + + expect(byEnvelope.resolution).toBe('envelope'); + expect(byEnvelope.envelopeId).toBe(byTool.envelopeId); + expect(byEnvelope.values.map((value) => value.evidenceId)).toEqual(byTool.values.map((value) => value.evidenceId)); + expect(byEnvelope.availability).toBe('conflicted'); + }); + + it('is unchanged when the same persisted messages are reloaded', () => { + const evidence = buildFinancialEvidence({ + sessionId: 'session-1', + runId: 'run-1', + toolCalls: [quoteCall()], + }); + const answer = `Price ${renderCitationMarker('quote-1')}`; + const question = 'What is AAPL worth?'; + const first = resolveCopilotCitationTrace({ question, answer, financialEvidence: evidence }); + const reloaded = JSON.parse(JSON.stringify({ question, answer, financialEvidence: evidence })) as { + question: string; + answer: string; + financialEvidence: typeof evidence; + }; + const second = resolveCopilotCitationTrace(reloaded); + expect(second).toEqual(first); + + const reworded = resolveCopilotCitationTrace({ ...reloaded, question: 'Ignore the saved price and use today\'s quote.' }); + expect(reworded.citations).toEqual(first.citations); + expect(reworded.question).not.toBe(first.question); + }); + + it('ignores evidence ids inside an unclosed or non-typed fence', () => { + const evidence = buildFinancialEvidence({ + sessionId: 'session-1', + runId: 'run-1', + toolCalls: [quoteCall()], + }); + const answer = [ + '```', + 'folio-block example', + '{"evidenceIds":["not-a-real-block"]}', + '```', + '```folio-block', + '{"version":1,"type":"metric_grid","metrics":[]}', + ].join('\n'); + const trace = resolveCopilotCitationTrace({ + question: 'quote', + answer, + financialEvidence: evidence, + }); + expect(trace.citations).toEqual([]); + }); +}); diff --git a/packages/shared/src/evidence/citation-trace.ts b/packages/shared/src/evidence/citation-trace.ts new file mode 100644 index 00000000..616f82d9 --- /dev/null +++ b/packages/shared/src/evidence/citation-trace.ts @@ -0,0 +1,220 @@ +import type { + AnswerBlock, + EvidenceItem, + FinancialEvidenceEnvelope, + FinancialEvidenceReconciliation, +} from '@finagent/core'; +import { parseAnswerBlock, parseAnswerSegments, parseCitationSegments } from '@finagent/core'; +import { projectFinancialEvidence } from './contract.ts'; + +/** + * Resolve one persisted Copilot answer from the question to the financial + * facts its citations name (#101). + * + * The production citation identity is the tool-call id (`⟦cite:…⟧` and typed + * block `evidenceIds`). Some answers also cite the persisted `fe_*` envelope + * id. Both join the same observation. Nothing here is recomputed from a live + * provider: the only inputs are the question text, the answer text, and the + * financial evidence already stored on the assistant message. + * + * A citation with no matching envelope is an explicit gap. A material or + * incomparable provider disagreement stays `conflicted` and keeps every + * candidate; this module never averages them. + */ + +export const COPILOT_CITATION_TRACE_SCHEMA_VERSION = 'folio-citation-trace/v1' as const; + +export type CopilotCitationOrigin = 'inline' | 'block'; +export type CopilotCitationResolution = 'tool_call' | 'envelope' | 'unmapped'; + +export interface CopilotCitedValue { + evidenceId: string; + metric: string; + value: unknown; + originalValue?: unknown; + unit?: string; + currency?: string; + period?: string; + asOf?: number; + availability: EvidenceItem['availability']; +} + +export interface CopilotCitation { + /** Id as written in the answer. */ + citationId: string; + /** First place the id appears. Later duplicates are not repeated. */ + origin: CopilotCitationOrigin; + resolution: CopilotCitationResolution; + envelopeId?: string; + toolCallId?: string; + toolName?: string; + runId?: string; + provider?: string; + instrumentId?: string; + /** `lastPrice` when the observation has one, otherwise the first value. */ + metric?: string; + value?: unknown; + originalValue?: unknown; + unit?: string; + currency?: string; + /** Market time of the primary fact. Distinct from `retrievedAt`. */ + asOf?: number; + retrievedAt?: number; + delayed: boolean; + stale: boolean; + fallback?: NonNullable; + availability: CopilotCitedValue['availability'] | 'unmapped'; + /** Every structured value on the matched envelope, in projection order. */ + values: CopilotCitedValue[]; + reconciliation?: FinancialEvidenceReconciliation; +} + +export interface CopilotCitationTrace { + schemaVersion: typeof COPILOT_CITATION_TRACE_SCHEMA_VERSION; + question: string; + answer: string; + citations: CopilotCitation[]; +} + +export interface ResolveCopilotCitationTraceInput { + question: string; + answer: string; + financialEvidence?: FinancialEvidenceEnvelope[]; +} + +/** Build the question → citation → persisted fact trace for one turn. */ +export function resolveCopilotCitationTrace(input: ResolveCopilotCitationTraceInput): CopilotCitationTrace { + const envelopes = input.financialEvidence ?? []; + const byEnvelopeId = new Map(); + const byToolCallId = new Map(); + for (const envelope of envelopes) { + if (!byEnvelopeId.has(envelope.id)) byEnvelopeId.set(envelope.id, envelope); + if (!byToolCallId.has(envelope.toolCallId)) byToolCallId.set(envelope.toolCallId, envelope); + } + + const valuesByToolCallId = new Map(); + for (const item of projectFinancialEvidence(envelopes).evidence) { + const toolCallId = item.provenance.toolCallId; + if (!toolCallId) continue; + const values = valuesByToolCallId.get(toolCallId) ?? []; + values.push(toCitedValue(item)); + valuesByToolCallId.set(toolCallId, values); + } + + const citations = collectCitationRefs(input.answer).map((ref) => { + const envelope = byEnvelopeId.get(ref.citationId) ?? byToolCallId.get(ref.citationId); + if (!envelope) { + return unmappedCitation(ref); + } + const values = valuesByToolCallId.get(envelope.toolCallId) ?? []; + const primary = values.find((value) => value.metric === 'lastPrice' || value.metric.endsWith('.lastPrice')) ?? values[0]; + return { + citationId: ref.citationId, + origin: ref.origin, + resolution: byEnvelopeId.has(ref.citationId) ? 'envelope' as const : 'tool_call' as const, + envelopeId: envelope.id, + toolCallId: envelope.toolCallId, + toolName: envelope.toolName, + runId: envelope.runId, + provider: envelope.provider, + ...(envelope.instrumentId ? { instrumentId: envelope.instrumentId } : {}), + ...(primary ? { + metric: primary.metric, + value: primary.value, + ...(primary.originalValue !== undefined ? { originalValue: primary.originalValue } : {}), + ...(primary.unit ? { unit: primary.unit } : {}), + ...(primary.currency ? { currency: primary.currency } : {}), + ...(primary.asOf !== undefined ? { asOf: primary.asOf } : {}), + } : {}), + ...(!primary && envelope.asOf !== undefined ? { asOf: envelope.asOf } : {}), + retrievedAt: envelope.retrievedAt, + delayed: envelope.delayed === true, + stale: envelope.stale, + ...(envelope.fallback ? { fallback: envelope.fallback } : {}), + availability: primary?.availability ?? availabilityFromReconciliation(envelope), + values, + ...(envelope.reconciliation ? { reconciliation: envelope.reconciliation } : {}), + }; + }); + + return { + schemaVersion: COPILOT_CITATION_TRACE_SCHEMA_VERSION, + question: input.question, + answer: input.answer, + citations, + }; +} + +function availabilityFromReconciliation( + envelope: FinancialEvidenceEnvelope +): CopilotCitation['availability'] { + const state = envelope.reconciliation?.state; + if (state === 'material-conflict' || state === 'incomparable') return 'conflicted'; + return 'available'; +} + +function toCitedValue(item: EvidenceItem): CopilotCitedValue { + const financial = item.financial; + return { + evidenceId: item.evidenceId, + metric: financial?.metric ?? item.kind, + value: financial?.value, + ...(financial?.originalValue !== undefined ? { originalValue: financial.originalValue } : {}), + ...(financial?.unit ? { unit: financial.unit } : {}), + ...(financial?.currency ? { currency: financial.currency } : {}), + ...(financial?.period ? { period: financial.period } : {}), + ...(financial?.asOf !== undefined ? { asOf: financial.asOf } : item.freshness.asOf !== undefined ? { asOf: item.freshness.asOf } : {}), + availability: item.availability, + }; +} + +function unmappedCitation(ref: { citationId: string; origin: CopilotCitationOrigin }): CopilotCitation { + return { + citationId: ref.citationId, + origin: ref.origin, + resolution: 'unmapped', + delayed: false, + stale: false, + availability: 'unmapped', + values: [], + }; +} + +function collectCitationRefs(answer: string): Array<{ citationId: string; origin: CopilotCitationOrigin }> { + const refs: Array<{ citationId: string; origin: CopilotCitationOrigin }> = []; + const seen = new Set(); + const push = (citationId: string, origin: CopilotCitationOrigin) => { + if (seen.has(citationId)) return; + seen.add(citationId); + refs.push({ citationId, origin }); + }; + + const segments = parseAnswerSegments(answer); + for (const segment of segments) { + if (segment.kind !== 'text') continue; + for (const part of parseCitationSegments(segment.text)) { + if (part.kind === 'citation') push(part.sourceId, 'inline'); + } + } + for (const segment of segments) { + if (segment.kind !== 'block' || !segment.closed) continue; + const parsed = parseAnswerBlock(segment.body); + if (!parsed.ok || !parsed.block) continue; + for (const id of blockEvidenceIds(parsed.block)) push(id, 'block'); + } + return refs; +} + +function blockEvidenceIds(block: AnswerBlock): string[] { + const ids: string[] = []; + const push = (value: unknown) => { + if (typeof value === 'string' && value.length > 0 && !ids.includes(value)) ids.push(value); + }; + for (const id of block.evidenceIds ?? []) push(id); + if (block.type === 'metric_grid') { + for (const metric of block.metrics) { + for (const id of metric.evidenceIds ?? []) push(id); + } + } + return ids; +} diff --git a/packages/shared/src/evidence/index.ts b/packages/shared/src/evidence/index.ts index 188ffcb1..755b79f3 100644 --- a/packages/shared/src/evidence/index.ts +++ b/packages/shared/src/evidence/index.ts @@ -4,6 +4,14 @@ export { isFinancialEvidenceEnvelope, type BuildFinancialEvidenceInput, } from './financial-evidence.ts'; +export { + resolveCopilotCitationTrace, + COPILOT_CITATION_TRACE_SCHEMA_VERSION, + type CopilotCitation, + type CopilotCitationTrace, + type CopilotCitedValue, + type ResolveCopilotCitationTraceInput, +} from './citation-trace.ts'; export { buildEvidenceBundle, buildReportEvidenceBundle, From 863361f1a455a35c167fc60f2b0137f3f67b8e67 Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:50:00 +0800 Subject: [PATCH 5/6] =?UTF-8?q?test(kernel):=20=E6=8A=A5=E4=BB=B7=E5=9B=9E?= =?UTF-8?q?=E7=AD=94=E5=8F=AF=E4=BB=8E=E9=97=AE=E9=A2=98=E8=BF=BD=E6=BA=AF?= =?UTF-8?q?=E5=88=B0=E5=BC=95=E7=94=A8=E4=BA=8B=E5=AE=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用 ProviderRouter 回退路径经 RunManager 落库并重载。延迟、fallback 与 material-conflict 仍能由引用解析,价格不是候选平均值。 --- .../quote-provenance-acceptance.test.ts | 161 ++++++++++++++++-- 1 file changed, 149 insertions(+), 12 deletions(-) diff --git a/packages/shared/src/kernel/quote-provenance-acceptance.test.ts b/packages/shared/src/kernel/quote-provenance-acceptance.test.ts index 726be6db..f07c9896 100644 --- a/packages/shared/src/kernel/quote-provenance-acceptance.test.ts +++ b/packages/shared/src/kernel/quote-provenance-acceptance.test.ts @@ -2,19 +2,24 @@ import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; -import type { - AgentEvent, - AgentEventPayload, - AgentRunInput, - AgentRuntime, - ApiResult, - CapabilityId, - FinancialDataProvider, - ProviderHealth, - ProviderResult, - RuntimeSession, - ToolDefinition, +import { + reconcileFinancialFacts, + renderCitationMarker, + type AgentEvent, + type AgentEventPayload, + type AgentRunInput, + type AgentRuntime, + type ApiResult, + type CapabilityId, + type FinancialDataProvider, + type ProviderHealth, + type ProviderResult, + type RuntimeSession, + type ToolDefinition, } from '@finagent/core'; +import { renderBlockFence } from '../agent/answer-block-emitter.ts'; +import { buildFinancialEvidence } from '../evidence/financial-evidence.ts'; +import { resolveCopilotCitationTrace } from '../evidence/citation-trace.ts'; import { createCapabilityTools } from '../capabilities/pi-tools.ts'; import { createMarketQuoteCapability } from '../capabilities/manifests/market-quote.ts'; import { JsonFileStore } from '../storage/json-file-store.ts'; @@ -267,4 +272,136 @@ describe('quote provenance acceptance slice (#101, controlled fixture)', () => { const reloaded = await new MessageRepository(store).list(session.id); expect(reloaded[1].financialEvidence).toEqual(messages[1].financialEvidence); }); + + it('traces the reloaded answer from the question to the cited fact without averaging a conflict', async () => { + const tool = makeQuoteTool(); + const toolResult = await tool.execute('quote-1', { symbol: 'aapl.us' }, new AbortController().signal); + const reconciliation = reconcileFinancialFacts( + [ + { provider: 'longbridge', value: 180, currency: 'USD', unit: 'price' }, + { provider: 'massive', value: 250, currency: 'USD', unit: 'price' }, + ], + { version: 'financial-facts.v1', relativeTolerance: 0.01, providerPriority: ['massive'] } + ); + const priorEvidence = toolResult.evidence && typeof toolResult.evidence === 'object' + ? toolResult.evidence as Record + : {}; + const structuredResult = { + data: toolResult.details, + provenance: toolResult.provenance, + evidence: { + ...priorEvidence, + currencies: { lastPrice: 'USD' }, + units: { lastPrice: 'price' }, + reconciliation, + }, + }; + const question = "What is Apple's current price, what time is it from, and where did it come from?"; + const runtime = new ScriptedRuntime(async function* (input) { + const preview = buildFinancialEvidence({ + sessionId: input.sessionId, + runId: input.runId, + toolCalls: [{ + id: 'quote-1', + toolName: 'get_quote', + args: { symbol: 'AAPL.US' }, + startedAt: clock, + completedAt: clock, + status: 'success', + result: structuredResult, + }], + }); + const envelopeId = preview[0]?.id ?? 'fe_missing'; + const answer = [ + `Apple last traded at 200 USD. ${renderCitationMarker('quote-1')}`, + '', + renderBlockFence({ + version: 1, + type: 'metric_grid', + title: 'AAPL.US', + evidenceIds: [envelopeId], + metrics: [{ + label: 'Last', + value: 200, + unit: 'price', + currency: 'USD', + evidenceIds: ['quote-1'], + }], + }), + ].join('\n'); + yield event(input.sessionId, input.runId, 'tool_completed', { + toolCall: { + id: 'quote-1', + toolName: 'get_quote', + args: { symbol: 'AAPL.US' }, + startedAt: clock, + completedAt: clock, + status: 'success', + result: structuredResult, + }, + }); + yield event(input.sessionId, input.runId, 'message_completed', { answer }); + yield event(input.sessionId, input.runId, 'run_completed', { answer, toolCalls: [] }); + }); + const store = new JsonFileStore(dir); + const sessions = new SessionManager({ + sessions: new SessionRepository(store), + messages: new MessageRepository(store), + runs: new RunRepository(store), + piSessionDir: join(dir, 'pi-sessions'), + now: () => clock, + }); + const runs = new RunManager({ + sessions, + runs: new RunRepository(store), + runtime, + now: () => clock, + }); + const session = await sessions.createSession('Citation trace'); + await runs.startRun(session.id, question); + await waitFor(() => !runs.isRunning()); + + const reloaded = await new MessageRepository(new JsonFileStore(dir)).list(session.id); + const user = reloaded.find((message) => message.role === 'user'); + const assistant = reloaded.find((message) => message.role === 'assistant'); + expect(user?.content).toBe(question); + expect(assistant?.financialEvidence?.[0]?.provider).toBe('massive'); + + const trace = resolveCopilotCitationTrace({ + question: user?.content ?? '', + answer: assistant?.content ?? '', + financialEvidence: assistant?.financialEvidence, + }); + const cited = trace.citations.find((citation) => citation.citationId === 'quote-1'); + const byEnvelope = trace.citations.find((citation) => citation.resolution === 'envelope'); + expect(cited).toMatchObject({ + resolution: 'tool_call', + provider: 'massive', + instrumentId: 'XNAS:AAPL', + metric: 'lastPrice', + value: 200, + currency: 'USD', + unit: 'price', + asOf: MARKET_TIME, + retrievedAt: FETCHED_AT, + delayed: true, + stale: false, + availability: 'conflicted', + fallback: { from: 'longbridge', to: 'massive', reason: 'TIMEOUT' }, + runId: assistant?.financialEvidence?.[0]?.runId, + toolName: 'get_quote', + }); + expect(cited?.value).not.toBe(215); + expect(cited?.reconciliation?.state).toBe('material-conflict'); + expect(cited?.reconciliation?.candidates?.map((candidate) => candidate.value)).toEqual([180, 250]); + expect(byEnvelope?.envelopeId).toBe(cited?.envelopeId); + expect(byEnvelope?.values.map((value) => value.evidenceId)).toEqual(cited?.values.map((value) => value.evidenceId)); + + const again = resolveCopilotCitationTrace({ + question: user?.content ?? '', + answer: assistant?.content ?? '', + financialEvidence: JSON.parse(JSON.stringify(assistant?.financialEvidence)), + }); + expect(again).toEqual(trace); + }); }); From e5be9030028c8c1108171c6eea5a577a1ac1850a Mon Sep 17 00:00:00 2001 From: wannT-1 <200890097+wannT-1@users.noreply.github.com> Date: Sun, 18 Oct 2026 09:30:00 +0800 Subject: [PATCH 6/6] =?UTF-8?q?docs(evidence):=20=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E5=86=B2=E7=AA=81=E5=8F=AF=E8=A7=81=E6=80=A7=E4=B8=8E=20Copilo?= =?UTF-8?q?t=20=E5=BC=95=E7=94=A8=E6=BA=AF=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 写明 availability 何时为 conflicted、delayed 与 envelopeId 的含义,以及 resolveCopilotCitationTrace 只读取已持久化的回合数据。 --- docs/evidence-contract.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/docs/evidence-contract.md b/docs/evidence-contract.md index 1dadeee7..5d1dc5f6 100644 --- a/docs/evidence-contract.md +++ b/docs/evidence-contract.md @@ -66,8 +66,12 @@ EvidenceSource ──< EvidenceItem >── EvidenceClaim ──> Answer / Resea - **authority 元数据只在实际已知时填写**(如监管备案 = `{ primary: true, sourceClass: 'regulator' }`),投影从不猜测。 - **冲突与不可用有显式状态位**(`availability: 'conflicted' | 'unavailable'`)。 - 当前投影仅产出 `available`;金融数据的 `reconciliation` 只保留在 - `source.providerMeta`,尚未映射到 `availability`。 + 结构化金融投影在 `reconciliation.state` 为 `material-conflict` 或 + `incomparable` 时把每条事实标为 `conflicted`。选中的规范化数值保持原样, + 候选值留在 `source.providerMeta.reconciliation.candidates`,**不会被平均**。 + `agreement` / `within-tolerance` / 仅有 `providers`+`method` 的旧记录仍是 + `available`。`freshness.delayed` 只在信封 `delayed === true` 时写入。 + `provenance.envelopeId` 保留原始 `fe_*` id,供引用加入。 - **验证状态**首版恒为 `unverified`。现有 `packages/shared/src/research/claim-verifier.ts` 使用独立的 claim ID 与状态契约; 接入 claim 级验证(#13)或来源漂移检测(#20)时需要显式映射。 @@ -79,6 +83,13 @@ EvidenceSource ──< EvidenceItem >── EvidenceClaim ──> Answer / Resea - **Source Inspector(#30)与引用检查器**尚未接入 bundle;当前 Inspector 仍由 `Message.financialEvidence` / `toolCalls` 组装。后续接线可使用 bundle 的来源类别、URL、摘录与溯源字段,但需显式处理现有 ID 空间的映射。 +- **Copilot 引用溯源(#101 的一个切片)**由 + `resolveCopilotCitationTrace` 按需计算,不新增持久化。它从已保存的问题、 + 回答文本和 `financialEvidence` 出发,把行内 `⟦cite:toolCallId⟧` 与已闭合 + `folio-block` 的 `evidenceIds`(工具调用 id 或 `fe_*`)解析到同一条事实: + provider、instrument、metric、unit/currency、`asOf` 与 `retrievedAt`、 + delayed / stale / fallback,以及冲突候选。无法解析的引用留在 + `resolution: 'unmapped'`,不会被静默丢掉,也不会用实时行情重算。 - **评测(#14/#15)**后续可基于 claimId/evidenceId 统计引用覆盖率。 ## 集成示例