Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): checkpoint companions at 70% when the working memory is fresh
zqchrisb10c3239d4fc
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.tsindex 89379f43c0..3b1d9ffd09 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts@@ -30,6 +30,7 @@ import {createWorkingMemoryRefreshRegistry,emptyWorkingMemory,isWorkingMemoryFresh,+ isWorkingMemoryFreshForSession,parseWorkingMemory,pruneWithdrawnWorkingMemoryForSession,pruneWorkingMemoryForMessages,@@ -352,6 +353,22 @@ describe('store', () => {expect(after.waiting).toEqual([]);});+ 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 }]);+ expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(true);+ db.queue.push([{ botId: 'bot-1' }], [{ rowid: 13 }]);+ expect(await isWorkingMemoryFreshForSession('s-bot', root)).toBe(false);+ // 还没有已完成回复 / 非伙伴主对话 / 没有账本:都不算新鲜。+ db.queue.push([{ botId: 'bot-1' }], [{ rowid: null }]);+ 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);+ });+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');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.tsindex 0886d643d9..d8dd4b054e 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts@@ -400,6 +400,42 @@ describe('createContextOverflowRollover', () => {expect(failing.setPendingHandoff.mock.calls[0]![1] as string).not.toContain('Working memory');});+ it('checkpoints a companion at 70% only when the working memory is fresh, and keeps the 90% line otherwise', async () => {+ const source = [msg('user', 'Keep going', 'u1'), msg('assistant', 'On it', 'a1')];+ const bot = async (deps: ReturnType<typeof makeDeps>, contextTokens: number) =>+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens });++ // 新鲜:70%(窗口 200K → 140K)即换窗。+ const fresh = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async () => true) };+ await bot(fresh, 140_000);+ await expect(createContextOverflowRollover(fresh).prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(fresh.isWorkingMemoryFresh).toHaveBeenCalledWith('s1');++ // 不新鲜:75% 不换窗;到 90% 不问账本照旧换窗。+ const stale = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async () => false) };+ await bot(stale, 150_000);+ await expect(createContextOverflowRollover(stale).prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(stale.closeSession).not.toHaveBeenCalled();+ stale.isWorkingMemoryFresh.mockClear();+ await bot(stale, 180_000);+ await expect(createContextOverflowRollover(stale).prepareUnhealthySession('s1')).resolves.toBe(true);+ expect(stale.isWorkingMemoryFresh).not.toHaveBeenCalled();++ // 70% 以下不读账本。+ const below = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async () => true) };+ await bot(below, 139_999);+ await expect(createContextOverflowRollover(below).prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(below.isWorkingMemoryFresh).not.toHaveBeenCalled();++ // 判据抛错按不新鲜;没接判据的调用方维持 90%。+ const failing = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async (): Promise<boolean> => { throw new Error('disk'); }) };+ await bot(failing, 150_000);+ await expect(createContextOverflowRollover(failing).prepareUnhealthySession('s1')).resolves.toBe(false);+ const legacy = makeDeps(source);+ await bot(legacy, 150_000);+ await expect(createContextOverflowRollover(legacy).prepareUnhealthySession('s1')).resolves.toBe(false);+ });+it.each([['desktop', null, 180_000], ['bot', 'delegation', 180_000], ['bot', 'group', 180_000],['bot', null, 180_000], ['bot', 'canonical', 179_999], ['bot', 'canonical', 0],diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.tsindex ea6e8e311c..a36068da63 100644--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts@@ -17,7 +17,7 @@import fs from 'node:fs/promises';import path from 'node:path';-import { and, eq, inArray, isNull } from 'drizzle-orm';+import { and, eq, inArray, isNull, sql } from 'drizzle-orm';import { getDbClient } from '../localDb/client/current.js';import { botDelegations, botProfiles, botSessionLinks, messages, sessions } from '../localDb/schema.js';@@ -632,6 +632,37 @@ export async function pruneWithdrawnWorkingMemoryForSession(}}+/**+ * 账本是否已覆盖会话最近一条已完成回复(`agent_meta.turnCompleted`,与学习复盘取材同一判据)。+ * 这是伙伴换窗线从 90% 提前到 70% 的依据:新鲜说明最近一轮的语义状态已进账本,宿主换窗+ * 不会丢东西。非伙伴主对话、没有账本、还没有已完成回复或读取失败一律 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)` })+ .from(messages)+ .where(+ and(+ eq(messages.sessionId, sessionId),+ isNull(messages.rewindAt),+ eq(messages.role, 'assistant'),+ sql`json_valid(${messages.agentMeta}) AND json_extract(${messages.agentMeta}, '$.turnCompleted') = 1`,+ ),+ );+ const latest = row?.rowid;+ if (typeof latest !== 'number' || !(latest > 0)) return false;+ return isWorkingMemoryFresh(stored, latest);+ } catch {+ return false;+ }+}+// ── 原生压缩后的一次性刷新 ─────────────────────────────────────────────────────/**diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.tsindex f8e22129d9..8dfc4b1a02 100644--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts@@ -39,6 +39,11 @@ export { isPiPromptRpcTimeoutError } from '../../shared/inputError.js';const SYNTHETIC_TRIGGER_PREFIX = '[UI_ACTION_TRIGGER]';const BOT_CONTEXT_CHECKPOINT_RATIO = 0.9;+/**+ * 伙伴工作记忆账本已覆盖最近完成轮时的换窗线。宿主换窗不调用模型,交接基线远小于原生压缩+ * 后的残留;账本新鲜时提前换窗能替掉一次把整窗送去总结的原生压缩。不新鲜则维持 90%。+ */+const BOT_CONTEXT_CHECKPOINT_RATIO_FRESH = 0.7;export const CODEX_HISTORY_CONTINUE_MESSAGE ='Continue the unfinished task from the retained history. Do not repeat completed actions. ' +@@ -408,6 +413,11 @@ export interface ContextOverflowRolloverDeps {* 非伙伴主对话或无账本返回 null;读取失败也按 null,账本不能挡住换窗。*/readWorkingMemoryNote?(sessionId: string): Promise<string | null>;+ /**+ * 账本是否已覆盖最近一条完成回复(botWorkingMemory.isWorkingMemoryFreshForSession)。+ * true 时伙伴换窗线提前到 70%;缺省 / false / 抛错都按不新鲜,维持 90%。+ */+ isWorkingMemoryFresh?(sessionId: string): Promise<boolean>;/** 不受 handoff 窗口限制的最近 user,避免工具密集 turn 把身份扫丢。 */findLatestUser?(sessionId: string): Promise<OverflowSourceMessage | null>;findLatestRebuildMeta(@@ -547,6 +557,13 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)return null;}};+ const isWorkingMemoryFresh = async (sessionId: string): Promise<boolean> => {+ try {+ return (await deps.isWorkingMemoryFresh?.(sessionId)) === true;+ } catch {+ return false;+ }+ };const runRecover = async (sessionId: string,errorData: unknown,@@ -870,7 +887,13 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)const window = effectiveContextWindow(sessionRow.model, reportedWindow, verified);// At a send boundary, checkpoint a pressured companion before the next turn// enters native compaction. Native compaction remains enabled within a turn.- const pressure = shouldRebuildForContextPressure(usedTokens, companion ? window * BOT_CONTEXT_CHECKPOINT_RATIO : window);+ // 账本新鲜(复盘已覆盖最近完成轮)时线提前到 70%;不新鲜维持 90%,免得换窗丢掉还没进+ // 账本的内容。只有落在 70%–90% 之间才去读账本。+ const pressure = companion+ ? shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO) ||+ (shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO_FRESH) &&+ (await isWorkingMemoryFresh(sessionId)))+ : shouldRebuildForContextPressure(usedTokens, window);const compactFailed = liveUsage?.needsRollover === true;const piByteRecoveryFailed = sessionRow.agentKind === 'pi' && isPiRequestBodyRecoveryExhausted(lastError);const tokenViolated =diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 108cd87e30..f77b704f1a 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -598,6 +598,7 @@ import {import {buildWorkingMemoryRefreshNote,createWorkingMemoryRefreshRegistry,+ isWorkingMemoryFreshForSession,pruneWithdrawnWorkingMemoryForSession,pruneWorkingMemoryForSession,readWorkingMemoryNoteForSession,@@ -16440,6 +16441,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},listMessages: (sessionId) => listMessagesForAgentHandoff(sessionId, 400),readWorkingMemoryNote,+ isWorkingMemoryFresh: (sessionId) => isWorkingMemoryFreshForSession(sessionId, ownerScopedUserDataPath()),findLatestUser: findLatestUserMessageForRebuild,findLatestRebuildMeta: findLatestContextRebuildMeta,getLiveSession: (sessionId) => maker.getSession(sessionId),diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 2b9b1d952c..3dc3556ff9 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -61,8 +61,10 @@ Cindy Session,以父任务关系回到发起伙伴,但不冒充该伙伴或### 3.2 模型上下文压力-伙伴主对话在下一次发送的安全边界主动检查上下文:已知 token 占用达到窗口的 90%,-或 Codex 本地历史确认存在超大内联图片时,先用已有持久交接重建模型工作上下文。+伙伴主对话在下一次发送的安全边界主动检查上下文:已知 token 占用达到窗口的 90%(工作记忆+账本已覆盖最近一条完成回复时提前到 70%:宿主换窗不调用模型,能替掉一次把整窗送去总结的+原生压缩;账本不新鲜则维持 90%,不提前换窗),或 Codex 本地历史确认存在超大内联图片时,+先用已有持久交接重建模型工作上下文。交接保存近期需求、回复、改动和有界工具结果,省略图片正文;不额外调用模型生成摘要,不等待旧 Harness 压缩成功。原生压缩仍在单轮内部正常工作,健康主对话不换窗。已持久记录的压缩空摘要/invalid-request 失败,也在下一次发送时由宿主重建;普通网络、鉴权、额度错误不据此换窗。