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(companions): use ordinary session compaction without background maintenance

Chris9672a99bc98f
diff --git a/apps/desktop/src/main/im/shared/orchestrator.ts b/apps/desktop/src/main/im/shared/orchestrator.ts
index a98367028f..8696b99d5f 100644
--- a/apps/desktop/src/main/im/shared/orchestrator.ts
+++ b/apps/desktop/src/main/im/shared/orchestrator.ts
@@ -167,7 +167,7 @@ export function createImOrchestrator(
? acquirePendingAgentSwitchForImSend(sessionId, () => defaultRouteSync.syncUnderLock(sessionId))
: acquirePendingAgentSwitchForDirectSend(sessionId),
channelDefaultRoute: defaultRouteSync,
- // 发送前上下文体检与桌面直发同源(到线换窗 / 空闲间隔刷新 / 坏历史重建)。
+ // 发送前故障恢复与桌面直发同源;健康上下文交给 Session 原生压缩。
prepareUnhealthySession: (sessionId) => prepareUnhealthySessionForSend(sessionId),
// 伙伴自有连接: 消息落在伙伴的主任务 / 隐藏专线上。
...(options.companionBotId
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index 0a51b4897a..503e0695e9 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -714,8 +714,8 @@ export interface ImTurnRunnerDeps {
/** 连接交给伙伴后的路由(只对实现了 adapter.companionLane 的渠道生效)。 */
companion?: ImCompanionRouteDeps;
/**
- * 与桌面直发同源的发送前上下文体检(`register.prepareUnhealthySessionForSend`):到线换窗、
- * 空闲间隔刷新、已知坏历史重建。伙伴主对话与 IM 专线同一条规则,不为 IM 单设一套。
+ * 与桌面直发同源的发送前故障恢复(`register.prepareUnhealthySessionForSend`)。
+ * 健康伙伴主对话与 IM 专线均沿用 Session 原生压缩,不按空闲时长或伙伴阈值换窗。
* 体检重建时会以 'runtime-refresh' 关掉当前 live handle,新 handle 由
* `refreshSessionAfterPendingAgentSwitch` 按最新 DB 行重建。
*/
@@ -1513,8 +1513,8 @@ export function createTurnRunner(
return { kind: 'rejected', reason: 'companion_unavailable' };
}
}
- // 发送前上下文体检(与桌面直发、官方 hook 同一个入口): 伙伴对话隔了半天再开口、
- // 占用到线、已知坏历史都在这里换干净的原生会话。关闭原因是 'runtime-refresh',
+ // 发送前故障恢复(与桌面直发、官方 hook 同一个入口): 仅在真实满窗或已知
+ // 压缩失败、坏历史等恢复条件下重建原生会话。关闭原因是 'runtime-refresh',
// 上面的 close 监听在有 acquirePendingAgentSwitch 时会保住本任务; 新 live session
// 由下面的 refreshSessionAfterPendingAgentSwitch 按最新 DB 行(sdkSessionId 已清空)
// 重建并换绑。体检失败按直发同一口径让这条消息失败, 不带着过期的 resume 选项发送。
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 1d5d8787c7..c0183486b2 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@ -20,8 +20,6 @@ import {
type ContextOverflowRolloverDeps,
type OverflowSourceMessage,
withReplaySourceNotes,
- BOT_IDLE_GAP_REBUILD_MS,
- measureIdleGap,
} from '../contextOverflowRollover';
import { buildHandoffText } from '../agentHandoff';
@@ -372,14 +370,14 @@ describe('createContextOverflowRollover', () => {
};
}
- it.each(['cc', 'pi'])('checkpoints a pressured %s companion before send, retaining outcomes without replay', async (agentKind) => {
+ it.each(['cc', 'pi'])('recovers a full %s companion through the ordinary Session guard, retaining outcomes without replay', async (agentKind) => {
const deps = makeDeps([
msg('user', 'Keep the game keyboard accessible', 'u1'),
{ ...msg('tool_use', { toolName: 'Write', input: { file_path: '/game/index.html' } }, 't1'), toolUseId: 'write-1' },
{ ...msg('tool_result', { fullText: 'Saved index.html; keyboard test passed' }, 'r1'), toolUseId: 'write-1' },
msg('assistant', 'Keyboard controls are ready. Next: add touch controls.', 'a1'),
]);
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), agentKind, source: 'bot', botRole: 'canonical', contextTokens: 180_000 });
+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), agentKind, source: 'bot', botRole: 'canonical', contextTokens: 200_000 });
const withOwn = { ...deps, listCompanionSessionIds: vi.fn(async () => ({ sessionIds: ['s1', 's-old', 's-bg'], chatsTruncated: false })) };
const rollover = createContextOverflowRollover(withOwn);
await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(true);
@@ -400,162 +398,37 @@ describe('createContextOverflowRollover', () => {
expect(deps.commitRebuild).toHaveBeenCalledTimes(1);
});
- describe('idle-gap refresh (one rule for the companion chat and its IM lanes)', () => {
- const HOUR = 60 * 60 * 1000;
- const botRow = async (deps: ReturnType<typeof makeDeps>, botRole: string) =>
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole, contextTokens: 20_000 });
-
- it.each(['canonical', 'channel', 'group'])('rebuilds a %s bot chat whose last activity is older than the idle gap', async (botRole) => {
- const old = Date.now() - 2 * BOT_IDLE_GAP_REBUILD_MS - 3 * HOUR;
- const deps = makeDeps([
- msg('user', 'Plan the Friday dinner', 'u1', old - HOUR),
- msg('assistant', 'Booked the table for 7pm.', 'a1', old),
- ]);
- await botRow(deps, botRole);
- await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(true);
- expect(deps.closeSession).toHaveBeenCalledWith('s1');
- expect((deps.commitRebuild.mock.calls[0] as unknown[])[2]).toMatchObject({ reason: 'idle-gap', sourceUserClientId: 'u1' });
- const handoff = deps.setPendingHandoff.mock.calls[0]![1] as string;
- expect(handoff).toContain('idle for about 1 day 3 hours');
- expect(handoff).toContain('Treat the user\'s new message as the current topic');
- expect(handoff).toContain('Booked the table for 7pm.');
- expect(handoff).toContain('== Recalling earlier history (use when needed) ==');
- expect(deps.replayUserMessage).not.toHaveBeenCalled();
- });
-
- it('measures the gap up to the already-persisted pending user message and does not count it as activity', async () => {
- const now = Date.now();
- const deps = makeDeps([
- msg('user', 'Earlier question', 'u1', now - 30 * HOUR),
- msg('assistant', 'Earlier answer', 'a1', now - 29 * HOUR),
- // Group lanes persist the inbound message before dispatch; it is the message being sent now.
- msg('user', 'New question after a day', 'u2', now - 1000),
- ]);
- await botRow(deps, 'channel');
- await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(true);
- expect((deps.commitRebuild.mock.calls[0] as unknown[])[2]).toMatchObject({ reason: 'idle-gap', sourceUserClientId: 'u2' });
- const handoff = deps.setPendingHandoff.mock.calls[0]![1] as string;
- expect(handoff).toContain('Earlier answer');
- expect(handoff).not.toContain('New question after a day');
- });
-
- it('does not rebuild when the chat was active within the idle gap, is not a bot chat, or has no usable timestamps', async () => {
- const now = Date.now();
- const recent = makeDeps([msg('user', 'hi', 'u1', now - 3 * HOUR), msg('assistant', 'hello', 'a1', now - 2 * HOUR)]);
- await botRow(recent, 'canonical');
- await expect(createContextOverflowRollover(recent).prepareUnhealthySession('s1')).resolves.toBe(false);
-
- const desktop = makeDeps([msg('user', 'hi', 'u1', now - 40 * HOUR), msg('assistant', 'hello', 'a1', now - 39 * HOUR)]);
- await expect(createContextOverflowRollover(desktop).prepareUnhealthySession('s1')).resolves.toBe(false);
-
- const delegation = makeDeps([msg('user', 'hi', 'u1', now - 40 * HOUR), msg('assistant', 'hello', 'a1', now - 39 * HOUR)]);
- await botRow(delegation, 'delegation');
- await expect(createContextOverflowRollover(delegation).prepareUnhealthySession('s1')).resolves.toBe(false);
-
- const untimed = makeDeps([msg('user', 'hi', 'u1'), msg('assistant', 'hello', 'a1')]);
- await botRow(untimed, 'canonical');
- await expect(createContextOverflowRollover(untimed).prepareUnhealthySession('s1')).resolves.toBe(false);
- for (const deps of [recent, desktop, delegation, untimed]) expect(deps.closeSession).not.toHaveBeenCalled();
- });
-
- it('does not rebuild twice for the same pending message when the previous send failed after an idle-gap rebuild', async () => {
- const now = Date.now();
- const deps = {
- ...makeDeps([
- msg('user', 'Earlier question', 'u1', now - 30 * HOUR),
- msg('assistant', 'Earlier answer', 'a1', now - 29 * HOUR),
- msg('user', 'Retry me', 'u2', now - 5000),
- msg('error', { reason: 'network', message: 'ECONNRESET' }, 'e1', now - 4000),
- ]),
- findLatestRebuildMeta: vi.fn(async () => ({ reason: 'idle-gap', sourceUserClientId: 'u2' })),
- };
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 20_000 });
- await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);
+ // Product decision 2026-10-23: companion age / token checkpoints must not
+ // replace a healthy native session, regardless of the input channel.
+ it.each(['cc', 'pi', 'codex'])('keeps healthy %s companion contexts for native compaction across repeated sends', async (agentKind) => {
+ for (const botRole of ['canonical', 'thread', 'channel', 'group']) {
+ const old = Date.now() - 48 * 60 * 60 * 1000;
+ const source = [msg('user', 'Keep the plan', 'u1', old), msg('assistant', 'Plan retained', 'a1', old + 1)];
+ const deps = makeDeps(source);
+ const rollover = createContextOverflowRollover(deps);
+ for (const contextTokens of [20_000, 140_000, 180_000, 199_999]) {
+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), agentKind, source: 'bot', botRole, contextTokens });
+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);
+ source.push(msg('user', '[UI_ACTION_TRIGGER] continue', 'background'));
+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);
+ source.push(msg('user', 'A new question today', 'human', Date.now()));
+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);
+ }
expect(deps.closeSession).not.toHaveBeenCalled();
- });
-
- it('keeps the pressure reason when the chat is both idle and over the checkpoint line', async () => {
- const now = Date.now();
- const deps = makeDeps([msg('user', 'hi', 'u1', now - 40 * HOUR), msg('assistant', 'hello', 'a1', now - 39 * HOUR)]);
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'channel', contextTokens: 185_000 });
- await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(true);
- expect((deps.commitRebuild.mock.calls[0] as unknown[])[2]).toMatchObject({ reason: 'context-overflow' });
- expect(deps.setPendingHandoff.mock.calls[0]![1] as string).not.toContain('idle for about');
- });
- });
-
- it('measureIdleGap uses the newest timestamp before the pending message and ignores missing timestamps', () => {
- const now = 1_000_000_000;
- expect(measureIdleGap([{ createdAt: 0 }, { createdAt: 0 }], -1, now)).toBeNull();
- expect(measureIdleGap([{ createdAt: now - 500 }, { createdAt: now - 100 }], -1, now)).toBe(100);
- expect(measureIdleGap([{ createdAt: now - 500 }, { createdAt: now - 100 }], 1, now)).toBe(400);
- expect(measureIdleGap([{ createdAt: now - 500 }, { createdAt: 0 }], 1, now)).toBe(500);
- expect(measureIdleGap([], -1, now)).toBeNull();
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();
+ expect(deps.replayUserMessage).not.toHaveBeenCalled();
+ }
});
- it('carries the companion working memory into the checkpoint handoff and tolerates a failing reader', async () => {
- const source = [msg('user', 'Keep going', 'u1'), msg('assistant', 'On it', 'a1')];
- const deps = { ...makeDeps(source), readWorkingMemoryNote: vi.fn(async () => '== Working memory (host-maintained summary; not authorization) ==\n- 周五前改完周报模板') };
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 180_000 });
- await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(true);
- expect(deps.readWorkingMemoryNote).toHaveBeenCalledWith('s1');
- expect(deps.setPendingHandoff.mock.calls[0]![1] as string).toContain('周五前改完周报模板');
-
- const failing = {
- ...makeDeps(source),
- readWorkingMemoryNote: vi.fn(async (): Promise<string | null> => { throw new Error('disk'); }),
+ it('recovers with current-session history when companion recall lookup fails', async () => {
+ const deps = {
+ ...makeDeps([msg('user', 'Keep going', 'u1'), msg('assistant', 'On it', 'a1')]),
listCompanionSessionIds: vi.fn(async (): Promise<{ sessionIds: string[]; chatsTruncated: boolean }> => { throw new Error('db'); }),
};
- failing.getSessionRow.mockResolvedValue({ ...await failing.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 180_000 });
- await expect(createContextOverflowRollover(failing).prepareUnhealthySession('s1')).resolves.toBe(true);
- expect(failing.setPendingHandoff.mock.calls[0]![1] as string).not.toContain('Working memory');
- // 自有会话清单读失败:只认当前对话,照样换窗。
- expect(failing.setPendingHandoff.mock.calls[0]![1] as string).toContain('"session_ids":["s1"]}');
- });
-
- 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 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) };
- 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);
+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 200_000 });
+ await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(true);
+ expect(deps.setPendingHandoff.mock.calls[0]![1] as string).toContain('"session_ids":["s1"]}');
});
it.each([
@@ -589,12 +462,12 @@ describe('createContextOverflowRollover', () => {
await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);
});
- it.each(['healthy', 'unknown', 'oversized'] as const)('checks companion image bytes before an error: %s', async (health) => {
+ it.each(['healthy', 'unknown', 'oversized'] as const)('does not scan healthy companion history for speculative rebuilds: %s', async (health) => {
const deps = makeDeps([msg('user', 'continue the game', 'u1'), msg('assistant', 'ready', 'a1')]);
deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', agentKind: 'codex' });
const classifyCodexHistory = vi.fn(async () => health);
- await expect(createContextOverflowRollover({ ...deps, classifyCodexHistory }).prepareUnhealthySession('s1')).resolves.toBe(health === 'oversized');
- expect(classifyCodexHistory).toHaveBeenCalledOnce();
+ await expect(createContextOverflowRollover({ ...deps, classifyCodexHistory }).prepareUnhealthySession('s1')).resolves.toBe(false);
+ expect(classifyCodexHistory).not.toHaveBeenCalled();
expect(deps.replayUserMessage).not.toHaveBeenCalled();
});
@@ -628,9 +501,9 @@ describe('createContextOverflowRollover', () => {
expect(deps.closeSession).not.toHaveBeenCalled();
});
- it('does not checkpoint while native background execution is still active', async () => {
+ it('does not rebuild a full context while native background execution is still active', async () => {
const deps = makeDeps([msg('user', 'continue', 'u1')]);
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 190_000 });
+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 200_000 });
deps.getLiveSession.mockReturnValue({ isTurnRunning: () => false, listBackgroundTasks: () => [{ id: 'active' }] });
await expect(createContextOverflowRollover(deps).prepareUnhealthySession('s1')).resolves.toBe(false);
expect(deps.closeSession).not.toHaveBeenCalled();
@@ -638,7 +511,7 @@ describe('createContextOverflowRollover', () => {
it.each(['history', 'close'])('stopping companion preparation during %s forbids a late rebuild', async (stage) => {
const deps = makeDeps([msg('user', 'continue', 'u1')]);
- deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 190_000 });
+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), source: 'bot', botRole: 'canonical', contextTokens: 200_000 });
const rollover = createContextOverflowRollover(deps);
if (stage === 'history') deps.listMessages.mockImplementation(async () => { rollover.cancelRecovery('s1'); return [msg('user', 'continue', 'u1')]; });
else deps.closeSession.mockImplementation(async () => { rollover.cancelRecovery('s1'); });
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index a324e06cbd..97a22f00f0 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -69,6 +69,9 @@ vi.mock('../../turnCostBroadcaster.js', () => ({
vi.mock('../../modelMismatchBroadcaster.js', () => ({
recordModelMismatchOnMessage: effects.fn('recordModelMismatchOnMessage'),
}));
+vi.mock('../botLearningReview.js', () => ({
+ reviewTeammateLearning: effects.fn('reviewTeammateLearning'),
+}));
vi.mock('../../usage/claudeAccountUsage.js', () => ({
triggerClaudeAccountUsageRefresh: effects.fn('triggerClaudeAccountUsageRefresh'),
}));
@@ -554,9 +557,11 @@ describe('production Session event pipeline', () => {
it.each(['completed', 'failed', 'cancelled', 'interrupted'])(
'runs the upstream-merge follow-up only for a successful product boundary: %s', async (status) => {
const h = harness();
+ effects.fn('consumeLastTopLevelAssistantPersistId').mockReturnValueOnce('completed-reply');
h.emit(event('status', { isRunning: true }));
h.emit(event('done', { status }));
await microtasks();
+ expect(effects.fn('reviewTeammateLearning')).not.toHaveBeenCalled();
expect(h.deps.onSuccessfulProductTurn).toHaveBeenCalledTimes(status === 'completed' ? 1 : 0);
expect(h.deps.onUnsuccessfulProductTurn).toHaveBeenCalledTimes(status === 'completed' ? 0 : 1);
await h.dispose();
diff --git a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
index 75c5eb378b..00268548a1 100644
--- a/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
+++ b/apps/desktop/src/main/maker-ipc/botSystemPrompt.ts
@@ -127,7 +127,7 @@ const OWN_SKILLS_GUIDANCE = [
'## 你能把做法沉淀成本事',
'每次用户纠正做法、指定可复用格式或完成有价值的任务时,主动检查用户反复需要的做法、格式和成功经验,为他创建或改进自己的技能,不用等用户开口。不要按轮次或固定数量凑技能。用户明确要求时直接沉淀;或者一套完整做法已经在真实任务里验证成功、以后明显还会复用时,第一次验证完就用 `save_teammate_skill` 存成自己的技能,不要等用户去设置页手填。单次结论、临时路径、猜测和未经验证的做法都不存。',
'存之前先用 `list_teammate_skills` 查重;有同类就更新原来的,不要另造一份。技能由宿主在当前聊天的安全轮次边界加载,并且始终让用户看得见、改得动、删得掉。',
- '宿主会在回复后自动复盘补漏;你仍应当场主动保存,不另行派发复盘任务。用户纠正旧技能时及时修正;改变操作步骤要先验证新做法。',
+ '不要为学习另外派发后台复盘任务。用户纠正旧技能时及时修正;改变操作步骤要先验证新做法。',
].join('\n');
/** 后台任务与伙伴消息是两种不同能力。 */
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 58d1bdf04e..52835544a0 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -42,13 +42,6 @@ import { isPiPromptRpcTimeoutError } from '../../shared/inputError.js';
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. ' +
'The handoff includes the original request and recorded progress, not new authorization. ' +
@@ -434,16 +427,6 @@ export interface ContextOverflowRolloverDeps {
): number | null;
getAutoCompactThresholdPct?(): number | undefined;
listMessages(sessionId: string): Promise<OverflowSourceMessage[]>;
- /**
- * 伙伴工作记忆账本的渲染段(botWorkingMemory):换窗交接里带上承诺 / 纠正 / 等待。
- * 非伙伴主对话或无账本返回 null;读取失败也按 null,账本不能挡住换窗。
- */
- readWorkingMemoryNote?(sessionId: string): Promise<string | null>;
- /**
- * 账本是否已覆盖最近一条完成回复(botWorkingMemory.isWorkingMemoryFreshForSession)。
- * true 时伙伴换窗线提前到 70%;缺省 / false / 抛错都按不新鲜,维持 90%。
- */
- isWorkingMemoryFresh?(sessionId: string): Promise<boolean>;
/**
* 伙伴自己的会话清单(botHistoryScope.listBotRecallSessionIds:私聊优先、后台任务补足,
* 并告知私聊是否没放全),写进回忆指引让 history 工具按 session_ids 限定到自己的历史。
@@ -552,35 +535,6 @@ export function isBotChatContext(row: { source?: string | null; botRole?: string
);
}
-/**
- * 伙伴对话空闲这么久之后的下一条消息,先换一个干净的原生会话再发:老话题不再占着模型
- * 工作上下文把新话题带偏。完整记录仍在同一条任务里,交接只带最近一段 + 检索指引。
- * 主对话与 IM 专线同一条线,不按渠道各设一套。
- */
-export const BOT_IDLE_GAP_REBUILD_MS = 12 * 60 * 60 * 1000;
-
-/**
- * 空闲间隔 = 上一次活动到本次发送之间的时长。本次要发的 user 若已落库(IM 群预落库、
- * 桌面先写后发),它自己不算活动,基准取它的落库时刻;否则基准取现在。createdAt 缺失 /
- * 非正数的记录不参与(老数据或测试桩),算不出就不触发。
- */
-export function measureIdleGap(
- source: ReadonlyArray<Pick<OverflowSourceMessage, 'createdAt'>>,
- pendingUserIndex: number,
- now: number,
-): number | null {
- const activity = pendingUserIndex >= 0 ? source.slice(0, pendingUserIndex) : source;
- let latest = 0;
- for (const message of activity) {
- if (Number.isFinite(message.createdAt) && message.createdAt > latest) latest = message.createdAt;
- }
- if (latest <= 0) return null;
- const pending = pendingUserIndex >= 0 ? source[pendingUserIndex] : undefined;
- const reference =
- pending && Number.isFinite(pending.createdAt) && pending.createdAt > 0 ? pending.createdAt : now;
- return Math.max(0, reference - latest);
-}
-
export type OverflowClaimResult = 'claimed' | 'in-flight' | 'idle';
export type ModelWindowSwitchPreparationResult =
@@ -664,21 +618,6 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
*/
const rebuiltWithLearnedCompat = new Set<string>();
- // 账本是增强:读不到、抛错都按没有,绝不挡住换窗。
- const readWorkingMemoryNote = async (sessionId: string): Promise<string | null> => {
- try {
- return (await deps.readWorkingMemoryNote?.(sessionId)) ?? null;
- } catch {
- return null;
- }
- };
- const isWorkingMemoryFresh = async (sessionId: string): Promise<boolean> => {
- try {
- return (await deps.isWorkingMemoryFresh?.(sessionId)) === true;
- } catch {
- return false;
- }
- };
// 伙伴自有会话清单同样是增强:非伙伴不查,读不到按只认当前对话。
const companionRecall = async (
sessionId: string,
@@ -905,7 +844,6 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
includeToolResults: oversized || isBotChatContext(sessionRow),
companion: isBotChatContext(sessionRow),
...(await companionRecall(sessionId, isBotChatContext(sessionRow))),
- workingMemory: await readWorkingMemoryNote(sessionId),
});
await deps.commitRebuild(sessionId, handoff, {
reason: 'context-overflow',
@@ -1101,7 +1039,6 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
reason: 'model-window-switch',
companion: isBotChatContext(sessionRow),
...(await companionRecall(sessionId, isBotChatContext(sessionRow))),
- workingMemory: await readWorkingMemoryNote(sessionId),
});
await deps.commitRebuild(sessionId, handoff, {
reason: 'model-window-switch',
@@ -1132,7 +1069,8 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
if (!sessionRow.sdkSessionId) return false;
const live = deps.getLiveSession(sessionId);
if (live?.isTurnRunning() || (live?.listBackgroundTasks?.().length ?? 0) > 0) return false;
- // 伙伴的 IM 专线与主对话同一套规则:到线换窗、带工具结果、空闲间隔刷新。
+ // All companion lanes use the ordinary Session recovery boundary. Healthy
+ // contexts stay with the harness; age and companion identity do not rotate them.
const botChat = isBotChatContext(sessionRow);
const source = await deps.listMessages(sessionId);
const lastError = findLatestRebuildableError(source, sessionRow.agentKind === 'pi', botChat);
@@ -1159,51 +1097,19 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
sessionRow.agentKind,
);
const window = effectiveContextWindow(sessionRow.model, reportedWindow, verified);
- // Codex owns native pressure compaction, including companions. Other harnesses
- // retain their send-boundary companion checkpoints and full-window guard.
- // 账本新鲜(复盘已覆盖最近完成轮)时线提前到 70%;不新鲜维持 90%,免得换窗丢掉还没进
- // 账本的内容。只有落在 70%–90% 之间才去读账本;提前换窗必须拿到渲染好的账本段并原样
- // 带进交接——同一个快照只读一次,免得判新鲜之后第二次读取失败,交接反而没带账本。
- let earlyWorkingMemory: string | undefined;
- const pressure = sessionRow.agentKind === 'codex' ? false : botChat
- ? shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO) ||
- (shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO_FRESH) &&
- (await isWorkingMemoryFresh(sessionId)) &&
- (earlyWorkingMemory = (await readWorkingMemoryNote(sessionId)) ?? undefined) !== undefined)
- : shouldRebuildForContextPressure(usedTokens, window);
+ // Native compaction owns healthy contexts. Keep the existing full-window
+ // recovery guard shared with ordinary Sessions (Codex manages its own limit).
+ const pressure = sessionRow.agentKind !== 'codex' && shouldRebuildForContextPressure(usedTokens, window);
const compactFailed = liveUsage?.needsRollover === true;
const piByteRecoveryFailed = sessionRow.agentKind === 'pi' && isPiRequestBodyRecoveryExhausted(lastError);
- // 空闲间隔:伙伴对话隔了半天以上再开口,先换干净的原生会话,老话题不带偏新话题。
- // 本次要发的 user 已落库时它自己不算活动(见 measureIdleGap);同一条消息因发送失败
- // 重试时,上一次已按空闲间隔重建过就不再重建。
- let pendingUserIndexForGap = -1;
- for (let i = source.length - 1; i >= 0; i -= 1) {
- const message = source[i];
- if (message && message.role === 'user' && !isSyntheticUser(message)) {
- if (source.slice(i + 1).every((later) => later.role === 'error')) pendingUserIndexForGap = i;
- break;
- }
- }
- const idleGapMs = botChat ? measureIdleGap(source, pendingUserIndexForGap, Date.now()) : null;
- let idleGap = idleGapMs !== null && idleGapMs >= BOT_IDLE_GAP_REBUILD_MS;
- if (idleGap && pendingUserIndexForGap >= 0) {
- const previous = await deps.findLatestRebuildMeta(sessionId);
- if (
- previous?.reason === 'idle-gap' &&
- previous.sourceUserClientId === source[pendingUserIndexForGap]?.clientId
- ) {
- idleGap = false;
- }
- }
const tokenViolated =
isContextOverflowErrorData(lastError) ||
isPiPromptRpcTimeoutError(lastError) ||
pressure ||
compactFailed ||
- idleGap ||
(botChat && isCompanionCompactFailure(lastError));
const oversized = isOversizedHistoryErrorData(lastError);
- const historyHealth = (oversized || botChat) && sessionRow.agentKind === 'codex'
+ const historyHealth = oversized && sessionRow.agentKind === 'codex'
? await deps.classifyCodexHistory?.(sessionRow.sdkSessionId)
: undefined;
const action = decideCindyCompression({
@@ -1227,20 +1133,9 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
lastUserIndex = -1;
}
if (!lastUser) return false;
- const otherTrigger =
- isContextOverflowErrorData(lastError) ||
- isPiPromptRpcTimeoutError(lastError) ||
- pressure ||
- compactFailed ||
- (botChat && isCompanionCompactFailure(lastError)) ||
- piByteRecoveryFailed ||
- historyHealth === 'oversized' ||
- oversized;
const rebuildReason: ContextRebuildReason = isPiPromptRpcTimeoutError(lastError)
? 'pi-prompt-timeout'
- : idleGap && !otherTrigger
- ? 'idle-gap'
- : 'context-overflow';
+ : 'context-overflow';
// 待发出/失败的 user 还会由本次 send 或 Retry 再 wire 一次,交接里不能带。
// 已完成的最后一轮(后面有非 error)要留在交接里。
// lastUser 若不在 handoff 窗口里(index < 0),窗口全是其后的 tool/assistant,算已完成。
@@ -1261,17 +1156,10 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
fromLabel: label,
toLabel: label,
sessionId,
- reason:
- rebuildReason === 'idle-gap'
- ? 'idle-gap'
- : botChat || isOversizedHistoryErrorData(lastError)
- ? 'native-session-recovery'
- : rebuildReason,
- ...(rebuildReason === 'idle-gap' && idleGapMs !== null ? { idleGapMs } : {}),
+ reason: botChat || isOversizedHistoryErrorData(lastError) ? 'native-session-recovery' : rebuildReason,
includeToolResults: botChat || isOversizedHistoryErrorData(lastError),
companion: botChat,
...(await companionRecall(sessionId, botChat)),
- workingMemory: earlyWorkingMemory ?? (await readWorkingMemoryNote(sessionId)),
});
await deps.commitRebuild(sessionId, handoff, {
reason: rebuildReason,
@@ -1287,7 +1175,6 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
deps.log.info('unhealthy native session rebuilt before send; skip compact/resume', {
sessionId,
reason: rebuildReason,
- ...(rebuildReason === 'idle-gap' ? { idleGapMs } : {}),
sourceUserClientId: lastUser.clientId,
});
return true;
@@ -1336,7 +1223,6 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
includeToolResults: !target || isCanonicalBotContext(row),
companion: companionChat,
...(await companionRecall(sessionId, companionChat)),
- workingMemory: await readWorkingMemoryNote(sessionId),
});
// Durable handoff, SDK reset and complete target route succeed or fail together.
// No user turn or tool call is replayed by this control-plane operation.
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 18dae74717..1ba9481dd6 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -641,12 +641,8 @@ import {
type BotCompactRuntimeSession,
} from './botCompactRuntimeRefresh.js';
import {
- buildWorkingMemoryRefreshNote,
- createWorkingMemoryRefreshRegistry,
- isWorkingMemoryFreshForSession,
pruneWithdrawnWorkingMemoryForSession,
pruneWorkingMemoryForSession,
- readWorkingMemoryNoteForSession,
} from './botWorkingMemory.js';
import { listBotRecallSessionIds } from '../localDb/botHistoryScope.js';
import { createWireNoteMemory } from './wireNoteMemory.js';
@@ -3625,13 +3621,6 @@ type BotCompactRuntimeRefreshHandler = (
* and let the instance-scoped coordinator own all compact settle signals.
*/
let botCompactRuntimeRefreshHandler: BotCompactRuntimeRefreshHandler | null = null;
-/**
- * 伙伴工作记忆账本(botWorkingMemory):换窗交接带账本;原生压缩后下一次发送补一份。
- * 登记对所有会话生效,真正注入只在伙伴主对话且有账本时发生。
- */
-const workingMemoryRefresh = createWorkingMemoryRefreshRegistry();
-const readWorkingMemoryNote = (sessionId: string): Promise<string | null> =>
- readWorkingMemoryNoteForSession(sessionId, ownerScopedUserDataPath());
/**
* 逐轮环境说明(界面语言 / 客户端设备 / 个人版制作说明)的去重记忆:同一原生上下文里内容
* 没变就不重复前置。原生压缩边界、`/clear`、换窗重建后整体重发一次(见 wireNoteMemory.ts)。
@@ -5970,7 +5959,6 @@ const sessionEventDependencies: SessionEventDependencies = {
onUnsuccessfulProductTurn: interruptProductTurn,
deferUnsuccessfulProductTurn: (owner) => deferredProductTurnFailureGate.defer(owner),
get botCompactRuntimeRefreshCoordinator() { return botCompactRuntimeRefreshCoordinator; },
- get workingMemoryRefresh() { return workingMemoryRefresh; },
get wireNoteMemory() { return wireNoteMemory; },
get attemptBotCompactRuntimeRefresh() { return attemptBotCompactRuntimeRefresh; },
get botDelegationServiceHolder() { return botDelegationServiceHolder; },
@@ -10640,7 +10628,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
closeSession: (sessionId) => maker.closeSession(sessionId, 'agent-switch'),
listMessagesForHandoff: (sessionId, after) =>
listMessagesForAgentHandoff(sessionId, 400, after),
- readWorkingMemoryNote,
findParkedEngineSession: (sessionId, targetDbKind) =>
findParkedEngineSession(sessionId, targetDbKind),
applyAgentSwitchToDb: async (sessionId, patch) => {
@@ -10897,8 +10884,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
getMessage: getMessageDeletionTarget,
listMessagesForContext: (sessionId) => listMessagesForAgentHandoff(sessionId, 400),
- readWorkingMemoryNote: (sessionId, opts) =>
- readWorkingMemoryNoteForSession(sessionId, ownerScopedUserDataPath(), opts),
pruneWorkingMemory: (sessionId, deletedMessageIds) =>
pruneWorkingMemoryForSession(sessionId, ownerScopedUserDataPath(), deletedMessageIds),
getLiveSession: (sessionId) => maker.getSession(sessionId),
@@ -17487,15 +17472,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
readReplyQuoteNote,
// 私聊话题的 [话题说明]:按持久化的话题链接现读,不是话题时为 null。
readBotThreadNote: readBotDmThreadContextNote,
- // 原生压缩后的账本刷新:只对伙伴主对话且有账本的会话真正注入;读不到按无账本,
- // 标记仍由事务在 accepted 后按代次消费。
- peekWorkingMemoryRefresh: async (sessionId) => {
- const generation = workingMemoryRefresh.pendingGeneration(sessionId);
- if (generation === null) return null;
- const rendered = await readWorkingMemoryNote(sessionId);
- return { generation, note: rendered ? buildWorkingMemoryRefreshNote(rendered) : null };
- },
- consumeWorkingMemoryRefresh: (sessionId, generation) => workingMemoryRefresh.consume(sessionId, generation),
planRepeatableWireNotes: (sessionId, notes, opts) => wireNoteMemory.plan(sessionId, notes, opts),
applyPendingAgentSwitch: async (sessionId, options) => {
if (!options?.scheduled) await scheduledModelScope.restore(sessionId);
@@ -17730,8 +17706,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return resolveConfiguredContextWindow(catalog, makerAgentKind, providerId, modelId);
},
listMessages: (sessionId) => listMessagesForAgentHandoff(sessionId, 400),
- readWorkingMemoryNote,
- isWorkingMemoryFresh: (sessionId) => isWorkingMemoryFreshForSession(sessionId, ownerScopedUserDataPath()),
// 伙伴自有会话(当前 + 恢复前旧对话整体优先,后台任务补足),写进回忆指引限定 history 工具范围。
listCompanionSessionIds: (sessionId) => listBotRecallSessionIds(sessionId, COMPANION_SESSION_IDS_LIMIT),
findLatestUser: findLatestUserMessageForRebuild,
@@ -21319,8 +21293,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
agentHandoffPending.invalidate(sid);
// 清空后的原生上下文没看过任何环境说明:下一轮整体重发。
wireNoteMemory.reset(sid);
- // 清空前登记的压缩刷新标记同样作废:否则清空后的第一次发送会把清空前的账本注入。
- workingMemoryRefresh.reset(sid);
getAgentIslandService()?.notifyQueueEmptied(sid);
// 清上下文后,active 目标失去其依据(objective 引用的内容已被抹掉)→ 一并清除目标。
goalClearObserver?.(sid);
diff --git a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
index 69ac7c619c..169fa65f8d 100644
--- a/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
+++ b/apps/desktop/src/main/maker-ipc/sessionEventTerminal.ts
@@ -1,4 +1,3 @@
-import { reviewTeammateLearning } from './botLearningReview.js';
import { botLearningTracker } from './botLearningTracker.js';
import { learningTurnIdentity } from './botLearningFeedback.js';
import type { BotDelegationService } from './botDelegationService.js';
@@ -647,11 +646,6 @@ export function finishSessionTerminalEvent(
!deps.agentInputCoordinatorHolder?.isAutoResumePending(session.id) &&
!deps.agentInputCoordinatorHolder?.isAutoResumeDeferred(session.id)
) {
- if (turnBoundaryAssistantPersistId && !session.remoteHostId) {
- const replyId = turnBoundaryAssistantPersistId;
- void reviewTeammateLearning(session.id, replyId).catch(() =>
- deps.log.warn('Teammate learning review did not complete'));
- }
const callback = deps.onSuccessfulProductTurn;
if (callback && terminalOwner) {
void callback(session.id, terminalOwner).catch(() =>
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 14cdebd478..092d0abd1e 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -189,31 +189,22 @@ Discord 传输层只放行主人,钉钉群里被 @ 时成员也能触发(成
主任务不能被普通创建入口覆盖。
- 旧版本遗留的 history Session 继续可回看、搜索,不做破坏性迁移。
-### 3.2 模型上下文自管理:一条规则,主对话与 IM 专线同用
-
-伙伴的对话——主任务(桌面与主人私聊都落在这里)、IM 群/话题/外部私聊专线、伙伴群聊专线——
-共用**同一个**发送前上下文体检(`contextOverflowRollover.prepareUnhealthySession`,判据
-`isBotChatContext`:`source='bot'` 且角色为 canonical/channel/group)。桌面直发、官方 hook 与个人
-IM 轮次都从这个入口进(`im/shared/turnRunner` 在伙伴守卫之后、拿发送锁之前调用),不允许为 IM
-单独再造一套换窗或换任务机制;委派与历史任务不是对话,不进这条规则。体检触发的几种情况:
-
-- **空闲间隔刷新**:上一次活动(最近一条已记录消息;本次要发的消息若已提前落库,不算活动)距本次
- 发送 ≥ 12 小时(`BOT_IDLE_GAP_REBUILD_MS`),先换一个干净的原生会话再发。目的只有一个:隔了半天
- 再开口,老话题不能占着模型工作上下文把新话题带偏。交接按 `idle-gap` 口径写明「空闲了约 N 小时/
- 天,没有出错,完整记录仍在同一条任务里,把新消息当成当前话题,用户不提就不接旧线索,需要细节用
- 历史工具」;同一条消息因发送失败重试时不重复刷新。它仍是同一条任务:时间线、记忆、文件、专线
- 绑定都不变,界面上只多一条「隔了一段时间再聊,已整理上下文后继续」的分隔卡。
-- **容量到线(Claude Code/Pi)**:已知 token 占用达到窗口的 90%(工作记忆
-账本已覆盖最近一条完成回复、且账本段能渲染出来并原样带进交接时提前到 70%:宿主换窗不调用
-模型,能替掉一次把整窗送去总结的原生压缩;账本不新鲜或渲染不出来则维持 90%,不提前换窗),
-先用已有持久交接重建模型工作上下文。Codex 的 token 压力和同引擎缩窗交给原生压缩,
-仅本地历史确认存在超大内联图片或发生下述明确失败时才用容量兜底。
-- **已知坏历史**:已持久记录的压缩空摘要/invalid-request 失败、上下文溢出、Pi 无响应,也在下一次
- 发送时由宿主重建;普通网络、鉴权、额度错误不据此换窗。
-
-交接保存近期需求、回复、改动和有界工具结果(伙伴对话一律带工具结果,专线与主对话相同),省略图片
-正文;不额外调用模型生成摘要,不等待旧 Harness 压缩成功。原生压缩仍在单轮内部正常工作,健康对话
-不换窗。工作记忆账本与「按需回忆」的自有会话清单只有主对话能解析出内容,专线读不到就按无,不挡换窗。
+### 3.2 上下文沿用 Session 原生压缩(2026-10-23)
+
+伙伴的主任务、私聊话题、IM 群/外部私聊专线和伙伴群聊专线,均长期复用各自的同一条 Session。
+健康上下文交给 Session / Harness 已有压缩机制,不因伙伴身份另外添加上下文维护自动化:
+
+- 不按空闲时长(包括隔夜 12 小时)、打开次数或 70% / 90% 占用提前重建原生会话。
+- 不根据工作记忆新鲜度替代原生压缩,不主动扫描健康 Codex 历史来提前换窗。
+- 不在后台唤醒、自动续跑或人工输入时执行伙伴专属整理,因此不产生日常整理提示卡。
+- 不在回复后调用辅助模型复盘学习、维护短期工作记忆账本,压缩后也不重新注入旧账本。
+- 用户明确建立的例行任务、后台任务与其结果回传、手动记忆 / Skill 工具、既有长期记忆及文件不受影响。
+
+发送前 `contextOverflowRollover.prepareUnhealthySession` 只保留故障恢复边界:普通 Session 共用的
+真实满窗保护、上下文溢出、明确压缩失败、Pi 无响应或已确认的损坏历史。Codex 的 token 压力
+继续交给原生压缩;普通网络、鉴权、额度错误不据此换窗。恢复保留同一产品任务和完整聊天记录。
+历史故障交接仍保存近期需求、回复、改动和有界工具结果,省略图片正文;仅故障恢复使用交接,
+不能把这个兜底路径重新当成伙伴的日常压缩。
Codex 图片历史在运行中确定失败时,伙伴主对话与普通桌面任务共用一次隐藏续接:
保留原请求与已记录进展,不重放原请求或已完成工具;结果不明先核实。每条输入最多自动
@@ -224,27 +215,8 @@ tool 副作用时自动重放。原生后台工作尚未结束时不自动关闭
自动恢复无法完成时保留错误与既有继续/重试入口;「重启伙伴」无需旧模型参与,保留
同一条时间线、记忆与文件,并携带工具结果重新建立上下文。重启不自动重放请求。
-宿主另为伙伴主对话维护一份**工作记忆账本**(Bot Home 下的 `working-memory.json`):进行中线索、
-伙伴答应过的事、在等谁、用户最新纠正与决定、近期完成,每条带来源消息位置。账本由回复后的
-学习复盘顺手更新,不新增模型调用;复盘取材从账本上次覆盖到的位置接上,某轮复盘失败漏掉的内容
-由后续复盘按序分批补进账本(每批有界),覆盖水位只推进到连续补完的位置;本轮取材本身被截断时
-同样不推进水位,补完之前账本不算新鲜,且这样的轮次里以水位之后那一轮为证据的删改延后、只追加(等那
-一轮被完整回补再提交,免得随后 rewind 时无法回滚),追加的条目按临时条目记账、不占正式容量(超容量先
-裁临时条目,跨多次复盘都不会把正式条目挤出去),水位推进到当前回复时转正;回补前缀内有证据的删改照常
-提交(它们不会再被回放第二次);新鲜度要求覆盖到最近一条完成回复或更晚的带内容交互答复(至少一条非空
-白答案的提问卡、带计划的批准/带反馈的打回),取消或答案全空白的交互不抬水位;超过单条上限的用户/伙伴消息按块分多次复盘,相邻块留重叠,水位可停在
-消息中间,整条看完才算覆盖(工具结果不是新条目的证据来源,仍只取开头);换窗交接里账本段与检索
-指引同属硬截断时必须整段保住的尾部;用户在提问卡、计划审阅
-里给出的答复与反馈按用户消息进入复盘取材,可作为账本证据;水位以消息的 client_id
-为持久判据(rowid 在数据库瘦身后可能重排),老对话第一次建账本从对话开头(清空边界之后)分批
-补起,不跳过任何一轮;
-新条目必须有本轮用户或伙伴原话证据,
-漏写的旧条目保留,删除同样要证据。上述所有换窗交接(重启、换引擎、缩窗、容量到线、删消息重建)都带上账本;原生自动
-压缩之后的下一次发送再补一次,交接首条已带时不重复。账本是摘要,不是授权:历史授权不是新的
-执行许可;后台任务状态从任务记录现读,不信账本文本。来源消息离开可见时间线(删除、rewind/
-编辑上一条、`/clear` 边界之前)时对应条目同步失效:渲染前统一过滤,提交后持久清掉,清空还作废
-清空前登记的压缩刷新标记。不是伙伴主对话、没有账本或读取失败时一律按无,不能挡住换窗。实现见
-`botWorkingMemory.ts`,回归见 `botWorkingMemory.test.ts`。
+旧版 `working-memory.json` 保留,不迁移或删除用户历史,但不再自动生成、刷新或注入模型上下文。
+删除消息、撤回和清空对旧账本的失效清理仍保留,避免历史隐私内容在兼容工具里复现。
完整聊天记录与模型工作上下文必须分离:压缩可以丢弃模型不再需要的旧 tool result 和中间过程,
但用户时间线、搜索索引和审计记录仍按既有持久化策略保留。完整消息继续写入 SQLite,界面与
@@ -309,7 +281,7 @@ Cindy 应用,也不取消伙伴已委派的独立任务。操作中禁用重
│ ├── USER.md 该 Bot 认识的用户
│ ├── MEMORY.md 该 Bot 的记忆索引
│ └── *.md 该 Bot 的长期记忆
-├── working-memory.json 宿主维护的工作记忆账本(见 3.2),用户不直接编辑
+├── working-memory.json 旧版工作记忆账本(见 3.2),不再自动维护或注入
└── skills/<slug>/SKILL.md 该 Bot 自有或后学的 Skill
```
@@ -479,15 +451,7 @@ Mobile 使用电脑端已连接的模型目录;目录为空时保持创建禁
第一次出现就记;每次纠正做法、指定可复用格式或完成有价值的任务后,主动整理格式与已验证的做法,形成或改进
个性化 Skill。一次已经验证且明显可复用的成功也可立即沉淀,不设轮次数或 Skill 数量配额。
写入前去重,写入后可见、可编辑、可删除;尊重记忆开关和不保存要求,不记流水账或臆造流程。
- 学习同时覆盖当场主动保存与回复后的宿主后台复盘。复盘复用已配置辅助模型,不创建可见任务、
- 不派协同 worker、不延迟回复;同伙伴串行,成功回复只触发一次。引用本次交流与最新记忆/技能快照,
- 无新经验则不写;记忆关闭时不提取记忆,并尊重不保存要求。更新只覆盖复盘读到的版本,冲突让新版本胜出。
- 回复后复盘同样覆盖私聊话题与 IM 专线。IM 专线只复盘持久消息来源确认由主人触发的回复,
- 只把主人原话作为偏好与技能的用户证据,不把群友发言、引用背景或缺失身份的旧记录当成主人要求。
- 后台保存 Skill 复核该回复对应的持久来源,不借用已经结束或下一轮的渠道租约。
- 话题学习写入同一伙伴的长期记忆与自有 Skill;主任务的短期工作账本及其覆盖水位仍只由主任务维护。
- 话题在自己的回复元数据中保存独立补读位置,长消息及超预算轮次在后续复盘按块补齐;
- 位置随任务、撤回和清空边界读取,不跨话题复用,也不把启用前的整段旧历史自动补入。
+ 学习仅在当前交互内使用现有工具,不在成功回复后另起宿主辅助模型复盘,也不补读整段历史建账本。
真实保存回执持久附在来源伙伴发言气泡底部:脑子和书本两行分别表示记忆与技能,禁止放在任何
发言气泡上方、独立插入时间线、标注“上一轮”或新建成功详情 UI。提前写入等待对应回复,
迟到写入只补原回复。桌面点击分别打开现有伙伴设置的记忆页和能力页;手机复用伙伴设置面板。