import { randomUUID } from 'node:crypto'; import { copyFile, readFile, unlink } from 'node:fs/promises'; import { join } from 'node:path'; import { clearExperiences, EXPERIENCE_CONTEXT_HEADER, experienceEntry, recallExperiences, } from './experienceStore.js'; import { assertAutomaticFactAllowed, withDestinationBarrier, blockFact, withFactBarriers, } from './factGovernance.js'; import { clearGlobalProjectKnowledge, clearProjectKnowledge, isLiveKnowledgeCandidate, PROJECT_KNOWLEDGE_CONTEXT_HEADER, projectKnowledgeEntry, projectKnowledgeStatus, recallProjectKnowledge, } from './projectKnowledge.js'; import { countTextTokens } from '../context/tokenCounter.js'; import { containsForbiddenSecret, deriveTopicKey, hydrateRecord, parsePersona, serializePersona, sha256, validateMemoryInput, } from './codec.js'; import { DEFAULT_RETENTION, DEFAULT_SESSION_PIPELINE, DEFAULT_SETTINGS, LEGACY_LEARNING_CADENCE, MEMORY_SETTINGS_REVISION, MEMORY_RETENTION_DAYS_MAX, MEMORY_RETENTION_DAYS_MIN, MEMORY_RETENTION_MB_MAX, MEMORY_RETENTION_MB_MIN, PERSONA_MAX_CHARS, } from './constants.js'; import { clearConversationEpisodes, episodicMemoryService, } from './episodicMemory.js'; import { acquireFileLock, appendPrivateLine, atomicWriteFile, auditFilePath, enqueueMemoryMutation, personaFilePath, scopeDirectory, settingsFilePath, } from './fileStore.js'; import { ensureMemoryMigrated } from './migration.js'; import { clearScopeTransactionQuarantine, readVersionedMemory, refreshTopicView, removeVersionedMemory, replaceMemoryBatchVersioned, replaceVersionedMemory, scanMemoryScope, writeNewMemory, } from './repository.js'; import { isReviewDue, isUnconfirmed, memoryTerms, recallFromSnapshot, takeTokenBudget, truncateTokenBudget, } from './retrieval.js'; import { recallQueryFor, referenceFallback } from './recallQuery.js'; import { sourceAnchor } from './automaticPolicy.js'; import type { ConversationSearchOptions, ForgetCandidateCleanup, MemoryClearResult, MemoryContextBundle, MemoryDiagnostic, MemoryForgetResult, MemoryEditablePatch, MemoryRecord, MemoryRecordV2, MemoryScope, MemorySettings, MemorySnapshot, MemoryUpdate, MemoryVersion, PersonaDocument, PersonaInput, VersionedMemoryRecord, VersionedMemorySettings, VersionedPersonaDocument, } from './types.js'; export type { ConversationEpisode, ConversationSearchOptions, ConversationSearchResult, MemoryClearResult, MemoryCategory, MemoryContextBundle, MemoryDiagnostic, MemoryEditablePatch, MemoryEvidence, MemoryRecord, MemoryRecordV2, MemoryScope, MemorySensitivity, MemorySettings, MemorySnapshot, MemoryStatus, MemoryUpdate, MemoryVersion, PersonaDocument, PersonaInput, VersionedMemoryRecord, VersionedMemorySettings, VersionedPersonaDocument, } from './types.js'; export { containsForbiddenSecret } from './codec.js'; export class MemoryTopicConflictError extends Error { constructor(readonly recordId: string) { super( `已有同主题记忆 ${recordId};内容变更必须使用 UpdateMemory,不能静默覆盖`, ); this.name = 'MemoryTopicConflictError'; } } function mergeSettings(raw: Partial): MemorySettings { const review = raw.reviewAfterDays; const retention = raw.retention; const legacyCadence = raw.settingsRevision === undefined && raw.learning?.minPendingTurns === LEGACY_LEARNING_CADENCE.minPendingTurns && raw.learning?.minIntervalHours === LEGACY_LEARNING_CADENCE.minIntervalHours; return { settingsRevision: MEMORY_SETTINGS_REVISION, factLearning: raw.factLearning ?? DEFAULT_SETTINGS.factLearning, learning: { ...DEFAULT_SETTINGS.learning!, ...(legacyCadence ? { enabled: raw.learning!.enabled } : raw.learning), }, autoRemember: typeof raw.autoRemember === 'boolean' ? raw.autoRemember : DEFAULT_SETTINGS.autoRemember, reviewAfterDays: { profile: review?.profile ?? DEFAULT_SETTINGS.reviewAfterDays!.profile, preference: review?.preference ?? DEFAULT_SETTINGS.reviewAfterDays!.preference, topic: review?.topic ?? DEFAULT_SETTINGS.reviewAfterDays!.topic, person: review?.person ?? DEFAULT_SETTINGS.reviewAfterDays!.person, project: review?.project ?? DEFAULT_SETTINGS.reviewAfterDays!.project, decision: review?.decision ?? DEFAULT_SETTINGS.reviewAfterDays!.decision, }, retention: { episodeDays: retention?.episodeDays ?? DEFAULT_RETENTION.episodeDays, episodeMaxMegabytes: retention?.episodeMaxMegabytes ?? DEFAULT_RETENTION.episodeMaxMegabytes, }, sessionPipeline: { enabled: raw.sessionPipeline?.enabled ?? DEFAULT_SESSION_PIPELINE.enabled, extractWindowDays: raw.sessionPipeline?.extractWindowDays ?? DEFAULT_SESSION_PIPELINE.extractWindowDays, idleHours: raw.sessionPipeline?.idleHours ?? DEFAULT_SESSION_PIPELINE.idleHours, maxSessionsPerRun: raw.sessionPipeline?.maxSessionsPerRun ?? DEFAULT_SESSION_PIPELINE.maxSessionsPerRun, retentionDays: raw.sessionPipeline?.retentionDays ?? DEFAULT_SESSION_PIPELINE.retentionDays, maxRawMemories: raw.sessionPipeline?.maxRawMemories ?? DEFAULT_SESSION_PIPELINE.maxRawMemories, }, }; } function validateSettingsPatch(patch: Partial): void { if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw new Error('记忆设置必须是对象'); if ( patch.autoRemember !== undefined && typeof patch.autoRemember !== 'boolean' ) throw new Error('autoRemember 必须为布尔值'); if ( patch.factLearning !== undefined && typeof patch.factLearning !== 'boolean' ) throw new Error('factLearning 必须为布尔值'); if (patch.learning !== undefined) { const value = patch.learning; if ( !value || typeof value.enabled !== 'boolean' || !Number.isInteger(value.minPendingTurns) || value.minPendingTurns < 1 || value.minPendingTurns > 100 || !Number.isFinite(value.minIntervalHours) || value.minIntervalHours < 0 || value.minIntervalHours > 8760 ) { throw new Error( 'learning 需要 enabled 布尔值、minPendingTurns 1-100、minIntervalHours 0-8760', ); } } if (patch.reviewAfterDays !== undefined) { if ( !patch.reviewAfterDays || typeof patch.reviewAfterDays !== 'object' || Array.isArray(patch.reviewAfterDays) ) throw new Error('reviewAfterDays 必须是对象'); for (const [category, days] of Object.entries(patch.reviewAfterDays)) { if (!Number.isInteger(days) || days < 7 || days > 3_650) { throw new Error(`复核周期 ${category} 必须是 7-3650 之间的整数天`); } } } if (patch.sessionPipeline !== undefined) { const value = patch.sessionPipeline; if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('sessionPipeline 必须是对象'); if (value.enabled !== undefined && typeof value.enabled !== 'boolean') throw new Error('sessionPipeline.enabled 必须为布尔值'); const boundedInt = ( field: string, input: number | undefined, min: number, max: number, ) => { if (input === undefined) return; if (!Number.isInteger(input) || input < min || input > max) throw new Error(`sessionPipeline.${field} 必须是 ${min}-${max} 之间的整数`); }; boundedInt('extractWindowDays', value.extractWindowDays, 1, 365); boundedInt('maxSessionsPerRun', value.maxSessionsPerRun, 1, 20); boundedInt('retentionDays', value.retentionDays, 1, 365); boundedInt('maxRawMemories', value.maxRawMemories, 1, 1_024); if ( value.idleHours !== undefined && (!Number.isFinite(value.idleHours) || value.idleHours < 0 || value.idleHours > 720) ) throw new Error('sessionPipeline.idleHours 必须是 0-720 之间的小时数'); } if (patch.retention === undefined) return; if ( !patch.retention || typeof patch.retention !== 'object' || Array.isArray(patch.retention) ) throw new Error('retention 必须是对象'); const { episodeDays, episodeMaxMegabytes } = patch.retention; if ( episodeDays !== undefined && (!Number.isInteger(episodeDays) || episodeDays < MEMORY_RETENTION_DAYS_MIN || episodeDays > MEMORY_RETENTION_DAYS_MAX) ) { throw new Error( `会话原文保留天数必须是 ${MEMORY_RETENTION_DAYS_MIN}-${MEMORY_RETENTION_DAYS_MAX} 之间的整数`, ); } if ( episodeMaxMegabytes !== undefined && (!Number.isInteger(episodeMaxMegabytes) || episodeMaxMegabytes < MEMORY_RETENTION_MB_MIN || episodeMaxMegabytes > MEMORY_RETENTION_MB_MAX) ) { throw new Error( `会话原文体积上限必须是 ${MEMORY_RETENTION_MB_MIN}-${MEMORY_RETENTION_MB_MAX} 之间的整数 MB`, ); } } const lastGoodSettings = new Map(); const settingsWarnings = new Map(); function parseSettings(raw: string): MemorySettings { const parsed = JSON.parse(raw) as Partial; validateSettingsPatch(parsed); return mergeSettings(parsed); } async function settingsDocument( lockHeld = false, ): Promise { const path = settingsFilePath(); let raw: string | undefined; try { raw = await readFile(path, 'utf8'); const settings = parseSettings(raw); // Manual edits are first-class too: retain the last successfully validated // disk value across restarts. Serialize with settings updates and recheck // the source so an older reader cannot overwrite a newer recovery copy. const release = lockHeld ? async () => {} : await acquireFileLock(path); let warning: string | undefined; try { if ((await readFile(path, 'utf8')) === raw) { lastGoodSettings.set(path, structuredClone(settings)); const content = `${JSON.stringify(settings, null, 2)}\n`; if ( (await readFile(`${path}.last-good`, 'utf8').catch(() => '')) !== content ) await atomicWriteFile(`${path}.last-good`, content); } settingsWarnings.delete(path); } catch (error) { warning = `有效记忆设置已加载,但恢复备份无法更新:${(error as Error).message}`; if (settingsWarnings.get(path) !== warning) process.stderr.write(`[minimal-agent] ${warning}\n`); settingsWarnings.set(path, warning); } finally { await release(); } return { settings, version: sha256(raw), ...(warning ? { warning } : {}), }; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') { settingsWarnings.delete(path); const settings = structuredClone(DEFAULT_SETTINGS); return { settings, version: sha256(`${JSON.stringify(settings, null, 2)}\n`), }; } const warning = `记忆设置读取失败,未恢复自动记忆默认值:${(error as Error).message}`; if (settingsWarnings.get(path) !== warning) process.stderr.write(`[minimal-agent] ${warning}\n`); settingsWarnings.set(path, warning); const settings = lastGoodSettings.get(path) ?? (await readFile(`${path}.last-good`, 'utf8') .then(parseSettings) .catch(() => null)); if (!settings) throw new Error(`${warning};没有有效备份,请修复 ${path}`); return { settings: structuredClone(settings), version: sha256(raw ?? warning), warning, }; } } /** Serialize changes of consent with short commit sections, never with model requests. */ async function lockMemoryConsent(signal?: AbortSignal) { return acquireFileLock(settingsFilePath() + '.consent', signal); } export type LearningConsentMode = 'facts' | 'history' | 'experience' | 'explicit-experience'; export async function hasLearningConsent(mode: LearningConsentMode) { const { settings, warning } = await settingsDocument(); if (warning) return false; if (mode === 'explicit-experience') return true; // The maintenance command can review previously authorized evidence. if (!settings.autoRemember) return false; if (mode === 'experience') return settings.learning?.enabled === true; return settings.factLearning && (mode !== 'history' || settings.sessionPipeline?.enabled !== false); } /** Lock order: consent → settings / record or candidate locks. Never hold across model I/O. */ export async function acquireLearningWriteConsent(mode: LearningConsentMode, signal?: AbortSignal) { const release = await lockMemoryConsent(signal); try { const allowed = await hasLearningConsent(mode); signal?.throwIfAborted(); if (allowed) return release; } catch (error) { await release(); throw error; } await release(); return undefined; } export const acquireFactWriteConsent = (requirePipeline: boolean, signal?: AbortSignal) => acquireLearningWriteConsent(requirePipeline ? 'history' : 'facts', signal); /** 审计日志单代上限;超限挪成 `.1`,保留最近两代。 */ const AUDIT_MAX_BYTES = 4 * 1024 * 1024; /** Reference budget the per-section caps in buildContextBundle are expressed * against, and the floor below which they never shrink. Historically it was * hardcoded in five places; it is a ratio base now, not a ceiling. */ export const MEMORY_CONTEXT_BASE_BUDGET = 3_000; function skippedCleanup(): ForgetCandidateCleanup { return { status: 'skipped', purgedWorkspaces: [], failed: [] }; } async function appendAudit(input: { action: string; record?: MemoryRecord; version?: string; result: 'ok' | 'conflict' | 'not_found'; }): Promise { await appendPrivateLine( auditFilePath(), JSON.stringify({ timestamp: Date.now(), action: input.action, id: input.record?.id, scope: input.record?.scope, workspaceId: input.record?.workspaceId, revision: input.record?.revision, version: input.version, result: input.result, }), // 审计日志同样是 append-only,必须轮转——它此前是仓库里第二个只增不减的存储。 { maxBytes: AUDIT_MAX_BYTES }, ).catch(() => undefined); } const EMPTY_SCOPE_SNAPSHOT: MemorySnapshot = Object.freeze({ records: [], versions: {}, diagnostics: [], createdAt: 0, }) as MemorySnapshot; /** * 合并快照的记忆化。 * * ⚠️ 这不是"顺手加个缓存",是修一个死缓存:`retrieval.ts` 用 * `WeakMap` 按快照对象缓存 BM25 索引,而本函数以前**每次都 * 返回全新对象字面量** —— 于是 recall / buildContextBundle 这两条热路径上 WeakMap 永远 * miss,每轮对话都要重建整个索引,`recordSearchIndexCacheHit()` 一次都不会触发(诊断计数 * 器因此说谎)。单测直接对同一个 snapshot 对象调两次 recallFromSnapshot,机制是对的, * 但生产集成从不复用对象,属于"测试通过、生产死代码"。 * * 用底层两个 scope 快照的**对象标识**做键:scanMemoryScope 在缓存命中时返回同一个对象, * 有变更时才换新对象——比时间戳更精确,也不怕时钟碰撞。 */ let combinedSnapshotCache: { personal: MemorySnapshot; workspace: MemorySnapshot; workspaceId?: string; combined: MemorySnapshot; } | null = null; async function combinedSnapshot(workspaceId?: string): Promise { await ensureMemoryMigrated(); const personal = await scanMemoryScope('personal'); const workspace = workspaceId ? await scanMemoryScope('workspace', workspaceId) : EMPTY_SCOPE_SNAPSHOT; const cached = combinedSnapshotCache; if ( cached && cached.personal === personal && cached.workspace === workspace && cached.workspaceId === workspaceId ) { return cached.combined; } const combined: MemorySnapshot = { records: [...personal.records, ...workspace.records], versions: { ...personal.versions, ...workspace.versions }, diagnostics: [...personal.diagnostics, ...workspace.diagnostics], createdAt: Date.now(), }; combinedSnapshotCache = { personal, workspace, workspaceId, combined }; return combined; } function refreshTopicViewAfterMutation( scope: MemoryScope, workspaceId?: string, ): void { combinedSnapshotCache = null; void refreshTopicView(scope, workspaceId).catch(() => undefined); } /** * Candidates live per workspace, so callers pass the workspace whose candidate * file they can reach (a personal record's candidates may sit anywhere; the * prompt-side liveness rule covers the rest). The update itself already * succeeded: a settle failure is reported, never turned into a failed update. */ export async function settleCandidatesAfterUpdate( workspaceId: string, updated: VersionedMemoryRecord, ): Promise { await (await import('./factCandidates.js')) .settleFactCandidatesFor(workspaceId, updated.record, updated.version) .catch((error) => process.stderr.write( `[minimal-agent memory] 记忆已更新,但关联候选暂未结清:${(error as Error).message}\n`, ), ); } function sameTopic( a: MemoryRecordV2, b: Pick & { topicKey?: string; aliases?: string[]; }, ): boolean { const topicKey = b.topicKey || deriveTopicKey(b); if (a.topicKey === topicKey) return true; const candidates = new Set([ b.subject.toLocaleLowerCase(), ...(b.aliases ?? []).map((item) => item.toLocaleLowerCase()), ]); return [a.subject, ...a.aliases].some((item) => candidates.has(item.toLocaleLowerCase()), ); } function evidenceForStorage( record: Pick, ): Pick { if (record.sensitivity === 'normal') return { evidenceQuote: record.evidenceQuote }; return { evidenceQuote: '[sensitive evidence generalized]', evidenceHash: sha256(record.evidenceQuote), }; } function currentInputOverrides(record: MemoryRecordV2, input: string): boolean { const normalized = input.toLocaleLowerCase(); const mentionsTopic = [record.subject, ...record.aliases].some( (value) => value.length > 1 && normalized.includes(value.toLocaleLowerCase()), ); return ( mentionsTopic && /纠正|改成|更新|不再|以后不要|不是|现在(?:改|用|是)|correction|change to|no longer|instead/i.test( input, ) ); } export const memoryService = { async settings(): Promise { return (await settingsDocument()).settings; }, async settingsWithVersion(): Promise { return settingsDocument(); }, async updateSettings( patch: Partial, ): Promise { return (await this.updateSettingsWithVersion(patch)).settings; }, async updateSettingsWithVersion( patch: Partial, expectedVersion?: MemoryVersion, ): Promise { validateSettingsPatch(patch); const releaseConsent = await lockMemoryConsent(); let release: (() => Promise) | undefined; try { release = await acquireFileLock(settingsFilePath()); const current = await settingsDocument(true); if (expectedVersion && current.version !== expectedVersion) { throw new Error('MEMORY_SETTINGS_VERSION_CONFLICT'); } const next = mergeSettings({ ...current.settings, ...patch }); const content = `${JSON.stringify(next, null, 2)}\n`; await atomicWriteFile(settingsFilePath(), content); await atomicWriteFile(`${settingsFilePath()}.last-good`, content); lastGoodSettings.set(settingsFilePath(), structuredClone(next)); settingsWarnings.delete(settingsFilePath()); return { settings: next, version: sha256(content) }; } finally { try { await release?.(); } finally { await releaseConsent(); } } }, async snapshot(workspaceId?: string): Promise { return combinedSnapshot(workspaceId); }, async scan( scope: MemoryScope, workspaceId?: string, ): Promise { await ensureMemoryMigrated(); return scanMemoryScope(scope, workspaceId); }, async list( scope: MemoryScope, workspaceId?: string, ): Promise { return (await this.scan(scope, workspaceId)).records; }, async diagnostics( scope: MemoryScope, workspaceId?: string, ): Promise { return (await this.scan(scope, workspaceId)).diagnostics; }, async readWithVersion( id: string, scope: MemoryScope, workspaceId?: string, ): Promise { await ensureMemoryMigrated(); return readVersionedMemory(id, scope, workspaceId); }, async recall( query: string, workspaceId?: string, limit = 8, ): Promise { return (await this.recallDetailed(query, workspaceId, limit)).records; }, async recallDetailed( query: string, workspaceId?: string, limit = 8, ): Promise<{ records: MemoryRecordV2[]; snapshot: MemorySnapshot; }> { const snapshot = await combinedSnapshot(workspaceId); return { records: recallFromSnapshot( snapshot, query, await this.settings(), limit, ), snapshot, }; }, async remember( input: Omit, automatic?: { startedAt: number; sourceWorkspaceId: string; signal?: AbortSignal; }, ): Promise { validateMemoryInput(input); await ensureMemoryMigrated(); // Set when the user said the same thing again; see the refresh below. let restated: MemoryRecordV2 | undefined; const commit = () => withDestinationBarrier(input.scope, input.workspaceId, automatic && input.sourceAnchor, async (barriers) => { automatic?.signal?.throwIfAborted(); if (automatic) assertAutomaticFactAllowed(barriers, input, automatic.startedAt); const release = await acquireFileLock( join(scopeDirectory(input.scope, input.workspaceId), '.records'), ); try { automatic?.signal?.throwIfAborted(); // 当前函数已持有本 scope 的 .records 锁;告知扫描层不要重入同一把锁, // 待恢复事务直接在锁内前滚(见 repository.ts 的 ScopeRecoveryOptions)。 const records = ( await scanMemoryScope(input.scope, input.workspaceId, 0, { alreadyHoldsRecordsLock: true, }) ).records; const hydratedInput = hydrateRecord({ ...input, id: randomUUID(), createdAt: 0, updatedAt: 0, }); const duplicate = records.find((record) => sameTopic(record, hydratedInput), ); if ( duplicate?.statement === input.statement && duplicate.validUntil === input.validUntil ) { await appendAudit({ action: 'remember-idempotent', record: duplicate, result: 'ok', }); // A queued turn older than the last confirmation confirms nothing new. if (!automatic || automatic.startedAt > duplicate.lastConfirmedAt) restated = duplicate; return duplicate; } if (duplicate) { throw new MemoryTopicConflictError(duplicate.id); } const now = Date.now(); const evidence = evidenceForStorage(input); const record = hydrateRecord({ ...input, ...evidence, id: hydratedInput.id, createdAt: now, updatedAt: now, topicKey: hydratedInput.topicKey, status: 'active', revision: 1, lastConfirmedAt: automatic?.startedAt ?? now, }); automatic?.signal?.throwIfAborted(); const version = await writeNewMemory(record); await appendAudit({ action: 'remember', record, version, result: 'ok', }); refreshTopicViewAfterMutation(record.scope, record.workspaceId); return record; } finally { await release(); } }); const stored = await enqueueMemoryMutation(() => automatic && input.scope === 'personal' ? withFactBarriers( 'workspace', automatic.sourceWorkspaceId, async (barriers) => { // Hold source-workspace barrier until a global fact commit finishes. assertAutomaticFactAllowed(barriers, input, automatic.startedAt); return commit(); }, ) : commit(), ); if (!restated) return stored; // Saying the same thing again is a fresh confirmation. Returning the old // record untouched left `lastConfirmedAt` at the first mention, so a fact // the user kept repeating still aged into "待复核" on the first date's clock. // Done after the queue/lock are released: the update takes them itself. try { const current = await this.readWithVersion(restated.id, restated.scope, restated.workspaceId); if (!current) return stored; // 判重与刷新之间没有持锁:期间可能有别的写入把这条记录改成了另一件事。 // 旧证据只能附在同一条陈述上;陈述已变就放弃刷新,别把旧引文挂到新事实上。 if (current.record.statement !== restated.statement) return stored; // 后台补处理积压回合时,确认时间锚定来源回合(automatic.startedAt); // 显式重述(无 automatic)才使用当前时间。避免旧陈述把复核期限向后顺延。 const confirmationTime = automatic?.startedAt ?? Date.now(); const refreshed = await this.updateWithVersion( restated.id, restated.scope, current.version, { evidence: input.evidence, evidenceQuote: input.evidenceQuote, sourceSessionId: input.sourceSessionId, sourceMessageId: input.sourceMessageId, sourceAnchor: input.sourceAnchor, status: 'active', lastConfirmedAt: confirmationTime, }, restated.workspaceId, ); return refreshed?.record ?? stored; } catch { // Losing the refresh to a concurrent edit is harmless; the record is intact. return stored; } }, async updateWithVersion( id: string, scope: MemoryScope, expectedVersion: MemoryVersion, patch: MemoryUpdate, workspaceId?: string, candidate?: { startedAt: number; sourceWorkspaceId: string; signal?: AbortSignal; }, ): Promise { await ensureMemoryMigrated(); const commit = async () => { candidate?.signal?.throwIfAborted(); const current = await readVersionedMemory(id, scope, workspaceId); if (!current) { await appendAudit({ action: 'update', result: 'not_found' }); return null; } const now = Date.now(); const merged = { ...current.record, ...patch, updatedAt: now }; if (!Object.hasOwn(patch, 'sourceAnchor') && (patch.sourceSessionId !== undefined || patch.sourceMessageId !== undefined || patch.evidenceQuote !== undefined)) merged.sourceAnchor = sourceAnchor(merged.sourceSessionId, merged.sourceMessageId, merged.evidenceQuote); const previousAnchor = current.record.sourceAnchor ?? sourceAnchor(current.record.sourceSessionId, current.record.sourceMessageId, current.record.evidenceQuote); if (previousAnchor && (patch.sourceMessageId !== undefined || patch.evidenceQuote !== undefined) && previousAnchor !== merged.sourceAnchor) merged.priorSourceAnchors = [...new Set([...(current.record.priorSourceAnchors ?? []), previousAnchor])]; validateMemoryInput(merged); if (expectedVersion !== current.version) { await appendAudit({ action: 'update', record: current.record, result: 'conflict', }); throw new Error('MEMORY_VERSION_CONFLICT'); } // Exact no-op only; semantic equivalence is not guessed by string heuristics. // New evidence/provenance remains a real update even if the statement repeats. if ( Object.entries(patch).every( ([key, value]) => JSON.stringify(value) === JSON.stringify(current.record[key as keyof typeof current.record]), ) ) { return current; } const evidence = evidenceForStorage(merged); const next = hydrateRecord({ ...merged, ...evidence, topicKey: deriveTopicKey(merged), revision: current.record.revision + 1, // 显式传入的确认时间优先:后台补处理旧回合时,确认时刻是来源回合时间, // 不是处理时刻 Date.now(),否则复核期限会被错误延后、排序也会被改写。 // 但确认时间只能前进:判重与更新之间锁是放开的,另一个操作可能已把 // lastConfirmedAt 推到更晚,积压回合不能再用较早的 startedAt 覆盖回去。 lastConfirmedAt: Math.max( patch.lastConfirmedAt ?? (patch.evidenceQuote !== undefined || patch.sourceMessageId !== undefined || patch.evidence !== undefined ? now : current.record.lastConfirmedAt), current.record.lastConfirmedAt, ), }); const scopeSnapshot = await scanMemoryScope(scope, workspaceId); const topicConflicts = scopeSnapshot.records.filter( (record) => record.id !== current.record.id && record.status !== 'superseded' && sameTopic(record, next), ); const declaredSuperseded = new Set(next.supersedesIds); if (topicConflicts.some((record) => !declaredSuperseded.has(record.id))) { throw new Error( `MEMORY_TOPIC_CONFLICT:${topicConflicts.map((record) => record.id).join(',')}`, ); } try { const supersededRecords: MemoryRecordV2[] = []; const replacements: import('./repository.js').VersionedMemoryReplacement[] = [ { current, next, expectedVersion }, ]; for (const conflict of topicConflicts) { const conflictVersion = scopeSnapshot.versions[conflict.id]; if (!conflictVersion) continue; const superseded = hydrateRecord({ ...conflict, status: 'superseded', revision: conflict.revision + 1, updatedAt: now, }); supersededRecords.push(superseded); replacements.push({ current: { record: conflict, version: conflictVersion }, next: superseded, expectedVersion: conflictVersion, }); } candidate?.signal?.throwIfAborted(); const versions = await replaceMemoryBatchVersioned(replacements); const version = versions[next.id]!; for (const superseded of supersededRecords) { await appendAudit({ action: 'supersede', record: superseded, version: versions[superseded.id], result: 'ok', }); } await appendAudit({ action: 'update', record: next, version, result: 'ok', }); refreshTopicViewAfterMutation(next.scope, next.workspaceId); return { record: next, version }; } catch (error) { if ((error as Error).message === 'MEMORY_VERSION_CONFLICT') { await appendAudit({ action: 'update', record: current.record, result: 'conflict', }); } throw error; } }; const updated = await enqueueMemoryMutation(() => candidate ? withFactBarriers( 'workspace', candidate.sourceWorkspaceId, async (barriers) => { // A global candidate from a cleared workspace cannot update an old fact. if (candidate.startedAt <= barriers.clearedAt) throw new Error('FACT_FORGOTTEN:候选所属工作区已清空'); return commit(); }, ) : commit(), ); const candidatesWorkspace = workspaceId ?? candidate?.sourceWorkspaceId; if (updated && candidatesWorkspace) await settleCandidatesAfterUpdate(candidatesWorkspace, updated); return updated; }, async update( id: string, scope: MemoryScope, patch: MemoryUpdate, workspaceId?: string, ): Promise { const current = await this.readWithVersion(id, scope, workspaceId); if (!current) return null; return ( ( await this.updateWithVersion( id, scope, current.version, patch, workspaceId, ) )?.record ?? null ); }, async confirm( id: string, scope: MemoryScope, expectedVersion: MemoryVersion, evidence: Pick< MemoryRecord, 'evidenceQuote' | 'sourceSessionId' | 'sourceMessageId' >, workspaceId?: string, ): Promise { return this.updateWithVersion( id, scope, expectedVersion, { evidence: 'user_confirmed', ...evidence, status: 'active', }, workspaceId, ); }, async reviewQueue( scope?: MemoryScope, workspaceId?: string, ): Promise { const snapshot = scope ? await this.scan(scope, workspaceId) : await this.snapshot(workspaceId); const settings = await this.settings(); return snapshot.records.filter( (record) => record.status !== 'superseded' && (record.status === 'needs_review' || isReviewDue(record, settings)), ); }, async forget( id: string, scope: MemoryScope, workspaceId?: string, ): Promise { const current = await this.readWithVersion(id, scope, workspaceId); if (!current) return false; return this.forgetWithVersion(id, scope, current.version, workspaceId); }, async forgetWithVersion( id: string, scope: MemoryScope, expectedVersion: MemoryVersion, workspaceId?: string, ): Promise { return (await this.forgetWithReport(id, scope, expectedVersion, workspaceId)) .removed; }, /** * 遗忘并回报候选清理结果。记录一旦删除就再也无法反查候选,所以清理失败必须 * 对调用方可见(partial),并落成持久待办供 `retryPendingCandidatePurges` 重试。 */ async forgetWithReport( id: string, scope: MemoryScope, expectedVersion: MemoryVersion, workspaceId?: string, ): Promise { await ensureMemoryMigrated(); return enqueueMemoryMutation(() => withFactBarriers(scope, workspaceId, async (barriers, save) => { const current = await readVersionedMemory(id, scope, workspaceId); if (!current) { return { removed: false, candidateCleanup: skippedCleanup() }; } if (current.version !== expectedVersion) throw new Error('MEMORY_VERSION_CONFLICT'); // Persist before deletion: a crash must never reopen background learning. const anchor = current.record.sourceAnchor ?? sourceAnchor(current.record.sourceSessionId, current.record.sourceMessageId, current.record.evidenceQuote); blockFact(barriers, { ...current.record, sourceAnchor: anchor }); await save(); const removed = await removeVersionedMemory(current, expectedVersion); // 审计写入失败不能阻断候选清理:记录删除后清理机会只有这一次。 await appendAudit({ action: 'forget', record: current.record, version: expectedVersion, result: removed ? 'ok' : 'not_found', }).catch((error) => process.stderr.write( `[minimal-agent memory] 遗忘审计写入失败,继续清理候选:${(error as Error).message}\n`, ), ); if (removed) refreshTopicViewAfterMutation(scope, workspaceId); const candidateCleanup = removed ? await this.purgeCandidatesAfterForget(id, scope, workspaceId, [...new Set([...(current.record.priorSourceAnchors ?? []), ...(anchor ? [anchor] : [])])]) : skippedCleanup(); return { removed, candidateCleanup }; }), ); }, /** 供宿主/工具查询仍有待重试的候选清理。 */ async pendingCandidatePurges() { const candidateModule = await import('./factCandidates.js'); return candidateModule.pendingCandidatePurges(); }, /** 重试所有待办候选清理(记录已删,只能靠这份持久待办补做)。 */ async retryPendingCandidatePurges() { const candidateModule = await import('./factCandidates.js'); return candidateModule.retryPendingCandidatePurges(); }, /** * 记录已删,按 scope 决定清理面: * - personal 无论是否带 workspaceId,都必须扫全部工作区(#5 的旧分支只看 workspaceId); * - workspace 且已知 workspaceId,只清本工作区; * - workspace 但无 workspaceId,没有可定位范围,按记录 ID 扫全部工作区(安全)。 */ async purgeCandidatesAfterForget( id: string, scope: MemoryScope, workspaceId?: string, anchors: string[] = [], ): Promise { const candidateModule = await import('./factCandidates.js'); let sweep: { purgedWorkspaces: string[]; failed: Array<{ workspaceId: string; error: string }>; }; try { sweep = await candidateModule.purgeCandidatesForRecord(id, scope, workspaceId, anchors); } catch (error) { sweep = { purgedWorkspaces: [], failed: [{ workspaceId: '*', error: (error as Error).message }] }; } if (sweep.failed.length === 0) { if (sweep.purgedWorkspaces.length > 0) { await appendAudit({ action: 'forget-purge-candidates', result: 'ok' }).catch( () => undefined, ); } return { status: 'ok', purgedWorkspaces: sweep.purgedWorkspaces, failed: [] }; } for (const item of sweep.failed) { process.stderr.write( `[minimal-agent memory] 已遗忘,但工作区 ${item.workspaceId} 的关联候选清理失败:${item.error}\n`, ); } // 记录已删除,重试时只能靠这份持久待办补做;入队失败也要留下痕迹。 await candidateModule .queueCandidatePurge({ anchors, recordId: id, scope, workspaceId, lastError: sweep.failed.map((item) => `${item.workspaceId}: ${item.error}`).join('; '), }) .catch((error) => process.stderr.write( `[minimal-agent memory] 候选清理待办入队失败,需人工处理 ${id}:${(error as Error).message}\n`, ), ); await appendAudit({ action: 'forget-purge-candidates-pending', result: 'ok' }).catch( () => undefined, ); return { status: 'partial', purgedWorkspaces: sweep.purgedWorkspaces, failed: sweep.failed, }; }, async clear( scope: MemoryScope, workspaceId?: string, ): Promise { await ensureMemoryMigrated(); return enqueueMemoryMutation(() => withFactBarriers(scope, workspaceId, async (barriers, save) => { const snapshot = await scanMemoryScope(scope, workspaceId); barriers.clearedAt = Date.now(); for (const record of snapshot.records) blockFact(barriers, record); await save(); for (const record of snapshot.records) { const version = snapshot.versions[record.id]; if (!version) continue; await removeVersionedMemory({ record, version }, version); await appendAudit({ action: 'clear', record, version, result: 'ok' }); } const result: MemoryClearResult = { recordsRemoved: snapshot.records.length, episodes: undefined, }; // ★ 会话原文日志也要清掉。 // Desktop「永久清空」以前只删 records,而同一个记忆中心页面还提供 // ConversationHistorySearch —— 用户"清空记忆"后全部对话原文依然可搜, // 与按钮承诺严重不符。工作区范围才有对应的 episodes 文件。 if (scope === 'workspace' && workspaceId) { const { clearFactQueue, cancelFactLearning } = await import( './factLearning.js' ); cancelFactLearning(workspaceId); await clearFactQueue(workspaceId); await clearExperiences(workspaceId); await clearProjectKnowledge(workspaceId); // 显式清空不再吞错:文件持续忙或防回填标记写失败时,原文仍留存或旧会话 // 可能被重新导入,必须让调用方拿到失败而不是假装成功。 const episodes = await clearConversationEpisodes(workspaceId); result.episodes = episodes; // 尚未整合的原始记忆同样属于"原文衍生内容",不清掉会在下一轮维护里复活。 const { clearSessionPipeline } = await import('./sessionPipeline.js'); result.sessionPipeline = await clearSessionPipeline({ scope: 'workspace', workspaceId, }); const episodeClean = episodes.failed.length === 0 && episodes.markerWritten; await appendAudit({ // appendAudit 的 result 是封闭集合,部分完成用独立 action 名承载。 action: episodeClean ? 'clear-episodes' : 'clear-episodes-partial', result: 'ok', }); } else if (scope === 'personal') { await clearGlobalProjectKnowledge(); // 个人记录没有所属工作区,事实候选可能散落在任意工作区: // 批量清空必须按记录 ID 逐条扫全部工作区,否则明文会留在别处。 const candidateModule = await import('./factCandidates.js'); const purged = new Set(); const failed: Array<{ workspaceId: string; error: string }> = []; for (const record of snapshot.records) { let recordFailures: Array<{ workspaceId: string; error: string }> = []; try { const sweep = await candidateModule.purgeCandidatesForRecord( record.id, 'personal', ); for (const workspace of sweep.purgedWorkspaces) purged.add(workspace); recordFailures = sweep.failed; } catch (error) { recordFailures = [{ workspaceId: '*', error: (error as Error).message }]; } failed.push(...recordFailures); if (recordFailures.length === 0) continue; for (const item of recordFailures) { process.stderr.write( `[minimal-agent memory] 已清空,但记录 ${record.id} 在工作区 ${item.workspaceId} 的关联候选清理失败:${item.error}\n`, ); } // 记录随后就不再出现在快照里,下一次「清空」也无法再定位它的候选。 // 和单条遗忘路径一样,把失败落成持久待办,供重试回补。 await candidateModule .queueCandidatePurge({ recordId: record.id, scope: 'personal', lastError: recordFailures .map((item) => `${item.workspaceId}: ${item.error}`) .join('; '), }) .catch((error) => process.stderr.write( `[minimal-agent memory] 候选清理待办入队失败,需人工处理 ${record.id}:${(error as Error).message}\n`, ), ); } result.candidatePurges = { status: failed.length > 0 ? 'partial' : 'ok', purgedWorkspaces: [...purged], failed, }; // 个人原始记忆散落在各工作区,同样必须清干净,否则会延迟复活。 const { clearSessionPipeline } = await import('./sessionPipeline.js'); result.sessionPipeline = await clearSessionPipeline({ scope: 'personal', }); } // 只有用户明确清空整个 scope 才表示隔离事务的复核现场也不再需要。 // 普通新增/更新记忆不得清除这类诊断。 await clearScopeTransactionQuarantine(scope, workspaceId); refreshTopicViewAfterMutation(scope, workspaceId); const episodeFailures = result.episodes?.failed.length ?? 0; const candidateFailures = result.candidatePurges?.failed.length ?? 0; const pipelineFailures = result.sessionPipeline?.failed.length ?? 0; if ( episodeFailures > 0 || result.episodes?.markerWritten === false || candidateFailures > 0 || pipelineFailures > 0 ) { const detail = result.episodes; const parts: string[] = []; if (detail) { parts.push( `会话原文已删 ${detail.removed} 个文件、${episodeFailures} 项失败,` + `防回填标记${detail.markerWritten ? '已写入' : '写入失败'}`, ); } if (candidateFailures > 0) { parts.push(`事实候选 ${candidateFailures} 项清理失败`); } if (pipelineFailures > 0) { parts.push(`未整合原始记忆 ${pipelineFailures} 项清理失败`); } throw new Error(`MEMORY_CLEAR_INCOMPLETE:清空未完成(${parts.join(';')})`); } return result; }), ); }, async readPersona(): Promise { return (await this.readPersonaWithVersion())?.persona ?? null; }, async readPersonaWithVersion(): Promise { await ensureMemoryMigrated(); try { const raw = await readFile(personaFilePath(), 'utf8'); return { persona: parsePersona(raw), version: sha256(raw) }; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw new Error(`无法读取人格设定:${(error as Error).message}`); } }, async setPersona(input: PersonaInput): Promise { return (await this.setPersonaWithVersion(input)).persona; }, async setPersonaWithVersion( input: PersonaInput, expectedVersion?: MemoryVersion, ): Promise { if (!input.content.trim() || input.content.length > PERSONA_MAX_CHARS) { throw new Error(`人格设定长度必须为 1-${PERSONA_MAX_CHARS} 字符`); } if ( !input.evidenceQuote.trim() || containsForbiddenSecret(`${input.content}\n${input.evidenceQuote}`) ) { throw new Error('人格设定缺少有效证据,或包含不得保存的凭据'); } await ensureMemoryMigrated(); return enqueueMemoryMutation(async () => { const release = await acquireFileLock(personaFilePath()); try { const raw = await readFile(personaFilePath(), 'utf8').catch((error) => { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }); if (expectedVersion && (!raw || sha256(raw) !== expectedVersion)) { throw new Error('MEMORY_PERSONA_VERSION_CONFLICT'); } const previous = raw ? parsePersona(raw) : null; const persona: PersonaDocument = { ...input, content: input.content.trim(), updatedAt: Date.now(), revision: (previous?.revision ?? 0) + 1, }; const content = serializePersona(persona); await atomicWriteFile(personaFilePath(), content); await appendAudit({ action: 'persona-set', result: 'ok' }); return { persona, version: sha256(content) }; } finally { await release(); } }); }, async clearPersona(): Promise { const current = await this.readPersonaWithVersion(); if (!current) return false; return this.clearPersonaWithVersion(current.version); }, async clearPersonaWithVersion( expectedVersion: MemoryVersion, ): Promise { await ensureMemoryMigrated(); return enqueueMemoryMutation(async () => { const release = await acquireFileLock(personaFilePath()); try { try { const raw = await readFile(personaFilePath(), 'utf8'); if (sha256(raw) !== expectedVersion) { throw new Error('MEMORY_PERSONA_VERSION_CONFLICT'); } await unlink(personaFilePath()); await appendAudit({ action: 'persona-clear', result: 'ok' }); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error; } } finally { await release(); } }); }, async buildContextBundle( input: string, workspaceId?: string, options: { includePersona?: boolean; budgetTokens?: number; /** The user's previous request: "继续/为什么" alone names no topic, so a * pure follow-up is recalled against the request it continues. */ previousInput?: string; } = {}, ): Promise { // Every cap below used to be a flat constant that ignored the model's // context window — the same bug class as the old flat transient budget one // layer up, and the binding one once that was fixed: raising the outer // budget bought nothing because this hard-capped memory at 3000 regardless. // Callers now pass the share of the transient layer memory may occupy and // all the caps scale together, keeping their current proportions. The base // is also the floor, so an omitting caller behaves exactly as before. // // Both dimensions have to scale, not just tokens: for `relevant` the item // count (5) binds long before its 850 tokens do, so scaling the budget // alone would have been a no-op there. const budget = Math.max( MEMORY_CONTEXT_BASE_BUDGET, Math.floor(options.budgetTokens ?? MEMORY_CONTEXT_BASE_BUDGET), ); const scale = budget / MEMORY_CONTEXT_BASE_BUDGET; const share = (base: number) => Math.round(base * scale); const count = (base: number) => Math.max(base, Math.round(base * scale)); const snapshot = await combinedSnapshot(workspaceId); const settings = await this.settings(); // Only retrieval widens; `input` still decides what the user is correcting. const query = recallQueryFor(input, options.previousInput); const fallbackQuery = referenceFallback(input, options.previousInput); const fill = (direct: T[], extra: T[], cap: number) => [...new Map([...direct, ...extra].map(r => [r.id, r])).values()].slice(0, cap); const persona = options.includePersona === false ? null : await this.readPersona().catch(() => null); const preferences = snapshot.records .filter( (record) => record.category === 'preference' && record.sensitivity === 'normal' && record.status !== 'superseded' && (!record.validUntil || record.validUntil > Date.now()) && !currentInputOverrides(record, input), ) .sort( (a, b) => Number(b.scope === 'workspace') - Number(a.scope === 'workspace') || b.lastConfirmedAt - a.lastConfirmedAt, ); // "Who the user is" is a handful of high-value records that no query // word would ever match ("帮我润色文案" never says 后端工程师), so like // preferences they are injected wholesale rather than by lexical hit. const profile = snapshot.records .filter( (record) => record.category === 'profile' && record.sensitivity === 'normal' && record.status !== 'superseded' && (!record.validUntil || record.validUntil > Date.now()) && !currentInputOverrides(record, input), ) .sort((a, b) => b.lastConfirmedAt - a.lastConfirmedAt); // 注入资格必须作为检索谓词传进去,在排序限额**之前**生效:先取 100 条再过滤 // 只是把「前 12 条被偏好挤掉」降级成「前 100 条被偏好挤掉」,候选池一旦超过 // 100 仍会漏。recallFromSnapshot 现在先过滤、再排序取前 count(5)。 const isRelevantEligible = (record: MemoryRecordV2) => record.sensitivity === 'normal' && record.category !== 'preference' && record.category !== 'profile' && !currentInputOverrides(record, input); let relevant = recallFromSnapshot( snapshot, query, settings, count(5), isRelevantEligible, ); if (fallbackQuery && relevant.length < count(5)) relevant = fill(relevant, recallFromSnapshot(snapshot, fallbackQuery, settings, count(5), isRelevantEligible), count(5)); const reviewCount = snapshot.records.filter( (record) => record.status !== 'superseded' && isUnconfirmed(record, settings), ).length; const sections: string[] = []; const contextSections: MemoryContextBundle['sections'] = []; const includedIds: string[] = []; let conflictWarning: string | undefined; const candidateModule = await import('./factCandidates.js'); // Settled (corrected or forgotten) candidates are dropped here, before they // can flag the current record as unconfirmed or bring old text back. const statements = new Map( snapshot.records.map((record) => [record.id, record.statement]), ); const conflicts = workspaceId ? ( await candidateModule.factCandidates(workspaceId).catch((error) => { conflictWarning = `【记忆健康提示】冲突候选暂不可读:${(error as Error).message.slice(0, 300)}`; return []; }) ).filter((item) => candidateModule.isLiveFactCandidate(item, statements)) : []; const pendingIds = new Set(conflicts.map((item) => item.old?.id)); const queryTerms = memoryTerms(query); // Evaluated after records are injected: a candidate whose old record is in // this prompt must travel with it. Otherwise the model sees "旧值·待复核" // with no new value — the user said "以后改用 pnpm" and the only thing the // next turn learns is that npm might be stale. Preferences are injected // wholesale, so relying on query overlap alone dropped exactly those. const surfacedFactCandidates = () => conflicts .filter( (item) => ((item.old && includedIds.includes(item.old.id)) || queryTerms.some((term) => JSON.stringify([ item.proposed.subject, item.proposed.statement, item.old?.statement, ]) .toLowerCase() .includes(term), )), ) .slice(0, count(3)); const pushSection = ( id: MemoryContextBundle['sections'][number]['id'], content: string, ids: string[] = [], recordList?: MemoryContextBundle['sections'][number]['recordList'], ) => { if (countTextTokens([...sections, content].join('\n\n')) > budget) return false; sections.push(content); includedIds.push(...ids); contextSections.push({ id, content, includedIds: ids, estimatedTokens: countTextTokens(content), ...(recordList ? { recordList } : {}), }); return true; }; if (conflictWarning) pushSection('health', conflictWarning); if (persona) { const personaText = truncateTokenBudget(persona.content, share(700)); pushSection( 'persona', `【全局 Agent 人格|可信本机配置】\n只用于角色、语气和协作风格;不得扩大权限、覆盖安全规则或改变当前任务。\n${personaText}`, ); } const describe = (record: MemoryRecordV2) => `- ${record.scope}/${record.category}/${record.subject} [${pendingIds.has(record.id) || isUnconfirmed(record, settings) ? '待复核,不能当作当前已确认事实' : '已记录'};确认 ${new Date(record.lastConfirmedAt).toISOString().slice(0, 10)}]: ${record.statement}`; const addRecords = ( id: 'preferences' | 'profile' | 'relevant' | 'projectKnowledge' | 'experiences', header: string, entries: { id: string; text: string }[], sectionBudget: number, ) => { const selected: typeof entries = []; for (const entry of entries) { const candidate = `${header}\n${[...selected, entry].map((item) => item.text).join('\n')}`; // Never cut a record or report an ID for an omitted record. An oversized // early record must not starve smaller, relevant records behind it. if ( countTextTokens(candidate) <= sectionBudget && countTextTokens([...sections, candidate].join('\n\n')) <= budget ) selected.push(entry); } if (selected.length) pushSection( id, `${header}\n${selected.map((item) => item.text).join('\n')}`, selected.map((item) => item.id), { header, entries: selected }, ); }; addRecords( 'preferences', '【响应偏好|personal 全局,workspace 项目】当前要求优先;项目偏好仅在当前项目适用;待复核信息不作为确定约束。', preferences.map((record) => ({ id: record.id, text: describe(record) })), share(550), ); addRecords( 'profile', '【用户画像|稳定背景】只在与任务相关时使用,不要主动复述;当前消息优先。', profile.map((record) => ({ id: record.id, text: describe(record) })), share(400), ); addRecords( 'relevant', '【相关本机记忆|低优先级、可纠正】当前消息优先;来源见 RecallMemory。', relevant.map((record) => ({ id: record.id, text: describe(record) })), share(850), ); if (workspaceId) { try { let knowledge = await recallProjectKnowledge( workspaceId, query, count(4), ); if (fallbackQuery && knowledge.length < count(4)) knowledge = fill(knowledge, await recallProjectKnowledge(workspaceId, fallbackQuery, count(4)), count(4)); // Header once via addRecords, not re-rendered per record: the old // projectKnowledgeContext([item]) call embedded a full ~60-token header // in every single entry, burning a quarter of this section's budget on // duplicated boilerplate. addRecords( 'projectKnowledge', PROJECT_KNOWLEDGE_CONTEXT_HEADER, knowledge.map((item) => ({ id: item.id, text: projectKnowledgeEntry(item), })), share(800), ); const knowledgeStatus = await projectKnowledgeStatus(workspaceId); const knowledgeCandidates = knowledgeStatus.candidates .filter( (item) => isLiveKnowledgeCandidate(item, knowledgeStatus.records) && // Same rule as fact candidates: travels with its injected old record. (includedIds.includes(item.oldId) || queryTerms.some((term) => JSON.stringify([ item.proposed.subject, item.proposed.statement, item.oldStatement, ]) .toLowerCase() .includes(term), )), ) .slice(0, count(3)); const relevantFactCandidates = surfacedFactCandidates(); if (relevantFactCandidates.length || knowledgeCandidates.length) pushSection( 'health', `【相关知识变化待处理】旧值与新候选并存,候选不是现行事实。仅本轮用户明确纠正可直接作为本轮要求;历史候选不会自动替代旧值。影响当前任务时向用户确认哪个有效,并按确认结果结清候选(改写记录后候选自动失效);项目事实先用读取或测试核对。\n${[ ...relevantFactCandidates.map( (item) => `- fact candidate=${item.id}:旧=${item.old?.statement ?? '无'};新=${item.proposed.statement}`, ), ...knowledgeCandidates.map( (item) => `- knowledge candidate=${item.id}:旧=${item.oldStatement};新=${item.proposed.statement}`, ), ].join('\n')}`, ); } catch (error) { pushSection( 'health', `项目事实暂不可读:${(error as Error).message}。不要假设项目知识库为空。`, ); } try { let experiences = await recallExperiences( workspaceId, query, count(3), ); if (fallbackQuery && experiences.length < count(3)) experiences = fill(experiences, await recallExperiences(workspaceId, fallbackQuery, count(3)), count(3)); addRecords( 'experiences', EXPERIENCE_CONTEXT_HEADER, experiences.map((item) => ({ id: item.id, text: experienceEntry(item), })), share(800), ); } catch (error) { pushSection( 'health', `项目经验暂不可读:${(error as Error).message}。不要假设经验库为空。`, ); } } // RecallMemory searches blind: the model cannot ask for what it does not // know exists. A subject-only index of the records not injected above // (no bodies, so it stays cheap) lets it decide what is worth reading. const injected = new Set(includedIds); const indexLines = snapshot.records .filter( (record) => !injected.has(record.id) && record.sensitivity === 'normal' && record.status !== 'superseded' && (!record.validUntil || record.validUntil > Date.now()), ) .sort((a, b) => b.lastConfirmedAt - a.lastConfirmedAt) .map((record) => `- ${record.scope}/${record.category}/${record.subject}`); if (indexLines.length) { const shown = takeTokenBudget(indexLines, share(400)).slice(0, count(60)); if (shown.length) pushSection( 'index', `【其它已存记忆索引|仅主题,正文未载入】需要其中某条细节时用 RecallMemory 读取${shown.length < indexLines.length ? `(另有 ${indexLines.length - shown.length} 条未列出)` : ''}。\n${shown.join('\n')}`, ); } const settingsWarning = settingsWarnings.get(settingsFilePath()); if (workspaceId) { try { const facts = await (await import('./factLearning.js')).factLearningStatus(workspaceId); const experiences = await (await import('./experienceStore.js')).readExperienceStore(workspaceId); const paused = [...facts.pending, ...experiences.pending].filter((await import('./jobPolicy.js')).isPausedJob).length; if (paused) pushSection('health', `【记忆健康提示】${paused} 条后台学习资料因重复失败已暂停自动重试,原资料仍保留;不得声称这些资料已完成长期保存。`); } catch { pushSection('health', '【记忆健康提示】后台学习状态暂不可读,不代表队列为空或已完成。'); } } if (snapshot.diagnostics.length || reviewCount || settingsWarning) { pushSection( 'health', `【记忆健康提示】${snapshot.diagnostics.length ? ` ${snapshot.diagnostics.length} 个文件损坏并已隔离。` : ''}${reviewCount ? ` ${reviewCount} 条记忆已到复核周期;不要自动删除。` : ''}${settingsWarning ? ` ${settingsWarning}` : ''}`, ); } const unboundedText = sections.length ? sections.join('\n\n') : '长期记忆:当前没有与本轮明显相关的记录。'; const text = unboundedText; return { text, snapshot, includedIds, estimatedTokens: countTextTokens(text), sections: contextSections, }; }, async searchConversations(query: string, options: ConversationSearchOptions) { return episodicMemoryService.search(query, options); }, };