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): review over-long user/assistant messages in chunks before counting them covered

zqchris75c476da80bd
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 8064afda39..5ead175029 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
@@ -301,6 +301,45 @@ it('advances the ledger watermark only through the contiguous backfilled prefix
h.floorRowid = null;
});
+it('walks an over-long user message in chunks and only counts it covered once the whole text was reviewed', async () => {
+ const ledger = { version: 1, revision: 4, coveredThroughRowid: 1, coveredThroughMessageId: 'r1', updatedAt: 0, threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [] };
+ const longRow = { id: 'long', role: 'user', content: JSON.stringify('x'.repeat(9000)), order: 2 };
+ const query = (getDbClient() as unknown as { query: ReturnType<typeof vi.fn> }).query;
+ // 缺口里有一条 9000 字的用户消息:第一次只看前 6000 字,水位停在这条消息的 6000 偏移,不算整条覆盖。
+ h.working = { ...ledger };
+ h.floorRowid = 1;
+ h.gapRows = [longRow];
+ h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });
+ await reviewTeammateLearning('session', 'reply');
+ let 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 字看完:整条覆盖,水位推进到当前回复且不再带偏移。
+ h.meta = { turnCompleted: true };
+ h.working = { ...ledger, coveredThroughRowid: 2, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 };
+ 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);
+ 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();
+ // 本轮取材里的长用户消息同样算截断:水位停在上一条完成回复,交给下一次分块回补。
+ h.meta = { turnCompleted: true };
+ h.working = { ...ledger, coveredThroughRowid: 3, coveredThroughMessageId: 'prev' };
+ h.floorRowid = 3;
+ h.turnRows = [{ id: 'user', role: 'user', content: JSON.stringify('y'.repeat(7000)), order: 4 }];
+ h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [], skills: [], working: { commitments: [] } }) });
+ await reviewTeammateLearning('session', 'reply3');
+ expect(h.writeWorking).toHaveBeenLastCalledWith('/test-owner', 'bot', expect.objectContaining({ coveredThroughRowid: 3, coveredThroughMessageId: 'prev' }), 4);
+ h.turnRows = null;
+ 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。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts
index 2fc1d5baab..677d6a0eab 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts
@@ -124,6 +124,16 @@ describe('applyWorkingMemoryProposal', () => {
{ now, coveredThroughRowid: 5, coveredThroughMessageId: 'a1' },
);
expect(remapped).toMatchObject({ coveredThroughRowid: 5, coveredThroughMessageId: 'a1' });
+ expect(remapped).not.toHaveProperty('coveredThroughOffset');
+ // 长消息分块中:偏移随 client_id 一起写入;补完后不再传偏移即清掉。
+ const chunked = applyWorkingMemoryProposal(
+ previous,
+ { threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [], resolved: [] },
+ messages,
+ { now, coveredThroughRowid: 12, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 },
+ );
+ expect(chunked).toMatchObject({ coveredThroughRowid: 12, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 });
+ expect(parseWorkingMemory({ version: 1, ...chunked }).coveredThroughOffset).toBe(6000);
});
it('requires evidence to change a field of an existing item, allows evidenced clearing, and bumps time only on real change', () => {
@@ -389,6 +399,10 @@ describe('store', () => {
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);
+ // 水位停在一条长消息中间(分块未补完):同样不算新鲜。
+ await writeBotWorkingMemory(root, 'bot-chunk', { ...emptyWorkingMemory(), updatedAt: 1, coveredThroughRowid: 12, coveredThroughMessageId: 'r12', coveredThroughOffset: 6000 }, 0);
+ db.queue.push([{ botId: 'bot-chunk' }]);
+ 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.ts
index 11e2147d7b..45176f8fc1 100644
--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts
+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts
@@ -29,6 +29,9 @@ import {
const running = new Map<string, Promise<void>>();
/** 本轮取材最多取多少条消息;超出即视为截断,水位不推进到当前回复。 */
const TURN_REVIEW_ROWS = 80;
+/** 单条正文每块多少字;用户 / 伙伴的长消息按块分多次复盘,整条补完才算覆盖。 */
+const MESSAGE_CHUNK_CHARS = 6000;
+const TEXT_ROLES = new Set(['user', 'assistant']);
/** 模型省略 working(本轮没改动)时用的空提案:不加不删,只让水位跟上。 */
const EMPTY_WORKING_PROPOSAL: WorkingMemoryProposal = {
threads: [],
@@ -94,12 +97,20 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
// 工作记忆账本随同一次复盘维护(不另起模型调用);读不到按空账本,写入 CAS 失败放弃本轮。
const workingBefore = await readBotWorkingMemory(root, row.botId);
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),
- });
+ // 单条正文按 MESSAGE_CHUNK_CHARS 分块。用户 / 伙伴的消息被截尾即 partial——它们是账本新条目
+ // 的证据来源,纠正 / 承诺可能就在长消息的尾部,没看完不能算覆盖;工具结果不是新条目的来源,
+ // 截尾只影响 resolved 证据(条目多留一阵),按已覆盖处理,不为它逐块回补。
+ const toSnapshot = (m: Record_, offset = 0) => {
+ const full: string = typeof JSON.parse(m.content) === 'string' ? JSON.parse(m.content) : m.content;
+ return {
+ id: m.id,
+ role: m.role,
+ order: m.order,
+ text: full.slice(offset, offset + MESSAGE_CHUNK_CHARS),
+ offset,
+ partial: TEXT_ROLES.has(m.role) && full.length > offset + MESSAGE_CHUNK_CHARS,
+ };
+ };
// /clear 之前的消息始终不取。
const clearedAtFilter = `AND created_at > COALESCE((SELECT cleared_at FROM sessions WHERE id=?), 0)`;
const prev = await db.queryOne<{ id: string; rowid: number }>(
@@ -118,10 +129,14 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
`,
[sessionId, row.rowid, prevCompleted, sessionId],
);
- const turnMessages = learningSnapshotBudget(records.map(toSnapshot), 40000);
- // 本轮本身被 LIMIT / 预算截断(工具密集的大轮次)时,漏掉的中间承诺 / 工具结果同样不能
- // 算"已覆盖":水位停在上一条完成回复,下一次复盘由缺口回补路径按序补齐。
- const turnTruncated = records.length >= TURN_REVIEW_ROWS || turnMessages.length < records.length;
+ const turnMessages = learningSnapshotBudget(records.map((m) => toSnapshot(m)), 40000);
+ // 本轮本身被 LIMIT / 预算截断(工具密集的大轮次)、或某条用户 / 伙伴消息被截尾时,漏掉的
+ // 中间承诺 / 工具结果 / 长消息尾部同样不能算"已覆盖":水位停在上一条完成回复,下一次复盘
+ // 由缺口回补路径按序(含分块)补齐。
+ const turnTruncated =
+ records.length >= TURN_REVIEW_ROWS ||
+ turnMessages.length < records.length ||
+ turnMessages.some((m) => m.partial);
// 缺口回补:账本上次覆盖到的行落后于上一条完成回复(某轮复盘 claim 后失败、CAS 冲突、
// 模型漏回 working),那段内容不会再被单独复盘;按 rowid 升序分批补进本次取材,覆盖水位
// 只推进到连续处理过的前缀末尾——补不完就不推进到当前回复,账本在补完前不算新鲜,换窗线
@@ -131,7 +146,8 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
// 存下的 rowid 数字在任何情况下都不拿来当下界:旧账本没有 client_id、或水位消息已被删 /
// 撤回解析不到,以及根本没有账本(老对话第一次建账本、首轮复盘 claim 后失败),一律从对话
// 开头(/clear 之后)起算——整段历史按缺口分批回补,补完之前不算新鲜,不跳过任何一轮。
- type Watermark = { rowid: number; id: string | undefined };
+ // 水位可以停在一条长消息中间(offset = 已覆盖的字符数):下一次从同一条消息的这个偏移接着取。
+ type Watermark = { rowid: number; id: string | undefined; offset?: number };
const resolvedFloor = workingBefore?.coveredThroughMessageId
? (
await db.queryOne<{ rowid: number }>(
@@ -142,26 +158,41 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
: undefined;
const floor: Watermark =
resolvedFloor !== undefined
- ? { rowid: resolvedFloor, id: workingBefore!.coveredThroughMessageId }
+ ? { rowid: resolvedFloor, id: workingBefore!.coveredThroughMessageId, offset: workingBefore!.coveredThroughOffset }
: { rowid: 0, id: undefined };
let covered: Watermark = turnTruncated ? { rowid: prevCompleted, id: prev?.id } : { rowid: row.rowid, id: replyId };
let gapMessages: ReturnType<typeof toSnapshot>[] = [];
if (floor.rowid < prevCompleted) {
+ // 水位停在半条消息里时把那条消息本身也取回来(rowid > x-1 即 rowid >= x)。
+ const gapAfter = floor.offset !== undefined ? floor.rowid - 1 : floor.rowid;
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, floor.rowid, prevCompleted, sessionId, GAP_BACKFILL_ROWS + 1],
+ [sessionId, gapAfter, 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) {
+ gapMessages = learningSnapshotPrefix(
+ gapRows
+ .slice(0, GAP_BACKFILL_ROWS)
+ .map((m) => toSnapshot(m, floor.offset !== undefined && m.order === floor.rowid ? floor.offset : 0)),
+ GAP_BACKFILL_CHARS,
+ );
+ const partialAt = gapMessages.findIndex((m) => m.partial);
+ if (partialAt >= 0) {
+ // 连续前缀停在这条长消息的当前块:水位记到块尾,后面的消息留给下一次。
+ gapMessages = gapMessages.slice(0, partialAt + 1);
+ const cut = gapMessages[partialAt]!;
+ covered = { rowid: cut.order, id: cut.id, offset: cut.offset + MESSAGE_CHUNK_CHARS };
+ } else if (gapRows.length > GAP_BACKFILL_ROWS || gapMessages.length < gapRows.length) {
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);
+ const messages = [...gapMessages, ...turnMessages]
+ .map(({ id, role, order, text }) => ({ id, role, order, text }))
+ .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'),
@@ -255,6 +286,7 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)
now: Date.now(),
coveredThroughRowid: covered.rowid,
...(covered.id ? { coveredThroughMessageId: covered.id } : {}),
+ ...(covered.offset !== undefined ? { coveredThroughOffset: covered.offset } : {}),
}),
workingBefore?.revision ?? 0,
);
diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts
index 19420e16b4..872d780c7c 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts
@@ -72,6 +72,11 @@ export interface BotWorkingMemory {
* 按不新鲜处理,下一次复盘写入后自愈。
*/
coveredThroughMessageId?: string;
+ /**
+ * 水位消息只覆盖到的字符偏移:用户 / 伙伴的长消息按 6000 字分块复盘,没补完整条时记下
+ * 已覆盖到哪里,下一次复盘从这里接着取。缺省 = 整条已覆盖。有偏移即不算新鲜。
+ */
+ coveredThroughOffset?: number;
updatedAt: number;
threads: WorkingThread[];
commitments: WorkingCommitment[];
@@ -140,6 +145,9 @@ export function parseWorkingMemory(raw: unknown): BotWorkingMemory {
...(typeof raw.coveredThroughMessageId === 'string' && raw.coveredThroughMessageId
? { coveredThroughMessageId: raw.coveredThroughMessageId }
: {}),
+ ...(typeof raw.coveredThroughOffset === 'number' && raw.coveredThroughOffset > 0
+ ? { coveredThroughOffset: Math.floor(raw.coveredThroughOffset) }
+ : {}),
updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : 0,
threads: list('threads', WORKING_MEMORY_LIMITS.threads, (item, src) => ({
...item,
@@ -278,7 +286,7 @@ export function applyWorkingMemoryProposal(
previous: BotWorkingMemory | null,
proposal: WorkingMemoryProposal,
messages: ProposalMessage[],
- opts: { now: number; coveredThroughRowid: number; coveredThroughMessageId?: string },
+ opts: { now: number; coveredThroughRowid: number; coveredThroughMessageId?: string; coveredThroughOffset?: number },
): Omit<BotWorkingMemory, 'revision' | 'version'> {
const prev = previous ?? emptyWorkingMemory();
const resolvedTexts = new Set(
@@ -337,7 +345,11 @@ export function applyWorkingMemoryProposal(
// 旧式只带 rowid 的调用保持"只前进不后退"。
const watermark =
opts.coveredThroughMessageId !== undefined
- ? { coveredThroughRowid: opts.coveredThroughRowid, coveredThroughMessageId: opts.coveredThroughMessageId }
+ ? {
+ coveredThroughRowid: opts.coveredThroughRowid,
+ coveredThroughMessageId: opts.coveredThroughMessageId,
+ ...(opts.coveredThroughOffset !== undefined ? { coveredThroughOffset: opts.coveredThroughOffset } : {}),
+ }
: opts.coveredThroughRowid > prev.coveredThroughRowid
? { coveredThroughRowid: opts.coveredThroughRowid }
: {
@@ -666,7 +678,8 @@ export async function isWorkingMemoryFreshForSession(sessionId: string, userData
const botId = await resolveCanonicalBotIdForSession(sessionId);
if (!botId) return false;
const stored = await readBotWorkingMemory(userDataDir, botId);
- if (!stored?.coveredThroughMessageId) return false;
+ // 没有 client_id(旧账本)或水位消息只覆盖了一部分(长消息分块中):都不算新鲜。
+ if (!stored?.coveredThroughMessageId || stored.coveredThroughOffset !== undefined) return false;
const db = getDbClient().drizzle;
const [covered] = await db
.select({ rowid: sql<number | null>`rowid` })
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 620d896f80..62713b4f27 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -82,8 +82,10 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭
伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的
学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容
由后续复盘按序分批补进账本(每批有界),覆盖水位只推进到连续补完的位置;本轮取材本身被截断时
-同样不推进水位,补完之前账本不算新鲜;水位以消息的 client_id 为持久判据(rowid 在数据库瘦身后
-可能重排),老对话第一次建账本从对话开头(清空边界之后)分批补起,不跳过任何一轮;
+同样不推进水位,补完之前账本不算新鲜;超过单条上限的用户/伙伴消息按块分多次复盘,水位可停在
+消息中间,整条看完才算覆盖(工具结果不是新条目的证据来源,仍只取开头);水位以消息的 client_id
+为持久判据(rowid 在数据库瘦身后可能重排),老对话第一次建账本从对话开头(清空边界之后)分批
+补起,不跳过任何一轮;
新条目必须有本轮用户或伙伴原话证据,
漏写的旧条目保留,删除同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动
压缩之后的下一次发送再补一次,交接首条已带时不重复。账本是摘要,不是授权:历史授权不是新的