/** Workspace-scoped learned experience. Never rewrites user facts or instructions. * One atomically replaced document commits the queue, records and run receipt * together. Immutable pre-commit backups allow a version-checked undo. */ import { randomUUID } from 'node:crypto'; import { failureSchema } from './jobPolicy.js'; import { readFile, readdir, rm } from 'node:fs/promises'; import { join } from 'node:path'; import { z } from 'zod'; import { containsForbiddenSecret, sha256 } from './codec.js'; import { checkDependencies, dependencySchema, portableDependencyPath } from './dependencies.js'; import { acquireFileLock, atomicWriteFile, scopeDirectory, } from './fileStore.js'; import { type ProjectKnowledgeSnapshot, parseProjectKnowledgeSnapshot, projectKnowledgeKindSchema, restoreProjectKnowledgeSnapshot, saveProjectKnowledgeBatch, snapshotProjectKnowledge, } from './projectKnowledge.js'; import { memoryTerms, takeTokenBudget } from './retrieval.js'; export const evidenceSchema = z.object({ id: z.string().min(1), tool: z.string().min(1), ok: z.boolean(), text: z.string().max(6000), hash: z.string(), dependencies: dependencySchema.optional(), kind: z .enum(['failure', 'mutation', 'verification', 'observation']) .optional(), }); export type ExperienceEvidence = z.infer; const itemSchema = z.object({ id: z.string().uuid(), topic: z.string(), problem: z.string(), conditions: z.string(), procedure: z.string(), invalidation: z.string(), status: z.enum(['supported', 'needs_review', 'superseded']), sources: z.array( z.object({ sessionId: z.string(), turnId: z.string(), evidence: z.array(evidenceSchema), }), ), revision: z.number().int(), createdAt: z.number(), updatedAt: z.number(), relatedIds: z.array(z.string()), conflictReason: z.string().optional(), /** Set when a user explicitly dismissed this item via MemoryMaintenance * dismiss (distinct from conflictReason, which tracks a topic clash with * another item). Surfaced to the next learningPrompt so the proposer * doesn't silently re-derive what was just rejected — see learning.ts. */ dismissedReason: z.string().optional(), lastValidatedAt: z.number().optional(), dependencyWarning: z.array(z.string()).optional(), adoptions: z .array( z.object({ id: z.string(), sessionId: z.string(), at: z.number(), reason: z.string(), evidenceBoundary: z.array(z.string()), status: z.enum(['open', 'reported']), }), ) .optional(), feedback: z .array( z.object({ key: z.string(), at: z.number(), sessionId: z.string(), outcome: z.enum(['success', 'failure', 'inapplicable']), adoptionId: z.string().optional(), reason: z.string(), evidence: z.array( z.object({ id: z.string(), tool: z.string(), text: z.string(), hash: z.string(), dependencies: dependencySchema.optional(), }), ), }), ) .optional(), }); export type Experience = z.infer; const taskSummarySchema = z.object({ turnId: z.string(), sessionId: z.string(), cwd: z.string(), request: z.string().max(2000), report: z.string().max(2000), status: z.enum(['success', 'partial', 'fail', 'uncertain']), completion: z.enum(['completed', 'interrupted', 'incomplete']), evidence: z.array(evidenceSchema).max(16), observedTools: z.number().int().nonnegative(), omittedTools: z.number().int().nonnegative(), createdAt: z.number(), }); export type MemoryTaskSummary = z.infer; const turnSchema = z.object({ id: z.string(), sessionId: z.string(), request: z.string(), outcome: z.string(), evidence: z.array(evidenceSchema), createdAt: z.number(), attempts: z.number().int().optional(), failure: failureSchema.optional(), nextAttemptAt: z.number().optional(), taskSummary: taskSummarySchema.omit({ evidence: true }).optional(), }); export type LearningTurn = z.infer; const runSchema = z.object({ id: z.string(), status: z.enum(['completed', 'failed', 'cancelled', 'undone']), startedAt: z.number(), finishedAt: z.number(), turnIds: z.array(z.string()), message: z.string(), beforeHash: z.string(), afterHash: z.string(), knowledgeBeforeRevision: z.number().int().optional(), knowledgeAfterRevision: z.number().int().optional(), /** Drafts the forget gate refused because the user had dismissed the same * conclusion. Recorded so a run that silently proposed nothing new is * distinguishable from one that was actively held back. */ blocked: z .array( z.object({ partition: z.enum(['experience', 'knowledge']), topic: z.string(), dismissedId: z.string(), reason: z.string(), }), ) .optional(), usage: z .object({ promptTokens: z.number().optional(), outputTokens: z.number().optional(), }) .optional(), }); const storeSchema = z.object({ version: z.literal(1), revision: z.number().int(), generation: z.number().int().default(0), items: z.array(itemSchema), pending: z.array(turnSchema), processed: z.array(z.string()), runs: z.array(runSchema), lastSuccessAt: z.number(), taskSummaries: z.array(taskSummarySchema).max(100).optional(), }); export type ExperienceStore = z.infer; export const EXPERIENCE_BACKUP_LIMIT = 20; export const experienceDirectory = (workspaceId: string) => join(scopeDirectory('workspace', workspaceId), 'learning'); const storePath = (workspaceId: string) => join(experienceDirectory(workspaceId), 'store.json'); export const experienceHash = (items: Experience[]) => sha256(JSON.stringify(items)); export async function readExperienceStore( workspaceId: string, ): Promise { await recoverLearningTransaction(workspaceId); return readExperienceStoreRaw(workspaceId); } async function readExperienceStoreRaw(workspaceId: string): Promise { try { return storeSchema.parse( JSON.parse(await readFile(storePath(workspaceId), 'utf8')), ); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; return { version: 1, revision: 0, generation: 0, items: [], pending: [], processed: [], runs: [], lastSuccessAt: 0, }; } } const transactionPath = (workspaceId: string) => join(experienceDirectory(workspaceId), 'transaction.json'); const transactionSchema = z.object({ runId: z.string().uuid(), before: z.unknown(), after: z.unknown(), }); /** Called under the experience lock. Revision-checked rollback must never * overwrite a subsequent human edit. Ambiguous recovery fails closed. */ async function recoverTransactionLocked(workspaceId: string): Promise { const path = transactionPath(workspaceId); const raw = await readFile(path, 'utf8').catch(error => { if (error.code === 'ENOENT') return null; throw error; }); if (!raw) return; const journal = transactionSchema.parse(JSON.parse(raw)); const store = await readExperienceStoreRaw(workspaceId); if (!store.runs.some(run => run.id === journal.runId && run.status === 'completed')) { const before = parseProjectKnowledgeSnapshot(journal.before); const after = parseProjectKnowledgeSnapshot(journal.after); const current = await snapshotProjectKnowledge(workspaceId); if (JSON.stringify(current) === JSON.stringify(after)) { await restoreProjectKnowledgeSnapshot(workspaceId, before, current.revision); } else if (JSON.stringify(current) !== JSON.stringify(before) && JSON.stringify({ ...current, revision: before.revision }) !== JSON.stringify(before)) { throw new Error('MEMORY_TRANSACTION_RECOVERY_CONFLICT:项目知识已有后续修改,保留恢复日志,禁止自动覆盖'); } } await rm(path, { force: true }); } export async function recoverLearningTransaction(workspaceId: string): Promise { const exists = await readFile(transactionPath(workspaceId), 'utf8').then(() => true, error => { if (error.code === 'ENOENT') return false; throw error; }); if (!exists) return; const release = await acquireFileLock(storePath(workspaceId)); try { await recoverTransactionLocked(workspaceId); } finally { await release(); } } export async function mutateExperienceStore( workspaceId: string, update: (store: ExperienceStore) => Promise, signal?: AbortSignal, ): Promise { const release = await acquireFileLock(storePath(workspaceId), signal); try { signal?.throwIfAborted(); await recoverTransactionLocked(workspaceId); const store = await readExperienceStoreRaw(workspaceId); const result = await update(store); signal?.throwIfAborted(); // Keep recent diagnostics and every still-undoable run hot. Archive before // dropping receipts so a crash can at worst leave a duplicate archive, // never erase history. Processed IDs remain intact for replay protection. if (store.runs.length > 1000) { const retained = new Set([ ...store.runs.slice(-1000).map(run => run.id), ...store.runs.filter(run => run.status === 'completed' || run.status === 'undone') .slice(-EXPERIENCE_BACKUP_LIMIT).map(run => run.id), ]); const archived = store.runs.filter(run => !retained.has(run.id)); if (archived.length) { const content = JSON.stringify(archived); await atomicWriteFile(join(experienceDirectory(workspaceId), 'run-archive', `${sha256(content)}.json`), content); store.runs = store.runs.filter(run => retained.has(run.id)); } } store.revision++; await atomicWriteFile( storePath(workspaceId), JSON.stringify(storeSchema.parse(store), null, 2) + '\n', ); return result; } finally { await release(); } } export async function enqueueLearningTurn( workspaceId: string, input: LearningTurn, generation?: number, ): Promise { const turn = turnSchema.parse(input); if (containsForbiddenSecret(JSON.stringify(turn))) return; await mutateExperienceStore(workspaceId, async (store) => { if (generation !== undefined && store.generation !== generation) return; if ( !store.processed.includes(turn.id) && !store.pending.some((item) => item.id === turn.id) ) store.pending.push(turn); }); } /** Diagnostic candidates, not confirmed memory; never automatically injected. */ export async function saveTaskSummary( workspaceId: string, input: MemoryTaskSummary, generation: number, ): Promise { const summary = taskSummarySchema.parse(input); if (containsForbiddenSecret(JSON.stringify(summary))) return; await mutateExperienceStore(workspaceId, async store => { if (store.generation !== generation) return; const summaries = store.taskSummaries ?? []; if (summaries.some(item => item.turnId === summary.turnId && item.sessionId === summary.sessionId)) return; store.taskSummaries = [...summaries, summary].slice(-100); }); } export const proposalSchema = z.object({ experiences: z .array( z.object({ topic: z.string().min(1).max(120), problem: z.string().min(1).max(1000), conditions: z.string().min(1).max(1000), procedure: z.string().min(1).max(2000), invalidation: z.string().min(1).max(1000), sources: z .array( z.object({ turnId: z.string(), evidenceIds: z.array(z.string()).min(1), }), ) .min(1), mergeIds: z.array(z.string().uuid()), }), ) .max(12), conflicts: z .array( z.object({ ids: z.array(z.string().uuid()).min(2), reason: z.string().min(1).max(1000), }), ) .max(20), projectKnowledge: z .array( z.object({ kind: projectKnowledgeKindSchema, subject: z.string().min(1).max(120), statement: z.string().min(1).max(1500), applicability: z.string().min(1).max(1000), aliases: z.array(z.string().max(120)).max(20).optional(), source: z.object({ turnId: z.string(), evidenceIds: z.array(z.string()).min(1).max(12), }), }), ) .max(8) .optional(), summary: z.string().max(2000), }); export type LearningProposal = z.infer; /** Reject invented provenance before any mutation. Tool success is evidence, * not a mathematical proof of a model's generalized claim. Prompt says so too. */ export async function commitLearningProposal( workspaceId: string, base: ExperienceStore, turns: LearningTurn[], proposal: LearningProposal, run: { id: string; startedAt: number; usage?: { promptTokens?: number; outputTokens?: number }; }, signal?: AbortSignal, ): Promise { proposal = proposalSchema.parse(proposal); if (containsForbiddenSecret(JSON.stringify(proposal))) throw new Error('经验提案含凭据,未保存'); try { await mutateExperienceStore( workspaceId, async (store) => { if (store.generation !== base.generation) throw new Error('LEARNING_SOURCE_CHANGED:用户已清空经验'); if (experienceHash(store.items) !== experienceHash(base.items)) throw new Error( 'EXPERIENCE_VERSION_CONFLICT:经验已被另一运行修改,请重新整理', ); for (const turn of turns) { if ( !store.pending.some( (item) => item.id === turn.id && sha256(JSON.stringify(turnSchema.parse(item))) === sha256(JSON.stringify(turnSchema.parse(turn))), ) ) throw new Error('LEARNING_SOURCE_CHANGED'); } // Validate every cross-reference before writing either partition. A bad // later item must not leave an earlier project fact behind. for (const draft of proposal.projectKnowledge ?? []) { const source = turns.find((item) => item.id === draft.source.turnId); if (!source) throw new Error(`未知项目事实来源回合:${draft.source.turnId}`); for (const id of draft.source.evidenceIds) { const evidence = source.evidence.find((item) => item.id === id); if ( !evidence || sha256(evidence.text) !== evidence.hash || !evidence.ok ) throw new Error(`项目事实缺少成功的一手工具证据:${id}`); } } for (const draft of proposal.experiences) { const validatedSources = draft.sources.map((source) => { const turn = turns.find((item) => item.id === source.turnId) ?? base.items .flatMap((item) => item.sources) .find((item) => item.turnId === source.turnId); if (!turn) throw new Error(`未知经验来源回合:${source.turnId}`); return source.evidenceIds.map((id) => { const evidence = turn.evidence.find((item) => item.id === id); if (!evidence || sha256(evidence.text) !== evidence.hash) throw new Error(`未知或已改变的工具证据:${id}`); return evidence; }); }); if (!validatedSources.some((items) => items.some((item) => item.ok))) throw new Error('经验缺少成功工具证据,不可提升为可复用经验'); for (const id of new Set(draft.mergeIds)) { if ( !store.items.some( (item) => item.id === id && item.status !== 'superseded', ) ) throw new Error(`无法合并未知/已替代经验:${id}`); } } for (const conflict of proposal.conflicts) for (const id of conflict.ids) { if ( !store.items.some( (item) => item.id === id && item.status !== 'superseded', ) ) throw new Error(`冲突引用未知/已替代经验:${id}`); } const before = structuredClone(store); const now = Date.now(); const blocked: NonNullable = []; let knowledgeSnapshot = await snapshotProjectKnowledge(workspaceId); let knowledgeAfterRevision: number | undefined; const knowledgeDrafts = (proposal.projectKnowledge ?? []).map(draft => { const source = turns.find((item) => item.id === draft.source.turnId); if (!source) throw new Error(`未知项目事实来源回合:${draft.source.turnId}`); const evidence = draft.source.evidenceIds.map((id) => { const item = source.evidence.find((item) => item.id === id); if (!item || sha256(item.text) !== item.hash || !item.ok) throw new Error(`项目事实缺少成功的一手工具证据:${id}`); return item; }); const dependency = evidence .map((item) => item.dependencies) .find(Boolean); return { scope: 'workspace' as const, workspaceId, kind: draft.kind, subject: draft.subject, statement: draft.statement, applicability: draft.applicability, aliases: draft.aliases ?? [], dependencies: dependency, provenance: [{ type: 'tool_verified' as const, sessionId: source.sessionId, turnId: source.id, evidenceIds: evidence.map(item => item.id) }] }; }); if (knowledgeDrafts.length) { const batch = await saveProjectKnowledgeBatch(workspaceId, knowledgeDrafts, signal, { startedAt: run.startedAt }, async (before, after) => { await atomicWriteFile(transactionPath(workspaceId), JSON.stringify({ runId: run.id, before, after })); }); knowledgeSnapshot = batch.before; knowledgeAfterRevision = batch.afterRevision; batch.results.forEach((result, index) => { if (result.blocked) blocked.push({ partition: 'knowledge', topic: `${knowledgeDrafts[index]!.kind}/${knowledgeDrafts[index]!.subject}`, dismissedId: result.blocked.dismissedId, reason: result.blocked.reason, }); }); await atomicWriteFile( join( experienceDirectory(workspaceId), 'backups', `${run.id}.knowledge.json`, ), JSON.stringify(knowledgeSnapshot), ); } for (const draft of proposal.experiences) { const sources = draft.sources.map((source) => { const turn = turns.find((item) => item.id === source.turnId) ?? base.items .flatMap((item) => item.sources) .find((item) => item.turnId === source.turnId); if (!turn) throw new Error(`未知经验来源回合:${source.turnId}`); const evidence = source.evidenceIds.map((id) => { const item = turn.evidence.find((item) => item.id === id); if (!item || sha256(item.text) !== item.hash) throw new Error(`未知或已改变的工具证据:${id}`); return item; }); return { sessionId: turn.sessionId, turnId: source.turnId, evidence, }; }); if ( !sources.some((source) => source.evidence.some((item) => item.ok)) ) throw new Error('经验缺少成功工具证据,不可提升为可复用经验'); const merges = [...new Set(draft.mergeIds)].map((id) => { const old = store.items.find( (item) => item.id === id && item.status !== 'superseded', ); if (!old) throw new Error(`无法合并未知/已替代经验:${id}`); return old; }); const signature = ( item: Pick< Experience, 'topic' | 'problem' | 'conditions' | 'procedure' | 'invalidation' >, ) => sha256( JSON.stringify([ item.topic, item.problem, item.conditions, item.procedure, item.invalidation, ]), ); // Forget gate, same role as projectKnowledge.ts's dismissedMatch and // factGovernance.ts's blocked hashes: `dismiss` soft-deletes by // setting `superseded`, which hides the item from the duplicate check // below — so without this a re-proposal of the identical conclusion // creates a brand-new item and quietly undoes the user's deletion. // Matched on the full five-field signature, not on topic: dismissing // one wrong conclusion must not blacklist the subject. Skipping this // one draft (rather than throwing) keeps the run's other experiences. const dismissed = store.items.find( (item) => item.dismissedReason && signature(item) === signature(draft), ); if (dismissed) { blocked.push({ partition: 'experience', topic: draft.topic, dismissedId: dismissed.id, reason: dismissed.dismissedReason!, }); continue; } const duplicate = store.items.find( (item) => item.status !== 'superseded' && signature(item) === signature(draft), ); if (duplicate && !merges.length) { const seen = new Set( duplicate.sources.map((source) => source.turnId), ); duplicate.sources.push( ...sources.filter((source) => !seen.has(source.turnId)), ); duplicate.revision++; duplicate.updatedAt = now; continue; } const id = randomUUID(); store.items.push({ id, topic: draft.topic, problem: draft.problem, conditions: draft.conditions, procedure: draft.procedure, invalidation: draft.invalidation, status: 'supported', sources: [...merges.flatMap((item) => item.sources), ...sources], revision: 1, createdAt: now, updatedAt: now, relatedIds: merges.map((item) => item.id), }); for (const old of merges) { old.status = 'superseded'; old.relatedIds.push(id); old.revision++; old.updatedAt = now; } } for (const conflict of proposal.conflicts) { for (const id of conflict.ids) { const item = store.items.find( (item) => item.id === id && item.status !== 'superseded', ); if (!item) throw new Error(`冲突引用未知/已替代经验:${id}`); item.status = 'needs_review'; item.conflictReason = conflict.reason; item.relatedIds = [ ...new Set([ ...item.relatedIds, ...conflict.ids.filter((other) => other !== id), ]), ]; item.revision++; item.updatedAt = now; } } await atomicWriteFile( join(experienceDirectory(workspaceId), 'backups', `${run.id}.json`), // Undo changes experience only; do not duplicate the entire raw queue. JSON.stringify( { ...before, pending: [], processed: [], runs: [], taskSummaries: [] }, null, 2, ), ); const ids = turns.map((turn) => turn.id); store.pending = store.pending.filter((turn) => !ids.includes(turn.id)); store.processed = [...new Set([...store.processed, ...ids])]; store.lastSuccessAt = now; store.runs.push({ ...run, status: 'completed', finishedAt: now, turnIds: ids, message: proposal.summary, beforeHash: experienceHash(before.items), afterHash: experienceHash(store.items), knowledgeBeforeRevision: proposal.projectKnowledge?.length ? knowledgeSnapshot.revision : undefined, knowledgeAfterRevision, blocked: blocked.length ? blocked : undefined, }); }, signal, ); } catch (error) { try { await recoverLearningTransaction(workspaceId); } catch (rollbackError) { throw new AggregateError([error, rollbackError], '记忆整理失败,项目事实恢复发生冲突;恢复日志已保留'); } throw error; } await recoverLearningTransaction(workspaceId); // A derived view only. The committed document above remains authoritative. await refreshExperienceIndex(workspaceId).catch((error) => { process.stderr.write( `[minimal-agent memory] 经验已提交,但派生索引待重建:${(error as Error).message}\n`, ); }); await pruneExperienceBackups(workspaceId).catch((error) => { process.stderr.write( `[minimal-agent memory] 整理已提交,旧备份清理失败:${(error as Error).message}\n`, ); }); } async function pruneExperienceBackups(workspaceId: string): Promise { const release = await acquireFileLock(storePath(workspaceId)); try { await recoverTransactionLocked(workspaceId); const store = await readExperienceStoreRaw(workspaceId); const retained = new Set( store.runs .filter((run) => run.status === 'completed' || run.status === 'undone') .slice(-EXPERIENCE_BACKUP_LIMIT) .flatMap((run) => [ `${run.id}.json`, ...(run.knowledgeAfterRevision === undefined ? [] : [`${run.id}.knowledge.json`]), ]), ); const directory = join(experienceDirectory(workspaceId), 'backups'); const files = await readdir(directory).catch((error) => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [] as string[]; throw error; }); for (const file of files) { if ( !retained.has(file) && z .string() .uuid() .safeParse(file.replace(/(?:\.knowledge)?\.json$/, '')).success ) await rm(join(directory, file), { force: true }); } } finally { await release(); } } export async function clearExperiences(workspaceId: string): Promise { await mutateExperienceStore(workspaceId, async (store) => { await rm(join(experienceDirectory(workspaceId), 'run-archive'), { recursive: true, force: true }); await rm(join(experienceDirectory(workspaceId), 'backups'), { recursive: true, force: true, }); store.generation++; store.items = []; store.pending = []; store.taskSummaries = []; store.processed = []; store.runs = []; store.lastSuccessAt = 0; }); await refreshExperienceIndex(workspaceId); } export async function refreshExperienceIndex( workspaceId: string, ): Promise { const release = await acquireFileLock(storePath(workspaceId)); try { await recoverTransactionLocked(workspaceId); const store = await readExperienceStoreRaw(workspaceId); await atomicWriteFile( join(experienceDirectory(workspaceId), 'index.md'), `# 项目经验索引(派生视图,revision ${store.revision})\n\n` + store.items .filter((item) => item.status !== 'superseded') .map( (item) => `- ${item.id} · ${item.topic.replace(/[\r\n]/g, ' ')} · ${item.status} · ${item.conditions.replace(/[\r\n]/g, ' ')}`, ) .join('\n') + '\n', ); } finally { await release(); } } export async function undoLearningRun( workspaceId: string, runId: string, ): Promise { if (!z.string().uuid().safeParse(runId).success) throw new Error('无效整理运行 ID'); let rollbackKnowledge: | { snapshot: ProjectKnowledgeSnapshot; revision: number } | undefined; try { await mutateExperienceStore(workspaceId, async (store) => { const run = store.runs.find( (run) => run.id === runId && run.status === 'completed', ); if (!run || run.afterHash !== experienceHash(store.items)) throw new Error('UNDO_CONFLICT:仅可撤销未被后续编辑覆盖的整理'); const backup = storeSchema.parse( JSON.parse( await readFile( join(experienceDirectory(workspaceId), 'backups', `${runId}.json`), 'utf8', ), ), ); if (experienceHash(backup.items) !== run.beforeHash) throw new Error('整理备份已改变,未覆盖当前经验'); if (run.knowledgeAfterRevision !== undefined) { const currentKnowledge = await snapshotProjectKnowledge(workspaceId); const knowledgeBackup = parseProjectKnowledgeSnapshot( JSON.parse( await readFile( join( experienceDirectory(workspaceId), 'backups', `${runId}.knowledge.json`, ), 'utf8', ), ), ); if (knowledgeBackup.revision !== run.knowledgeBeforeRevision) throw new Error('项目事实整理备份已改变,未覆盖当前记录'); await restoreProjectKnowledgeSnapshot( workspaceId, knowledgeBackup, run.knowledgeAfterRevision, ); rollbackKnowledge = { snapshot: currentKnowledge, revision: (await snapshotProjectKnowledge(workspaceId)).revision, }; } store.items = backup.items; run.status = 'undone'; run.message += '\n用户撤销;原回合保持已处理,避免自动重新学回。'; }); } catch (error) { if (rollbackKnowledge) { try { await restoreProjectKnowledgeSnapshot( workspaceId, rollbackKnowledge.snapshot, rollbackKnowledge.revision, ); } catch (rollbackError) { throw new AggregateError( [error, rollbackError], '撤销经验失败,项目事实回滚也发生冲突', ); } } throw error; } await refreshExperienceIndex(workspaceId); } export async function recallExperiences( workspaceId: string, query: string, limit = 5, ): Promise { if (!query.trim()) return []; const store = await readExperienceStore(workspaceId); const terms = memoryTerms(query); const selected = store.items .filter((item) => item.status !== 'superseded') .map((item) => ({ item, score: terms.reduce( (sum, term) => sum + (JSON.stringify([ item.topic, item.problem, item.conditions, item.procedure, ]) .normalize('NFKC') .toLowerCase() .includes(term) ? 1 : 0), 0, ) * (item.status === 'needs_review' ? 0.25 : 1) * (experienceReviewDue(item) ? 0.5 : 1), })) .filter((entry) => entry.score > 0) .sort((a, b) => b.score - a.score || b.item.updatedAt - a.item.updatedAt) .slice(0, Math.max(0, limit) + Math.min(Math.max(0, limit), 8)) .map((entry) => entry.item); const checked = await Promise.all( selected.map(async (item) => { const bindings = [ ...item.sources.flatMap((source) => source.evidence), ...(item.feedback?.at(-1)?.evidence ?? []), ].flatMap((evidence) => evidence.dependencies ? [evidence.dependencies] : [], ); const groups = new Map(); for (const binding of bindings) { const previous = groups.get(binding.root); const key = (path: string) => portableDependencyPath(path, binding.platform); const files = new Map( previous?.files.map((file) => [key(file.path), file]) ?? [], ); for (const file of binding.files) files.set(key(file.path), file); groups.set(binding.root, { ...binding, files: [...files.values()] }); } return { ...item, dependencyWarning: groups.size ? ( await Promise.all([...groups.values()].map(checkDependencies)) ).flat() : ['旧经验没有代码依赖快照,使用前核对环境'], }; }), ); const stale = (item: typeof checked[number]) => +(!!item.dependencyWarning.length || item.status === 'needs_review' || experienceReviewDue(item)); return checked.sort((a,b) => stale(a) - stale(b)).slice(0, limit); } export async function adoptExperience( workspaceId: string, id: string, sessionId: string, reason: string, evidenceBoundary: string[], signal?: AbortSignal, ): Promise { const adoptionId = randomUUID(); await mutateExperienceStore( workspaceId, async (store) => { const item = store.items.find( (item) => item.id === id && item.status !== 'superseded', ); if (!item) throw new Error('经验不存在或已替代'); item.adoptions = [ ...(item.adoptions ?? []), { id: adoptionId, sessionId, at: Date.now(), reason, evidenceBoundary, status: 'open' as const, }, ].slice(-50); }, signal, ); return adoptionId; } export const EXPERIENCE_REVIEW_DAYS = 180; export function experienceReviewDue( item: Experience, now = Date.now(), ): boolean { // Re-indexing, retrieval and wording edits do not renew factual validity. return ( now - (item.lastValidatedAt ?? item.createdAt) >= EXPERIENCE_REVIEW_DAYS * 86400000 ); } /** The caller resolves evidence against real host history. Outcome remains the * Agent's attributed assessment, not automatic proof inferred from exit codes. */ export async function recordExperienceFeedback( workspaceId: string, id: string, feedback: NonNullable[number], signal?: AbortSignal, ): Promise { const parsed = itemSchema.shape.feedback.unwrap().element.parse(feedback); if ( !parsed.evidence.length || parsed.evidence.some((item) => sha256(item.text) !== item.hash) || containsForbiddenSecret(JSON.stringify(parsed)) ) throw new Error('经验反馈需要真实且可保存的工具证据'); await mutateExperienceStore( workspaceId, async (store) => { const item = store.items.find( (item) => item.id === id && item.status !== 'superseded', ); if (!item) throw new Error('经验不存在或已替代,请重新召回'); if (item.feedback?.some((entry) => entry.key === parsed.key)) return; const adoption = item.adoptions?.find( (entry) => entry.id === parsed.adoptionId && entry.sessionId === parsed.sessionId, ); if (!adoption || adoption.status !== 'open') throw new Error( '请先 adopt 登记实际采用的经验,再关联采用后的工具证据', ); if ( parsed.evidence.some((evidence) => adoption.evidenceBoundary.includes(evidence.id), ) ) throw new Error('反馈必须引用采用之后的新工具结果'); adoption.status = 'reported'; item.feedback = [...(item.feedback ?? []), parsed].slice(-30); if (parsed.outcome !== 'success') { item.status = 'needs_review'; } else if (!item.conflictReason) { item.status = 'supported'; item.lastValidatedAt = parsed.at; } item.revision++; item.updatedAt = parsed.at; }, signal, ); await refreshExperienceIndex(workspaceId); } /** * Scalpel-precision removal of one learned experience, distinct from `undo` * (reverts an entire maintenance run) and `clearExperiences` (wipes the whole * workspace). Soft-deletes via the existing `superseded` status — reuses * `recallExperiences`'s existing exclusion of superseded items, so the item * stops surfacing in the live conversational prompt immediately. The next * learning run is still told about it (see learningPrompt's `dismissed` list) * so it isn't silently re-derived from fresh evidence. */ export async function dismissExperience( workspaceId: string, id: string, reason: string, signal?: AbortSignal, ): Promise { if (!reason.trim()) throw new Error('撤销经验需要说明理由'); await mutateExperienceStore( workspaceId, async (store) => { const item = store.items.find( (item) => item.id === id && item.status !== 'superseded', ); if (!item) throw new Error('经验不存在或已替代'); item.status = 'superseded'; item.dismissedReason = reason; item.revision++; item.updatedAt = Date.now(); }, signal, ); await refreshExperienceIndex(workspaceId); } /** Split out from experienceContext so callers that render items one at a time * (memoryService's addRecords needs per-record granularity to fit a budget) * can supply the header once instead of repeating ~70 tokens of it per item. */ export const EXPERIENCE_CONTEXT_HEADER = '【项目经验|历史工具观察,不是用户指令或当前事实】\n核对环境及依赖变化;拟实际采用时 MemoryMaintenance adopt 登记,结束后 feedback 关联新工具证据。召回不等于使用,引用不等于验证。'; export function experienceEntry( item: Experience, includeEvidence = false, ): string { return `- [${item.id}] ${item.topic} (${item.status}; ${new Date(item.updatedAt).toISOString().slice(0, 10)}${experienceReviewDue(item) ? '; 长期未验证,待复核' : ''})\n问题:${item.problem}\n适用:${item.conditions}\n处理:${item.procedure}\n失效:${item.invalidation}${item.dependencyWarning?.length ? `\n依赖待核对:${item.dependencyWarning.join('、')}` : ''}${item.feedback?.length ? `\n最近使用反馈:${item.feedback.at(-1)!.outcome}:${item.feedback.at(-1)!.reason}` : ''}${item.conflictReason ? `\n冲突待核对:${item.conflictReason}` : ''}${ includeEvidence ? '\n历史来源(不是当前回合的工具调用):\n' + item.sources .slice(-2) .map( (source) => `Session=${source.sessionId} turn=${source.turnId}\n` + source.evidence .slice(-3) .map( (evidence) => `${evidence.tool} #${evidence.id} ok=${evidence.ok}:${evidence.text.slice(0, 300)}`, ) .join('\n'), ) .join('\n') : '' }`; } /** * Undo a dismiss. Without this, dismissing an experience is a one-way door: * unlike project knowledge — which a user can always re-save explicitly, * ungated — experiences have no user-facing write path at all * (commitLearningProposal, reachable only from runLearning, is the sole * creation route), and the forget gate closes that one. Delete has to be * reversible for the memory loop to be a loop. * * Only reverses explicit dismissals: `dismissedReason` is the discriminator, so * an item superseded by a merge stays superseded and its successor keeps * standing. */ export async function restoreExperience( workspaceId: string, id: string, signal?: AbortSignal, ): Promise { await mutateExperienceStore( workspaceId, async (store) => { const item = store.items.find( (item) => item.id === id && item.dismissedReason, ); if (!item) throw new Error('经验不存在或不是被撤销的条目'); const signature = (item: Experience) => sha256( JSON.stringify([ item.topic, item.problem, item.conditions, item.procedure, item.invalidation, ]), ); // Restoring on top of an identical live item would leave two copies the // dedupe path can never merge again. const live = store.items.find( (other) => other.id !== id && other.status !== 'superseded' && signature(other) === signature(item), ); if (live) throw new Error(`已有等价的现行经验 ${live.id},无需恢复`); item.status = 'supported'; item.dismissedReason = undefined; item.revision++; item.updatedAt = Date.now(); }, signal, ); await refreshExperienceIndex(workspaceId); } export function experienceContext( items: Experience[], includeEvidence = false, maxTokens = includeEvidence ? 2500 : 1000, ): string { if (!items.length) return ''; return ( `${EXPERIENCE_CONTEXT_HEADER}\n` + takeTokenBudget( items.map((item) => experienceEntry(item, includeEvidence)), maxTokens, ).join('\n') ); }