Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot): treat sources before /clear as withdrawn from working memory
zqchris089d44baaa50
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.tsindex ee9ae3a706..89379f43c0 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';/*** 最小 drizzle 假链:每次 select() 按顺序弹出一组行;链上任何方法都返回自身并可 await。- * 读取路径依次 select:伙伴归属 → 来源消息存活 → 进行中的后台任务。+ * 读取路径依次 select:伙伴归属 → 会话 cleared_at → 来源消息存活 → 进行中的后台任务。*/const db = vi.hoisted(() => ({ queue: [] as unknown[][] }));vi.mock('../../localDb/client/current.js', () => ({@@ -293,19 +293,19 @@ describe('store', () => {0,);const dbRows = [- { clientId: 'live', rewindAt: null, role: 'assistant' },- { clientId: 'rewound', rewindAt: 1_700_000_000_000, role: 'user' },- { clientId: 'tomb', rewindAt: null, role: 'message_tombstone' },+ { clientId: 'live', rewindAt: null, role: 'assistant', createdAt: 10 },+ { clientId: 'rewound', rewindAt: 1_700_000_000_000, role: 'user', createdAt: 10 },+ { clientId: 'tomb', rewindAt: null, role: 'message_tombstone', createdAt: 10 },];- // 渲染:伙伴归属 → 来源存活 → 后台任务。- db.queue.push([{ botId: 'bot-1' }], dbRows, []);+ // 渲染:伙伴归属 → 会话 cleared_at → 来源存活 → 后台任务。+ db.queue.push([{ botId: 'bot-1' }], [{ clearedAt: null }], dbRows, []);const note = (await readWorkingMemoryNoteForSession('s-bot', root))!;expect(note).toContain('仍在时间线上的承诺');expect(note).not.toContain('撤回');expect(note).not.toContain('墓碑');// 磁盘上还没清;rewind 提交后对账持久清掉。expect((await readBotWorkingMemory(root, 'bot-1'))!.commitments).toHaveLength(3);- db.queue.push([{ botId: 'bot-1' }], dbRows);+ db.queue.push([{ botId: 'bot-1' }], [{ clearedAt: null }], dbRows);expect(await pruneWithdrawnWorkingMemoryForSession('s-bot', root)).toBe(3);const after = (await readBotWorkingMemory(root, 'bot-1'))!;expect(after.commitments.map((c) => c.id)).toEqual(['c-live']);@@ -318,6 +318,40 @@ describe('store', () => {expect(await pruneWithdrawnWorkingMemoryForSession('s-task', root)).toBe(0);});+ it('treats items whose source message predates /clear as withdrawn, and prunes them after the clear is persisted', async () => {+ await writeBotWorkingMemory(+ root,+ 'bot-1',+ {+ ...emptyWorkingMemory(),+ updatedAt: 1,+ commitments: [+ { id: 'c-after', text: '清空之后答应的事', messageId: 'after', updatedAt: 3 },+ { id: 'c-before', text: '清空之前答应的事', messageId: 'before', updatedAt: 2 },+ ],+ corrections: [{ id: 'x-before', text: '清空之前的纠正', messageId: 'before', updatedAt: 2 }],+ waiting: [{ id: 'w-before', text: '清空之前在等的回复', messageId: 'before', on: 'user', updatedAt: 2 }],+ },+ 0,+ );+ const clearedAt = 1_000;+ const dbRows = [+ { clientId: 'after', rewindAt: null, role: 'assistant', createdAt: clearedAt + 1 },+ // 清空边界本身也算清空前(与 listMessagesForAgentHandoff 的 createdAt > clearedAt 一致)。+ { clientId: 'before', rewindAt: null, role: 'user', createdAt: clearedAt },+ ];+ db.queue.push([{ botId: 'bot-1' }], [{ clearedAt }], dbRows, []);+ const note = (await readWorkingMemoryNoteForSession('s-bot', root))!;+ expect(note).toContain('清空之后答应的事');+ expect(note).not.toContain('清空之前');+ db.queue.push([{ botId: 'bot-1' }], [{ clearedAt }], dbRows);+ expect(await pruneWithdrawnWorkingMemoryForSession('s-bot', root)).toBe(3);+ const after = (await readBotWorkingMemory(root, 'bot-1'))!;+ expect(after.commitments.map((c) => c.id)).toEqual(['c-after']);+ expect(after.corrections).toEqual([]);+ expect(after.waiting).toEqual([]);+ });+it('treats a corrupt or foreign file as no ledger', async () => {await fs.mkdir(path.join(root, 'bots', 'bot-2'), { recursive: true });await fs.writeFile(workingMemoryPath(root, 'bot-2'), '{not json', 'utf8');@@ -357,6 +391,12 @@ describe('helpers', () => {expect(registry.pendingGeneration('s')).toBe(second);registry.consume('s', second);expect(registry.pendingGeneration('s')).toBeNull();+ // /clear:清空前登记的标记作废,清空后第一次发送不再注入旧账本;其它会话不受影响。+ registry.markCompacted('s');+ registry.markCompacted('other');+ registry.reset('s');+ expect(registry.pendingGeneration('s')).toBeNull();+ expect(registry.pendingGeneration('other')).not.toBeNull();const note = buildWorkingMemoryRefreshNote('BODY');expect(note).toContain('[Working memory refresh');expect(note).toContain('BODY');diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.tsindex f5bbfddd45..ea6e8e311c 100644--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts@@ -535,9 +535,10 @@ function sourceMessageIds(memory: BotWorkingMemory): string[] {}/**- * 账本条目的来源消息里,已经不在会话可见时间线上的那些:被 rewind(含「编辑上一条消息」)- * 软删(`rewind_at` 非空)、被删除成墓碑、或根本找不到。这些条目和被删消息产生的条目一样,- * 不能再借交接回到新上下文。+ * 账本条目的来源消息里,已经不在会话可见时间线上的那些:在 `/clear` 边界之前+ * (`created_at <= sessions.cleared_at`,与 listMessagesForAgentHandoff 同一判据)、被 rewind+ * (含「编辑上一条消息」)软删(`rewind_at` 非空)、被删除成墓碑、或根本找不到。这些条目和+ * 被删消息产生的条目一样,不能再借交接回到新上下文。*/export async function listWithdrawnSourceMessageIds(sessionId: string,@@ -545,12 +546,26 @@ export async function listWithdrawnSourceMessageIds(): Promise<Set<string>> {const ids = sourceMessageIds(memory);if (ids.length === 0) return new Set();- const rows = await getDbClient()- .drizzle.select({ clientId: messages.clientId, rewindAt: messages.rewindAt, role: messages.role })+ const db = getDbClient().drizzle;+ const [session] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const clearedAt = session?.clearedAt ?? null;+ const rows = await db+ .select({ clientId: messages.clientId, rewindAt: messages.rewindAt, role: messages.role, createdAt: messages.createdAt }).from(messages).where(and(eq(messages.sessionId, sessionId), inArray(messages.clientId, ids)));const live = new Set(- rows.filter((row) => row.rewindAt === null && row.role !== 'message_tombstone').map((row) => row.clientId),+ rows+ .filter(+ (row) =>+ row.rewindAt === null &&+ row.role !== 'message_tombstone' &&+ (clearedAt === null || row.createdAt > clearedAt),+ )+ .map((row) => row.clientId),);return new Set(ids.filter((id) => !live.has(id)));}@@ -596,8 +611,9 @@ export async function pruneWorkingMemoryForSession(}/**- * rewind 提交成功后调用:按数据库现状持久清掉来源已撤回的条目。rewind 不返回被软删的- * 消息清单,所以直接对账而不是接收 id 列表;失败不抛,渲染时的统一过滤仍兜底。+ * rewind / `/clear` 提交成功后调用:按数据库现状持久清掉来源已撤回的条目。两条路径都不+ * 返回被移出时间线的消息清单,所以直接对账而不是接收 id 列表;失败不抛,渲染时的统一+ * 过滤仍兜底。*/export async function pruneWithdrawnWorkingMemoryForSession(sessionId: string,@@ -631,6 +647,8 @@ export interface WorkingMemoryRefreshRegistry {pendingGeneration(sessionId: string): number | null;/** 引擎接受发送后调用;只有代次仍是当时读到的那一代才清除。 */consume(sessionId: string, generation: number): void;+ /** `/clear` 时调用:清空前登记的压缩标记作废,不能在清空后的第一次发送注入旧账本。 */+ reset(sessionId: string): void;}export function createWorkingMemoryRefreshRegistry(): WorkingMemoryRefreshRegistry {@@ -642,6 +660,7 @@ export function createWorkingMemoryRefreshRegistry(): WorkingMemoryRefreshRegistconsume: (sessionId, gen) => {if (pending.get(sessionId) === gen) pending.delete(sessionId);},+ reset: (sessionId) => void pending.delete(sessionId),};}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 770ce9eefd..a6439c6477 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -603,6 +603,7 @@ import {import {buildWorkingMemoryRefreshNote,createWorkingMemoryRefreshRegistry,+ pruneWithdrawnWorkingMemoryForSession,pruneWorkingMemoryForSession,readWorkingMemoryNoteForSession,} from './botWorkingMemory.js';@@ -19785,6 +19786,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)agentHandoffPending.invalidate(sid);// 清空后的原生上下文没看过任何环境说明:下一轮整体重发。wireNoteMemory.reset(sid);+ // 清空前登记的压缩刷新标记同样作废:否则清空后的第一次发送会把清空前的账本注入。+ workingMemoryRefresh.reset(sid);getAgentIslandService()?.notifyQueueEmptied(sid);// 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。goalClearObserver?.(sid);@@ -19799,6 +19802,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)typeof clearBoundary === 'number' ? clearBoundary : new Date(clearBoundary).getTime();try {await clearSessionContextInDb(sid, clearBoundaryMs);+ // cleared_at 落库后,清空前产生的伙伴工作记忆条目一并持久清掉(与 rewind / 删除+ // 同一失效模式);失败不影响 clear,渲染时按 cleared_at 的统一过滤仍兜底。+ await pruneWithdrawnWorkingMemoryForSession(sid, ownerScopedUserDataPath()).catch(() => 0);} catch (err) {// The in-memory fence is still authoritative for this process. Keep// /clear remains a local cleanup action even when persistence fails;diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex a2501cd747..f044022ed6 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -81,8 +81,10 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭学习复盘顺手更新,不新增模型调用;新条目必须有本轮用户或伙伴原话证据,漏写的旧条目保留,删除同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动压缩之后的下一次发送再补一次,交接首条已带时不重复。账本是摘要,不是授权:历史授权不是新的-执行许可;后台任务状态从任务记录现读,不信账本文本。不是伙伴主对话、没有账本或读取失败时一律-按无,不能挡住换窗。实现见 `botWorkingMemory.ts`,回归见 `botWorkingMemory.test.ts`。+执行许可;后台任务状态从任务记录现读,不信账本文本。来源消息离开可见时间线(删除、rewind/+编辑上一条、`/clear` 边界之前)时对应条目同步失效:渲染前统一过滤,提交后持久清掉,清空还作废+清空前登记的压缩刷新标记。不是伙伴主对话、没有账本或读取失败时一律按无,不能挡住换窗。实现见+`botWorkingMemory.ts`,回归见 `botWorkingMemory.test.ts`。完整聊天记录与模型工作上下文必须分离:压缩可以丢弃模型不再需要的旧 tool result 和中间过程,但用户时间线、搜索索引和审计记录仍按既有持久化策略保留。完整消息继续写入 SQLite,界面与