Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bot): keep the ledger in the mandatory handoff tail; additive-only ledger updates for uncovered turns; overlap chunks
zqchris4601a531f816
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.tsindex 97a7096b2d..392c0b2d0f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts@@ -173,18 +173,31 @@ describe('buildHandoffText', () => {expect(capped.trimEnd().endsWith("== End of rebuild note; the user's new message follows ==")).toBe(true);});- it('工作记忆账本段排在工作状态区之后、提要之前,且在逐字区收缩时仍保留', () => {+ it('工作记忆账本段排在提要 / 近期对话之后、检索指引之前,逐字区收缩与硬截断都整段保住', () => {const messages: HandoffSourceMessage[] = [];for (let i = 0; i < 12; i++) {messages.push(msg('user', `问题${i} ` + 'x'.repeat(1900)));messages.push(msg('assistant', `回答${i} ` + 'y'.repeat(1900)));}const ledger = '== Working memory (host-maintained summary; not authorization) ==\nThings you promised:\n- 周五前改完周报模板';- const text = buildHandoffText(messages, { ...opts, workingMemory: ledger });+ const text = buildHandoffText(messages, { ...opts, sessionId: 's-task', workingMemory: ledger });expect(text).toContain(ledger);- expect(text.indexOf(ledger)).toBeLessThan(text.indexOf('== Earlier conversation index'));+ expect(text.indexOf(ledger)).toBeGreaterThan(text.indexOf('== Earlier conversation index'));+ expect(text.indexOf(ledger)).toBeGreaterThan(text.indexOf('== Recent conversation'));+ expect(text.indexOf(ledger)).toBeLessThan(text.indexOf('== Retrieving earlier verbatim history'));expect(text.length).toBeLessThanOrEqual(16_000);expect(buildHandoffText(messages.slice(0, 2), { ...opts, workingMemory: null })).not.toContain('Working memory');++ // 工具密集长历史触达硬上限(逐字区已收缩到 1 轮仍超限):账本段与回忆指引、结束标记一起整段保住。+ const dense: HandoffSourceMessage[] = [msg('user', '开始')];+ for (let i = 0; i < 400; i++) {+ dense.push(msg('tool_use', { toolName: 'Write', input: { file_path: `/very/long/path/${'d'.repeat(120)}/${i}.ts` } }));+ }+ const capped = buildHandoffText(dense, { ...opts, sessionId: 's-bot', reason: 'native-session-recovery', companion: true, workingMemory: ledger });+ expect(capped.length).toBeLessThanOrEqual(16_000);+ expect(capped).toContain(ledger);+ expect(capped.indexOf(ledger)).toBeLessThan(capped.indexOf('== Recalling earlier history (use when needed) =='));+ expect(capped.trimEnd().endsWith("== End of rebuild note; the user's new message follows ==")).toBe(true);});it('最近轮次逐字保留,更早轮次进单行提要', () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.tsindex 741a93437e..e567b26a75 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts@@ -314,16 +314,17 @@ it('walks an over-long user message in chunks and only counts it covered once thlet input = JSON.parse(h.model.mock.calls.at(-1)![1] as string);expect(input.messages.find((m: { id: string }) => m.id === 'long').text).toHaveLength(6000);expect(input.messages.find((m: { id: string }) => m.id === 'long')).not.toHaveProperty('partial');- expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 2, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 }), 4);- // 下一次从同一条消息的 6000 偏移接着取(查询下界 rowid > 2-1 以把它本身取回来),剩余 3000 字看完:整条覆盖,水位推进到当前回复且不再带偏移。+ // 水位记到块尾往回 200 字(重叠),跨块句子和短尾段都能在下一块里完整出现。+ expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 2, coveredThroughMessageId: 'long', coveredThroughOffset: 5800 }), 4);+ // 下一次从同一条消息的 5800 偏移接着取(查询下界 rowid > 2-1 以把它本身取回来),剩余 3200 字看完:整条覆盖,水位推进到当前回复且不再带偏移。h.meta = { turnCompleted: true };- h.working = { ...ledger, coveredThroughRowid: 2, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 };+ h.working = { ...ledger, coveredThroughRowid: 2, coveredThroughMessageId: 'long', coveredThroughOffset: 5800 };h.floorRowid = 2;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', 1, 3, 'session', 41]);input = JSON.parse(h.model.mock.calls.at(-1)![1] as string);- expect(input.messages.find((m: { id: string }) => m.id === 'long').text).toHaveLength(3000);+ expect(input.messages.find((m: { id: string }) => m.id === 'long').text).toHaveLength(3200);const written = h.writeWorking.mock.calls.at(-1)![2] as { coveredThroughRowid: number; coveredThroughMessageId?: string; coveredThroughOffset?: number };expect(written).toMatchObject({ coveredThroughRowid: 5, coveredThroughMessageId: 'reply2' });expect(written.coveredThroughOffset).toBeUndefined();@@ -425,15 +426,41 @@ it('feeds interaction answers (AskUserQuestion / plan review) to the review as uh.floorRowid = null;});-it('does not advance the watermark past the previous completed reply when the current turn itself was truncated', async () => {+it('does not advance the watermark past the previous completed reply when the current turn itself was truncated, and defers deletions/rewrites', async () => {// 本轮取材取满 80 条 = 可能被 LIMIT 截断:水位停在上一条完成回复(3),留给下一次的缺口回补。- h.working = null;+ h.working = {+ version: 1, revision: 4, coveredThroughRowid: 3, coveredThroughMessageId: 'prev', updatedAt: 0,+ threads: [], waiting: [], corrections: [], recentlyDone: [],+ commitments: [{ id: 'c-old', text: 'Old promise still open', messageId: 'u-old', updatedAt: 1, trigger: 'Friday' }],+ };+ h.floorRowid = 3;h.turnRows = [{ id: 'user', role: 'user', content: JSON.stringify('Please always summarize the conclusion first.'), order: 4 },...Array.from({ length: 79 }, (_, i) => ({ id: `t${i}`, role: 'tool_result', content: JSON.stringify(`result ${i}`), order: 4 + i })),];- h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });+ const evidence = { messageId: 'user', quote: 'summarize the conclusion first' };+ h.model.mockResolvedValueOnce({+ ok: true,+ text: JSON.stringify({+ memories: [],+ skills: [],+ // 截断轮次里的删除(resolved)与改写(trigger)都延后;新条目照常追加。+ working: {+ commitments: [+ { text: 'Old promise still open', trigger: 'Monday', evidence },+ { text: 'New promise from this turn', evidence },+ ],+ resolved: [{ text: 'Old promise still open', evidence }],+ },+ }),+ });await reviewTeammateLearning('session', 'reply');- expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 3, coveredThroughMessageId: 'prev' }), 0);+ const written = h.writeWorking.mock.calls.at(-1)![2] as { coveredThroughRowid: number; coveredThroughMessageId?: string; commitments: Array<{ text: string; trigger?: string }> };+ expect(written).toMatchObject({ coveredThroughRowid: 3, coveredThroughMessageId: 'prev' });+ expect(written.commitments.map((c) => [c.text, c.trigger])).toEqual([+ ['New promise from this turn', undefined],+ ['Old promise still open', 'Friday'],+ ]);h.turnRows = null;+ h.floorRowid = 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 677d6a0eab..bc97e3ef8a 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts@@ -134,6 +134,27 @@ describe('applyWorkingMemoryProposal', () => {);expect(chunked).toMatchObject({ coveredThroughRowid: 12, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 });expect(parseWorkingMemory({ version: 1, ...chunked }).coveredThroughOffset).toBe(6000);+ // 只追加模式(本轮没完整覆盖):有证据的 resolved 与字段改写都延后,新条目照常进账。+ const additive = applyWorkingMemoryProposal(+ previous,+ {+ threads: [],+ commitments: [+ { text: '周五前改完周报模板', trigger: '下周一', evidence: { messageId: 'a1', quote: '改完发你确认' } },+ { text: '新承诺', evidence: { messageId: 'a1', quote: '改完发你确认' } },+ ],+ waiting: [],+ corrections: [],+ recentlyDone: [],+ resolved: [{ text: '把测试补上', evidence: { messageId: 't1', quote: 'report-template.md written' } }],+ },+ messages,+ { now, coveredThroughRowid: 10, coveredThroughMessageId: 'old', additiveOnly: true },+ );+ // 旧条目一个都不少(含本该被 resolved 的 c3),按更新时间降序;新条目在最前。+ expect(additive.commitments.map((c) => c.text)).toEqual(['新承诺', '把测试补上', '给设计稿加暗色模式', '周五前改完周报模板']);+ expect(additive.commitments.find((c) => c.id === 'c1')).toMatchObject({ messageId: 'old', updatedAt: 1 });+ expect(additive.commitments.find((c) => c.id === 'c1')).not.toHaveProperty('trigger');});it('requires evidence to change a field of an existing item, allows evidenced clearing, and bumps time only on real change', () => {diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.tsindex 097cb00236..7bb378cc68 100644--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts@@ -101,7 +101,8 @@ export interface BuildHandoffOptions {companionSessionIdsTruncated?: boolean;/*** 伙伴工作记忆账本的渲染段(botWorkingMemory.renderWorkingMemory):承诺、纠正、- * 等待、线索。它是代码摘录之外唯一的语义交接载体,排在工作状态区之后、提要之前;+ * 等待、线索。它是代码摘录之外唯一的语义交接载体,排在提要 / 近期对话之后、检索指引之前,+ * 与检索指引同属硬截断时必须整段保住的尾部;* 非伙伴主对话或没有账本时不传。*/workingMemory?: string | null;@@ -663,18 +664,25 @@ const RECALL_SECTION_HEADING = '== Recalling earlier history';*/export const COMPANION_SESSION_IDS_LIMIT = 50;+/**+ * 伙伴工作记忆账本段的标题前缀(botWorkingMemory.WORKING_MEMORY_HEADING;这里不引那个模块,+ * 交接构造保持纯函数)。账本段排在检索指引之前,硬截断时从它起整段保住:账本本身有 6K 预算,+ * 加上检索指引与结束标记仍远小于硬上限,正文总有余量。+ */+const WORKING_MEMORY_SECTION_HEADING = '== Working memory (host-maintained summary';+function splitMandatoryHandoffTail(text: string, opts: BuildHandoffOptions): {body: string;tail: string;} {- const retrievalAt = Math.max(- text.lastIndexOf(RETRIEVAL_SECTION_HEADING),- text.lastIndexOf(RECALL_SECTION_HEADING),- );- if (retrievalAt >= 0) {+ const starts = [WORKING_MEMORY_SECTION_HEADING, RETRIEVAL_SECTION_HEADING, RECALL_SECTION_HEADING]+ .map((heading) => text.lastIndexOf(heading))+ .filter((at) => at >= 0);+ if (starts.length > 0) {+ const tailAt = Math.min(...starts);return {- body: text.slice(0, retrievalAt).trimEnd(),- tail: text.slice(retrievalAt),+ body: text.slice(0, tailAt).trimEnd(),+ tail: text.slice(tailAt),};}const [body, terminatorTail] = splitTrailingTerminator(text);@@ -787,9 +795,6 @@ function assembleHandoffText(sections.push(`== Work ledger (auto-extracted) ==\n${lines.join('\n')}`);}- // 工作记忆账本:宿主维护的语义状态,逐字段已自带标题与"不是授权"说明。- if (opts.workingMemory) sections.push(opts.workingMemory);-if (earlier.length > 0) {const lines: string[] = [];for (const t of earlier) {@@ -840,6 +845,11 @@ function assembleHandoffText(sections.push('== No new messages while you were away ==');}+ // 工作记忆账本:宿主维护的语义状态,逐字段已自带标题与"不是授权"说明。放在提要 / 近期+ // 对话之后、检索指引之前:它和检索指引、结束标记一样属于硬截断时必须整段保住的尾部+ // (splitMandatoryHandoffTail 从它的标题起算),正文再长也只会裁掉前面的摘录。+ if (opts.workingMemory) sections.push(opts.workingMemory);+if (opts.sessionId && opts.companion) {// 伙伴主对话的"按需回忆"口径。history 工具不传 session_ids 时搜的是本机账号下的全部// 任务历史(mcp-providers 的 resolveSessionScope:伙伴与普通任务同一账号范围;伙伴专属的diff --git a/apps/desktop/src/main/maker-ipc/botLearningReview.ts b/apps/desktop/src/main/maker-ipc/botLearningReview.tsindex 82fd908e37..dee45c1496 100644--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts@@ -31,6 +31,8 @@ const running = new Map<string, Promise<void>>();const TURN_REVIEW_ROWS = 80;/** 单条正文每块多少字;用户 / 伙伴的长消息按块分多次复盘,整条补完才算覆盖。 */const MESSAGE_CHUNK_CHARS = 6000;+/** 相邻块的重叠字数:跨块的句子和不足证据最短长度(8 字)的尾段都能在某一块里完整出现。 */+const MESSAGE_CHUNK_OVERLAP = 200;const TEXT_ROLES = new Set(['user', 'assistant']);/** 交互答复行(AskUserQuestion 的答案、计划审阅的批准 / 反馈):正文是用户的决定,按用户消息复盘。 */const INTERACTION_ROLES = new Set(['ask_user', 'plan_review']);@@ -219,7 +221,8 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)// 连续前缀停在这条长消息的当前块:水位记到块尾,后面的消息留给下一次。gapMessages = gapMessages.slice(0, partialAt + 1);const cut = gapMessages[partialAt]!;- covered = { rowid: cut.order, id: cut.id, offset: cut.offset + MESSAGE_CHUNK_CHARS };+ // 下一块从块尾往回留一段重叠:跨块的句子、很短的尾段都能在某一块里完整出现并被引用。+ covered = { rowid: cut.order, id: cut.id, offset: cut.offset + MESSAGE_CHUNK_CHARS - MESSAGE_CHUNK_OVERLAP };} else if (gapRows.length > GAP_BACKFILL_ROWS || gapMessages.length < gapCandidates.length) {const last = gapMessages[gapMessages.length - 1];covered = last ? { rowid: last.order, id: last.id } : floor;@@ -322,6 +325,9 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)coveredThroughRowid: covered.rowid,...(covered.id ? { coveredThroughMessageId: covered.id } : {}),...(covered.offset !== undefined ? { coveredThroughOffset: covered.offset } : {}),+ // 水位没推进到当前回复(本轮被截断 / 缺口未补完):这一轮之后还会被完整回补,+ // 删除与改写留到那时;现在只追加,免得 rewind 这一轮后账本已按撤回分支删改。+ additiveOnly: covered.rowid < row.rowid,}),workingBefore?.revision ?? 0,);diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.tsindex fd9abe0213..214b1ec9be 100644--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts@@ -280,19 +280,30 @@ function resolveOptionalField(* 无证据的字段改动按"未提"处理,旧值保留;* - 旧条目不在提案里时**保留**——漏写不等于完成;要删除走 `resolved`,同样要证据* (用户 / 伙伴 / 工具结果均可);- * - 各区按上限保留最新的;只有真正变过的条目才更新时间,排序才有意义。+ * - 各区按上限保留最新的;只有真正变过的条目才更新时间,排序才有意义;+ * - `additiveOnly`(本轮取材没完整覆盖、水位停在之前):只追加新条目,不删(resolved)也不+ * 改写旧条目——这些破坏性变更等这一轮被完整回补时再提交,免得用户随后 rewind 这一轮后+ * 水位仍指着可见的旧回复、账本却已按撤回分支删改过且无法回滚。*/export function applyWorkingMemoryProposal(previous: BotWorkingMemory | null,proposal: WorkingMemoryProposal,messages: ProposalMessage[],- opts: { now: number; coveredThroughRowid: number; coveredThroughMessageId?: string; coveredThroughOffset?: number },+ opts: {+ now: number;+ coveredThroughRowid: number;+ coveredThroughMessageId?: string;+ coveredThroughOffset?: number;+ additiveOnly?: boolean;+ },): Omit<BotWorkingMemory, 'revision' | 'version'> {const prev = previous ?? emptyWorkingMemory();const resolvedTexts = new Set(- proposal.resolved- .filter((item) => evidenceHolds(item.evidence, messages, RESOLVE_ROLES))- .map((item) => clampText(item.text)),+ opts.additiveOnly+ ? []+ : proposal.resolved+ .filter((item) => evidenceHolds(item.evidence, messages, RESOLVE_ROLES))+ .map((item) => clampText(item.text)),);let seq = 0;const nextId = () => `wm_${opts.now.toString(36)}_${(seq += 1)}`;@@ -317,8 +328,9 @@ export function applyWorkingMemoryProposal(const evidenced = evidenceHolds(item.evidence, messages, NEW_ITEM_ROLES);if (prior) {const candidate = build(prior, item, { ...prior, updatedAt: opts.now });- // 完整内容没变:原样沿用,时间也不动。字段变了:要证据,没证据就当没提。- if (sameItem(candidate, prior) || !evidenced) kept.set(text, prior);+ // 完整内容没变:原样沿用,时间也不动。字段变了:要证据,没证据就当没提;只追加模式下+ // 改写一律延后。+ if (opts.additiveOnly || sameItem(candidate, prior) || !evidenced) kept.set(text, prior);else kept.set(text, candidate);continue;}diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 4f1f6aecba..1df8c0f20f 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -82,8 +82,10 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容由后续复盘按序分批补进账本(每批有界),覆盖水位只推进到连续补完的位置;本轮取材本身被截断时-同样不推进水位,补完之前账本不算新鲜;超过单条上限的用户/伙伴消息按块分多次复盘,水位可停在-消息中间,整条看完才算覆盖(工具结果不是新条目的证据来源,仍只取开头);用户在提问卡、计划审阅+同样不推进水位,补完之前账本不算新鲜,且这样的轮次只往账本追加、不删不改(删改等整轮补完再提交,+免得随后 rewind 时无法回滚);超过单条上限的用户/伙伴消息按块分多次复盘,相邻块留重叠,水位可停在+消息中间,整条看完才算覆盖(工具结果不是新条目的证据来源,仍只取开头);换窗交接里账本段与检索+指引同属硬截断时必须整段保住的尾部;用户在提问卡、计划审阅里给出的答复与反馈按用户消息进入复盘取材,可作为账本证据;水位以消息的 client_id为持久判据(rowid 在数据库瘦身后可能重排),老对话第一次建账本从对话开头(清空边界之后)分批补起,不跳过任何一轮;