Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot): anchor the ledger watermark on message client_id; a new ledger backfills from the start
zqchris69a40a483d14
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.tsindex c4df83873f..38f2faff01 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts@@ -21,6 +21,8 @@ const h = vi.hoisted(() => ({gapRows: [] as any[],/** 本轮取材查询返回的行;null = 默认一条用户消息。 */turnRows: null as any[] | null,+ /** 按账本 client_id 解析水位时返回的当前 rowid;null = 解析不到。 */+ floorRowid: null as number | null,}));vi.mock('../../appSessionState.js', () => ({activeOwnerScopeKey: () => h.owner,@@ -30,9 +32,11 @@ vi.mock('../../appSessionState.js', () => ({vi.mock('../../localDb/client/current.js', () => {const db = {queryOne: async (sql: string) =>- sql.includes('MAX(rowid)')- ? { rowid: h.prevCompleted }- : h.visible+ sql.includes('prev-completed')+ ? h.prevCompleted ? { id: 'prev', rowid: h.prevCompleted } : undefined+ : sql.includes('ledger-floor')+ ? h.floorRowid === null ? undefined : { rowid: h.floorRowid }+ : h.visible? {botId: 'bot',capabilities: JSON.stringify({ memory: h.enabled }),@@ -248,6 +252,8 @@ it('feeds the working memory to the review and writes an evidence-filtered ledge'bot',expect.objectContaining({coveredThroughRowid: 5,+ // 水位同时记下当前回复的 client_id,作为瘦身重排后仍然可靠的持久判据。+ coveredThroughMessageId: 'reply',commitments: [expect.objectContaining({ text: 'Lead every report with the conclusion', messageId: 'user' })],}),4,@@ -275,16 +281,36 @@ it('advances the ledger watermark only through the contiguous backfilled prefixgap(2, 41).map((m) => m.id),);expect(input.messages.at(-1).id).toBe('user');- expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 41 }), 4);- // 下一轮从 41 接上,剩余一条补完:水位推进到当前回复(102)。+ expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 41, coveredThroughMessageId: 'g41' }), 4);+ // 下一轮按 client_id 'g41' 解析回当前 rowid(41)接上,剩余一条补完:水位推进到当前回复(102)。h.meta = { turnCompleted: true };- h.working = { ...ledger, coveredThroughRowid: 41 };+ h.working = { ...ledger, coveredThroughRowid: 41, coveredThroughMessageId: 'g41' };+ h.floorRowid = 41;h.gapRows = gap(42, 42);h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });await reviewTeammateLearning('session', 'reply2');- expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 102 }), 4);+ expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 102, coveredThroughMessageId: 'reply2' }), 4);h.prevCompleted = 3;h.gapRows = [];+ h.floorRowid = null;+});++it('resolves the ledger floor by client_id so a VACUUM-renumbered rowid cannot fake freshness, and starts a brand-new ledger from the beginning', async () => {+ const query = (getDbClient() as unknown as { query: ReturnType<typeof vi.fn> }).query;+ // 瘦身后 rowid 重排:账本存的 500 已经没有意义,按 client_id 解析回当前的 1 接上,写回当前库的水位(5)而不是保留 500。+ h.working = { version: 1, revision: 4, coveredThroughRowid: 500, coveredThroughMessageId: 'old-reply', updatedAt: 0, threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [] };+ h.floorRowid = 1;+ h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });+ await reviewTeammateLearning('session', 'reply');+ expect(query.mock.calls.at(-1)![1]).toEqual(['session', 1, 3, 'session', 41]);+ expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 5, coveredThroughMessageId: 'reply' }), 4);+ // 没有账本:从对话开头起算,整段历史按缺口分批回补,而不是从上一条完成回复直接跳过去。+ h.meta = { turnCompleted: true };+ h.working = null;+ h.floorRowid = null;+ h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });+ await reviewTeammateLearning('session', 'reply2');+ expect(query.mock.calls.at(-1)![1]).toEqual(['session', 0, 3, 'session', 41]);});it('does not advance the watermark past the previous completed reply when the current turn itself was truncated', async () => {@@ -296,6 +322,6 @@ it('does not advance the watermark past the previous completed reply when the cu];h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });await reviewTeammateLearning('session', 'reply');- expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 3 }), 0);+ expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 3, coveredThroughMessageId: 'prev' }), 0);h.turnRows = null;});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.tsindex aeeeb43c72..2fc1d5baab 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts@@ -72,8 +72,9 @@ describe('applyWorkingMemoryProposal', () => {resolved: [],},messages,- { now, coveredThroughRowid: 42 },+ { now, coveredThroughRowid: 42, coveredThroughMessageId: 'a1' },);+ expect(next.coveredThroughMessageId).toBe('a1');expect(next.threads.map((t) => t.text)).toEqual(['改周报模板']);expect(next.commitments.map((c) => c.text)).toEqual(['周五前改完周报模板并发用户确认']);expect(next.commitments[0]).toMatchObject({ messageId: 'a1', trigger: '周五前' });@@ -113,8 +114,16 @@ describe('applyWorkingMemoryProposal', () => {// 原样带回的条目连时间都不动,排序才能表达"最新优先"。expect(next.commitments.find((c) => c.id === 'c1')).toMatchObject({ messageId: 'old', updatedAt: 1 });expect(next.recentlyDone.map((d) => d.text)).toEqual(['测试已补上']);- // 水位只前进不后退。+ // 旧式只带 rowid 的调用:水位只前进不后退。expect(next.coveredThroughRowid).toBe(10);+ // 带 client_id 的调用已按当前库解析过(瘦身重排后 rowid 可能变小):照用,不被旧数字卡住。+ const remapped = applyWorkingMemoryProposal(+ { ...previous, coveredThroughRowid: 500, coveredThroughMessageId: 'old' },+ { threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [], resolved: [] },+ messages,+ { now, coveredThroughRowid: 5, coveredThroughMessageId: 'a1' },+ );+ expect(remapped).toMatchObject({ coveredThroughRowid: 5, coveredThroughMessageId: 'a1' });});it('requires evidence to change a field of an existing item, allows evidenced clearing, and bumps time only on real change', () => {@@ -361,19 +370,25 @@ describe('store', () => {});it('is fresh only when the ledger covers the latest completed reply of a companion chat', async () => {- await writeBotWorkingMemory(root, 'bot-1', { ...emptyWorkingMemory(), updatedAt: 1, coveredThroughRowid: 12 }, 0);- // 伙伴归属 → 最近一条已完成回复的 rowid。- db.queue.push([{ botId: 'bot-1' }], [{ rowid: 12 }]);+ // 账本存的 rowid(999)是瘦身前的数字,不作数;按 client_id 'r12' 解析回当前 rowid 再比较。+ await writeBotWorkingMemory(root, 'bot-1', { ...emptyWorkingMemory(), updatedAt: 1, coveredThroughRowid: 999, coveredThroughMessageId: 'r12' }, 0);+ // 伙伴归属 → 水位消息的当前 rowid → 最近一条已完成回复的 rowid。+ db.queue.push([{ botId: 'bot-1' }], [{ rowid: 12 }], [{ rowid: 12 }]);expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(true);- db.queue.push([{ botId: 'bot-1' }], [{ rowid: 13 }]);+ db.queue.push([{ botId: 'bot-1' }], [{ rowid: 12 }], [{ rowid: 13 }]);expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(false);- // 还没有已完成回复 / 非伙伴主对话 / 没有账本:都不算新鲜。- db.queue.push([{ botId: 'bot-1' }], [{ rowid: null }]);+ // 还没有已完成回复 / 水位消息已不在 / 非伙伴主对话 / 没有账本 / 旧账本没有 client_id:都不算新鲜。+ db.queue.push([{ botId: 'bot-1' }], [{ rowid: 12 }], [{ rowid: null }]);+ expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(false);+ db.queue.push([{ botId: 'bot-1' }], []);expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(false);db.queue.push([]);expect(await isWorkingMemoryFreshForSession('s-task', root)).toBe(false);db.queue.push([{ botId: 'bot-none' }]);expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(false);+ await writeBotWorkingMemory(root, 'bot-legacy', { ...emptyWorkingMemory(), updatedAt: 1, coveredThroughRowid: 12 }, 0);+ db.queue.push([{ botId: 'bot-legacy' }]);+ expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(false);});it('treats a corrupt or foreign file as no ledger', async () => {diff --git a/apps/desktop/src/main/maker-ipc/botLearningReview.ts b/apps/desktop/src/main/maker-ipc/botLearningReview.tsindex 8c8bb668f5..475c7c2ab7 100644--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts@@ -92,14 +92,13 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)});// /clear 之前的消息始终不取。const clearedAtFilter = `AND created_at > COALESCE((SELECT cleared_at FROM sessions WHERE id=?), 0)`;- const prevCompleted =- (- await db.queryOne<{ rowid: number | null }>(- `SELECT MAX(rowid) AS rowid FROM messages WHERE session_id=? AND rowid < ? AND rewind_at IS NULL- AND role='assistant' AND json_valid(agent_meta) AND json_extract(agent_meta, '$.turnCompleted')=1`,- [sessionId, row.rowid],- )- )?.rowid ?? 0;+ const prev = await db.queryOne<{ id: string; rowid: number }>(+ `SELECT client_id AS id, rowid FROM messages WHERE session_id=? AND rowid < ? AND rewind_at IS NULL+ AND role='assistant' AND json_valid(agent_meta) AND json_extract(agent_meta, '$.turnCompleted')=1+ ORDER BY rowid DESC LIMIT 1 /* prev-completed */`,+ [sessionId, row.rowid],+ );+ const prevCompleted = prev?.rowid ?? 0;// 本轮取材:上一条完成回复之后到当前回复。const records = await db.query<Record_>(`@@ -116,23 +115,42 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)// 缺口回补:账本上次覆盖到的行落后于上一条完成回复(某轮复盘 claim 后失败、CAS 冲突、// 模型漏回 working),那段内容不会再被单独复盘;按 rowid 升序分批补进本次取材,覆盖水位// 只推进到连续处理过的前缀末尾——补不完就不推进到当前回复,账本在补完前不算新鲜,换窗线- // 不会因为一份有缺口的账本提前。每批有界且至少前进一条,几轮即收敛。没有账本时从上一条- // 完成回复接起,不回溯整段历史。- const ledgerFloor = workingBefore ? workingBefore.coveredThroughRowid : prevCompleted;- let coveredThroughRowid = turnTruncated ? prevCompleted : row.rowid;+ // 不会因为一份有缺口的账本提前。每批有界且至少前进一条,几轮即收敛。+ //+ // 水位的持久判据是消息 client_id(rowid 在瘦身 VACUUM 后可能重排),按它解析回当前 rowid;+ // 解析不到(水位消息被删 / 撤回)退回存下的 rowid。没有账本(老对话第一次建账本、或首轮+ // 复盘 claim 后失败)时从对话开头(/clear 之后)起算:整段历史按缺口分批回补,补完之前+ // 不算新鲜,不跳过任何一轮。+ type Watermark = { rowid: number; id: string | undefined };+ const floor: Watermark = workingBefore+ ? {+ rowid:+ (workingBefore.coveredThroughMessageId+ ? (+ await db.queryOne<{ rowid: number }>(+ `SELECT rowid FROM messages WHERE session_id=? AND client_id=? /* ledger-floor */`,+ [sessionId, workingBefore.coveredThroughMessageId],+ )+ )?.rowid+ : undefined) ?? workingBefore.coveredThroughRowid,+ id: workingBefore.coveredThroughMessageId,+ }+ : { rowid: 0, id: undefined };+ let covered: Watermark = turnTruncated ? { rowid: prevCompleted, id: prev?.id } : { rowid: row.rowid, id: replyId };let gapMessages: ReturnType<typeof toSnapshot>[] = [];- if (ledgerFloor < prevCompleted) {+ if (floor.rowid < prevCompleted) {const gapRows = await db.query<Record_>(`SELECT client_id AS id, role, content, rowid AS 'order' FROM messagesWHERE session_id=? AND rewind_at IS NULL AND rowid > ? AND rowid <= ? ${clearedAtFilter}AND ${REVIEW_ROLES} ORDER BY rowid ASC LIMIT ?`,- [sessionId, ledgerFloor, prevCompleted, sessionId, GAP_BACKFILL_ROWS + 1],+ [sessionId, floor.rowid, prevCompleted, sessionId, GAP_BACKFILL_ROWS + 1],);gapMessages = learningSnapshotPrefix(gapRows.slice(0, GAP_BACKFILL_ROWS).map(toSnapshot), GAP_BACKFILL_CHARS);if (gapRows.length > GAP_BACKFILL_ROWS || gapMessages.length < gapRows.length) {- coveredThroughRowid = gapMessages.length ? gapMessages[gapMessages.length - 1]!.order : ledgerFloor;+ const last = gapMessages[gapMessages.length - 1];+ covered = last ? { rowid: last.order, id: last.id } : floor;}}const messages = [...gapMessages, ...turnMessages].sort((a, b) => a.order - b.order);@@ -224,7 +242,8 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)row.botId,applyWorkingMemoryProposal(workingBefore, plan.working, messages, {now: Date.now(),- coveredThroughRowid,+ coveredThroughRowid: covered.rowid,+ ...(covered.id ? { coveredThroughMessageId: covered.id } : {}),}),workingBefore?.revision ?? 0,);diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.tsindex cec4ba07fc..19420e16b4 100644--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts@@ -66,6 +66,12 @@ export interface BotWorkingMemory {revision: number;/** 语义层已经读过的最后一条消息 rowid;换窗线是否能提前取决于它是否覆盖最近完成轮。 */coveredThroughRowid: number;+ /**+ * 水位对应消息的 client_id。messages 用 TEXT 主键,隐藏 rowid 在数据库瘦身(VACUUM INTO)后+ * 可能重排,持久判据以它为准:用的时候按 client_id 解析回当前 rowid。旧账本没有这一项时+ * 按不新鲜处理,下一次复盘写入后自愈。+ */+ coveredThroughMessageId?: string;updatedAt: number;threads: WorkingThread[];commitments: WorkingCommitment[];@@ -131,6 +137,9 @@ export function parseWorkingMemory(raw: unknown): BotWorkingMemory {...empty,revision: typeof raw.revision === 'number' && raw.revision >= 0 ? Math.floor(raw.revision) : 0,coveredThroughRowid: typeof raw.coveredThroughRowid === 'number' && raw.coveredThroughRowid >= 0 ? Math.floor(raw.coveredThroughRowid) : 0,+ ...(typeof raw.coveredThroughMessageId === 'string' && raw.coveredThroughMessageId+ ? { coveredThroughMessageId: raw.coveredThroughMessageId }+ : {}),updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : 0,threads: list('threads', WORKING_MEMORY_LIMITS.threads, (item, src) => ({...item,@@ -269,7 +278,7 @@ export function applyWorkingMemoryProposal(previous: BotWorkingMemory | null,proposal: WorkingMemoryProposal,messages: ProposalMessage[],- opts: { now: number; coveredThroughRowid: number },+ opts: { now: number; coveredThroughRowid: number; coveredThroughMessageId?: string },): Omit<BotWorkingMemory, 'revision' | 'version'> {const prev = previous ?? emptyWorkingMemory();const resolvedTexts = new Set(@@ -324,8 +333,19 @@ export function applyWorkingMemoryProposal(return { ...rest, ...(value ? { [key]: value } : {}) } as unknown as T;};+ // 水位:调用方带了 client_id 说明它已按当前库的 rowid 解析过(含瘦身重排后的回落),照用;+ // 旧式只带 rowid 的调用保持"只前进不后退"。+ const watermark =+ opts.coveredThroughMessageId !== undefined+ ? { coveredThroughRowid: opts.coveredThroughRowid, coveredThroughMessageId: opts.coveredThroughMessageId }+ : opts.coveredThroughRowid > prev.coveredThroughRowid+ ? { coveredThroughRowid: opts.coveredThroughRowid }+ : {+ coveredThroughRowid: prev.coveredThroughRowid,+ ...(prev.coveredThroughMessageId ? { coveredThroughMessageId: prev.coveredThroughMessageId } : {}),+ };return {- coveredThroughRowid: Math.max(prev.coveredThroughRowid, opts.coveredThroughRowid),+ ...watermark,updatedAt: opts.now,threads: merge(prev.threads, proposal.threads, WORKING_MEMORY_LIMITS.threads, (prior, item, seed) => ({...withField<WorkingThread, 'next'>(seed, 'next', resolveOptionalField(prior?.next, item.next)),@@ -637,17 +657,25 @@ export async function pruneWithdrawnWorkingMemoryForSession(/*** 账本是否已覆盖会话最近一条已完成回复(`agent_meta.turnCompleted`,与学习复盘取材同一判据)。* 这是伙伴换窗线从 90% 提前到 70% 的依据:新鲜说明最近一轮的语义状态已进账本,宿主换窗- * 不会丢东西。非伙伴主对话、没有账本、还没有已完成回复或读取失败一律 false——不新鲜就- * 不提前,维持原来的线。+ * 不会丢东西。水位按账本里的 client_id 解析回当前 rowid 再比较(rowid 在瘦身后可能重排,+ * 存下的数字不可信);非伙伴主对话、没有账本、账本没有 client_id、水位消息已不在、还没有+ * 已完成回复或读取失败一律 false——不新鲜就不提前,维持原来的线。*/export async function isWorkingMemoryFreshForSession(sessionId: string, userDataDir: string): Promise<boolean> {try {const botId = await resolveCanonicalBotIdForSession(sessionId);if (!botId) return false;const stored = await readBotWorkingMemory(userDataDir, botId);- if (!stored) return false;- const [row] = await getDbClient()- .drizzle.select({ rowid: sql<number | null>`MAX(rowid)` })+ if (!stored?.coveredThroughMessageId) return false;+ const db = getDbClient().drizzle;+ const [covered] = await db+ .select({ rowid: sql<number | null>`rowid` })+ .from(messages)+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, stored.coveredThroughMessageId)))+ .limit(1);+ if (typeof covered?.rowid !== 'number') return false;+ const [row] = await db+ .select({ rowid: sql<number | null>`MAX(rowid)` }).from(messages).where(and(@@ -659,7 +687,7 @@ export async function isWorkingMemoryFreshForSession(sessionId: string, userData);const latest = row?.rowid;if (typeof latest !== 'number' || !(latest > 0)) return false;- return isWorkingMemoryFresh(stored, latest);+ return isWorkingMemoryFresh({ ...stored, coveredThroughRowid: covered.rowid }, latest);} catch {return false;}diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 05336ed226..620d896f80 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -82,7 +82,8 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容由后续复盘按序分批补进账本(每批有界),覆盖水位只推进到连续补完的位置;本轮取材本身被截断时-同样不推进水位,补完之前账本不算新鲜;+同样不推进水位,补完之前账本不算新鲜;水位以消息的 client_id 为持久判据(rowid 在数据库瘦身后+可能重排),老对话第一次建账本从对话开头(清空边界之后)分批补起,不跳过任何一轮;新条目必须有本轮用户或伙伴原话证据,漏写的旧条目保留,删除同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动压缩之后的下一次发送再补一次,交接首条已带时不重复。账本是摘要,不是授权:历史授权不是新的