Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot): backfill ledger gaps in bounded ascending batches and advance the watermark only through the contiguous prefix
zqchris979b06d6ef17
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.tsindex 838e4f096f..292702f275 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts@@ -15,6 +15,10 @@ const h = vi.hoisted(() => ({skills: [] as any[],working: null as any,writeWorking: vi.fn(),+ /** 上一条完成回复的 rowid;当前回复是它 + 2(默认 5)。 */+ prevCompleted: 3 as number | null,+ /** 缺口回补查询(ORDER BY rowid ASC)返回的行。 */+ gapRows: [] as any[],}));vi.mock('../../appSessionState.js', () => ({activeOwnerScopeKey: () => h.owner,@@ -23,22 +27,31 @@ vi.mock('../../appSessionState.js', () => ({}));vi.mock('../../localDb/client/current.js', () => {const db = {- queryOne: async () =>- h.visible- ? {- botId: 'bot',- capabilities: JSON.stringify({ memory: h.enabled }),- rowid: 5,- meta: JSON.stringify(h.meta),- }- : undefined,- query: vi.fn(async () => [- {- id: 'user',- role: 'user',- content: JSON.stringify('Please always summarize the conclusion first.'),- },- ]),+ queryOne: async (sql: string) =>+ sql.includes('MAX(rowid)')+ ? { rowid: h.prevCompleted }+ : h.visible+ ? {+ botId: 'bot',+ capabilities: JSON.stringify({ memory: h.enabled }),+ // 当前回复:上一条完成回复 + 2(中间隔一条用户消息);默认 5。+ rowid: (h.prevCompleted ?? 0) + 2,+ meta: JSON.stringify(h.meta),+ }+ : undefined,+ query: vi.fn(async (sql: string) =>+ sql.includes('ORDER BY rowid ASC')+ ? h.gapRows+ : [+ {+ id: 'user',+ role: 'user',+ content: JSON.stringify('Please always summarize the conclusion first.'),+ // 本轮的用户消息:紧跟在上一条完成回复之后。+ order: (h.prevCompleted ?? 0) + 1,+ },+ ],+ ),};return { getDbClient: () => db };});@@ -220,10 +233,14 @@ it('feeds the working memory to the review and writes an evidence-filtered ledgeawait reviewTeammateLearning('session', 'reply');const input = JSON.parse(h.model.mock.calls[0]![1] as string);expect(input.workingMemory).toEqual({ threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [] });- // 取材下界带上账本上次覆盖到的行(1),失败轮次下次复盘补上;且不取 /clear 之前的消息。+ // 本轮取材从上一条完成回复(3)接起;账本只覆盖到 1,缺口 (1,3] 另按升序分批回补;都不取 /clear 之前的消息。const query = (getDbClient() as unknown as { query: ReturnType<typeof vi.fn> }).query;- expect(query.mock.calls.at(-1)![1]).toEqual(['session', 5, 'session', 5, 1, 'session']);- expect(String(query.mock.calls.at(-1)![0])).toContain('cleared_at');+ const recent = query.mock.calls.slice(-2);+ expect(recent.map((call) => call[1])).toEqual([+ ['session', 5, 3, 'session'],+ ['session', 1, 3, 'session', 41],+ ]);+ expect(recent.every((call) => String(call[0]).includes('cleared_at'))).toBe(true);expect(h.writeWorking).toHaveBeenCalledWith('/test-owner','bot',@@ -240,3 +257,30 @@ it('feeds the working memory to the review and writes an evidence-filtered ledgeawait reviewTeammateLearning('session', 'reply2');expect(h.writeWorking).not.toHaveBeenCalled();});++it('advances the ledger watermark only through the contiguous backfilled prefix while a gap is still being caught up', async () => {+ const ledger = { version: 1, revision: 4, coveredThroughRowid: 1, updatedAt: 0, threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [] };+ const gap = (from: number, to: number) =>+ Array.from({ length: to - from + 1 }, (_, i) => ({ id: `g${from + i}`, role: 'assistant', content: JSON.stringify(`gap ${from + i}`), order: from + i }));+ h.working = { ...ledger };+ h.prevCompleted = 100;+ // 缺口 (1,100] 里有 41 条,超过每批 40 条:只补前 40 条,水位停在第 40 条(rowid 41),不推进到当前回复。+ h.gapRows = gap(2, 42);+ h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });+ await reviewTeammateLearning('session', 'reply');+ const input = JSON.parse(h.model.mock.calls.at(-1)![1] as string);+ expect(input.messages.filter((m: { id: string }) => m.id.startsWith('g')).map((m: { id: string }) => m.id)).toEqual(+ gap(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)。+ h.meta = { turnCompleted: true };+ h.working = { ...ledger, coveredThroughRowid: 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);+ h.prevCompleted = 3;+ h.gapRows = [];+});diff --git a/apps/desktop/src/main/maker-ipc/botLearningReview.ts b/apps/desktop/src/main/maker-ipc/botLearningReview.tsindex 49d2ee95cf..cc18a119a1 100644--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts@@ -11,6 +11,7 @@ import { learningReceiptPublisher } from './botLearningFeedback.js';import {hasLearningEvidence,learningSnapshotBudget,+ learningSnapshotPrefix,learningReviewInstructions,learningReviewSchema,} from './botLearningReviewPlan.js';@@ -25,6 +26,10 @@ import {} from './botWorkingMemory.js';const running = new Map<string, Promise<void>>();+/** 缺口回补每批最多取多少条消息 / 多少字符;单条正文已截到 6000 字,所以每批至少前进一条。 */+const GAP_BACKFILL_ROWS = 40;+const GAP_BACKFILL_CHARS = 16000;+const REVIEW_ROLES = `role IN ('user','assistant','tool_use','tool_result')`;/** Once per durable successful reply; serial per teammate, outside the chat/agent loop. */export async function reviewTeammateLearning(sessionId: string, replyId: string): Promise<void> {const owner = activeOwnerScopeKey();@@ -76,36 +81,56 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)const root = ownerScopedUserDataPath();// 工作记忆账本随同一次复盘维护(不另起模型调用);读不到按空账本,写入 CAS 失败放弃本轮。const workingBefore = await readBotWorkingMemory(root, row.botId);- // 取材窗口从「上一条完成回复」和「账本上次覆盖到的行」中较早的一处接上:某轮复盘在- // claim 之后失败(模型出错、进程退出、CAS 冲突)不会再被重跑,若只从上一条完成回复- // 接起,那一轮就永远进不了账本,而账本的 coveredThroughRowid 却会被后面的成功写入- // 直接跳过去——换窗线提前的判据因此会把有缺口的账本当成新鲜的。没有账本时沿用- // 上一条完成回复(不回溯整段历史);/clear 之前的消息始终不取。- const ledgerFloor = workingBefore ? workingBefore.coveredThroughRowid : null;- const records = await db.query<{ id: string; role: string; content: string; order: number }>(+ type Record_ = { id: string; role: string; content: string; order: number };+ const toSnapshot = (m: Record_) => ({+ id: m.id,+ role: m.role,+ order: m.order,+ text: (typeof JSON.parse(m.content) === 'string' ? JSON.parse(m.content) : m.content).slice(0, 6000),+ });+ // /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 records = await db.query<Record_>(`SELECT client_id AS id, role, content, rowid AS 'order' FROM messages- WHERE session_id=? AND rewind_at IS NULL AND rowid <= ? AND rowid > MIN(COALESCE((- SELECT MAX(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- ), 0), COALESCE(?, 9223372036854775807))- AND created_at > COALESCE((SELECT cleared_at FROM sessions WHERE id=?), 0)- AND role IN ('user','assistant','tool_use','tool_result') ORDER BY CASE WHEN role='user' THEN 0 ELSE 1 END, rowid DESC LIMIT 80+ WHERE session_id=? AND rewind_at IS NULL AND rowid <= ? AND rowid > ? ${clearedAtFilter}+ AND ${REVIEW_ROLES} ORDER BY CASE WHEN role='user' THEN 0 ELSE 1 END, rowid DESC LIMIT 80`,- [sessionId, row.rowid, sessionId, row.rowid, ledgerFloor, sessionId],+ [sessionId, row.rowid, prevCompleted, sessionId],);- const messages = learningSnapshotBudget(- records.map((m) => ({- id: m.id,- role: m.role,- order: m.order,- text: (typeof JSON.parse(m.content) === 'string'- ? JSON.parse(m.content)- : m.content- ).slice(0, 6000),- })),- 40000,- ).sort((a, b) => a.order - b.order);+ const turnMessages = learningSnapshotBudget(records.map(toSnapshot), 40000);+ // 缺口回补:账本上次覆盖到的行落后于上一条完成回复(某轮复盘 claim 后失败、CAS 冲突、+ // 模型漏回 working),那段内容不会再被单独复盘;按 rowid 升序分批补进本次取材,覆盖水位+ // 只推进到连续处理过的前缀末尾——补不完就不推进到当前回复,账本在补完前不算新鲜,换窗线+ // 不会因为一份有缺口的账本提前。每批有界且至少前进一条,几轮即收敛。没有账本时从上一条+ // 完成回复接起,不回溯整段历史。+ const ledgerFloor = workingBefore ? workingBefore.coveredThroughRowid : prevCompleted;+ let coveredThroughRowid = row.rowid;+ let gapMessages: ReturnType<typeof toSnapshot>[] = [];+ if (ledgerFloor < prevCompleted) {+ const gapRows = await db.query<Record_>(+ `+ SELECT client_id AS id, role, content, rowid AS 'order' FROM messages+ WHERE 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],+ );+ 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 messages = [...gapMessages, ...turnMessages].sort((a, b) => a.order - b.order);if (!messages.some((m) => m.role === 'user') || !current()) return;const [{ getMaker }, { requestUtilityText }] = await Promise.all([import('../maker-host/index.js'),@@ -194,7 +219,7 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)row.botId,applyWorkingMemoryProposal(workingBefore, plan.working, messages, {now: Date.now(),- coveredThroughRowid: row.rowid,+ coveredThroughRowid,}),workingBefore?.revision ?? 0,);diff --git a/apps/desktop/src/main/maker-ipc/botLearningReviewPlan.ts b/apps/desktop/src/main/maker-ipc/botLearningReviewPlan.tsindex 5348887734..677f6905cd 100644--- a/apps/desktop/src/main/maker-ipc/botLearningReviewPlan.ts+++ b/apps/desktop/src/main/maker-ipc/botLearningReviewPlan.ts@@ -69,6 +69,22 @@ export function hasLearningEvidence();}+/**+ * 按序累加,遇到第一个放不下的就停:返回的是连续前缀,供缺口回补据此推进覆盖水位+ * (跳过中间一条就不能说"连续处理到了这里")。+ */+export function learningSnapshotPrefix<T>(records: readonly T[], maxChars: number): T[] {+ const selected: T[] = [];+ let remaining = maxChars;+ for (const record of records) {+ const size = JSON.stringify(record).length;+ if (size > remaining) break;+ selected.push(record);+ remaining -= size;+ }+ return selected;+}+/** Keep whole records within the review budget; omitted records can never be overwritten. */export function learningSnapshotBudget<T>(records: readonly T[], maxChars: number): T[] {const selected: T[] = [];diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 306db10e7a..2d17d1510e 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -81,7 +81,8 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭宿主另为伙伴主对话维护一份**工作记忆账本**(Bot Home 下的 `working-memory.json`):进行中线索、伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容-由下一次复盘补进账本,账本不会把有缺口的覆盖当成新鲜;新条目必须有本轮用户或伙伴原话证据,+由后续复盘按序分批补进账本(每批有界),覆盖水位只推进到连续补完的位置,补完之前账本不算新鲜;+新条目必须有本轮用户或伙伴原话证据,漏写的旧条目保留,删除同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动压缩之后的下一次发送再补一次,交接首条已带时不重复。账本是摘要,不是授权:历史授权不是新的执行许可;后台任务状态从任务记录现读,不信账本文本。来源消息离开可见时间线(删除、rewind/