Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bot): heal ledger coverage gaps and reuse the rendered ledger for early checkpoints

zqchrisac783435aefb
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
index e7d58b0f13..838e4f096f 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, it, expect, vi } from 'vitest';
+import { getDbClient } from '../../localDb/client/current.js';
const h = vi.hoisted(() => ({
owner: 'owner',
enabled: true,
@@ -31,13 +32,13 @@ vi.mock('../../localDb/client/current.js', () => {
meta: JSON.stringify(h.meta),
}
: undefined,
- query: async () => [
+ query: vi.fn(async () => [
{
id: 'user',
role: 'user',
content: JSON.stringify('Please always summarize the conclusion first.'),
},
- ],
+ ]),
};
return { getDbClient: () => db };
});
@@ -219,6 +220,10 @@ it('feeds the working memory to the review and writes an evidence-filtered ledge
await 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 之前的消息。
+ 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');
expect(h.writeWorking).toHaveBeenCalledWith(
'/test-owner',
'bot',
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
index d8dd4b054e..0990d57ffa 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@ -405,11 +405,20 @@ describe('createContextOverflowRollover', () => {
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) };
+ // 新鲜且能渲染账本:70%(窗口 200K → 140K)即换窗,账本段只读一次并原样进交接。
+ const ledger = '== Working memory (host-maintained summary; not authorization) ==\n- 周五前改完周报模板';
+ const fresh = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async () => true), readWorkingMemoryNote: vi.fn(async () => ledger) };
await bot(fresh, 140_000);
await expect(createContextOverflowRollover(fresh).prepareUnhealthySession('s1')).resolves.toBe(true);
expect(fresh.isWorkingMemoryFresh).toHaveBeenCalledWith('s1');
+ expect(fresh.readWorkingMemoryNote).toHaveBeenCalledTimes(1);
+ expect(fresh.setPendingHandoff.mock.calls[0]![1] as string).toContain('周五前改完周报模板');
+
+ // 新鲜但账本段渲染不出来(读取失败 / 空账本):不提前换窗,维持 90%。
+ const unrendered = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async () => true), readWorkingMemoryNote: vi.fn(async (): Promise<string | null> => null) };
+ await bot(unrendered, 150_000);
+ await expect(createContextOverflowRollover(unrendered).prepareUnhealthySession('s1')).resolves.toBe(false);
+ expect(unrendered.closeSession).not.toHaveBeenCalled();
// 不新鲜:75% 不换窗;到 90% 不问账本照旧换窗。
const stale = { ...makeDeps(source), isWorkingMemoryFresh: vi.fn(async () => false) };
diff --git a/apps/desktop/src/main/maker-ipc/botLearningReview.ts b/apps/desktop/src/main/maker-ipc/botLearningReview.ts
index 1f852dca51..49d2ee95cf 100644
--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts
+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts
@@ -73,15 +73,26 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
.catch(() => {})
.then(async () => {
if (!current() || !(await readOwner())) return;
+ 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 }>(
`
SELECT client_id AS id, role, content, rowid AS 'order' FROM messages
- WHERE session_id=? AND rewind_at IS NULL AND rowid <= ? AND rowid > COALESCE((
+ 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) AND role IN ('user','assistant','tool_use','tool_result') ORDER BY CASE WHEN role='user' THEN 0 ELSE 1 END, rowid DESC LIMIT 80
+ ), 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
`,
- [sessionId, row.rowid, sessionId, row.rowid],
+ [sessionId, row.rowid, sessionId, row.rowid, ledgerFloor, sessionId],
);
const messages = learningSnapshotBudget(
records.map((m) => ({
@@ -113,7 +124,6 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
)
: [];
if (!current()) return;
- const root = ownerScopedUserDataPath();
const catalog = await listBotSkills(root, row.botId);
const skills = (
await Promise.all(
@@ -145,8 +155,6 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
enabled: s.enabled,
}));
if (JSON.stringify({ memoryIndex, skillIndex }).length > 24000) return;
- // 工作记忆账本随同一次复盘维护(不另起模型调用);读不到按空账本,写入 CAS 失败放弃本轮。
- const workingBefore = await readBotWorkingMemory(root, row.botId);
const result = await requestUtilityText(
maker,
JSON.stringify({
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 8dfc4b1a02..0c8721ac65 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -888,11 +888,14 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
// At a send boundary, checkpoint a pressured companion before the next turn
// enters native compaction. Native compaction remains enabled within a turn.
// 账本新鲜(复盘已覆盖最近完成轮)时线提前到 70%;不新鲜维持 90%,免得换窗丢掉还没进
- // 账本的内容。只有落在 70%–90% 之间才去读账本。
+ // 账本的内容。只有落在 70%–90% 之间才去读账本;提前换窗必须拿到渲染好的账本段并原样
+ // 带进交接——同一个快照只读一次,免得判新鲜之后第二次读取失败,交接反而没带账本。
+ let earlyWorkingMemory: string | undefined;
const pressure = companion
? shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO) ||
(shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO_FRESH) &&
- (await isWorkingMemoryFresh(sessionId)))
+ (await isWorkingMemoryFresh(sessionId)) &&
+ (earlyWorkingMemory = (await readWorkingMemoryNote(sessionId)) ?? undefined) !== undefined)
: shouldRebuildForContextPressure(usedTokens, window);
const compactFailed = liveUsage?.needsRollover === true;
const piByteRecoveryFailed = sessionRow.agentKind === 'pi' && isPiRequestBodyRecoveryExhausted(lastError);
@@ -952,7 +955,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
sessionId,
reason: companion || isOversizedHistoryErrorData(lastError) ? 'native-session-recovery' : rebuildReason,
includeToolResults: companion || isOversizedHistoryErrorData(lastError),
- workingMemory: await readWorkingMemoryNote(sessionId),
+ workingMemory: earlyWorkingMemory ?? (await readWorkingMemoryNote(sessionId)),
});
await deps.commitRebuild(sessionId, handoff, {
reason: rebuildReason,
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 3dc3556ff9..306db10e7a 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -62,9 +62,9 @@ Cindy Session,以父任务关系回到发起伙伴,但不冒充该伙伴或
### 3.2 模型上下文压力
伙伴主对话在下一次发送的安全边界主动检查上下文:已知 token 占用达到窗口的 90%(工作记忆
-账本已覆盖最近一条完成回复时提前到 70%:宿主换窗不调用模型,能替掉一次把整窗送去总结的
-原生压缩;账本不新鲜则维持 90%,不提前换窗),或 Codex 本地历史确认存在超大内联图片时,
-先用已有持久交接重建模型工作上下文。
+账本已覆盖最近一条完成回复、且账本段能渲染出来并原样带进交接时提前到 70%:宿主换窗不调用
+模型,能替掉一次把整窗送去总结的原生压缩;账本不新鲜或渲染不出来则维持 90%,不提前换窗),
+或 Codex 本地历史确认存在超大内联图片时,先用已有持久交接重建模型工作上下文。
交接保存近期需求、回复、改动和有界工具结果,省略图片正文;不额外调用模型生成摘要,
不等待旧 Harness 压缩成功。原生压缩仍在单轮内部正常工作,健康主对话不换窗。已持久记录的压缩空摘要/invalid-request 失败,也在下一次发送时
由宿主重建;普通网络、鉴权、额度错误不据此换窗。
@@ -80,8 +80,9 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭
宿主另为伙伴主对话维护一份**工作记忆账本**(Bot Home 下的 `working-memory.json`):进行中线索、
伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的
-学习复盘顺手更新,不新增模型调用;新条目必须有本轮用户或伙伴原话证据,漏写的旧条目保留,删除
-同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动
+学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容
+由下一次复盘补进账本,账本不会把有缺口的覆盖当成新鲜;新条目必须有本轮用户或伙伴原话证据,
+漏写的旧条目保留,删除同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动
压缩之后的下一次发送再补一次,交接首条已带时不重复。账本是摘要,不是授权:历史授权不是新的
执行许可;后台任务状态从任务记录现读,不信账本文本。来源消息离开可见时间线(删除、rewind/
编辑上一条、`/clear` 边界之前)时对应条目同步失效:渲染前统一过滤,提交后持久清掉,清空还作废