From 34e3f6f8d900ad29aee3c186d466790584381117 Mon Sep 17 00:00:00 2001 From: chengke <404835780@qq.com> Date: Mon, 21 Sep 2026 19:46:52 +0800 Subject: [PATCH] feat(chat): inject profile, lessons, and crystal ranking factors Co-authored-by: Cursor --- src/agent-harness/answer-context.test.ts | 32 ++ src/agent-harness/answer-context.ts | 41 +++ src/agent-harness/runtime.ts | 7 + src/agent-harness/types.ts | 15 + src/domains/chat/commit-turn.test.ts | 332 ++++++++++++++++++--- src/domains/chat/commit-turn.ts | 119 +++++--- src/domains/chat/contracts.ts | 1 + src/domains/chat/index.test.ts | 72 +++++ src/domains/chat/index.ts | 66 +++- src/domains/chat/prompt.ts | 17 ++ src/domains/chat/retrieval-ranking.test.ts | 73 +++++ src/domains/chat/retrieval-ranking.ts | 28 ++ src/domains/chat/route-service.test.ts | 7 +- src/domains/chat/service.test.ts | 7 + src/domains/chat/service.ts | 1 + src/integrations/memento/client.ts | 172 ++++++++++- 16 files changed, 877 insertions(+), 113 deletions(-) create mode 100644 src/domains/chat/retrieval-ranking.test.ts create mode 100644 src/domains/chat/retrieval-ranking.ts diff --git a/src/agent-harness/answer-context.test.ts b/src/agent-harness/answer-context.test.ts index 69646d2..95ae672 100644 --- a/src/agent-harness/answer-context.test.ts +++ b/src/agent-harness/answer-context.test.ts @@ -53,6 +53,38 @@ describe("composeAnswerContext", () => { }) }) + it("puts profile and lessons before knowledge and memory", async () => { + const message = await composeAnswerContext({ + ledger: { + ...makeLedger(), + retrievalCount: 0, + chunks: [], + evidence: [], + }, + memoryItems: [], + profile: { occupation: "教师" }, + agentFeedbackLessons: [ + { + itemId: "fb_1", + text: "查毛利率 引用错了", + reflection: "下次先核对引用", + }, + ], + userText: "再查一次", + }) + + const text = userContentParts(message) + .filter((part) => part.type === "text") + .map((part) => part.text) + .join("\n") + expect(text.indexOf("## User Profile")).toBeLessThan( + text.indexOf("## Lessons from Past Mistakes"), + ) + expect(text).toContain("occupation: 教师") + expect(text).toContain("下次先核对引用") + expect(text).toContain("## User's Question") + }) + it("omits knowledge and memory sections when neither search ran", async () => { const message = await composeAnswerContext({ ledger: { diff --git a/src/agent-harness/answer-context.ts b/src/agent-harness/answer-context.ts index 3f269c6..6c1305a 100644 --- a/src/agent-harness/answer-context.ts +++ b/src/agent-harness/answer-context.ts @@ -1,9 +1,11 @@ import type { ModelMessage } from "ai" import type { + AgentFeedbackLesson, EvidenceLedgerSnapshot, EvidencePart, MemorySearchItem, + WorkspaceProfile, } from "./types" type UserContentParts = Exclude< @@ -16,9 +18,26 @@ export async function composeAnswerContext(input: { readonly memoryItems: readonly MemorySearchItem[] readonly memorySearchAttempted?: boolean readonly userText: string + readonly profile?: WorkspaceProfile | null + readonly agentFeedbackLessons?: readonly AgentFeedbackLesson[] }): Promise { const content: UserContentParts = [] + const profileText = formatProfile(input.profile) + if (profileText) { + appendText(content, `## User Profile\n${profileText}`) + } + + if (input.agentFeedbackLessons && input.agentFeedbackLessons.length > 0) { + appendText( + content, + [ + "## Lessons from Past Mistakes", + ...input.agentFeedbackLessons.map(formatLesson), + ].join("\n\n"), + ) + } + if (input.ledger.evidence.length === 0 && input.ledger.retrievalCount > 0) { appendText( content, @@ -93,6 +112,28 @@ function appendRawText(content: UserContentParts, text: string): void { content.push({ type: "text", text }) } +function formatProfile(profile: WorkspaceProfile | null | undefined): string | null { + if (!profile) return null + const lines = ( + [ + ["name", profile.name], + ["occupation", profile.occupation], + ["ageStage", profile.ageStage], + ["communicationHabit", profile.communicationHabit], + ["workHabit", profile.workHabit], + ] as const + ).flatMap(([key, value]) => + value && value.length > 0 ? [`${key}: ${value}`] : [], + ) + return lines.length > 0 ? lines.join("\n") : null +} + +function formatLesson(lesson: AgentFeedbackLesson): string { + return [lesson.text.trim(), lesson.reflection.trim()] + .filter((part) => part.length > 0) + .join("\n") +} + function formatMemoryItem(item: MemorySearchItem): string { return [ `[memory ref="${item.ref}" kind="${item.kind}"]`, diff --git a/src/agent-harness/runtime.ts b/src/agent-harness/runtime.ts index 586e3c0..2feb046 100644 --- a/src/agent-harness/runtime.ts +++ b/src/agent-harness/runtime.ts @@ -14,6 +14,7 @@ import { createEvidenceLedger } from "./ledger" import { knowhereToolText } from "./knowhere-text" import { memoryToolText } from "./memory-text" import type { + AgentFeedbackLesson, AgentTurn, AgentTurnInput, ContextPolicy, @@ -32,6 +33,7 @@ import type { OutputCitation, OutputManifest, ResolveConnectedAssets, + WorkspaceProfile, } from "./types" import { memorySearchKinds } from "./types" @@ -49,6 +51,8 @@ export type RunAgentHarnessInput = { readonly memoryTools: MemoryToolRuntime readonly resolveConnectedAssets?: ResolveConnectedAssets readonly maxSteps?: number + readonly profile?: WorkspaceProfile | null + readonly agentFeedbackLessons?: readonly AgentFeedbackLesson[] } type HarnessToolState = { @@ -220,6 +224,8 @@ export async function runAgentHarness( memoryItems: state.memoryItems ?? [], memorySearchAttempted: state.memorySearchAttempted === true, userText: input.turn.userText, + profile: input.profile, + agentFeedbackLessons: input.agentFeedbackLessons, }) await ledger.resolveConnectedAssets(input.resolveConnectedAssets) } @@ -250,6 +256,7 @@ export async function runAgentHarness( const ledgerSnapshot = ledger.snapshot() return { manifest, + memoryItems: state.memoryItems ?? [], trace: { intent: state.intent, contextPolicy: state.contextPolicy, diff --git a/src/agent-harness/types.ts b/src/agent-harness/types.ts index f7eb892..4566c2e 100644 --- a/src/agent-harness/types.ts +++ b/src/agent-harness/types.ts @@ -147,6 +147,20 @@ export type MemoryToolRuntime = { readonly search: (input: MemorySearchRequest) => Promise } +export type WorkspaceProfile = { + readonly name?: string + readonly occupation?: string + readonly ageStage?: string + readonly communicationHabit?: string + readonly workHabit?: string +} + +export type AgentFeedbackLesson = { + readonly itemId: string + readonly text: string + readonly reflection: string +} + export type MemoryCitation = { readonly ref: string readonly itemId: string @@ -316,4 +330,5 @@ export type HarnessTrace = { export type HarnessRunResult = { readonly manifest: OutputManifest readonly trace: HarnessTrace + readonly memoryItems: readonly MemorySearchItem[] } diff --git a/src/domains/chat/commit-turn.test.ts b/src/domains/chat/commit-turn.test.ts index 2acf442..e44fa6b 100644 --- a/src/domains/chat/commit-turn.test.ts +++ b/src/domains/chat/commit-turn.test.ts @@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest" const mocks = vi.hoisted(() => ({ handleChatTurn: vi.fn(), captureMemoryTurn: vi.fn(), - recordActivations: vi.fn(), + reportRetrieval: vi.fn(), })) vi.mock("./service", () => ({ @@ -13,7 +13,10 @@ vi.mock("./service", () => ({ vi.mock("@/integrations/memento/client", () => ({ captureMemoryTurn: mocks.captureMemoryTurn, - recordActivations: mocks.recordActivations, + reportRetrieval: mocks.reportRetrieval, + listActivations: vi.fn().mockResolvedValue([]), + getWorkspaceProfile: vi.fn().mockResolvedValue(null), + searchRelevantAgentFeedback: vi.fn().mockResolvedValue([]), })) import { commitChatTurn } from "./commit-turn" @@ -22,11 +25,11 @@ import type { Workspace } from "@/infrastructure/db/schema" describe("commitChatTurn", () => { beforeEach(() => { vi.clearAllMocks() - mocks.recordActivations.mockResolvedValue(undefined) + mocks.reportRetrieval.mockResolvedValue(undefined) mocks.captureMemoryTurn.mockResolvedValue(undefined) }) - it("records fluid memory activations from finalize after a successful turn", async () => { + it("reports retrieved chunks and memory plus the cited subset", async () => { mocks.handleChatTurn.mockImplementation(async (input) => { await input.generateAnswer({ question: "毛利率", @@ -59,17 +62,52 @@ describe("commitChatTurn", () => { const generateAnswer = vi.fn(async () => ({ manifest: { text: "按已有记忆。", - citations: [], + citations: [{ ref: "r1:result:1" }], memoryCitations: [ { ref: "mem:1", itemId: "item_1", kind: "stance" as const }, ], artifacts: [], unresolved: [], }, + memoryItems: [ + { + ref: "mem:1", + itemId: "item_1", + kind: "stance" as const, + text: "cited memory", + }, + { + ref: "mem:2", + itemId: "item_2", + kind: "event" as const, + text: "unused memory", + }, + ], trace: { ledger: { - retrievalCount: 0, - chunks: [], + retrievalCount: 1, + chunks: [ + { + ref: "r1:result:1", + kind: "result" as const, + chunkId: "chunk_1", + content: "cited", + contentPreview: "cited", + chunkType: "text", + score: 0.9, + source: { documentId: "doc_1" }, + }, + { + ref: "r1:result:2", + kind: "result" as const, + chunkId: "chunk_2", + content: "unused", + contentPreview: "unused", + chunkType: "text", + score: 0.4, + source: { documentId: "doc_1" }, + }, + ], assets: [], evidence: [], evidenceText: [], @@ -155,56 +193,256 @@ describe("commitChatTurn", () => { }) expect(Either.isRight(result)).toBe(true) - expect(mocks.captureMemoryTurn).toHaveBeenCalledWith({ + expect(mocks.reportRetrieval).toHaveBeenCalledWith({ workspaceId: "workspace_1", - sessionId: "thread_1", - turns: [ - { - userText: "毛利率", - assistantText: "按已有记忆。", - sourceMessageId: "msg_assistant", - referencedDocumentIds: ["doc_1"], - agentTrace: { - intentTask: "answer", - toolCalls: [ - { tool: "knowhere_search", ok: true, summary: '{"input":{"query":"当轮"}}' }, - ], - referencedDocumentIds: ["doc_1"], + retrieved: [ + { unitType: "crystal_chunk", unitRef: "doc_1:chunk_1" }, + { unitType: "crystal_chunk", unitRef: "doc_1:chunk_2" }, + { unitType: "fluid_memory", unitRef: "item_1" }, + { unitType: "fluid_memory", unitRef: "item_2" }, + ], + cited: [ + { unitType: "crystal_chunk", unitRef: "doc_1:chunk_1" }, + { unitType: "fluid_memory", unitRef: "item_1" }, + ], + }) + }) + + it("reports the retrieved set when nothing was written into the answer", async () => { + mocks.handleChatTurn.mockImplementation(async (input) => { + await input.generateAnswer({ + question: "毛利率", + messages: [], + sources: [], + excludedSourceIds: [], + searchSources: vi.fn(), + }) + return Either.right({ + threadId: "thread_1", + messages: [ + { id: "msg_user", role: "user", content: "毛利率" }, + { + id: "msg_assistant", + role: "assistant", + content: "没有用到检索结果。", + citations: [], }, - recentContext: [ + ], + }) + }) + + const generateAnswer = vi.fn(async () => ({ + manifest: { + text: "没有用到检索结果。", + citations: [], + memoryCitations: [], + artifacts: [], + unresolved: [], + }, + memoryItems: [ + { + ref: "mem:1", + itemId: "item_1", + kind: "stance" as const, + text: "unused memory", + }, + ], + trace: { + ledger: { + retrievalCount: 1, + chunks: [ { - userText: "上次问毛利率", - assistantText: "按文档算。", - agentTrace: { - intentTask: "answer", - toolCalls: [ - { - tool: "knowhere_search", - ok: true, - summary: '{"input":{"query":"毛利率"}}', - }, - ], - referencedDocumentIds: ["doc_1"], - }, + ref: "r1:result:1", + kind: "result" as const, + chunkId: "chunk_1", + content: "unused", + contentPreview: "unused", + chunkType: "text", + score: 0.4, + source: { documentId: "doc_1" }, }, ], + assets: [], + evidence: [], + evidenceText: [], + stopReasons: [], + failureReasons: [], + decisionTraces: [], }, + finalized: true, + priorTurnReads: [], + toolCalls: [], + imageHighlights: [], + validationErrors: [], + revisionsUsed: 0, + }, + })) + + const result = await commitChatTurn({ + workspace: makeWorkspace(), + sources: [], + question: "毛利率", + excludedSourceIds: [], + retrieval: { query: vi.fn() }, + generateAnswer, + repository: { + ensureDefaultChatThread: vi.fn(), + findChatThreadInWorkspace: vi.fn(), + listMessagesForThread: vi.fn().mockResolvedValue([]), + appendMessageToThread: vi.fn(), + }, + }) + + expect(Either.isRight(result)).toBe(true) + expect(mocks.reportRetrieval).toHaveBeenCalledWith({ + workspaceId: "workspace_1", + retrieved: [ + { unitType: "crystal_chunk", unitRef: "doc_1:chunk_1" }, + { unitType: "fluid_memory", unitRef: "item_1" }, ], + cited: [], + }) + }) + + it("reports an empty retrieved set when search ran and found nothing", async () => { + mocks.handleChatTurn.mockImplementation(async (input) => { + await input.generateAnswer({ + question: "毛利率", + messages: [], + sources: [], + excludedSourceIds: [], + searchSources: vi.fn(), + }) + return Either.right({ + threadId: "thread_1", + messages: [ + { id: "msg_user", role: "user", content: "毛利率" }, + { id: "msg_assistant", role: "assistant", content: "没有相关记忆。", citations: [] }, + ], + }) }) - expect(mocks.recordActivations).toHaveBeenCalledWith([ - { - workspaceId: "workspace_1", - unitType: "crystal_chunk", - unitRef: "doc_1:chunk_1", + + const result = await commitChatTurn({ + workspace: makeWorkspace(), + sources: [], + question: "毛利率", + excludedSourceIds: [], + retrieval: { query: vi.fn() }, + generateAnswer: vi.fn(async () => ({ + manifest: { + text: "没有相关记忆。", + citations: [], + memoryCitations: [], + artifacts: [], + unresolved: [], + }, + memoryItems: [], + trace: { + ledger: { + retrievalCount: 0, + chunks: [], + assets: [], + evidence: [], + evidenceText: [], + stopReasons: [], + failureReasons: [], + decisionTraces: [], + }, + finalized: true, + priorTurnReads: [], + toolCalls: [ + { + tool: "memory_search", + ok: true, + inputSummary: {}, + outputSummary: {}, + startedAt: "2026-09-21T00:00:00.000Z", + durationMs: 1, + }, + ], + imageHighlights: [], + validationErrors: [], + revisionsUsed: 0, + }, + })), + repository: { + ensureDefaultChatThread: vi.fn(), + findChatThreadInWorkspace: vi.fn(), + listMessagesForThread: vi.fn().mockResolvedValue([]), + appendMessageToThread: vi.fn(), }, - ]) - expect(mocks.recordActivations).toHaveBeenCalledWith([ - { - workspaceId: "workspace_1", - unitType: "fluid_memory", - unitRef: "item_1", + }) + + expect(Either.isRight(result)).toBe(true) + expect(mocks.reportRetrieval).toHaveBeenCalledWith({ + workspaceId: "workspace_1", + retrieved: [], + cited: [], + }) + }) + + it("does not report when the turn did not retrieve", async () => { + mocks.handleChatTurn.mockImplementation(async (input) => { + await input.generateAnswer({ + question: "你好", + messages: [], + sources: [], + excludedSourceIds: [], + searchSources: vi.fn(), + }) + return Either.right({ + threadId: "thread_1", + messages: [ + { id: "msg_user", role: "user", content: "你好" }, + { id: "msg_assistant", role: "assistant", content: "你好。", citations: [] }, + ], + }) + }) + + const result = await commitChatTurn({ + workspace: makeWorkspace(), + sources: [], + question: "你好", + excludedSourceIds: [], + retrieval: { query: vi.fn() }, + generateAnswer: vi.fn(async () => ({ + manifest: { + text: "你好。", + citations: [], + memoryCitations: [], + artifacts: [], + unresolved: [], + }, + memoryItems: [], + trace: { + ledger: { + retrievalCount: 0, + chunks: [], + assets: [], + evidence: [], + evidenceText: [], + stopReasons: [], + failureReasons: [], + decisionTraces: [], + }, + finalized: true, + priorTurnReads: [], + toolCalls: [], + imageHighlights: [], + validationErrors: [], + revisionsUsed: 0, + }, + })), + repository: { + ensureDefaultChatThread: vi.fn(), + findChatThreadInWorkspace: vi.fn(), + listMessagesForThread: vi.fn().mockResolvedValue([]), + appendMessageToThread: vi.fn(), }, - ]) + }) + + expect(Either.isRight(result)).toBe(true) + expect(mocks.reportRetrieval).not.toHaveBeenCalled() }) }) diff --git a/src/domains/chat/commit-turn.ts b/src/domains/chat/commit-turn.ts index 97c159e..f829382 100644 --- a/src/domains/chat/commit-turn.ts +++ b/src/domains/chat/commit-turn.ts @@ -1,9 +1,15 @@ import { Either } from "effect" -import type { MemoryCitation } from "@/agent-harness" +import type { + EvidenceAsset, + EvidenceChunk, + HarnessRunResult, + MemoryCitation, +} from "@/agent-harness" import { captureMemoryTurn, - recordActivations, + reportRetrieval, + type MementoRetrievalUnit, } from "@/integrations/memento/client" import { readChatAgentTrace, toRecentCaptureContext } from "./agent-trace" import { generateAgenticOutputManifest } from "./prompt" @@ -17,13 +23,18 @@ import { type CommitChatTurnInput = Parameters[0] /** - * Production chat-turn commit used by the HTTP route: answer → persist → - * capture fluid memory on Memento → record cited crystal/memory activations. + * Production chat-turn commit: answer → persist → capture fluid memory + * → report this turn's retrieved set and cited subset to Memento. */ export async function commitChatTurn( input: CommitChatTurnInput, ): Promise> { let memoryCitations: readonly MemoryCitation[] = [] + let citedChunkRefs: readonly { readonly ref: string }[] = [] + let retrievedChunks: readonly EvidenceChunk[] = [] + let retrievedAssets: readonly EvidenceAsset[] = [] + let retrievedMemoryItems: readonly { readonly itemId: string }[] = [] + let didRetrieve = false const result = await handleChatTurn({ ...input, generateAnswer: async (generateInput) => { @@ -31,6 +42,11 @@ export async function commitChatTurn( ...generateInput, }) memoryCitations = generated.manifest.memoryCitations + citedChunkRefs = generated.manifest.citations + retrievedChunks = generated.trace.ledger.chunks + retrievedAssets = generated.trace.ledger.assets + retrievedMemoryItems = generated.memoryItems + didRetrieve = turnHadRetrieval(generated) return generated }, }) @@ -65,14 +81,21 @@ export async function commitChatTurn( }, ], }) - void recordChunkActivations({ - workspaceId: input.workspace.id, - citations: assistantMessage.citations, - }) - void recordMemoryActivations({ - workspaceId: input.workspace.id, - memoryCitations, - }) + if (didRetrieve) { + void reportRetrieval({ + workspaceId: input.workspace.id, + retrieved: [ + ...toChunkUnits(retrievedChunks), + ...toMemoryUnits(retrievedMemoryItems), + ], + cited: [ + ...toChunkUnits( + resolveCitedChunks(citedChunkRefs, retrievedChunks, retrievedAssets), + ), + ...toMemoryUnits(memoryCitations), + ], + }) + } } return result @@ -91,52 +114,54 @@ export async function commitAgenticChatTurn( }) } -/** - * Fire-and-forget activation ledger write for crystal chunks actually cited - * in this turn's answer. Only citations with both a documentId and a - * chunkId count — a citation missing either can't be identified down to a - * chunk (see ChatCitationView / RetrievalResultView). - */ -export async function recordChunkActivations(input: { - readonly workspaceId: string - readonly citations: readonly ChatCitationView[] | undefined -}): Promise { - const activationInputs = (input.citations ?? []).flatMap((citation) => { - const documentId = citation.source.documentId - const chunkId = citation.chunkId +function turnHadRetrieval(generated: HarnessRunResult): boolean { + if (generated.trace.ledger.retrievalCount > 0) return true + if (generated.trace.ledger.chunks.length > 0) return true + if (generated.memoryItems.length > 0) return true + return generated.trace.toolCalls.some( + (call) => call.tool === "memory_search" || call.tool === "knowhere_search", + ) +} + +function toChunkUnits( + chunks: readonly EvidenceChunk[], +): MementoRetrievalUnit[] { + return chunks.flatMap((chunk) => { + const documentId = chunk.source.documentId + const chunkId = chunk.chunkId if (!documentId || !chunkId) return [] return [ { - workspaceId: input.workspaceId, unitType: "crystal_chunk" as const, - unitRef: toChunkUnitRef({ documentId, chunkId }), + unitRef: `${documentId}:${chunkId}`, }, ] }) - await recordActivations(activationInputs) } -/** - * Fire-and-forget activation ledger write for fluid memory items actually - * cited in this turn's finalize output. - */ -export async function recordMemoryActivations(input: { - readonly workspaceId: string - readonly memoryCitations: readonly MemoryCitation[] -}): Promise { - const activationInputs = input.memoryCitations.map((citation) => ({ - workspaceId: input.workspaceId, - unitType: "fluid_memory" as const, - unitRef: citation.itemId, - })) - await recordActivations(activationInputs) +function resolveCitedChunks( + citations: readonly { readonly ref: string }[], + chunks: readonly EvidenceChunk[], + assets: readonly EvidenceAsset[], +): EvidenceChunk[] { + const chunksByRef = new Map(chunks.map((chunk) => [chunk.ref, chunk])) + const assetsByRef = new Map(assets.map((asset) => [asset.ref, asset])) + return citations.flatMap((citation) => { + const direct = chunksByRef.get(citation.ref) + if (direct) return [direct] + const asset = assetsByRef.get(citation.ref) + const fromAsset = asset ? chunksByRef.get(asset.chunkRef) : undefined + return fromAsset ? [fromAsset] : [] + }) } -function toChunkUnitRef(input: { - readonly documentId: string - readonly chunkId: string -}): string { - return `${input.documentId}:${input.chunkId}` +function toMemoryUnits( + items: readonly { readonly itemId: string }[], +): MementoRetrievalUnit[] { + return items.map((item) => ({ + unitType: "fluid_memory" as const, + unitRef: item.itemId, + })) } function collectCitationDocumentIds( diff --git a/src/domains/chat/contracts.ts b/src/domains/chat/contracts.ts index 969a619..282688c 100644 --- a/src/domains/chat/contracts.ts +++ b/src/domains/chat/contracts.ts @@ -65,6 +65,7 @@ export type GenerateAnswer = (input: { export type AnswerQuestionInput = { question: string + workspaceId?: string namespace: string namespaces?: readonly string[] sources: readonly Source[] diff --git a/src/domains/chat/index.test.ts b/src/domains/chat/index.test.ts index b1c55be..849753e 100644 --- a/src/domains/chat/index.test.ts +++ b/src/domains/chat/index.test.ts @@ -31,6 +31,7 @@ const loggerMock = vi.hoisted(() => ({ warn: vi.fn(), error: vi.fn(), })); +const listActivationsMock = vi.hoisted(() => vi.fn().mockResolvedValue([])); vi.mock("@/lib/logger", () => ({ logger: { @@ -40,11 +41,19 @@ vi.mock("@/lib/logger", () => ({ }, })); +vi.mock("@/integrations/memento/client", () => ({ + listActivations: listActivationsMock, + getWorkspaceProfile: vi.fn().mockResolvedValue(null), + searchRelevantAgentFeedback: vi.fn().mockResolvedValue([]), +})); + afterEach(() => { vi.restoreAllMocks(); loggerMock.info.mockReset(); loggerMock.warn.mockReset(); loggerMock.error.mockReset(); + listActivationsMock.mockReset(); + listActivationsMock.mockResolvedValue([]); delete process.env.AI_GATEWAY_API_KEY; }); @@ -109,6 +118,63 @@ describe("answerQuestionWithRetrieval", () => { referencedDocumentIds: [], }, }); + expect(listActivationsMock).not.toHaveBeenCalled(); + }); + + it("multiplies Knowhere scores by the Memento ranking factor when a ledger row exists", async () => { + listActivationsMock.mockResolvedValue([ + { unitRef: "doc_included:chunk_1", rankingFactor: 1.25 }, + ]); + const retrieval = { + query: vi.fn().mockResolvedValue({ + results: [ + makeRetrievalResult({ + chunkId: "chunk_1", + score: 0.8, + source: { documentId: "doc_included" }, + }), + makeRetrievalResult({ + chunkId: "chunk_new", + score: 0.6, + source: { documentId: "doc_included" }, + }), + ], + evidenceText: "Grounding content", + referencedChunks: [], + namespace: "notebook-workspace", + query: "What does the document say?", + routerUsed: "workflow_single_step", + answerText: null, + }), + }; + let mixedScores: readonly (number | null)[] = []; + const generateAnswer = vi.fn(async ({ searchSources }) => { + const response = await searchSources({ + query: "What does the document say?", + }); + mixedScores = response.results.map((result) => result.score); + return makeHarnessRunResult("The answer is grounded."); + }); + + await Effect.runPromise( + answerQuestionWithRetrieval({ + question: "What does the document say?", + workspaceId: "workspace_1", + namespace: "notebook-workspace", + sources: [makeSource({ knowhereDocumentId: "doc_included" })], + excludedSourceIds: [], + retrieval, + generateAnswer, + messages: [], + }), + ); + + expect(listActivationsMock).toHaveBeenCalledWith({ + workspaceId: "workspace_1", + unitType: "crystal_chunk", + unitRefs: ["doc_included:chunk_1", "doc_included:chunk_new"], + }); + expect(mixedScores).toEqual([1, 0.6]); }); it("returns a slim Notebook TRACE and does not pass the Knowhere TRACE through", async () => { @@ -1189,6 +1255,7 @@ describe("answerQuestionWithRetrieval", () => { ], unresolved: [], }, + memoryItems: [], trace: { ...makeHarnessRunResult("").trace, finalized: true, @@ -1931,6 +1998,7 @@ describe("answerQuestionWithRetrieval", () => { ], unresolved: [], }, + memoryItems: [], trace: { ledger: { retrievalCount: 1, @@ -2280,6 +2348,7 @@ describe("answerQuestionWithRetrieval", () => { ], unresolved: [], }, + memoryItems: [], trace: { ...makeHarnessRunResult("").trace, finalized: true, @@ -2403,6 +2472,7 @@ describe("answerQuestionWithRetrieval", () => { ], unresolved: [], }, + memoryItems: [], trace: { ...makeHarnessRunResult("").trace, finalized: true, @@ -3162,6 +3232,7 @@ function makeHarnessRunResult(text: string): HarnessRunResult { artifacts: [], unresolved: [], }, + memoryItems: [], trace: { ledger: { retrievalCount: 0, @@ -3213,6 +3284,7 @@ function makeHarnessRunResultWithLedger( artifacts: input.artifacts ?? [], unresolved: [], }, + memoryItems: [], trace: { ...makeHarnessRunResult("").trace, imageHighlights: input.imageHighlights ?? [], diff --git a/src/domains/chat/index.ts b/src/domains/chat/index.ts index 9dd0f5d..5aba30b 100644 --- a/src/domains/chat/index.ts +++ b/src/domains/chat/index.ts @@ -49,6 +49,11 @@ import { import type { HardenableRetrievalResult } from "./media-asset-hardening" import { notebookKnowhereTools } from "./knowhere-tools" import { toChatAgentTrace } from "./agent-trace" +import { listActivations } from "@/integrations/memento/client" +import { + applyCrystalChunkRankingFactors, + crystalChunkUnitRef, +} from "./retrieval-ranking" const DEFAULT_TOP_K = 8 const MAX_AGENTIC_TOP_K = 12 @@ -235,13 +240,16 @@ export const answerQuestionWithRetrieval = ( ) { throw queryFailures[0] } - return mergeRetrievalResponses( - queryResponses, - retrievalPlan, - getAgenticMergedEvidenceLimits({ - namespaceCount: queryResponses.length, - topK: queryInput.topK, - }), + return mixMergedRetrievalScores( + input.workspaceId, + mergeRetrievalResponses( + queryResponses, + retrievalPlan, + getAgenticMergedEvidenceLimits({ + namespaceCount: queryResponses.length, + topK: queryInput.topK, + }), + ), ) } @@ -815,6 +823,50 @@ function getRetrievalNamespaces(input: AnswerQuestionInput): readonly string[] { return namespaces } +async function mixMergedRetrievalScores( + workspaceId: string | undefined, + response: AgenticRetrievalResponse, +): Promise { + if (!workspaceId) return response + const unitRefs = [ + ...new Set( + response.results.flatMap((result) => { + const unitRef = crystalChunkUnitRef(result) + return unitRef ? [unitRef] : [] + }), + ), + ] + if (unitRefs.length === 0) return response + + try { + const activations = await listActivations({ + workspaceId, + unitType: "crystal_chunk", + unitRefs, + }) + if (activations.length === 0) return response + return { + ...response, + results: applyCrystalChunkRankingFactors( + response.results, + new Map( + activations.map((activation) => [ + activation.unitRef, + activation.rankingFactor, + ]), + ), + ), + } + } catch (error) { + logger.warn("chat-agent: failed to mix retrieval ranking factors", { + workspaceId, + unitRefCount: unitRefs.length, + error: formatUnknownError(error), + }) + return response + } +} + function mergeRetrievalResponses( responses: readonly RetrievalQueryResponse[], retrievalPlan: AgenticRetrievalPlan, diff --git a/src/domains/chat/prompt.ts b/src/domains/chat/prompt.ts index d48dcc0..d55b86a 100644 --- a/src/domains/chat/prompt.ts +++ b/src/domains/chat/prompt.ts @@ -20,6 +20,10 @@ import { emptyFolderSearchMessage, isEmptyFolderScope, } from "./retrieval" +import { + getWorkspaceProfile, + searchRelevantAgentFeedback, +} from "@/integrations/memento/client" import { mementoMemoryTools } from "@/integrations/memento/memory-tools" import { notebookKnowhereTools } from "./knowhere-tools" @@ -60,6 +64,17 @@ export const generateAgenticOutputManifestEffect = ( messageCharLength: turn.userText.length, }) + const extras = yield* Effect.tryPromise(() => + Promise.all([ + getWorkspaceProfile(input.workspaceId), + searchRelevantAgentFeedback({ + workspaceId: input.workspaceId, + query: input.question, + }), + ]), + ) + const [profile, agentFeedbackLessons] = extras + const result = yield* Effect.tryPromise(() => runAgentHarness({ model: CHAT_MODEL, @@ -73,6 +88,8 @@ export const generateAgenticOutputManifestEffect = ( memoryTools: mementoMemoryTools.createRuntime({ workspaceId: input.workspaceId, }), + profile, + agentFeedbackLessons, ...(input.resolveConnectedAssets ? { resolveConnectedAssets: input.resolveConnectedAssets } : {}), diff --git a/src/domains/chat/retrieval-ranking.test.ts b/src/domains/chat/retrieval-ranking.test.ts new file mode 100644 index 0000000..d3132ee --- /dev/null +++ b/src/domains/chat/retrieval-ranking.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from "vitest" +import type { RetrievalResult } from "@ontos-ai/knowhere-sdk" + +import { + applyCrystalChunkRankingFactors, + crystalChunkUnitRef, +} from "./retrieval-ranking" + +describe("crystalChunkUnitRef", () => { + it("matches the reported crystal unit ref", () => { + expect( + crystalChunkUnitRef({ + chunkId: "chunk_1", + source: { documentId: "doc_1" }, + }), + ).toBe("doc_1:chunk_1") + }) + + it("returns null when the Knowhere row has no chunk id", () => { + expect( + crystalChunkUnitRef({ + source: { documentId: "doc_1" }, + }), + ).toBeNull() + }) +}) + +describe("applyCrystalChunkRankingFactors", () => { + it("leaves Knowhere scores unchanged when there is no ledger row", () => { + const results = [ + makeResult({ chunkId: "chunk_new", score: 0.8 }), + makeResult({ chunkId: "chunk_old", score: 0.4 }), + ] + expect( + applyCrystalChunkRankingFactors(results, new Map()), + ).toEqual(results) + }) + + it("multiplies only rows that have a ranking factor", () => { + const results = [ + makeResult({ chunkId: "chunk_used", score: 0.8 }), + makeResult({ chunkId: "chunk_new", score: 0.6 }), + ] + const mixed = applyCrystalChunkRankingFactors( + results, + new Map([["doc_1:chunk_used", 1.25]]), + ) + expect(mixed[0]?.score).toBeCloseTo(1, 5) + expect(mixed[1]?.score).toBe(0.6) + }) + + it("leaves a null Knowhere score alone", () => { + const results = [makeResult({ chunkId: "chunk_used", score: null })] + expect( + applyCrystalChunkRankingFactors( + results, + new Map([["doc_1:chunk_used", 1.5]]), + ), + ).toEqual(results) + }) +}) + +function makeResult( + overrides: Partial & { readonly chunkId?: string }, +): RetrievalResult { + return { + content: "text", + chunkType: "text", + score: 0.5, + source: { documentId: "doc_1" }, + ...overrides, + } +} diff --git a/src/domains/chat/retrieval-ranking.ts b/src/domains/chat/retrieval-ranking.ts new file mode 100644 index 0000000..d1504c1 --- /dev/null +++ b/src/domains/chat/retrieval-ranking.ts @@ -0,0 +1,28 @@ +import type { RetrievalResult } from "@ontos-ai/knowhere-sdk" + +export function crystalChunkUnitRef(result: { + readonly chunkId?: string + readonly source: { readonly documentId?: string | null } +}): string | null { + const documentId = result.source.documentId + const chunkId = result.chunkId + if (!documentId || !chunkId) return null + return `${documentId}:${chunkId}` +} + +/** + * Multiply Knowhere scores by Memento ranking factors. + * Missing unitRef or missing factor leaves the Knowhere score unchanged. + */ +export function applyCrystalChunkRankingFactors( + results: readonly RetrievalResult[], + factorByUnitRef: ReadonlyMap, +): RetrievalResult[] { + return results.map((result) => { + const unitRef = crystalChunkUnitRef(result) + if (!unitRef || result.score == null) return result + const factor = factorByUnitRef.get(unitRef) + if (factor == null) return result + return { ...result, score: result.score * factor } + }) +} diff --git a/src/domains/chat/route-service.test.ts b/src/domains/chat/route-service.test.ts index bafe30f..f87cf38 100644 --- a/src/domains/chat/route-service.test.ts +++ b/src/domains/chat/route-service.test.ts @@ -27,7 +27,7 @@ const mocks = vi.hoisted(() => ({ softDeleteChatThread: vi.fn(), startBackgroundReconciliation: vi.fn(), captureMemoryTurn: vi.fn(), - recordActivations: vi.fn(), + reportRetrieval: vi.fn(), })) vi.mock("ai", async (importOriginal) => { @@ -67,7 +67,10 @@ vi.mock("@/domains/sources/background-reconcile", () => ({ vi.mock("@/integrations/memento/client", () => ({ captureMemoryTurn: mocks.captureMemoryTurn, - recordActivations: mocks.recordActivations, + reportRetrieval: mocks.reportRetrieval, + listActivations: vi.fn().mockResolvedValue([]), + getWorkspaceProfile: vi.fn().mockResolvedValue(null), + searchRelevantAgentFeedback: vi.fn().mockResolvedValue([]), })) vi.mock("@/domains/sources/workflow-runtime", () => ({ diff --git a/src/domains/chat/service.test.ts b/src/domains/chat/service.test.ts index 0b2bf2c..88ed074 100644 --- a/src/domains/chat/service.test.ts +++ b/src/domains/chat/service.test.ts @@ -3,6 +3,12 @@ import type { RetrievalResult } from "@ontos-ai/knowhere-sdk"; import { Either } from "effect"; import type { HarnessRunResult } from "@/agent-harness"; +vi.mock("@/integrations/memento/client", () => ({ + listActivations: vi.fn().mockResolvedValue([]), + getWorkspaceProfile: vi.fn().mockResolvedValue(null), + searchRelevantAgentFeedback: vi.fn().mockResolvedValue([]), +})); + import { handleChatTurn } from "./service"; import type { ChatMessage, ChatThread, Source, Workspace } from "@/infrastructure/db/schema"; @@ -452,6 +458,7 @@ function makeHarnessRunResult(text: string): HarnessRunResult { artifacts: [], unresolved: [], }, + memoryItems: [], trace: { ledger: { retrievalCount: 0, diff --git a/src/domains/chat/service.ts b/src/domains/chat/service.ts index 39100eb..0dc0717 100644 --- a/src/domains/chat/service.ts +++ b/src/domains/chat/service.ts @@ -132,6 +132,7 @@ export const handleChatTurnEffect = (input: ChatTurnInput) => const answer = yield* answerQuestionWithRetrieval({ question: input.question, + workspaceId: input.workspace.id, namespace: input.workspace.namespace, namespaces: [sharedLibraryNamespace], sources: readySources, diff --git a/src/integrations/memento/client.ts b/src/integrations/memento/client.ts index 518f847..fb72d6b 100644 --- a/src/integrations/memento/client.ts +++ b/src/integrations/memento/client.ts @@ -30,12 +30,16 @@ export type MementoCaptureInput = { readonly turns: readonly MementoCaptureTurn[] } -export type MementoActivationInput = { - readonly workspaceId: string +export type MementoRetrievalUnit = { readonly unitType: "fluid_memory" | "crystal_chunk" readonly unitRef: string } +export type MementoActivation = { + readonly unitRef: string + readonly rankingFactor: number +} + export async function captureMemoryTurn( input: MementoCaptureInput, ): Promise { @@ -50,20 +54,168 @@ export async function captureMemoryTurn( } } -export async function recordActivations( - activations: readonly MementoActivationInput[], -): Promise { - if (activations.length === 0) return +export async function reportRetrieval(input: { + readonly workspaceId: string + readonly retrieved: readonly MementoRetrievalUnit[] + readonly cited: readonly MementoRetrievalUnit[] +}): Promise { + try { + await postJson("/activations", { + workspaceId: input.workspaceId, + retrieved: input.retrieved, + cited: input.cited, + }) + } catch (error) { + logger.warn("chat: failed to report retrieval", { + workspaceId: input.workspaceId, + retrievedCount: input.retrieved.length, + citedCount: input.cited.length, + error: summarizeUnknownError(error), + }) + } +} +export type MementoWorkspaceProfile = { + readonly name?: string + readonly occupation?: string + readonly ageStage?: string + readonly communicationHabit?: string + readonly workHabit?: string +} + +export type MementoAgentFeedbackLesson = { + readonly itemId: string + readonly text: string + readonly reflection: string +} + +export async function getWorkspaceProfile( + workspaceId: string, +): Promise { try { - await postJson("/activations", { activations }) + const body = await getJson( + `/profile?${new URLSearchParams({ workspaceId }).toString()}`, + ) + return parseWorkspaceProfile(body) } catch (error) { - logger.warn("chat: failed to record activations", { - workspaceId: activations[0]?.workspaceId, - count: activations.length, + logger.warn("chat: failed to load workspace profile", { + workspaceId, error: summarizeUnknownError(error), }) + return null + } +} + +export async function searchRelevantAgentFeedback(input: { + readonly workspaceId: string + readonly query: string +}): Promise { + try { + const query = new URLSearchParams({ + workspaceId: input.workspaceId, + query: input.query, + }) + const body = await getJson(`/agent-feedback/relevant?${query.toString()}`) + return parseAgentFeedbackLessons(body) + } catch (error) { + logger.warn("chat: failed to load agent feedback lessons", { + workspaceId: input.workspaceId, + error: summarizeUnknownError(error), + }) + return [] + } +} + +function parseWorkspaceProfile(body: unknown): MementoWorkspaceProfile | null { + if (typeof body !== "object" || body === null) return null + const profile = Reflect.get(body, "profile") + if (profile === null) return null + if (typeof profile !== "object" || profile === null) return null + const slots = ["name", "occupation", "ageStage", "communicationHabit", "workHabit"] as const + const parsed: Record = {} + for (const slot of slots) { + const value = Reflect.get(profile, slot) + if (typeof value === "string" && value.length > 0) parsed[slot] = value + } + return Object.keys(parsed).length > 0 ? parsed : null +} + +function parseAgentFeedbackLessons( + body: unknown, +): readonly MementoAgentFeedbackLesson[] { + if (typeof body !== "object" || body === null) return [] + const items = Reflect.get(body, "items") + if (!Array.isArray(items)) return [] + return items.flatMap((item) => { + if (typeof item !== "object" || item === null) return [] + const itemId = Reflect.get(item, "itemId") + const text = Reflect.get(item, "text") + const payload = Reflect.get(item, "payload") + if (typeof itemId !== "string" || itemId.length === 0) return [] + if (typeof text !== "string" || text.length === 0) return [] + if (typeof payload !== "object" || payload === null) return [] + const reflection = Reflect.get(payload, "reflection") + if (typeof reflection !== "string" || reflection.length === 0) return [] + return [{ itemId, text, reflection }] + }) +} + +export async function listActivations(input: { + readonly workspaceId: string + readonly unitType: MementoRetrievalUnit["unitType"] + readonly unitRefs: readonly string[] +}): Promise { + if (input.unitRefs.length === 0) return [] + const query = new URLSearchParams({ + workspaceId: input.workspaceId, + unitType: input.unitType, + unitRefs: input.unitRefs.join(","), + }) + const body = await getJson(`/activations?${query.toString()}`) + return parseActivations(body) +} + +function parseActivations(body: unknown): readonly MementoActivation[] { + if (typeof body !== "object" || body === null) { + throw new Error("memento /activations: invalid response") + } + const activations = Reflect.get(body, "activations") + if (!Array.isArray(activations)) { + throw new Error("memento /activations: invalid response") + } + return activations.flatMap((activation) => { + if (typeof activation !== "object" || activation === null) return [] + const unitRef = Reflect.get(activation, "unitRef") + const rankingFactor = Reflect.get(activation, "rankingFactor") + if (typeof unitRef !== "string" || unitRef.length === 0) return [] + if (typeof rankingFactor !== "number" || !Number.isFinite(rankingFactor)) { + return [] + } + return [{ unitRef, rankingFactor }] + }) +} + +async function getJson(path: string): Promise { + const { status, body } = await Effect.runPromise( + Effect.gen(function* () { + const { baseUrl, serviceKey } = readMementoConfig() + const request = HttpClientRequest.get(`${baseUrl}${path}`).pipe( + HttpClientRequest.setHeader( + "Authorization", + `Bearer ${serviceKey}`, + ), + ) + const response = yield* HttpClient.execute(request) + return { + status: response.status, + body: yield* response.json, + } + }).pipe(Effect.provide(FetchHttpClient.layer)), + ) + if (status < 200 || status >= 300) { + throw new Error(`memento ${path}: HTTP ${status}`) } + return body } async function postJson(path: string, body: unknown): Promise {