Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): learn from owner IM topics and refresh shared resources
Chrisd41917fffa1c
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.tsindex ef56cc5b92..27a54ad9d4 100644--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerSendOutcome.test.ts@@ -194,6 +194,7 @@ vi.mock('../fbotTitle', () => ({}));import { getActiveInteractionRoute } from '../../../maker-ipc/interactionRouter';+import { readChannelToolScope, type ChannelToolScope } from '../channelToolScope';import { createTurnRunner, type ImRunAgentTurnArgs, type ImTurnRunner } from '../turnRunner';import {readGroupHistoryAccess,@@ -451,6 +452,7 @@ interface TurnOverrides {onRouteResolved?: (sessionId: string) => void | Promise<void>;protectedContent?: boolean;groupHistoryAccess?: GroupHistoryAccessScope;+ channelToolScope?: ChannelToolScope;prePersistedUserMessage?: { sessionId: string; clientId: string };onEarlyReject?: (reason: string, text: string) => Promise<boolean> | boolean;attachments?: ImRunAgentTurnArgs['attachments'];@@ -478,6 +480,7 @@ async function startDefaultTurn(onTurnComplete = vi.fn(), overrides: TurnOverrid...(overrides.onRouteResolved ? { onRouteResolved: overrides.onRouteResolved } : {}),...(overrides.protectedContent === true ? { protectedContent: true } : {}),...(overrides.groupHistoryAccess ? { groupHistoryAccess: overrides.groupHistoryAccess } : {}),+ ...(overrides.channelToolScope ? { channelToolScope: overrides.channelToolScope } : {}),...(overrides.prePersistedUserMessage? { prePersistedUserMessage: overrides.prePersistedUserMessage }: {}),@@ -673,15 +676,30 @@ describe('turnRunner send outcome policy (feishu adapter characterization)', ()it('anchors direct IM capture to the durable accepted user message', async () => {mocks.persistUserMessage.mockResolvedValue({ clientId: 'im-anchor-client' });const h = setupSession(async () => ({ accepted: true }));+ const scope: ChannelToolScope = {+ channel: 'discord', botId: 'bot', laneUserId: 'lane', chatId: 'chat',+ chatKind: 'group', requesterIsOwner: true, companion: true,+ inputClientId: 'stale-input',+ };+ mocks.persistUserMessage.mockImplementationOnce(async () => {+ // Before persistence, a reused scope must not attribute this turn to the old input.+ expect(readChannelToolScope({ sessionId: h.session.id, sessionInstanceId: h.session.instanceId })?.inputClientId).toBeUndefined();+ return { clientId: 'im-anchor-client' };+ });- await runDefaultTurn();+ await runDefaultTurn(vi.fn(), { channelToolScope: scope });expect(mocks.beginTurnChangeSetAtDispatch).toHaveBeenCalledWith(h.session, 'im-anchor-client');+ expect(readChannelToolScope({ sessionId: h.session.id, sessionInstanceId: h.session.instanceId })?.inputClientId).toBe('im-anchor-client');+ expect(readChannelToolScope({ sessionId: h.session.id, sessionInstanceId: 'stale-instance' })).toBeNull();expect(mocks.persistUserMessage).toHaveBeenCalledWith(expect.objectContaining({source: expect.objectContaining({ im: 'feishu', contextSnapshot: {} }),}),);+ h.emit({ type: 'done', data: {} });+ await flushMicrotasks();+ expect(readChannelToolScope({ sessionId: h.session.id, sessionInstanceId: h.session.instanceId })).toBeNull();});it('uses the adapter service identity for both early persistence and accepted enrichment', async () => {diff --git a/apps/desktop/src/main/im/shared/channelToolScope.ts b/apps/desktop/src/main/im/shared/channelToolScope.tsindex e460faa2f0..7941ce6a1e 100644--- a/apps/desktop/src/main/im/shared/channelToolScope.ts+++ b/apps/desktop/src/main/im/shared/channelToolScope.ts@@ -108,7 +108,10 @@ export function isLaneTurnScopeChannel(channel: string): channel is LaneTurnScopreturn channel === 'wecom' || channel === 'dingtalk' || channel === 'discord' || channel === 'wechat' || channel === 'x';}-export type ChannelToolScope = TelegramToolScope | FeishuToolScope | LaneTurnScope;+export type ChannelToolScope = (TelegramToolScope | FeishuToolScope | LaneTurnScope) & {+ /** Local durable input, stamped by the IM runner after persistence succeeds. */+ inputClientId?: string;+};interface ActiveScope {sessionInstanceId: string;diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.tsindex cdd726a442..95c2e6da50 100644--- a/apps/desktop/src/main/im/shared/turnRunner.ts+++ b/apps/desktop/src/main/im/shared/turnRunner.ts@@ -1684,6 +1684,8 @@ export function createTurnRunner(});}if (item.channelToolScope) {+ // A retried dispatch must not reuse an earlier input receipt.+ delete item.channelToolScope.inputClientId;item.turn.channelToolScopeRelease = beginChannelToolScope({sessionId: rowId,sessionInstanceId: state.makerSession.instanceId,@@ -1793,6 +1795,7 @@ export function createTurnRunner(});if (persisted) {item.prePersistedUserMessage = { sessionId: rowId, clientId: persisted.clientId };+ if (item.channelToolScope) item.channelToolScope.inputClientId = persisted.clientId;await beginTurnChangeSetAtDispatch(state.makerSession, persisted.clientId);turnChangeSetStarted = true;}diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 8f977380ba..f5fab88062 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -2244,6 +2244,38 @@ describe('Bot canonical Session lifecycle', () => {});});+ // DB regression: shared learning used to leave running chats with the old+ // memory/Skill index. Exercise hydrate + persisted applied snapshots, not hash+ // implementation details; the minimal mutation keeps Profile and paths fixed.+ it.each(['canonical', 'channel', 'thread'])('refreshes shared learned resources in a running %s chat', async role => {+ const created = await invoke('local-db:bots:create-canonical-session', {+ botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ });+ h.sqlite!.prepare('UPDATE bot_session_links SET role=? WHERE session_id=?').run(role, created.session.id);+ const makeOpts = (): MakerSessionCreateOpts => ({+ id: created.session.id, agentKind: 'codex', workingDir: created.session.workingDir,+ workspaceKind: 'dialogue', model: 'gpt-5', permissionMode: 'bypassPermissions',+ });+ let index = '# Memory\n';+ let updatedAt = 'v1';+ const deps = {+ readMemoryIndex: async () => index,+ listOwnSkills: async () => ({ pluginRoot: '/skills', skills: [{+ name: 'report', description: 'A verified report format', path: '/skills/report', updatedAt,+ }] }),+ };+ const initial = await hydrateBotProfileRuntime(makeOpts(), deps);+ await markBotProfileRuntimeApplied(initial!);+ expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(false);+ index += '- [Conclusion first](feedback_conclusion.md)\n';+ const changed = await hydrateBotProfileRuntime(makeOpts(), deps);+ expect(changed?.runtimeEpochChanged).toBe(true);+ await markBotProfileRuntimeApplied(changed!);+ expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(false);+ updatedAt = 'v2';+ expect((await hydrateBotProfileRuntime(makeOpts(), deps))?.runtimeEpochChanged).toBe(true);+ });+it('refreshes canonical Skill resources in place when their fingerprint changes', async () => {await invoke('local-db:bots:update', {id: 'bot-1',diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.tsindex cea4c4e1d4..8321885217 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLearningReview.test.ts@@ -4,6 +4,8 @@ const h = vi.hoisted(() => ({owner: 'owner',enabled: true,visible: true,+ role: 'canonical',+ inputMeta: null as string | null,meta: { turnCompleted: true } as Record<string, unknown>,model: vi.fn(),write: vi.fn(),@@ -39,6 +41,9 @@ vi.mock('../../localDb/client/current.js', () => {: h.visible? {botId: 'bot',+ role: h.role,+ canonicalSessionId: 'main',+ inputMeta: h.inputMeta,capabilities: JSON.stringify({ memory: h.enabled }),// 当前回复:上一条完成回复 + 2(中间隔一条用户消息);默认 5。rowid: (h.prevCompleted ?? 0) + 2,@@ -109,6 +114,12 @@ beforeEach(() => {h.owner = 'owner';h.enabled = true;h.visible = true;+ h.role = 'canonical';+ h.inputMeta = null;+ h.prevCompleted = 3;+ h.turnRows = null;+ h.gapRows = [];+ h.floorRowid = null;h.meta = { turnCompleted: true };h.memories = [];h.skills = [];@@ -120,6 +131,58 @@ beforeEach(() => {text: JSON.stringify({ memories: [proposal], skills: [] }),});});++// Unit regression: the real review entry used to omit channel/thread replies.+// Existing cases only exercised canonical text; verify retained owner provenance,+// post-turn Skill authorization and the separate canonical working-memory cursor.+it.each(['channel', 'thread'])('learns from an owner %s reply without changing the canonical ledger', async role => {+ h.role = role;+ h.inputMeta = JSON.stringify({ imSource: { origin: { sender: { isOwner: true } } } });+ h.turnRows = [+ { id: 'user', role: 'user', content: 'Please always summarize the conclusion first.', order: 4, meta: h.inputMeta },+ // Real agent replies persist as plain text; parsing them as JSON aborts learning.+ { id: 'reply', role: 'assistant', content: 'Understood.', order: 5 },+ { id: 'guest', role: 'user', content: JSON.stringify('The owner prefers a totally different format.'), order: 3,+ meta: JSON.stringify({ imSource: { origin: { sender: { isOwner: false } } } }) },+ ];+ const skill = { slug: 'conclusion-first', ...proposal };+ h.model.mockResolvedValueOnce({ ok: true, text: JSON.stringify({ memories: [proposal], skills: [skill] }) });+ h.saveSkill.mockImplementationOnce(async (_params, deps) => {+ if (role === 'channel') expect(await deps.resolveBotId()).toEqual({ ok: true, botId: 'bot', canonicalSessionId: 'main' });+ return { ok: true, created: true, skill: { slug: skill.slug, name: skill.title } };+ });+ await reviewTeammateLearning('session', 'reply');+ expect(h.write).toHaveBeenCalledOnce();+ expect(h.saveSkill).toHaveBeenCalledOnce();+ expect(h.writeWorking).not.toHaveBeenCalled();+ expect(h.refresh).toHaveBeenCalledWith('main', 'resource');+ expect(h.publish).toHaveBeenCalledWith('reply', [expect.objectContaining({ kind: 'skill' })]);+ if (role === 'channel') {+ expect(JSON.parse(h.model.mock.calls[0][1]).messages.map((m: { id: string }) => m.id)).toEqual(['user', 'reply']);+ }+});++it.each([false, undefined])('does not learn from a channel reply without verified owner identity (%s)', async isOwner => {+ h.role = 'channel';+ h.inputMeta = JSON.stringify({ imSource: { origin: { sender: { isOwner } } } });+ await reviewTeammateLearning('session', 'reply');+ expect(h.model).not.toHaveBeenCalled();+ expect(h.write).not.toHaveBeenCalled();+ expect(h.saveSkill).not.toHaveBeenCalled();+});++it('rechecks the durable channel source after the model returns', async () => {+ h.role = 'channel';+ h.inputMeta = JSON.stringify({ imSource: { origin: { sender: { isOwner: true } } } });+ h.turnRows = [{ id: 'user', role: 'user', content: JSON.stringify('Please always summarize the conclusion first.'), order: 4, meta: h.inputMeta }];+ h.model.mockImplementationOnce(async () => {+ h.inputMeta = null;+ return { ok: true, text: JSON.stringify({ memories: [proposal], skills: [{ slug: 'format', ...proposal }] }) };+ });+ await reviewTeammateLearning('session', 'reply');+ expect(h.write).not.toHaveBeenCalled();+ expect(h.saveSkill).not.toHaveBeenCalled();+});it('applies evidence-backed missing learning and publishes only to the frozen reply ID', async () => {await reviewTeammateLearning('session', 'original-reply');expect(h.write).toHaveBeenCalledWith(@@ -210,6 +273,7 @@ it('updates an existing Skill using its snapshot version and ignores disabled Skawait reviewTeammateLearning('session', 'reply');expect(h.saveSkill).toHaveBeenCalledWith(expect.objectContaining({ slug: skill.slug, expectedUpdatedAt: 'v1' }),+ undefined,);expect(h.publish).toHaveBeenCalledWith('reply', [expect.objectContaining({ kind: 'skill', action: 'updated' }),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.tsindex 417c8f9d13..c2249a34dc 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillRuntimeProjection.test.ts@@ -221,8 +221,12 @@ describe('complete personal Skills with bounded startup projection', () => {await seedBotSkillIfMissing(userDataDir, botId, input);const collect = () => collectBotOwnSkillMounts(botId, deps());expect((await collect()).skills[0].description).toBe('Original');- await saveBotSkill(userDataDir, botId, { ...input, description: 'Saved update' });- expect((await collect()).skills[0].description).toBe('Saved update');+ const saved = await saveBotSkill(userDataDir, botId, { ...input, description: 'Saved update' });+ expect((await collect()).skills[0]).toMatchObject({ description: 'Saved update', updatedAt: saved.record.updatedAt });+ // Runtime epochs need the persisted revision even for body-only edits at+ // the same path; the old projection discarded it and sibling chats stayed stale.+ const bodyEdit = await saveBotSkill(userDataDir, botId, { ...input, description: 'Saved update', body: 'Revised steps' });+ expect((await collect()).skills[0].updatedAt).toBe(bodyEdit.record.updatedAt);await importBotSkillFiles(userDataDir, botId, 'imported', [{ name: 'SKILL.md',bytes: Buffer.from('---\nname: imported\ndescription: Imported\n---\nSteps'), executable: false }], () => {});expect((await collect()).skills.map(item => item.name)).toEqual(['imported', 'report']);diff --git a/apps/desktop/src/main/maker-ipc/botLearningReview.ts b/apps/desktop/src/main/maker-ipc/botLearningReview.tsindex 4f02544ebc..bfdc1b97b8 100644--- a/apps/desktop/src/main/maker-ipc/botLearningReview.ts+++ b/apps/desktop/src/main/maker-ipc/botLearningReview.ts@@ -80,19 +80,32 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)!isAppSessionBoundaryPending() && activeOwnerScopeKey() === owner && getDbClient() === db;await drainPersistQueue();if (!current()) return;- const readOwner = () =>- db.queryOne<{ botId: string; capabilities: string; rowid: number; meta: string }>(+ const readOwner = async () => {+ const candidate = await db.queryOne<{+ botId: string; role: string; canonicalSessionId: string | null;+ capabilities: string; rowid: number; meta: string; inputMeta: string | null;+ }>(`- SELECT b.bot_id AS botId, v.capabilities_json AS capabilities, m.rowid, m.agent_meta AS meta+ SELECT b.bot_id AS botId, b.role, p.canonical_session_id AS canonicalSessionId,+ v.capabilities_json AS capabilities, m.rowid, m.agent_meta AS meta,+ (SELECT u.agent_meta FROM messages u WHERE u.session_id=m.session_id+ AND u.client_id=json_extract(m.agent_meta, '$.replyToClientId') AND u.role='user'+ AND u.rewind_at IS NULL AND (s.cleared_at IS NULL OR u.created_at > s.cleared_at)) AS inputMetaFROM messages m JOIN sessions s ON s.id=m.session_idJOIN bot_session_links b ON b.session_id=s.id JOIN bot_profiles p ON p.id=b.bot_idJOIN bot_profile_versions v ON v.bot_id=p.id AND v.version=p.current_versionWHERE m.session_id=? AND m.client_id=? AND m.role='assistant' AND m.rewind_at IS NULL- AND b.role='canonical' AND b.archived_at IS NULL AND p.status='active' AND s.source='bot' AND s.status='active'+ AND b.role IN ('canonical','thread','channel') AND b.archived_at IS NULL AND p.status='active' AND s.source='bot' AND s.status='active'AND s.remote_host_id IS NULL AND (s.cleared_at IS NULL OR m.created_at > s.cleared_at)`,[sessionId, replyId],);+ // The live IM lease is already released when this asynchronous review runs.+ // Only the host-stamped input of this exact reply can authorize lane learning.+ if (candidate?.role === 'channel'+ && JSON.parse(candidate.inputMeta || '{}').imSource?.origin?.sender?.isOwner !== true) return null;+ return candidate;+ };const row = await readOwner();if (!current() || !row) return;const meta = JSON.parse(row.meta || '{}');@@ -121,16 +134,31 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)if (!current() || !(await readOwner())) return;const root = ownerScopedUserDataPath();// 工作记忆账本随同一次复盘维护(不另起模型调用);读不到按空账本,写入 CAS 失败放弃本轮。- const workingBefore = await readBotWorkingMemory(root, row.botId);- type Record_ = { id: string; role: string; content: string; order: number };+ // The existing ledger/watermark belongs to the canonical timeline. Topic+ // learning shares durable memory, never overwrites that timeline's cursor.+ const maintainsWorkingMemory = row.role === 'canonical';+ const workingBefore = maintainsWorkingMemory ? await readBotWorkingMemory(root, row.botId) : null;+ type Record_ = { id: string; role: string; content: string; order: number; meta?: string };// 单条正文按 MESSAGE_CHUNK_CHARS 分块。用户 / 伙伴的消息被截尾即 partial——它们是账本新条目// 的证据来源,纠正 / 承诺可能就在长消息的尾部,没看完不能算覆盖;工具结果不是新条目的来源,// 截尾只影响 resolved 证据(条目多留一阵),按已覆盖处理,不为它逐块回补。const toSnapshot = (m: Record_, offset = 0) => {- const parsed: unknown = JSON.parse(m.content);+ // Message storage accepts both plain text and serialized structured content.+ let parsed: unknown = m.content;+ try { parsed = JSON.parse(m.content); } catch { /* Plain text is already the snapshot. */ }+ const source = JSON.parse(m.meta || '{}').imSource;// 交互答复行的正文是用户的决定,归一成文本后按用户消息对待(证据规则同用户消息)。const interaction = INTERACTION_ROLES.has(m.role);- const full: string = interaction ? interactionText(parsed) : typeof parsed === 'string' ? parsed : m.content;+ let full: string = interaction ? interactionText(parsed) : typeof parsed === 'string' ? parsed : m.content;+ if (row.role === 'channel') {+ // Interaction rows have no durable sender attribution. Quoted/group+ // context is not the owner's own statement, even in an owner turn.+ if (interaction || (m.role === 'user' && source?.origin?.sender?.isOwner !== true)) full = '';+ else if (m.role === 'user') {+ const text = typeof parsed === 'string' ? parsed : (parsed as { text?: unknown } | null)?.text;+ full = typeof source.userText === 'string' ? source.userText : typeof text === 'string' ? text : '';+ }+ }const role = interaction ? 'user' : m.role;return {id: m.id,@@ -155,7 +183,7 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)// 本轮取材:上一条完成回复之后到当前回复。const records = await db.query<Record_>(`- SELECT client_id AS id, role, content, rowid AS 'order' FROM messages+ SELECT client_id AS id, role, content, agent_meta AS meta, rowid AS 'order' FROM messagesWHERE session_id=? AND rewind_at IS NULL AND rowid <= ? AND rowid > ? ${clearedAtFilter}AND ${REVIEW_ROLES} ORDER BY CASE WHEN role='user' THEN 0 ELSE 1 END, rowid DESC LIMIT ${TURN_REVIEW_ROWS}`,@@ -200,12 +228,12 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)let gapMessages: ReturnType<typeof toSnapshot>[] = [];// 水位停在半条消息里时,哪怕那条消息就是上一条完成回复(后面的轮次被 rewind 掉了),// 剩下的部分也得接着补,所以带偏移时取等号。- if (floor.rowid < prevCompleted || (floor.offset !== undefined && floor.rowid === prevCompleted)) {+ if (maintainsWorkingMemory && (floor.rowid < prevCompleted || (floor.offset !== undefined && 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+ SELECT client_id AS id, role, content, agent_meta AS meta, rowid AS 'order' FROM messagesWHERE session_id=? AND rewind_at IS NULL AND rowid > ? AND rowid <= ? ${clearedAtFilter}AND ${REVIEW_ROLES} ORDER BY rowid ASC LIMIT ?`,@@ -315,7 +343,7 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)// 每次校验通过的复盘都写回水位:模型按指令在"本轮没改动"时省略 working,但这一轮同样// 已被复盘过,水位必须跟上,否则一句问候就让账本被判不新鲜、70% 换窗悄悄退回 90%。// 没有提案时按空提案合并——旧条目原样保留,只推进水位(和 client_id)。- if (await readOwner()) {+ if (maintainsWorkingMemory && await readOwner()) {try {await writeBotWorkingMemory(root,@@ -382,7 +410,16 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)description: proposal.description,body: proposal.body,expectedUpdatedAt: prior?.updatedAt ?? null,- });+ }, row.role === 'channel' ? {+ // Internal review authority is tied to the durable reply/input, not a+ // model argument or whichever IM lease happens to be active now.+ resolveBotId: async () => {+ const latest = current() ? await readOwner() : null;+ return latest && current() && latest.botId === row.botId+ ? { ok: true, botId: latest.botId, canonicalSessionId: latest.canonicalSessionId }+ : { ok: false, errorCode: 'BOT_SESSION_INACTIVE', message: 'Learning source is no longer active' };+ },+ } : undefined);if (saved.ok && current())publish(replyId, [{@@ -393,7 +430,12 @@ export async function reviewTeammateLearning(sessionId: string, replyId: string)},]);}- if (memorySaved && current()) await requestBotRuntimeEpochRefresh(sessionId, 'resource');+ if (memorySaved && current()) {+ for (const id of new Set([sessionId, row.canonicalSessionId].filter((id): id is string => !!id))) {+ if (!current()) return;+ await requestBotRuntimeEpochRefresh(id, 'resource');+ }+ }});running.set(key, job);try {diff --git a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts b/apps/desktop/src/main/maker-ipc/botProfileRuntime.tsindex 3147a30dc8..ffde6d4205 100644--- a/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts+++ b/apps/desktop/src/main/maker-ipc/botProfileRuntime.ts@@ -138,7 +138,7 @@ export interface BotProfileRuntimeDeps {listOwnSkills?: (input: { botId: string }) => Promise<{pluginRoot: string;baseline?: { pluginRoot: string; skill: { name: string; description: string; path: string; filePath: string } };- skills: { name: string; description: string; path: string; filePath?: string }[];+ skills: { name: string; description: string; path: string; filePath?: string; updatedAt?: string }[];}>;readSkillSource?: (input: {path: string;@@ -717,7 +717,7 @@ export async function hydrateBotProfileRuntime(伙伴在任务里刚学会一个技能,紧接着要能续跑同一个任务;把自己写的文件也冻上,等于「一学会就再也 resume 不了」。*/- let ownSkills: { name: string; description: string; path: string; filePath?: string }[] = [];+ let ownSkills: { name: string; description: string; path: string; filePath?: string; updatedAt?: string }[] = [];let ownSkillPluginRoots: string[] = [];// SSH remote 会话的 harness 跑在远端文件系统上,本机 userData 里的技能目录// 在那边不存在 —— 与其挂一串打不开的路径,不如这类会话直接不挂。@@ -1046,12 +1046,17 @@ export async function hydrateBotProfileRuntime(profilePrompt: opts.botProfilePrompt ?? '',contextPrompt: opts.botProfileContextPrompt ?? '',userProfilePrompt: opts.botUserProfilePrompt ?? '',+ // All live chats compare this epoch before their next input. Shared learning+ // must invalidate their frozen indexes even when the Profile did not change.+ memoryIndex: opts.makerMemoryIndexSnapshot ?? '',skillResources: resolvedSkillEntries.map((entry) => ({name: entry.runtimeCommandName?.trim() || entry.name.trim(),path: entry.path?.trim() || null,sha256: entry.contentSha256 ?? null,})),- botOwnSkillResources: ownSkills.map((entry) => ({ name: entry.name, path: entry.path })),+ botOwnSkillResources: ownSkills.map((entry) => ({+ name: entry.name, path: entry.path, description: entry.description, updatedAt: entry.updatedAt ?? null,+ })),mcpResources: resolvedMcpServers.map((name) => {const entry = mcpCatalog.find((item) => item.name === name);return { name, generation: entry?.generation ?? null };diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.tsindex 9dd2c2c238..c8ec061158 100644--- a/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeCache.ts@@ -4,7 +4,7 @@ import path from 'node:path';type Projection = {pluginRoot: string;artifacts?: string[];- skills: { name: string; description: string; path: string; filePath: string }[];+ skills: { name: string; description: string; path: string; filePath: string; updatedAt?: string }[];};type Entry = {revision: number;diff --git a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.tsindex 4d97728f93..0bb55b09a9 100644--- a/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillRuntimeProjection.ts@@ -79,7 +79,7 @@ export async function projectBotSkillMounts(root: string, skills: Iterable<BotSkpluginRoot: root,// Only the byte-bounded native prefix is sorted/retained in memory.skills: small.sort((a, b) => a.name.localeCompare(b.name)).map(item => ({- name: item.name, description: item.description, path: item.dirPath, filePath: item.filePath,+ name: item.name, description: item.description, path: item.dirPath, filePath: item.filePath, updatedAt: item.updatedAt,})),};diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.tsindex 09faa51c93..4ac167e08c 100644--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts@@ -375,7 +375,7 @@ export async function collectBotOwnSkillMounts(): Promise<{pluginRoot: string;baseline: Awaited<ReturnType<typeof collectTeammateGuideMount>>;- skills: { name: string; description: string; path: string; filePath: string }[];+ skills: { name: string; description: string; path: string; filePath: string; updatedAt?: string }[];}> {const boundary = captureOwnerBoundary(deps);const userDataDir = await skillHomeOf(deps, botId, boundary);diff --git a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.tsindex de2203c6b8..2367778045 100644--- a/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts+++ b/apps/desktop/src/main/maker-ipc/sessionEventPreparation.ts@@ -1,4 +1,5 @@import { taskResultClientIdForInput } from '../../shared/botCollaboration.js';+import { readChannelToolScope } from '../im/shared/channelToolScope.js';import { isQuietScheduledOutput } from '../scheduler-host/silent-output.js';import { captureTurnUsageContext, type TurnUsageContext } from './turnUsageContext.js';import type { BotCompactRuntimeRefreshCoordinator } from './botCompactRuntimeRefresh.js';@@ -235,6 +236,14 @@ export function prepareSessionEvent(},}: event;+ // Personal IM dispatches directly, outside AgentInputCoordinator. Preserve+ // its accepted durable input on the reply before the turn lease is released.+ if (!activeInputId && event.turnScope !== 'background') {+ const inputClientId = readChannelToolScope({ sessionId: session.id, sessionInstanceId: session.instanceId })?.inputClientId;+ if (inputClientId) attributedEvent = {+ ...attributedEvent, agentMeta: { ...attributedEvent.agentMeta, replyToClientId: inputClientId },+ };+ }if (event.type === 'error' && isTerminalTurnErrorEvent(event)) {const reason =!session.remoteHostId && session.agentKind === 'claude-code'diff --git a/docs/dev-rules/im-turn-flow.md b/docs/dev-rules/im-turn-flow.mdindex 9378d87772..683fa9b067 100644--- a/docs/dev-rules/im-turn-flow.md+++ b/docs/dev-rules/im-turn-flow.md@@ -103,6 +103,9 @@ Telegram / Slack / X)是同一件事的两套实现:把渠道里的一条消workdir 快照放行,再由 `codexEnvironment.buildSessionMcpConfig` / `piEnvironment` 逐会话收可见性)。渠道工具租约还被 `botSkillService` 复用来判定专线上「是不是主人触发的轮次」;没有 `channelToolScopeFor`的可绑定渠道靠 `LaneTurnScope` 兜住这一判定,否则主人在专线上也只能只读技能。+ `onAccepted` 成功落库后把本轮输入的 `clientId` 绑定到同一租约;事件持久化在租约释放前+ 将它写为 `replyToClientId`。后台学习只据这条确切输入的持久主人来源判定,不借用后续轮次+ 的租约或最近一条消息。受保护内容未落库时不绑定,复用作用域前清除旧输入。6b. **发送前上下文体检同源**:个人 IM 的 `dispatchQueuedSend` 在伙伴守卫(`companion.prepareSend`)之后、拿发送锁(`acquirePendingAgentSwitch`)之前调用 `deps.prepareUnhealthySession`(orchestrator 接`register.prepareUnhealthySessionForSend`),与桌面直发、官方 hook 走同一个diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 71f2bc8a72..a8ac8cf35e 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -450,10 +450,16 @@ Mobile 使用电脑端已连接的模型目录;目录为空时保持创建禁学习同时覆盖当场主动保存与回复后的宿主后台复盘。复盘复用已配置辅助模型,不创建可见任务、不派协同 worker、不延迟回复;同伙伴串行,成功回复只触发一次。引用本次交流与最新记忆/技能快照,无新经验则不写;记忆关闭时不提取记忆,并尊重不保存要求。更新只覆盖复盘读到的版本,冲突让新版本胜出。+ 回复后复盘同样覆盖私聊话题与 IM 专线。IM 专线只复盘持久消息来源确认由主人触发的回复,+ 只把主人原话作为偏好与技能的用户证据,不把群友发言、引用背景或缺失身份的旧记录当成主人要求。+ 后台保存 Skill 复核该回复对应的持久来源,不借用已经结束或下一轮的渠道租约。+ 话题学习写入同一伙伴的长期记忆与自有 Skill;主任务的短期工作账本及其覆盖水位仍只由主任务维护。真实保存回执持久附在来源伙伴发言气泡底部:脑子和书本两行分别表示记忆与技能,禁止放在任何发言气泡上方、独立插入时间线、标注“上一轮”或新建成功详情 UI。提前写入等待对应回复,迟到写入只补原回复。桌面点击分别打开现有伙伴设置的记忆页和能力页;手机复用伙伴设置面板。保存 Skill 后请求主任务在安全轮次边界刷新,不打断运行中的工作或授权卡;同一个聊天继续使用新技能。+ 主任务、私聊话题和 IM 专线在下一次发送前比较共享记忆目录与自有 Skill 更新版本,变化时沿用安全刷新,+ 因此在一个话题学到的内容也能进入已有的其他聊天;不把每个话题的完整消息历史合并进主聊天。桌面伙伴设置的「记忆」页承载这一承诺:同页开关记忆(关闭后已存记忆仍可查看、删除);按关于你 / 你的要求 / 项目 / 参考分组列出标题与正文开头,搜索复用记忆检索,内部 `digest` 不展示;详情显示全文,编辑自动保存,单条标题与正文沿用存储上限。改正文时摘要按正文首句确定性刷新,