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): defer only current-turn ledger deletions; freshness counts only resolved interactions with content

zqchris008389df3c8f
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 e567b26a75..cea4c4e1d4 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts
@@ -464,3 +464,44 @@ it('does not advance the watermark past the previous completed reply when the cu
h.turnRows = null;
h.floorRowid = null;
});
+
+it('commits deletions evidenced inside the backfilled prefix even while the gap is incomplete, but still defers those evidenced by the current turn', async () => {
+ // 缺口 (1,100] 有 41 条、分两批回补:取消旧承诺的用户消息只出现在第一批,错过就补不上。
+ h.working = {
+ version: 1, revision: 4, coveredThroughRowid: 1, coveredThroughMessageId: 'r1', updatedAt: 0,
+ threads: [], waiting: [], corrections: [], recentlyDone: [],
+ commitments: [
+ { id: 'c-cancelled', text: 'Ship the weekly report template', messageId: 'u-old', updatedAt: 1 },
+ { id: 'c-current', text: 'Add dark mode to the mockup', messageId: 'u-old', updatedAt: 2 },
+ ],
+ };
+ h.floorRowid = 1;
+ h.prevCompleted = 100;
+ h.gapRows = [
+ { id: 'g2', role: 'user', content: JSON.stringify('Forget the weekly report template, we dropped it.'), order: 2 },
+ ...Array.from({ length: 40 }, (_, i) => ({ id: `g${3 + i}`, role: 'assistant', content: JSON.stringify(`gap ${3 + i}`), order: 3 + i })),
+ ];
+ h.model.mockResolvedValueOnce({
+ ok: true,
+ text: JSON.stringify({
+ memories: [],
+ skills: [],
+ working: {
+ commitments: [],
+ resolved: [
+ { text: 'Ship the weekly report template', evidence: { messageId: 'g2', quote: 'we dropped it' } },
+ { text: 'Add dark mode to the mockup', evidence: { messageId: 'user', quote: 'summarize the conclusion first' } },
+ ],
+ },
+ }),
+ });
+ await reviewTeammateLearning('session', 'reply');
+ const written = h.writeWorking.mock.calls.at(-1)![2] as { coveredThroughRowid: number; coveredThroughMessageId?: string; commitments: Array<{ text: string }> };
+ // 水位停在第一批末尾(rowid 41),没推进到当前回复。
+ expect(written).toMatchObject({ coveredThroughRowid: 41, coveredThroughMessageId: 'g41' });
+ // 前缀内证据的删除照常生效;当前轮证据的删除延后到这一轮被完整回补时。
+ expect(written.commitments.map((c) => c.text)).toEqual(['Add dark mode to the mockup']);
+ h.prevCompleted = 3;
+ h.gapRows = [];
+ 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.ts
index bedd86fbac..243447efc2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botWorkingMemory.test.ts
@@ -134,7 +134,7 @@ describe('applyWorkingMemoryProposal', () => {
);
expect(chunked).toMatchObject({ coveredThroughRowid: 12, coveredThroughMessageId: 'long', coveredThroughOffset: 6000 });
expect(parseWorkingMemory({ version: 1, ...chunked }).coveredThroughOffset).toBe(6000);
- // 只追加模式(本轮没完整覆盖):有证据的 resolved 与字段改写都延后,新条目照常进账。
+ // 本轮没完整覆盖:以水位之后那一轮(a1 / t1)为证据的 resolved 与字段改写都延后,新条目照常进账。
const additive = applyWorkingMemoryProposal(
previous,
{
@@ -149,12 +149,23 @@ describe('applyWorkingMemoryProposal', () => {
resolved: [{ text: '把测试补上', evidence: { messageId: 't1', quote: 'report-template.md written' } }],
},
messages,
- { now, coveredThroughRowid: 10, coveredThroughMessageId: 'old', additiveOnly: true },
+ { now, coveredThroughRowid: 10, coveredThroughMessageId: 'old', deferEvidenceFrom: new Set(['a1', 't1']) },
);
// 旧条目一个都不少(含本该被 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');
+ // 延后只针对水位之后那一轮的证据:回补前缀里的证据(t1 不在集合里)照常删除。
+ const prefixEvidenced = applyWorkingMemoryProposal(
+ previous,
+ {
+ threads: [], commitments: [], waiting: [], corrections: [], recentlyDone: [],
+ resolved: [{ text: '把测试补上', evidence: { messageId: 't1', quote: 'report-template.md written' } }],
+ },
+ messages,
+ { now, coveredThroughRowid: 10, coveredThroughMessageId: 'old', deferEvidenceFrom: new Set(['a1']) },
+ );
+ expect(prefixEvidenced.commitments.map((c) => c.text)).not.toContain('把测试补上');
// 只追加模式下分区已满:新条目延后,不把最旧的旧条目挤出去。
const fullWaiting = Array.from({ length: WORKING_MEMORY_LIMITS.waiting }, (_, i) => ({
id: `w${i}`, text: `等第${i}个回复`, on: 'user' as const, updatedAt: i + 1,
@@ -166,7 +177,7 @@ describe('applyWorkingMemoryProposal', () => {
waiting: [{ text: '等新的回复', on: 'user', evidence: { messageId: 'a1', quote: '改完发你确认' } }],
},
messages,
- { now, coveredThroughRowid: 10, coveredThroughMessageId: 'old', additiveOnly: true },
+ { now, coveredThroughRowid: 10, coveredThroughMessageId: 'old', deferEvidenceFrom: new Set(['a1']) },
);
expect(crowded.waiting.map((w) => w.id).sort()).toEqual(fullWaiting.map((w) => w.id).sort());
// 非只追加模式照旧:新条目进账,最旧的被容量裁掉。
diff --git a/apps/desktop/src/main/maker-ipc/botLearningReview.ts b/apps/desktop/src/main/maker-ipc/botLearningReview.ts
index dee45c1496..4f02544ebc 100644
--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts
+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts
@@ -325,9 +325,10 @@ 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,
+ // 水位没推进到当前回复(本轮被截断 / 缺口未补完):当前这一轮之后还会被完整回补,
+ // 以它为证据的删除与改写留到那时、现在只追加,免得 rewind 这一轮后账本已按撤回
+ // 分支删改。回补前缀(水位之内)里的证据照常提交——它们不会再被回放第二次。
+ ...(covered.rowid < row.rowid ? { deferEvidenceFrom: new Set(turnMessages.map((m) => m.id)) } : {}),
}),
workingBefore?.revision ?? 0,
);
diff --git a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts
index 99b937287d..3349f117d3 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkingMemory.ts
@@ -281,9 +281,11 @@ function resolveOptionalField(
* - 旧条目不在提案里时**保留**——漏写不等于完成;要删除走 `resolved`,同样要证据
* (用户 / 伙伴 / 工具结果均可);
* - 各区按上限保留最新的;只有真正变过的条目才更新时间,排序才有意义;
- * - `additiveOnly`(本轮取材没完整覆盖、水位停在之前):只追加新条目,不删(resolved)也不
- * 改写旧条目——这些破坏性变更等这一轮被完整回补时再提交,免得用户随后 rewind 这一轮后
- * 水位仍指着可见的旧回复、账本却已按撤回分支删改过且无法回滚。
+ * - `deferEvidenceFrom`(本轮取材没完整覆盖、水位停在之前时,水位之后那一轮的消息 id):
+ * 以这些消息为证据的删除(resolved)/ 改写延后,只追加新条目——这些破坏性变更等那一轮被
+ * 完整回补时再提交,免得用户随后 rewind 那一轮后水位仍指着可见的旧回复、账本却已按撤回
+ * 分支删改过且无法回滚。以回补前缀(水位之内)消息为证据的删改照常提交:缺口分多批回放
+ * 时,取消某承诺的证据只会出现在它所在的那一批,错过就再也补不上。
*/
export function applyWorkingMemoryProposal(
previous: BotWorkingMemory | null,
@@ -294,16 +296,16 @@ export function applyWorkingMemoryProposal(
coveredThroughRowid: number;
coveredThroughMessageId?: string;
coveredThroughOffset?: number;
- additiveOnly?: boolean;
+ deferEvidenceFrom?: ReadonlySet<string>;
},
): Omit<BotWorkingMemory, 'revision' | 'version'> {
const prev = previous ?? emptyWorkingMemory();
+ const deferred = (item: ProposedItem): boolean =>
+ !!item.evidence && !!opts.deferEvidenceFrom?.has(item.evidence.messageId);
const resolvedTexts = new Set(
- opts.additiveOnly
- ? []
- : proposal.resolved
- .filter((item) => evidenceHolds(item.evidence, messages, RESOLVE_ROLES))
- .map((item) => clampText(item.text)),
+ proposal.resolved
+ .filter((item) => !deferred(item) && evidenceHolds(item.evidence, messages, RESOLVE_ROLES))
+ .map((item) => clampText(item.text)),
);
let seq = 0;
const nextId = () => `wm_${opts.now.toString(36)}_${(seq += 1)}`;
@@ -329,16 +331,16 @@ export function applyWorkingMemoryProposal(
const evidenced = evidenceHolds(item.evidence, messages, NEW_ITEM_ROLES);
if (prior) {
const candidate = build(prior, item, { ...prior, updatedAt: opts.now });
- // 完整内容没变:原样沿用,时间也不动。字段变了:要证据,没证据就当没提;只追加模式下
- // 改写一律延后。
- if (opts.additiveOnly || sameItem(candidate, prior) || !evidenced) kept.set(text, prior);
+ // 完整内容没变:原样沿用,时间也不动。字段变了:要证据,没证据就当没提;证据来自水位
+ // 之后那一轮的改写延后。
+ if (deferred(item) || sameItem(candidate, prior) || !evidenced) kept.set(text, prior);
else kept.set(text, candidate);
continue;
}
if (!evidenced) continue;
- // 只追加模式下新条目不能把旧条目挤出容量:区满了就延后新增(这一轮之后会被完整回补),
- // 否则 rewind 这一轮时来源清理只能删掉新条目,被挤掉的旧承诺回不来。
- if (opts.additiveOnly && existing.length + added >= cap) continue;
+ // 证据来自水位之后那一轮的新条目不能把旧条目挤出容量:区满了就延后新增(那一轮之后
+ // 会被完整回补),否则 rewind 那一轮时来源清理只能删掉新条目,被挤掉的旧承诺回不来。
+ if (deferred(item) && existing.length + added >= cap) continue;
added += 1;
kept.set(text, build(null, item, { id: nextId(), text, messageId: item.evidence!.messageId, updatedAt: opts.now }));
}
@@ -713,8 +715,10 @@ export async function isWorkingMemoryFreshForSession(sessionId: string, userData
)
.limit(1);
if (typeof covered?.rowid !== 'number') return false;
- // 必须覆盖的水位 = 最近一条完成回复,或更晚落库的交互答复(计划审阅的批准 / 打回、提问卡
- // 答案在回复完成之后才写入):它们承载用户决定,没被复盘过就不能算新鲜。
+ // 必须覆盖的水位 = 最近一条完成回复,或更晚落库、**带内容**的交互答复(已回答的提问卡、
+ // 批准 / 打回的计划审阅,状态与 botLearningReview.interactionText 的取材口径一致):它们
+ // 承载用户决定,没被复盘过就不能算新鲜。取消 / 未回答的空交互行没有内容,不抬水位——
+ // 否则一次取消就让账本永远不新鲜。
const [row] = await db
.select({ rowid: sql<number | null>`MAX(rowid)` })
.from(messages)
@@ -727,7 +731,14 @@ export async function isWorkingMemoryFreshForSession(sessionId: string, userData
eq(messages.role, 'assistant'),
sql`json_valid(${messages.agentMeta}) AND json_extract(${messages.agentMeta}, '$.turnCompleted') = 1`,
),
- inArray(messages.role, ['ask_user', 'plan_review']),
+ and(
+ inArray(messages.role, ['ask_user', 'plan_review']),
+ sql`json_valid(${messages.content}) AND CASE json_extract(${messages.content}, '$.status')
+ WHEN 'answered' THEN json_type(${messages.content}, '$.answers') = 'object' AND json_extract(${messages.content}, '$.answers') <> '{}'
+ WHEN 'approved' THEN trim(coalesce(json_extract(${messages.content}, '$.plan'), '')) <> ''
+ WHEN 'revised' THEN trim(coalesce(json_extract(${messages.content}, '$.feedback'), '')) <> ''
+ ELSE 0 END`,
+ ),
),
),
);
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 1df8c0f20f..ad3ffcb64d 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -82,8 +82,10 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭
伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的
学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容
由后续复盘按序分批补进账本(每批有界),覆盖水位只推进到连续补完的位置;本轮取材本身被截断时
-同样不推进水位,补完之前账本不算新鲜,且这样的轮次只往账本追加、不删不改(删改等整轮补完再提交,
-免得随后 rewind 时无法回滚);超过单条上限的用户/伙伴消息按块分多次复盘,相邻块留重叠,水位可停在
+同样不推进水位,补完之前账本不算新鲜,且这样的轮次里以水位之后那一轮为证据的删改延后、只追加(等那
+一轮被完整回补再提交,免得随后 rewind 时无法回滚),回补前缀内有证据的删改照常提交(它们不会再被回放
+第二次);新鲜度要求覆盖到最近一条完成回复或更晚的带内容交互答复(已回答的提问卡、批准/打回的计划
+审阅),取消的空交互不抬水位;超过单条上限的用户/伙伴消息按块分多次复盘,相邻块留重叠,水位可停在
消息中间,整条看完才算覆盖(工具结果不是新条目的证据来源,仍只取开头);换窗交接里账本段与检索
指引同属硬截断时必须整段保住的尾部;用户在提问卡、计划审阅
里给出的答复与反馈按用户消息进入复盘取材,可作为账本证据;水位以消息的 client_id