/** * ============================================================ * src/memory/turnJournal.ts —— 「一个用户回合」的会话原文记账 * ------------------------------------------------------------ * 把 user 输入与本回合最终 assistant 回答写进 `episodes/*.jsonl`, * 给 `SearchConversations` 提供可检索的历史原文。 * * ★ 为什么是独立模块、而不是塞进 loop.ts: * `runQuery` 不等于「一个用户回合」——子 Agent(tools/agent/agent.ts 直接调 * runQuery,且**携带同一份 workspaceId/sessionId**)和 workflow 的每个 llm/agent 步 * 都会各调一次 runQuery。记在那里会把子任务提示词当成「用户说的话」灌进历史检索, * 污染的正是这个功能要保护的东西。 * * 也不能只留在 `session/runTurn.ts`:TUI 走的是 `ui/hooks/useChat.ts` → runWithPlugins, * **根本不经过 runTurn**。此前的后果是 TUI 对话永远不入库,而一次性的 * `.backfill-.json` 标记又让 SearchConversations 在首次搜索后永久停更 —— * 工具宣称"搜索本机历史会话原文",实际对 TUI 用户静默失效。 * * 所以:实现只有这一份,调用点恰好落在两个真正的「用户回合」边界上 * (runTurn 与 useChat.submit),子 Agent 与 workflow 步一概不记。 * ============================================================ */ import { applyEpisodeRetention, commitEpisodeLearning, episodicMemoryService, finishRetentionSweep, shouldSweepRetention, } from './episodicMemory.js'; import { memoryService } from './memoryService.js'; import { randomUUID } from 'node:crypto'; import { containsForbiddenSecret, sha256 } from './codec.js'; import { enqueueLearningTurn, readExperienceStore, saveTaskSummary, type MemoryTaskSummary, type ExperienceEvidence } from './experienceStore.js'; import { selectTaskEvidence, taskExcerpt } from './taskEvidence.js'; import { scheduleMemoryMaintenance, type LearningModel } from './learning.js'; import type { Message } from '../types.js'; import { enqueueFactTurn, factLearningStatus, hasExplicitAffirmation, scheduleFactLearning } from './factLearning.js'; import { captureDependencies } from './dependencies.js'; import { getWorkingDir } from '../bootstrap/workingDir.js'; import { declinesLearning, userWrittenText } from './userWritten.js'; import { isSystemEventMessage } from '../runtime/systemEvents.js'; import { priorMemoryIds, refersToEarlier } from './recallQuery.js'; import { isReadOnlyShellCommand } from '../tools/bash/semantics.js'; export interface TurnJournalInput { memoryContext?: { access?: string; workspaceId?: string; sessionId?: string; }; userInput: string; userMessageId?: string; cwd?: string; history?: readonly Message[]; learning?: { model: LearningModel; signal?: AbortSignal }; } export interface TurnJournal { /** Observe real host events, not assistant claims or parsed tool text. */ observe(event: { type: string; [key: string]: unknown }): void; /** 回合收尾时调用:从 history 里取本回合最后一条 assistant 消息入库。 */ finish(history: readonly Message[], startIndex: number): Promise; } function messageText(message: Message): string { if (typeof message.content === 'string') return message.content; if (!Array.isArray(message.content)) return ''; return message.content .filter((part): part is Extract => part.type === 'text') .map((part) => part.text) .join('\n'); } function lastAssistantMessage( messages: readonly Message[], start: number, ): Message | undefined { for (let index = messages.length - 1; index >= start; index -= 1) { if (messages[index]?.role === 'assistant') return messages[index]; } return undefined; } /** * The turn's answer as the user read it. When a live answer paused before a * text-drawn diagram, the part already shown was committed as its own * text-only progress message and the model continued in the final one; both * halves are the answer. Only contiguous text-only assistant messages right * before the last one join it (ephemeral notices in between are skipped); tool * rounds and user messages end the run. */ function turnAnswerText(messages: readonly Message[], start: number): string { let index = messages.length - 1; while (index >= start && messages[index]?.role !== 'assistant') index -= 1; if (index < start) return ''; const parts = [messageText(messages[index]!)]; for (let cursor = index - 1; cursor >= start; cursor -= 1) { const message = messages[cursor]!; if (message.role === 'system' && message._ephemeral) continue; if (message.role !== 'assistant' || message.tool_calls?.length || message.presentation !== 'progress') break; parts.unshift(messageText(message)); } return parts.join(''); } const PURE_CONTINUATION = /^(?:继续|接着(?:来|做)?|好的?|行|嗯+|ok(?:ay)?|go on|continue|next|下一步|开始吧?|谢谢|thanks?)[。.!!~\s]*$/i; /** Both current events and legacy previews use the same minimal evidence fields. */ function evidenceArguments(raw: unknown, toolName: string): Record { if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}; const args = raw as Record; const selected: Record = {}; for (const key of ['file_path', 'filePath', 'path', 'notebook_path', 'command', 'cmd', 'subject', 'category', 'scope', 'statement', 'content']) { const value = args[key]; if (typeof value !== 'string') continue; if (key === 'content' && !/Memory|Persona/.test(toolName)) continue; if (!containsForbiddenSecret(value)) selected[key] = value; } if (toolName === 'ApplyPatch') { const patch = args.patch ?? args.input; if (typeof patch === 'string') { selected.patchPaths = [...patch.matchAll(/^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/gm)] .map(match => match[1]!.replace(/\r$/, '')) .filter(path => !containsForbiddenSecret(path)); } } return selected; } /** * 这一回合的用户原话要不要交给事实提炼器。 * * ⚠️ 以前靠一条关键词正则(记住/始终/我是/改成…)决定,于是「我喜欢简洁一点的回答」 * 「我们用 pnpm」这类最常见的偏好说法根本进不了队列——记忆系统对它们静默失明。 * 现在判断交给提炼模型(它本来就会对无事实的回合返回空数组,且逐字证据闸门不变), * 这里只排除**确定**没有事实的输入: * - 斜杠命令:是给宿主的指令,不是陈述; * - 纯续接词(「继续」「好的」):提示词明确要求不展开成事实。明确确认(「是的」 * 「按这个」)不在此列——它们命中下面的旧信号,是确认前文方案的唯一入口; * - 长输入且无明确信号:粘进来的邮件/文档里的第一人称句子能通过逐字引用闸门, * 「引述他人不算」只靠提示词挡。这条是为准确性,不是为省调用。 * 曾经整条丢弃,于是 2300 字的消息末尾那句「以后回答简洁点」永远进不了队列。 * 现在只交出**用户自己写的部分**:去掉围栏代码块和 `>` 引用行(那是贴进来的资料, * 不是陈述);仍超长就保留首尾及有事实信号的中段。不新增任何模型判断, * 逐字证据闸门不变,且交出去的文本就是证据来源,引用只能出自这一段。 */ const FACT_TEXT_MAX_CHARS = 2_000; async function verifiedLearningSettings() { const document = await memoryService.settingsWithVersion().catch(() => undefined); // A recovery copy is suitable for the settings UI, not a new source grant. return document && !document.warning ? document.settings : undefined; } export function factTurnText(userInput: string, explicitSignal: boolean): string | undefined { const value = userInput.trim(); if (!value || value.startsWith('/')) return undefined; if (!explicitSignal && PURE_CONTINUATION.test(value)) return undefined; const written = userWrittenText(value).trim(); if (!written) return undefined; if (explicitSignal || written.length <= FACT_TEXT_MAX_CHARS) return written; // Keep literal spans only. A quoted separator prevents an evidence quote // crossing two non-adjacent excerpts from passing hasUserWrittenQuote. const spans = [{ start: 0, end: 420 }, { start: written.length - 650, end: written.length }]; const signal = /习惯|偏好|默认|统一|约定|决定|改用|不再|每次|always|usually|prefer|default|instead/gi; for (const match of written.matchAll(signal)) { if (spans.some(s => match.index! >= s.start && match.index! < s.end)) continue; if (spans.length >= 5) break; spans.push({ start: Math.max(0, match.index! - 95), end: Math.min(written.length, match.index! + 180) }); } const merged: typeof spans = []; for (const span of spans.sort((a,b) => a.start - b.start)) { const last = merged.at(-1); if (last && span.start <= last.end) last.end = Math.max(last.end, span.end); else merged.push(span); } return merged.map(({ start, end }) => written.slice(start, end)).join('\n> [省略]\n'); } /** * 会话原文的保留清理:节流后台执行,绝不阻塞本回合。 * 与 `clipboardImage::pruneOldTempImages` 同款 fire-and-forget,不需要常驻定时器。 */ function sweepRetentionInBackground(workspaceId: string): void { if (!shouldSweepRetention(workspaceId)) return; void (async () => { try { const settings = await memoryService.settings(); if (!settings.retention) return; await applyEpisodeRetention(workspaceId, settings.retention); } finally { finishRetentionSweep(workspaceId); } })().catch(() => undefined); } /** * 开一次回合记账。缺权限 / 缺 workspaceId / 缺 sessionId 都返回 null(不记,也不报错)—— * 记账是附加能力,绝不能反过来阻断对话。 */ export async function startTurnJournal( input: TurnJournalInput, ): Promise { const context = input.memoryContext; // 判据是 `!== 'denied'`:只要宿主没有明确拒绝记忆访问就记账,`read-only` 也照记。 // 这是**有意放松**的(2026-08-13 明确决定:优先保证检索效果与性能)——收紧成"只有可写 // 权限才记"会让 `-p`(默认 read-only)和部分 Desktop 场景的历史检索大面积失效。 // 真正的隐私边界由 `denied` 与保留窗口(MemorySettings.retention)负责,不靠这里收窄。 if (!context || context.access === 'denied' || !context.workspaceId || !context.sessionId) { return null; } const target = { workspaceId: context.workspaceId, sessionId: context.sessionId }; const turnId = input.userMessageId ?? randomUUID(); const createdAt = Date.now(); const handledQuotes = new Set(); const handledTopics = new Map(); const evidence: ExperienceEvidence[] = []; const inputs = new Map(); const structuredInputs = new Map>(); const paths = new Map(); const cwd = input.cwd ?? getWorkingDir(); let completed = false; let interrupted = false; let userInterrupted = false; let learningRevoked = false; let finished = false; let observedTools = 0; // Supplements are independent human sources, not more text authorized by // the first message. Child journals record facts only (no duplicated answer // or task evidence); lifecycle signals still revoke learning on cancellation. const supplements = new Map>(); // Only the immediately preceding visible answer can be affirmed; never // copy its unverified text from UI history into the durable work queue. const previousAnswerId = hasExplicitAffirmation(input.userInput) ? (() => { const history = input.history ?? []; for (let i = history.length - 1; i >= 0; i--) { const message = history[i]!; if (message.role === 'system' && message._ephemeral) continue; return message.role === 'assistant' && !message.tool_calls?.length ? message.id : undefined; } })() : undefined; const userSignalsChange = /记住|长期(?:偏好|使用|采用)|始终(?:用|使用)|我(?:叫|是|决定(?:用|为)|确定(?:用|为))|以后(?:都|请)|今后(?:都|请)|(?:本项目|本仓库|我们)(?:统一(?:用|为)|决定(?:用|为)|确定(?:用|为)|采用)|架构(?:定为|采用)|技术栈(?:是|采用)|测试入口(?:为|是)|部署(?:使用|条件)|纠正|改成|更新为|不再|不要再|instead|no longer|remember|prefer/i.test(input.userInput) || Boolean(previousAnswerId); const classifyEvidence = (tool: string, ok: boolean, args: string): ExperienceEvidence['kind'] => { if (!ok) return 'failure'; if (/^(?:Edit|Write|MultiEdit|ApplyPatch|Trash)$/.test(tool)) return 'mutation'; if (/^(?:Bash|PowerShell)$/.test(tool)) { let command = args; try { const parsed = JSON.parse(args); command = parsed.command ?? parsed.cmd ?? args; } catch { /* retain preview */ } if (/\b(?:test|typecheck|lint|build|check|doctor|status|verify|deploy)\b/i.test(command)) return 'verification'; return isReadOnlyShellCommand(command) ? 'observation' : 'mutation'; } if (/^(?:LSP|BrowserBatch|BrowserCDP)$/.test(tool)) return 'verification'; return 'observation'; }; const canLearn = (context.access === 'read-write' || context.access === 'local-owner') && !declinesLearning(input.userInput); const originSettings = canLearn ? await verifiedLearningSettings() : undefined; const factAllowed = originSettings?.autoRemember === true && originSettings.factLearning === true; const learningEligible = factAllowed && originSettings?.sessionPipeline?.enabled !== false; const pendingLearningToken = learningEligible ? randomUUID() : undefined; const generation = originSettings?.autoRemember && originSettings.learning?.enabled ? await readExperienceStore(target.workspaceId).then(store => store.generation).catch(error => { process.stderr.write(`[minimal-agent memory] 项目经验暂不可用,未启用本轮学习:${(error as Error).message}\n`); return undefined; }) : undefined; await episodicMemoryService.append({ ...target, role: 'user', learningEligible, content: input.userInput, messageId: turnId, pendingLearningToken, }).catch(() => undefined); sweepRetentionInBackground(target.workspaceId); if (originSettings && input.learning) { const settings = originSettings; const options = { workspaceId: target.workspaceId, model: input.learning.model, signal: input.learning.signal, currentSessionId: target.sessionId, }; if (settings.autoRemember && settings.factLearning) { // A corrupt/temporarily unavailable queue must not block the user turn. const pending = await factLearningStatus(target.workspaceId).catch(error => { process.stderr.write(`[minimal-agent memory] 事实队列暂不可读,本回合跳过恢复:${(error as Error).message}\n`); return undefined; }); if (pending?.pending.length) scheduleFactLearning(options); } // 两条学习路径彼此独立:经验学习关闭、经验库不可读时,会话记忆管线 // 仍应随普通回合调度(管线自己会跳过被关闭的部分),否则「关掉经验 // 学习」会连带让历史会话永远不再被提炼。 const experienceReady = settings.autoRemember && settings.learning?.enabled === true && generation !== undefined; const pipelineReady = settings.autoRemember && settings.factLearning && (settings.sessionPipeline?.enabled ?? true); if (experienceReady || pipelineReady) scheduleMemoryMaintenance(options); } return { observe(event) { if (event.type === 'user_message_committed' && event.inputSource === 'supplement') { const message = event.message as Message | undefined; if (message?.role === 'user' && !isSystemEventMessage(message) && message.id && message.id !== turnId && !supplements.has(message.id)) { if (declinesLearning(messageText(message))) learningRevoked = true; supplements.set(message.id, startTurnJournal({ ...input, userMessageId: message.id, userInput: messageText(message), history: [], }).catch(() => null)); } } if (event.type === 'memory_learning_revoked') learningRevoked = true; if (learningRevoked) for (const journal of supplements.values()) void journal.then(j => j?.observe({ type: 'memory_learning_revoked' })); if (['turn_done', 'interrupted', 'error'].includes(event.type)) { for (const journal of supplements.values()) void journal.then(j => j?.observe(event)); } // assistant_message is emitted before tool_start and contains original // arguments. UI previews are truncated and must never be evidence parsers. if (event.type === 'assistant_message') { const message = event.message as Message | undefined; if (message?.role === 'assistant') for (const call of message.tool_calls ?? []) { try { structuredInputs.set(call.id, evidenceArguments(JSON.parse(call.function.arguments), call.function.name)); } catch { /* Invalid arguments are rejected by execution, not guessed. */ } } } if (event.type === 'tool_start' && typeof event.toolCallId === 'string' && typeof event.argsPreview === 'string') { try { const args = structuredInputs.get(event.toolCallId) ?? evidenceArguments( JSON.parse(event.argsPreview), typeof event.toolName === 'string' ? event.toolName : '', ); inputs.set(event.toolCallId, JSON.stringify(args)); paths.set(event.toolCallId, [args.file_path, args.filePath, args.path, args.notebook_path, ...(Array.isArray(args.patchPaths) ? args.patchPaths : [])].filter(value => typeof value === 'string')); } catch { // A truncated JSON preview cannot be safely classified or copied: // it may contain partial file contents or a partially hidden secret. inputs.set(event.toolCallId, '参数预览不完整,未记录'); } } if (event.type === 'turn_done') completed = event.completionStatus === 'completed'; if (event.type === 'interrupted' || (event.type === 'error' && event.code !== 'compact_failed')) interrupted = true; // Only the user stopping the turn can mean "I misspoke"; an agent-side // failure (llm_error/max_turns/stalled) says nothing about their words. if (event.type === 'interrupted' || (event.type === 'error' && event.code === 'aborted')) userInterrupted = true; if (event.type !== 'tool_end' || typeof event.toolCallId !== 'string' || typeof event.toolName !== 'string' || typeof event.content !== 'string' || typeof event.ok !== 'boolean') return; structuredInputs.delete(event.toolCallId); if (event.executed === false) { inputs.delete(event.toolCallId); paths.delete(event.toolCallId); return; } if (event.ok && /^(RememberMemory|UpdateMemory|ConfirmMemory|SetPersona)$/.test(event.toolName)) { try { const args = JSON.parse(inputs.get(event.toolCallId) ?? '{}'); for (const value of [args.statement, args.content]) if (typeof value === 'string' && value.trim()) handledQuotes.add(value.trim()); if (typeof args.subject === 'string' && args.subject.trim()) { const key = `${args.subject.trim()}\0${args.category ?? ''}\0${args.scope ?? ''}`; handledTopics.set(key, { subject: args.subject.trim(), category: args.category, scope: args.scope }); } } catch { /* The learner still performs semantic dedupe against storage. */ } } // Maintenance cannot learn its own reports. Only actual task tool outputs. if (/Memory|Memories|Persona|Conversations|^Agent|^Advisor/.test(event.toolName)) { inputs.delete(event.toolCallId); paths.delete(event.toolCallId); return; } const excerpt = event.content.length <= 2900 ? event.content : `${event.content.slice(0, 1500)}\n[工具结果中段省略]\n${event.content.slice(-1300)}`; const args = inputs.get(event.toolCallId) ?? '参数未记录'; const text = `调用:${taskExcerpt(args, 1000)}\n结果:${excerpt}`; inputs.delete(event.toolCallId); if (!text.trim() || containsForbiddenSecret(text)) { paths.delete(event.toolCallId); return; } observedTools++; evidence.push({ id: event.toolCallId, tool: event.toolName, ok: event.ok, text, hash: sha256(text), kind: classifyEvidence(event.toolName, event.ok, args) }); const selected = selectTaskEvidence(evidence); evidence.splice(0, evidence.length, ...selected); const retained = new Set(evidence.map(item => item.id)); for (const id of paths.keys()) if (!retained.has(id) && !inputs.has(id)) paths.delete(id); }, async finish(history, startIndex) { if (finished) return; finished = true; await Promise.all([...supplements.values()].map(async pending => { const journal = await pending; await journal?.finish([], 0); })); structuredInputs.clear(); const content = turnAnswerText(history, startIndex); const settings = canLearn && !learningRevoked ? await verifiedLearningSettings() : undefined; const factGrant = Boolean(factAllowed && !userInterrupted && !input.learning?.signal?.aborted && settings?.autoRemember && settings.factLearning); const grant = Boolean(pendingLearningToken && factGrant && settings?.sessionPipeline?.enabled !== false); if (grant && pendingLearningToken) await commitEpisodeLearning(target.workspaceId, target.sessionId, pendingLearningToken, createdAt) .catch(error => process.stderr.write(`[minimal-agent memory] 历史学习回执未写入:${(error as Error).message}\n`)); if (content) await episodicMemoryService.append({ ...target, role: 'assistant', messageId: lastAssistantMessage(history, startIndex)?.id, confirmationEligible: factGrant && completed && !interrupted && !containsForbiddenSecret(content), learningEligible: grant, content, }).catch(() => undefined); if (!settings?.autoRemember) return; let taskSummary: MemoryTaskSummary | undefined; if (generation !== undefined && settings.learning?.enabled && evidence.some(item => item.kind !== 'observation')) { for (const item of evidence) item.dependencies = await captureDependencies(cwd, paths.get(item.id) ?? []); taskSummary = { turnId, sessionId: target.sessionId, cwd, request: taskExcerpt(input.userInput), report: taskExcerpt(content), // A successful command or a normal turn ending never proves task success. status: interrupted || !completed ? (evidence.some(item => item.kind === 'mutation') ? 'partial' : 'uncertain') : 'uncertain', completion: interrupted ? 'interrupted' : completed ? 'completed' : 'incomplete', evidence: [...evidence], observedTools, omittedTools: observedTools - evidence.length, createdAt, }; // 经验摘要与用户事实是两套独立存储:摘要写入失败不得跳过后面的事实入队, // 否则一次经验库磁盘故障会让本回合用户陈述永久离开事实学习队列。 await saveTaskSummary(target.workspaceId, taskSummary, generation) .catch((error) => process.stderr.write( `[minimal-agent memory] 经验摘要写入失败,本回合事实入队继续:${(error as Error).message}\n`, )); } if (input.learning?.signal?.aborted) return; // User facts depend only on what the user said, never on how the agent's // delivery went. ⚠️ This used to share the `completed` gate below, so // "记住我喜欢简洁回答" answered with "好的,已记住" but no tool call landed // as claims_unverified and the fact was silently dropped — the loop broke // in exactly the case memory exists for. const factText = factGrant ? factTurnText(input.userInput, userSignalsChange) : undefined; if (factText) { // Separate stores, separate failures: a corrupt fact queue must not // also cost this turn its experience source below. const queued = await enqueueFactTurn(target.workspaceId, { id: turnId, sessionId: target.sessionId, text: factText, createdAt, handledQuotes: [...handledQuotes], handledTopics: [...handledTopics.values()], confirmationSourceId: previousAnswerId, priorIds: refersToEarlier(input.userInput) ? priorMemoryIds(input.history) : undefined, }).then(() => true, (error) => { process.stderr.write(`[minimal-agent memory] 事实队列不可写,本回合原话未入队:${(error as Error).message}\n`); return false; }); if (queued && input.learning) scheduleFactLearning({ workspaceId: target.workspaceId, model: input.learning.model, signal: input.learning.signal }); } if (generation === undefined || !settings.learning?.enabled) return; // Experiences, unlike facts, are distilled from the agent's own outcome, // which an unverified/incomplete turn cannot vouch for. const eligible = completed && !interrupted && Boolean(content); const failures = evidence.filter(item => item.kind === 'failure'); const mutations = evidence.filter(item => item.kind === 'mutation'); const verifications = evidence.filter(item => item.kind === 'verification'); let lastSuccess = -1; let lastFailure = -1; evidence.forEach((item, index) => { if (!item.ok) lastFailure = index; else lastSuccess = index; }); // A later observation can contain a real verification log. This only // admits evidence for inspection; it does not classify the task as solved. const recoveryCandidate = failures.length > 0 && lastSuccess > lastFailure; // A passing check is itself tool-verified project knowledge (how to test, // build, deploy here). It used to also require a keyword in the user's // message, so "跑一下看看" → `bun test` green taught nothing. const meaningfulChange = mutations.length > 0 || recoveryCandidate || verifications.length > 0; if (eligible && evidence.some(item => item.ok) && meaningfulChange) { // Keep the causal failure, the actual mutations and the final checks. // This is bounded by semantic value, not arbitrary tool-call count. const unique = (items: ExperienceEvidence[]) => items.filter((item, index, all) => all.findIndex(other => other.id === item.id) === index); const selected = unique([ ...failures.slice(0, 2), ...failures.slice(-2), ...mutations.slice(-3), ...verifications.slice(-3), ]); if (selected.length < 10) selected.push(...unique(evidence.filter(item => item.kind === 'observation').slice(-10)).slice(0, 10 - selected.length)); for (const item of selected) item.dependencies = await captureDependencies(cwd, paths.get(item.id) ?? []); // 经验库不可用时同样只降级、不抛出:finish() 抛错会把一次磁盘故障放大成 // 宿主侧整轮失败,而本回合的事实入队早已在上面独立完成。 await enqueueLearningTurn(target.workspaceId, { id: turnId, sessionId: target.sessionId, request: taskExcerpt(input.userInput), outcome: taskExcerpt(content), evidence: selected, createdAt: Date.now(), taskSummary, }, generation).catch((error) => process.stderr.write( `[minimal-agent memory] 学习回合入队失败,本回合事实不受影响:${(error as Error).message}\n`, )); } // A later eligible turn also resumes durable pending work after restart. if (input.learning) scheduleMemoryMaintenance({ workspaceId: target.workspaceId, model: input.learning.model, signal: input.learning.signal, currentSessionId: target.sessionId }); }, }; }