Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): let task executors report final delivery
Chris9339b9d71dd2
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.tsindex 837bd0cde5..b9915eed00 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts@@ -36,6 +36,7 @@ function row(patch: Partial<WatchedSession>): WatchedSession {online: true,title: 'Task',workingDir: null,+ finalDelivery: true,phase: 'running',phaseSince: 0,lastActivityAt: 0,diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.tsindex e9907d357b..195d7db3b3 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts@@ -8,13 +8,13 @@import { afterEach, beforeEach, expect, it, vi } from 'vitest';import type { BotAutonomyRuntime } from '../runtime.js';import type { RoutineEngine } from '@cindy/maker-scheduler';-import type { LocalSessionMeta } from '../taskWatch.js';+import { TaskWatch, type LocalSessionMeta, type OwnershipSnapshot } from '../taskWatch.js';import type { BotGlance } from '../../../shared/botAutonomy.js';const h = vi.hoisted(() => ({scope: 'a', scheduler: 'sched' as string | null, ready: true,glance: vi.fn(), refreshRemote: vi.fn(),- readMetas: vi.fn(), readOwnership: vi.fn(), handled: vi.fn(),+ readMetas: vi.fn(), readOwnership: vi.fn(), handled: vi.fn(), reportDelivery: vi.fn(),}));vi.mock('../../appSessionState.js', () => ({activeOwnerScopeKey: () => h.scope, isAppSessionBoundaryPending: () => false,@@ -28,7 +28,7 @@ vi.mock('../../maker-host/bot-autonomy-settings-store.js', () => ({vi.mock('../hostData.js', () => ({readLocalSessionMetas: h.readMetas, readTaskOwnership: h.readOwnership, readBotDirectory: vi.fn(),}));-import { configureBotAutonomyHost, currentFollowUpEvents, getBotAutonomyGlance, setActiveBotAutonomy } from '../hub.js';+import { configureBotAutonomyHost, reportTaskDelivery, readTaskDeliveryNote, currentFollowUpEvents, getBotAutonomyGlance, setActiveBotAutonomy } from '../hub.js';const meta = (id: string, source = 'desktop'): LocalSessionMeta => ({id, source, title: 'Completed task', workingDir: null, status: 'active', hiddenAt: null,@@ -41,7 +41,8 @@ const events = ['mine', 'delegated', 'shared', 'deleted'].map(subject => ({beforeEach(() => {h.scope = 'a'; h.scheduler = 'sched'; h.ready = true;h.handled.mockReset().mockResolvedValue(false);- configureBotAutonomyHost({ isCompletionHandledByTeammate: h.handled });+ h.reportDelivery.mockReset().mockReturnValue(true);+ configureBotAutonomyHost({ isCompletionHandledByTeammate: h.handled, readSessionExecution: () => ({ instanceId: 'live', generation: 2 }) });h.refreshRemote.mockReset().mockResolvedValue(undefined);h.glance.mockReset().mockReturnValue({botId: 'sched', scope: 'all', waiting: [], working: [], lastSweepAt: 0, doneToday: 0, offlineDevices: [],@@ -50,7 +51,7 @@ beforeEach(() => {h.readMetas.mockReset().mockResolvedValue([meta('mine'), meta('delegated'), meta('shared', 'shared')]);h.readOwnership.mockReset().mockResolvedValue({ bots, creatorBySession: new Map([['delegated', 'sched']]), responsibleByBot: new Map() });setActiveBotAutonomy({ scope: 'a', engine: {} as RoutineEngine,- runtime: { glance: h.glance, watch: { isReady: () => h.ready, getSchedulerBotId: () => h.scheduler, refreshRemote: h.refreshRemote, list: () => [], getBots: () => bots } } as unknown as BotAutonomyRuntime });+ runtime: { glance: h.glance, watch: { reportDelivery: h.reportDelivery, isReady: () => h.ready, getSchedulerBotId: () => h.scheduler, refreshRemote: h.refreshRemote, list: () => [], getBots: () => bots } } as unknown as BotAutonomyRuntime });});afterEach(() => setActiveBotAutonomy(null));@@ -155,3 +156,49 @@ it('keeps unattributed legacy completion events', async () => {expect((await currentFollowUpEvents('sched', legacy))?.events).toEqual(legacy);expect(h.handled).not.toHaveBeenCalled();});++// Unit / #7253: no delivery context for unrelated work or the companion's own+// main chat; explicit assignments still receive it while all-task follow is off.+it('limits delivery reporting context to followed work and drops stale owner reads', async () => {+ h.scheduler = null;+ expect(await readTaskDeliveryNote('mine')).toBeNull();+ expect(await readTaskDeliveryNote('delegated')).toContain('report_task_delivery');+ h.readOwnership.mockImplementationOnce(async () => { h.scope = 'b'; return { bots: new Map(), creatorBySession: new Map() }; });+ expect(await readTaskDeliveryNote('delegated')).toBeNull();+});++// Unit / #7253: a retired runtime cannot borrow a replacement's current turn.+// Existing watch identity tests do not enter the Host callback with caller context.+it('rejects a delivery call from a retired runtime before recording it', () => {+ expect(reportTaskDelivery('delegated', true, 'retired')).toMatchObject({ ok: false, errorCode: 'PRECONDITION_FAILED' });+ expect(h.reportDelivery).not.toHaveBeenCalled();+ expect(reportTaskDelivery('delegated', true, 'live')).toEqual({ ok: true });+ expect(h.reportDelivery).toHaveBeenCalledWith('delegated', { instanceId: 'live', generation: 2 }, true);+});++// Unit / #7253 live acceptance: starting the following companion refreshes+// ownership while its notification is queued. Identical reads used to revoke+// dispatch on every retry. Exercise the actual Host consent gate with TaskWatch;+// then revoke responsibility without changing the bot directory to retain safety.+it('keeps a final delivery dispatch valid across identical refreshes but revokes real ownership changes', async () => {+ const readOwnership = async () => structuredClone(await h.readOwnership()) as OwnershipSnapshot;+ const watch = new TaskWatch({ now: () => 10, onChange: () => {}, log: { info() {}, warn() {}, debug() {} },+ getActivitySnapshots: () => [], isToolCallInFlight: () => false, getPendingInteractions: () => [],+ readLocalSessions: h.readMetas, readInterruptedSessions: async () => [], readOwnership,+ readSchedulerOverride: () => ({ customized: true, schedulerBotId: h.scheduler }),+ listRemoteDevices: async () => null, invokeRemote: async () => null,+ });+ await watch.start();+ setActiveBotAutonomy({ scope: 'a', engine: {} as RoutineEngine, runtime: { watch } as BotAutonomyRuntime });+ try {+ const batch = await currentFollowUpEvents('sched', events);+ expect(batch?.canDispatch()).toBe(true);+ await watch.refreshFollowers();+ expect(batch?.canDispatch()).toBe(true);+ const changed = await readOwnership();+ changed.creatorBySession.set('delegated', 'another');+ h.readOwnership.mockResolvedValue(changed);+ await watch.refreshFollowers();+ expect(batch?.canDispatch()).toBe(false);+ } finally { watch.stop(); }+});diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.tsindex 3adae3010b..24a3c9e833 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts@@ -14,8 +14,7 @@* 停止被当成做完叫醒伙伴;首次安装时事件赶在 ensure 之前发布、accepted=0 后永久丢失;伙伴主任务的欢迎轮出错* 后宿主把 errored 发给它自己,排在正在失败的主任务后面打转;启动时第一次读归属失败,补快照里已出错的任务被按* 「没人跟」结清、之后归属读到也不再发;内置规则落地失败仍发布(accepted=0 + 回执)后永久丢失;- * 120 字符的合法伙伴 id 拼出超过 128 字符的规则 id、永远没有内置规则;PR 任务每处理一轮评审就发一次- * finished、逐轮叫醒伙伴模型(实测 6 小时 57 次唤醒里 49 次是 finished)。+ * 120 字符的合法伙伴 id 拼出超过 128 字符的规则 id、永远没有内置规则。* - tier:unit(真实引擎 + 内存 load/save;状态表 IO 为内存 fake;时间由 now() 推进)。*/import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';@@ -94,6 +93,7 @@ async function setup(options: {log,onChange,getActivitySnapshots: () => [],+ readSessionExecution: (id) => ({ instanceId: id, generation: 1 }),isToolCallInFlight: () => false,getPendingInteractions: () => [],readLocalSessions: async (ids) => ids.map(meta),@@ -555,7 +555,10 @@ it.each([false, true])('keeps a fast delegation completion across delayed ownerstry {await runtime.start();options.creators.child = options.creators.stopped = options.creators.stale = 'a';- for (const id of ['child', 'unrelated', 'stopped']) runtime.watch.applyActivity(id, running(id));+ for (const id of ['child', 'unrelated', 'stopped']) {+ runtime.watch.applyActivity(id, running(id));+ runtime.watch.reportDelivery(id, { instanceId: id, generation: 1 }, true);+ }for (const id of ['child', 'unrelated', 'stale']) runtime.watch.applyActivity(id, completed(id));runtime.watch.applyActivity('stopped', null);await runtime.watch.settled();@@ -569,10 +572,6 @@ it.each([false, true])('keeps a fast delegation completion across delayed ownerst.advance(30_000);await vi.advanceTimersByTimeAsync(30_000);}- // finished 等安静期满才发:期满前不叫醒,期满后由扫描发出一次。- expect(publish).not.toHaveBeenCalled();- t.advance(AUTONOMY_THRESHOLDS.finishedQuietMs);- await vi.advanceTimersByTimeAsync(30_000);expect(publish).toHaveBeenCalledOnce();expect(publish).toHaveBeenCalledWith(HOST_SESSIONS_SOURCE_ID,expect.objectContaining({ type: 'finished', subject: 'child' }), expect.any(Function));@@ -606,10 +605,10 @@ it.each(['ensure', 'publish'] as const)('retries the last completion after %s faawait runtime.start();runtime.watch.applyActivity('child', running('child'));await runtime.watch.settled();+ expect(runtime.watch.reportDelivery('child', { instanceId: 'child', generation: 1 }, true)).toBe(true);runtime.watch.applyActivity('child', { ...running('child'), phase: 'completed' } as SessionActivitySnapshot);await runtime.watch.settled();- t.advance(AUTONOMY_THRESHOLDS.finishedQuietMs);- await vi.advanceTimersByTimeAsync(30_000);+ await vi.advanceTimersByTimeAsync(0);expect(runtime.watch.needsSweep()).toBe(false);failing = false;publish.mockClear();@@ -626,6 +625,7 @@ it.each(['ensure', 'publish'] as const)('retries the last completion after %s faexpect(publish).toHaveBeenCalledOnce();// The event ledger expires after 24h. A later settings/activity refresh must not replay it.t.advance(25 * 60 * 60_000);+ expect(runtime.watch.reportDelivery('child', { instanceId: 'child', generation: 1 }, true)).toBe(false);runtime.watch.applyActivity('child', { ...running('child'), phase: 'completed' } as SessionActivitySnapshot);await runtime.refreshFollowers();await vi.advanceTimersByTimeAsync(0);@@ -636,38 +636,28 @@ it.each(['ensure', 'publish'] as const)('retries the last completion after %s fa}});-// Unit / bot follow-up wake storm: a PR task handles one review round per turn, and every-// turn end used to publish `finished` and wake the teammate's model (49 of 57 wakes in 6h).-// Rounds that resume within the quiet period are superseded; the final round still wakes once.-it('wakes the follower once for the final round, not for every intermediate turn end', async () => {- vi.useFakeTimers();+// Unit / #7253: the production runtime must wake only on an explicit delivery,+// regardless of idle duration. Existing tests cover terminal delivery/retries, not+// semantic intermediate turns. Minimal input: false/absent report + completed.+it('publishes final delivery immediately and stays silent for intermediate or unreported ends', async () => {const t = await setup({ schedulerOff: true, creators: { child: 'a' } });const publish = vi.fn<AutonomyEngine['publish']>(async () => ({ accepted: 1, duplicate: false }));const runtime = t.create({ registerSource: vi.fn(), publish, ensureBuiltin: vi.fn(async () => ({} as never)) });- const turn = (phase: 'running' | 'completed') => ({- ...running('child'), phase, startedAtMs: t.now(), lastActivityAtMs: t.now(),- } as SessionActivitySnapshot);+ await runtime.start({ timers: false });try {- await runtime.start();- for (let round = 0; round < 3; round += 1) {- runtime.watch.applyActivity('child', turn('running'));- t.advance(60_000);- await vi.advanceTimersByTimeAsync(1_000);- runtime.watch.applyActivity('child', turn('completed'));- t.advance(AUTONOMY_THRESHOLDS.finishedQuietMs / 2);- await vi.advanceTimersByTimeAsync(30_000);+ for (const final of [undefined, false, true]) {+ runtime.watch.applyActivity('child', running('child'));+ await runtime.watch.settled();+ if (final !== undefined) expect(runtime.watch.reportDelivery('child', { instanceId: 'child', generation: 1 }, final)).toBe(true);+ const ended = t.now();+ runtime.watch.applyActivity('child', { ...running('child'), phase: 'completed', lastActivityAtMs: ended } as SessionActivitySnapshot);+ await runtime.watch.settled();+ await runtime.evaluate();+ expect(publish).toHaveBeenCalledTimes(final ? 1 : 0);+ if (final) expect(publish.mock.calls[0][1]).toMatchObject({ type: 'finished', occurredAt: ended });+ t.advance(3_600_000);+ await runtime.sweep();+ expect(publish).toHaveBeenCalledTimes(final ? 1 : 0);}- expect(publish).not.toHaveBeenCalled();- const finalSince = t.now() - AUTONOMY_THRESHOLDS.finishedQuietMs / 2;- t.advance(AUTONOMY_THRESHOLDS.finishedQuietMs / 2);- await vi.advanceTimersByTimeAsync(30_000);- expect(publish).toHaveBeenCalledOnce();- expect(publish).toHaveBeenCalledWith(HOST_SESSIONS_SOURCE_ID,- expect.objectContaining({ type: 'finished', id: `finished:child:${finalSince}` }), expect.any(Function));- await vi.advanceTimersByTimeAsync(120_000);- expect(publish).toHaveBeenCalledOnce();- } finally {- runtime.stop();- vi.useRealTimers();- }+ } finally { runtime.stop(); }});diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.tsindex e42bd42941..1921837701 100644--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts@@ -491,13 +491,13 @@ it('captures completion execution before asynchronous reads or a later turn', asawait h.watch.start();h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: null }));await h.watch.settled();+ expect(h.watch.reportDelivery('child', execution, true)).toBe(true);h.watch.applyActivity('child', activity('child', 'completed', { turnGeneration: null }));execution = { instanceId: 'native-2', generation: 2 };await h.watch.settled();- const quietAt = h.now() + AUTONOMY_THRESHOLDS.finishedQuietMs;- const [candidate] = new AutonomyEventLedger().evaluate(h.watch.list(), quietAt).due;+ const [candidate] = new AutonomyEventLedger().evaluate(h.watch.list(), h.now()).due;expect(candidate).toBeDefined();- const saved = JSON.parse(JSON.stringify(toRoutineEvent(candidate, quietAt)));+ const saved = JSON.parse(JSON.stringify(toRoutineEvent(candidate, h.now())));expect(saved.data).toMatchObject({ executionInstanceId: 'native-1', executionGeneration: 1 });h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: 2 }));await h.watch.settled();@@ -505,3 +505,33 @@ it('captures completion execution before asynchronous reads or a later turn', asexpect(saved.data).toMatchObject({ executionInstanceId: 'native-1', executionGeneration: 1 });h.watch.stop();});++// Unit / #7253: a model report must not survive a different native execution,+// nor turn stopped/error activity into delivery. Existing identity coverage only+// freezes event attribution. Minimal input: true in generation 1, completion in 2.+it('binds delivery reports to the live execution and permits correcting a report before completion', async () => {+ let execution = { instanceId: 'native', generation: 1 };+ const h = harness({ metas: [meta('child')], creators: { child: 'a' }, readSessionExecution: () => execution });+ await h.watch.start();+ try {+ h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: 1 }));+ expect(h.watch.reportDelivery('child', execution, true)).toBe(true);+ expect(h.watch.reportDelivery('child', execution, false)).toBe(true);+ await h.watch.settled();+ expect(h.watch.get('child')?.finalDelivery).toBe(false);+ expect(h.watch.reportDelivery('child', execution, true)).toBe(true);+ execution = { instanceId: 'native', generation: 2 };+ expect(h.watch.reportDelivery('child', { ...execution, generation: 1 }, true)).toBe(false);+ h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: 2 }));+ h.watch.applyActivity('child', activity('child', 'completed', { turnGeneration: 2 }));+ await h.watch.settled();+ expect(new AutonomyEventLedger().evaluate(h.watch.list(), h.now()).due).toEqual([]);+ expect(h.watch.reportDelivery('child', execution, true)).toBe(false);+ h.watch.applyActivity('child', activity('child', 'running', { turnGeneration: 3 }));+ execution = { instanceId: 'native', generation: 3 };+ expect(h.watch.reportDelivery('child', execution, true)).toBe(true);+ h.watch.applyActivity('child', null);+ await h.watch.settled();+ expect(new AutonomyEventLedger().evaluate(h.watch.list(), h.now()).due).toEqual([]);+ } finally { h.watch.stop(); }+});diff --git a/apps/desktop/src/main/bot-autonomy/events.ts b/apps/desktop/src/main/bot-autonomy/events.tsindex 21823bbea3..f4a211aed2 100644--- a/apps/desktop/src/main/bot-autonomy/events.ts+++ b/apps/desktop/src/main/bot-autonomy/events.ts@@ -1,7 +1,7 @@/*** 伙伴自主跟进 · 事件判定(程序级,不经模型)。*- * 从状态表判定 stuck / waiting / errored / usage-limit / finished(做完后安静满 finishedQuietMs),发布到例行任务引擎的宿主+ * 从状态表判定 stuck / waiting / errored / usage-limit / finished,发布到例行任务引擎的宿主* 内置事件源 `host:sessions`。去重:同一任务同一 (类型, phaseSince) 只发一次(事件 id 天然唯一,* 引擎另有 24h 回执去重);防打转:同一任务同一类事件 24h 内最多* `AUTONOMY_THRESHOLDS.maxEventsPerSessionPerDay` 次,超出只记日志。@@ -77,30 +77,14 @@ export function dueEventType(row: WatchedSession, now: number): AutonomyEventTypcase 'usage-limit':return 'usage-limit';case 'finished':- return emitsFinished(row) && now - row.phaseSince >= AUTONOMY_THRESHOLDS.finishedQuietMs ? 'finished' : null;+ // 自动化运行的任务有自己的结果通知,「做完」不再叫醒伙伴;卡住 / 等你 / 出错照常。+ // 伙伴主任务的一轮回复做完不是「任务做完」:否则别的伙伴每回一句话都会叫醒总调度。+ return row.source === 'routine' || row.canonicalOfBotId || !row.finalDelivery ? null : 'finished';default:return null;}}-/**- * 自动化运行的任务有自己的结果通知,「做完」不再叫醒伙伴;卡住 / 等你 / 出错照常。- * 伙伴主任务的一轮回复做完不是「任务做完」:否则别的伙伴每回一句话都会叫醒总调度。- */-function emitsFinished(row: WatchedSession): boolean {- return row.source !== 'routine' && !row.canonicalOfBotId;-}--/** 本机任务做完、finished 还没发:这一行由扫描到点判定(发出或结清后即离表)。 */-export function awaitsFinishedEvent(row: WatchedSession): boolean {- return row.online && row.deviceId === null && row.phase === 'finished' && emitsFinished(row);-}--/** 还在安静期内:这一行要留在表里,期满再判定。 */-export function awaitsFinishedQuiet(row: WatchedSession, now: number): boolean {- return awaitsFinishedEvent(row) && now - row.phaseSince < AUTONOMY_THRESHOLDS.finishedQuietMs;-}-export interface AutonomyEventCandidate {id: string;type: AutonomyEventType;diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.tsindex eef1fb6e10..8e585edaa7 100644--- a/apps/desktop/src/main/bot-autonomy/hub.ts+++ b/apps/desktop/src/main/bot-autonomy/hub.ts@@ -67,6 +67,29 @@ export function noteBotAutonomyInputProjection(projection: unknown): void {runtime.watch.applyInputProjection(projection as BotAutonomyInputProjection);}+/** Only followed work needs a model delivery report; no extra teammate context. */+export async function readTaskDeliveryNote(sessionId: string): Promise<string | null> {+ const active = current;+ if (!active || !scopeIsCurrent(active.scope)) return null;+ const ownership = await readTaskOwnership(ownerScopedUserDataPath());+ if (current !== active || !scopeIsCurrent(active.scope)) return null;+ if ([...ownership.bots.values()].some(bot => bot.canonicalSessionId === sessionId)) return null;+ if (!ownership.creatorBySession.has(sessionId) && !active.runtime.watch.getSchedulerBotId()) return null;+ return '[Task delivery] Host bookkeeping, not a user message: before your final answer in every turn, call cindy_helper.call_tool({name:"report_task_delivery",args:{final_delivery:true|false}}). Judge whether this turn newly delivers the requested result: PR delivered for human review, merged/closed, or goal achieved is true; intermediate review fixes, waiting for CI, or repeated status is false. A true report followed by normal completion notifies the following teammate.';+}++export function reportTaskDelivery(sessionId: string, finalDelivery: boolean, sessionInstanceId?: string):+ { ok: true } | { ok: false; errorCode: string; message: string } {+ const active = current;+ const execution = hostDeps.readSessionExecution?.(sessionId);+ if (!active || !scopeIsCurrent(active.scope) || !execution+ || (sessionInstanceId !== undefined && sessionInstanceId !== execution.instanceId)+ || !active.runtime.watch.reportDelivery(sessionId, execution, finalDelivery)) {+ return { ok: false, errorCode: 'PRECONDITION_FAILED', message: 'The current task execution is not running.' };+ }+ return { ok: true };+}+export function getBotAutonomyGlance(botId: string, options?: GlanceOptions, refreshRemote = true,): BotGlance {diff --git a/apps/desktop/src/main/bot-autonomy/runtime.ts b/apps/desktop/src/main/bot-autonomy/runtime.tsindex fb0495d4a2..9b6e272ebf 100644--- a/apps/desktop/src/main/bot-autonomy/runtime.ts+++ b/apps/desktop/src/main/bot-autonomy/runtime.ts@@ -22,8 +22,6 @@ import {import { FOLLOW_UP_BUILTIN_VERSION, buildFollowUpRoutineInput, builtinFollowUpRoutineId } from './builtinRoutine.js';import {AutonomyEventLedger,- awaitsFinishedEvent,- awaitsFinishedQuiet,hostSessionsSource,isPendingForFallback,sweepEventId,@@ -125,8 +123,7 @@ export class BotAutonomyRuntime {}private needsSweep(): boolean {- return this.watch.needsSweep() || this.deferredEvents.size > 0- || this.watch.list().some(awaitsFinishedEvent);+ return this.watch.needsSweep() || this.deferredEvents.size > 0;}stop(): void {@@ -302,9 +299,7 @@ export class BotAutonomyRuntime {}const unsettled = new Set(due.filter(candidate => !this.ledger.isSettled(candidate.id)).map(candidate => candidate.row.sessionId));for (const row of rows) {- if (row.phase === 'finished' && !unsettled.has(row.sessionId) && !awaitsFinishedQuiet(row, now)) {- this.watch.retireFinished(row.sessionId, row.phaseSince);- }+ if (row.phase === 'finished' && !unsettled.has(row.sessionId)) this.watch.retireFinished(row.sessionId, row.phaseSince);}this.pruneReminded(now);this.syncSweepTimer();diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.tsindex d4e76647b4..88ee83a54b 100644--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts@@ -36,8 +36,8 @@ import {truncateSummary,} from './phase.js';-/** 做完的行在表里停留多久(之后只留在「今天做完」计数里);须长于 finished 的安静期,否则事件来不及判定。 */-export const FINISHED_ROW_RETENTION_MS = AUTONOMY_THRESHOLDS.finishedQuietMs + 15 * 60_000;+/** 做完的行在表里停留多久(之后只留在「今天做完」计数里)。 */+export const FINISHED_ROW_RETENTION_MS = 15 * 60_000;/** 伙伴、委派与接手关系的重读间隔。 */export const OWNERSHIP_REFRESH_MS = 60_000;/** 设备目录(服务端 HTTP)重读间隔;轮询本身按 remotePollMs。 */@@ -88,6 +88,24 @@ export interface OwnershipSnapshot {responsibleByBot: Map<string, Set<string>>;}+/** The directory reference is a dispatch consent token: identical IO refreshes+ * must not revoke a queued follow-up, while any ownership/availability change must. */+function sameOwnership(a: OwnershipSnapshot, b: OwnershipSnapshot): boolean {+ if (a.bots.size !== b.bots.size || a.creatorBySession.size !== b.creatorBySession.size+ || a.responsibleByBot.size !== b.responsibleByBot.size) return false;+ for (const [id, bot] of a.bots) {+ const other = b.bots.get(id);+ if (!other || bot.status !== other.status || bot.allowSchedulerFollow !== other.allowSchedulerFollow+ || !!bot.shadowed !== !!other.shadowed || (bot.canonicalSessionId ?? null) !== (other.canonicalSessionId ?? null)) return false;+ }+ for (const [id, creator] of a.creatorBySession) if (b.creatorBySession.get(id) !== creator) return false;+ for (const [id, sessions] of a.responsibleByBot) {+ const other = b.responsibleByBot.get(id);+ if (!other || sessions.size !== other.size || [...sessions].some(session => !other.has(session))) return false;+ }+ return true;+}+export interface RemoteDeviceTarget {deviceId: string;name: string;@@ -139,6 +157,7 @@ function inputProjectionErrorReason(projection: BotAutonomyInputProjection): strinterface LocalFacts {activity: SessionActivitySnapshot | null;execution?: BotAutonomyExecution;+ delivery?: { execution: BotAutonomyExecution; final: boolean };/** Live activity reached completion before ownership/metadata could create a row. */observedCompletion: boolean;inputError: string | null;@@ -285,6 +304,18 @@ export class TaskWatch {if (this.observesLocal(sessionId) || !this.ownershipLoaded) this.queue(sessionId);}+ /** A report belongs to one live execution, never to the next turn or another task. */+ reportDelivery(sessionId: string, execution: BotAutonomyExecution, final: boolean): boolean {+ if (this.stopped) return false;+ const facts = this.local.get(sessionId);+ const live = this.deps.readSessionExecution?.(sessionId);+ if (!facts?.activity || facts.activity.phase !== 'running'+ || !live || live.instanceId !== execution.instanceId || live.generation !== execution.generation) return false;+ this.local.set(sessionId, { ...facts, delivery: { execution: { ...execution }, final } });+ this.queue(sessionId);+ return true;+ }+applyInputProjection(projection: BotAutonomyInputProjection): void {if (this.stopped || typeof projection?.sessionId !== 'string') return;const facts = this.factsFor(projection.sessionId);@@ -509,6 +540,9 @@ export class TaskWatch {lastActivityAt: activity?.lastActivityAtMs ?? previous?.lastActivityAt ?? phaseSince,startedAt: activity?.startedAtMs ?? previous?.startedAt ?? null,...(facts.execution ? { execution: facts.execution } : {}),+ finalDelivery: facts.delivery?.final === true+ && facts.delivery.execution.instanceId === facts.execution?.instanceId+ && facts.delivery.execution.generation === facts.execution?.generation,pendingQuestion,pendingRequestId,pendingInteractionId,@@ -623,7 +657,7 @@ export class TaskWatch {try {const next = await this.deps.readOwnership();if (this.stopped) return;- this.ownership = next;+ this.ownership = sameOwnership(this.ownership, next) ? { ...next, bots: this.ownership.bots } : next;this.ownershipAt = this.deps.now();this.ownershipLoaded = true;this.ownershipReadFailures = 0;@@ -949,6 +983,7 @@ function localSource(meta: LocalSessionMeta, creatorBotId: string | null): Watchfunction sameRow(a: WatchedSession | null, b: WatchedSession): boolean {return !!a+ && a.finalDelivery === b.finalDelivery&& a.phase === b.phase&& a.phaseSince === b.phaseSince&& a.title === b.titlediff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.tsindex 422d520787..18a1443e31 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts@@ -3372,6 +3372,30 @@ describe('Cindy Make task note', () => {expect(vi.mocked(session.send).mock.calls[2][0]).toContain('[Side chat context]');});+ // Unit / #7253: only wire context explains delivery reporting. The previous+ // source-note coverage did not protect all harnesses, dedupe, or persistence.+ it.each(['claude-code', 'codex', 'pi'] as const)('adds deduplicated delivery context to %s without saving it as user text', async (agentKind) => {+ const memory = createWireNoteMemory();+ const session = createSession({ agentKind });+ const note = '[Task delivery] Report newly delivered results before ending.';+ const { deps } = createDeps({+ getSession: () => session,+ readTaskDeliveryNote: async () => note,+ planRepeatableWireNotes: (id, notes, opts) => memory.plan(id, notes, opts),+ });+ const transaction = createMakerSendTransaction(deps);+ await transaction.sendToAgentAccepted('session-1', 'Complete the work', undefined, {+ persistUserMessage: { clientId: 'delivery-1', content: 'Complete the work' },+ });+ expect(vi.mocked(session.send).mock.calls[0][0]).toContain(note);+ expect(vi.mocked(deps.createDbMessage).mock.calls[0][1].content).toBe('Complete the work');+ await transaction.sendToAgentAccepted('session-1', 'Continue');+ expect(vi.mocked(session.send).mock.calls[1][0]).toBe('Continue');+ memory.reset('session-1');+ await transaction.sendToAgentAccepted('session-1', 'Continue after compaction');+ expect(vi.mocked(session.send).mock.calls[2][0]).toContain(note);+ });+it('does not decorate native commands or ordinary fork messages with side-chat instructions', async () => {const session = createSession({ agentKind: 'claude-code' });const readTaskSource = vi.fn(async () => 'side-chat');diff --git a/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.tsindex 118e62e8e0..fc38ae3d82 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/wireNoteMemory.test.ts@@ -84,3 +84,15 @@ describe('wireNoteMemory', () => {expect(memory.plan('s2', { 'ui-language': UI }).notes).toEqual({ 'ui-language': UI });});});++// Unit / #7253: idle direct sends add only delivery context. They must not erase+// language/device deduplication already committed by the ordinary send path.+it('preserves other notes when an idle send commits only delivery context', () => {+ const memory = createWireNoteMemory();+ const notes = { 'ui-language': UI, 'task-delivery': 'Report final delivery' } as const;+ memory.plan('s1', notes).commit();+ memory.plan('s1', { 'task-delivery': notes['task-delivery'] }, { partial: true }).commit();+ expect(memory.plan('s1', notes).notes).toEqual({});+ memory.plan('s1', { 'task-delivery': notes['task-delivery'] }, { partial: true, force: true }).commit();+ expect(memory.plan('s1', notes).notes).toEqual({ 'ui-language': UI });+});diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.tsindex 3ff23c255e..c56700c10b 100644--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts@@ -591,6 +591,7 @@ export interface MakerSendTransactionDeps {* 与 `[客户端说明]` 同层,只进 wire 消息。*/readBotThreadNote?(sessionId: string): Promise<string | null>;+ readTaskDeliveryNote?(sessionId: string): Promise<string | null>;/*** 逐轮环境说明去重(见 wireNoteMemory.ts):返回本轮真正要前置的段;与上一次已被* 引擎接受的内容相同的段不再重复。`force` 在交接首条(原生上下文刚重建)时整体重发。@@ -1593,6 +1594,7 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make'side-chat': allowsEnvironmentNotes && taskSource === 'side-chat'? SIDE_CHAT_CONTEXT : null,'bot-thread': botThreadNote,+ 'task-delivery': allowsEnvironmentNotes ? await deps.readTaskDeliveryNote?.(sessionId) ?? null : null,'client-environment': mobileClientNote,'cindy-make': cindyMakeNote,'ui-language': uiLanguageNote,@@ -1613,6 +1615,9 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Makeif (plannedNotes['side-chat']) {outgoing = prependNoteToWireUserMessage(outgoing as HandoffWireMessage, plannedNotes['side-chat']);}+ if (plannedNotes['task-delivery']) {+ outgoing = prependNoteToWireUserMessage(outgoing as HandoffWireMessage, plannedNotes['task-delivery']);+ }if (plannedNotes['bot-thread']) {outgoing = prependNoteToWireUserMessage(outgoing as HandoffWireMessage, plannedNotes['bot-thread']);}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 9e53ea2510..dcd35afc0b 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -1,3 +1,4 @@+import { readTaskDeliveryNote } from '../bot-autonomy/hub.js';import { setVoiceTaskDispatch, setVoiceCallMemoryReader } from '../voice-conversation/taskBridge.js';import { buildBotMemoryScopeKey } from '@cindy/maker-core';import { createOrcaWorkerProjectHandlers } from './orcaWorkerProjectHandlers';@@ -11698,9 +11699,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions){ visibleText: source.persistedText ?? message },): null;- const outgoingMessage: UserMessage = sourceNote+ const sourcedMessage: UserMessage = sourceNote? (prependNoteToWireUserMessage(withHandoff as HandoffWireMessage, sourceNote) as UserMessage): withHandoff;+ const deliveryNote = shouldPrependMobileClientPromptNote(message, session.agentKind)+ ? await readTaskDeliveryNote(session.id) : null;+ const deliveryPlan = wireNoteMemory.plan(session.id, { 'task-delivery': deliveryNote }, { force: !!pendingHandoff, partial: true });+ const outgoingMessage = deliveryPlan.notes['task-delivery']+ ? prependNoteToWireUserMessage(sourcedMessage as HandoffWireMessage, deliveryPlan.notes['task-delivery']) as UserMessage+ : sourcedMessage;// Idle direct sends never carry internal coordination (that is force-queued).const releaseTurnSource = noteChannelTurnSource(session.id, channelTurnSourceFor(source?.origin, false));try {@@ -11733,7 +11740,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)if (pendingHandoff && sendResult.accepted) {agentHandoffPending.consume(session.id);}- if (sendResult.accepted) void touchSessionActivityInDb(session.id);+ if (sendResult.accepted) {+ deliveryPlan.commit();+ void touchSessionActivityInDb(session.id);+ }return sendResult;} catch (err) {if (turnChangeSetStarted) {@@ -18178,6 +18188,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)readReplyQuoteNote,// 私聊话题的 [话题说明]:按持久化的话题链接现读,不是话题时为 null。readBotThreadNote: readBotDmThreadContextNote,+ readTaskDeliveryNote,planRepeatableWireNotes: (sessionId, notes, opts) => wireNoteMemory.plan(sessionId, notes, opts),applyPendingAgentSwitch: async (sessionId, options) => {if (!options?.scheduled) await scheduledModelScope.restore(sessionId);diff --git a/apps/desktop/src/main/maker-ipc/wireNoteMemory.ts b/apps/desktop/src/main/maker-ipc/wireNoteMemory.tsindex 5fa99c82c5..962557b9f9 100644--- a/apps/desktop/src/main/maker-ipc/wireNoteMemory.ts+++ b/apps/desktop/src/main/maker-ipc/wireNoteMemory.ts@@ -18,7 +18,7 @@* `[消息来源]` 不在此列:它陈述的是"本条"由谁发,逐条都要带。*/-export type RepeatableWireNoteKind = 'ui-language' | 'client-environment' | 'cindy-make' | 'side-chat' | 'bot-thread';+export type RepeatableWireNoteKind = 'ui-language' | 'client-environment' | 'cindy-make' | 'side-chat' | 'bot-thread' | 'task-delivery';export type RepeatableWireNotes = Partial<Record<RepeatableWireNoteKind, string | null>>;@@ -30,12 +30,12 @@ export interface WireNotePlan {}export interface WireNoteMemory {- plan(sessionId: string, notes: RepeatableWireNotes, opts?: { force?: boolean }): WireNotePlan;+ plan(sessionId: string, notes: RepeatableWireNotes, opts?: { force?: boolean; partial?: boolean }): WireNotePlan;/** 原生上下文失去连续性(压缩边界 / clear / 重建):下一轮整体重发。 */reset(sessionId: string): void;}-const KINDS: readonly RepeatableWireNoteKind[] = ['ui-language', 'client-environment', 'cindy-make', 'side-chat', 'bot-thread'];+const KINDS: readonly RepeatableWireNoteKind[] = ['ui-language', 'client-environment', 'cindy-make', 'side-chat', 'bot-thread', 'task-delivery'];export function createWireNoteMemory(): WireNoteMemory {const lastSent = new Map<string, Map<RepeatableWireNoteKind, string | null>>();@@ -62,8 +62,10 @@ export function createWireNoteMemory(): WireNoteMemory {commit() {// plan 之后 reset 过:这份计划面对的是旧上下文,不记为已发送,下一轮整体重发。if (epochOf(sessionId) !== epoch) return;- const next = new Map<RepeatableWireNoteKind, string | null>();- for (const kind of KINDS) next.set(kind, notes[kind] ?? null);+ const next = opts?.partial && !opts.force ? new Map(lastSent.get(sessionId)) : new Map<RepeatableWireNoteKind, string | null>();+ for (const kind of KINDS) {+ if (!opts?.partial || kind in notes) next.set(kind, notes[kind] ?? null);+ }lastSent.set(sessionId, next);},};diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex 9366675040..7e5da7f2b2 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -1,3 +1,4 @@+import { reportTaskDelivery } from '../bot-autonomy/hub.js';import { todoForCaller } from '../maker-ipc/botTodoAccess.js';import { getDeviceId } from '../authManager.js';import { buildHistorySessionDeepLink } from '../deepLink.js';@@ -795,6 +796,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcgetSessionRuntime: wrap((service, params) => service.getSessionRuntime(params)),setSessionRuntime: wrap((service, params) => service.setSessionRuntime(params)),},+ taskDelivery: { report: reportTaskDelivery },setCurrentSessionTitle: async ({ sessionId, title }) => {if (!tryGetDbClient()) {return { ok: false, errorCode: 'HOST_NOT_READY', message: 'localDb not ready' };diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.tsindex fa9abe4bf9..b9a3be7430 100644--- a/apps/desktop/src/shared/botAutonomy.ts+++ b/apps/desktop/src/shared/botAutonomy.ts@@ -65,11 +65,6 @@ export const AUTONOMY_THRESHOLDS = {stuckInToolAfterMs: 45 * 60_000,/** 等权限 / 等回答达到这么久 → waiting(主人不在时伙伴代答或提醒)。 */waitingAfterMs: 5 * 60_000,- /**- * 做完后安静满这么久、仍停在做完才发 finished。期间任务又开始下一轮(例如 PR 每来一轮评审处理一轮),- * 这一轮的做完被下一轮取代、不叫醒伙伴;最后一轮停下后照常发,最终交付不会漏。- */- finishedQuietMs: 20 * 60_000,/** 同一任务同一类事件 24h 内最多发布次数,防止伙伴与任务互相推着打转。 */maxEventsPerSessionPerDay: 6,/** 远程电脑状态轮询间隔(仅有在线且已授权的电脑时才轮询)。 */@@ -107,6 +102,8 @@ export interface WatchedSession {online: boolean;title: string;workingDir: string | null;+ /** Executing model explicitly reported final delivery for this execution. */+ finalDelivery?: boolean;phase: WatchedPhase;/** 进入当前 phase 的时刻(ms)。同一 (phase, phaseSince) 只发布一次事件。 */phaseSince: number;diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.mdindex bf84a93254..d7680b08ac 100644--- a/docs/product-rules/agent-user-parity.md+++ b/docs/product-rules/agent-user-parity.md@@ -155,3 +155,5 @@ Host 不因当前输入缺少主人标记再追加行动同意判定。只认运当前调用的委托、权限撤销和延迟交付检查继续保留;不恢复过期授权,不自动重发。实现见 `maker-ipc/taskActionAuthorization.ts`、`taskActionHost.ts` 与`mcp-integrations/codexHttpBridge.ts`;回归见各自授权及 HTTP 桥接测试。++执行任务的模型可用 `cindy_helper` 的 cindy 类 `report_task_delivery` 报告本轮是否新交付最终结果;只限当前任务执行者,子 Agent 不可代报。三个 Harness 共用此入口;它不结束任务或授予操作权限。跟进通知门控见 `cindy-bots-runtime.md` §6.3。diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 60d098caa1..4b66d00f7a 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -876,7 +876,7 @@ Session 任务遵守同一套机制与呈现契约:| `waiting` | 等权限 / 等回答满 5 分钟 || `errored` | 出错,或启动时发现上一轮被打断 || `usage-limit` | 撞上用量上限、宿主正在等重置后自动继续 |-| `finished` | 观察到任务完成(灵动岛完成态)后安静满 20 分钟仍停在做完;期间任务又开始下一轮(如 PR 每来一轮评审处理一轮),这一轮的做完被下一轮取代、不发,最后一轮停下后照常发。主人点停止 / 中止的任务静默离表,不算做完、不发事件。自动化的运行任务不发,它有自己的结果通知 |+| `finished` | 执行任务的模型用 `report_task_delivery` 明确报告本轮新交付了最终结果(如 PR 交付待人审、合并/关闭或目标已达成),且同一执行轮次正常结束时立即发出;中间评审修复、等 CI、重复状态通知和未报告的轮次不发。回执按当前任务及执行身份绑定,不跨轮次沿用,不依赖静默时长。主人点停止 / 中止的任务静默离表,不算做完、不发事件。自动化的运行任务不发,它有自己的结果通知 || `sweep` | 条件兜底:某跟进伙伴还有 ≥1 件等你 / 出错 / 用量上限 / 卡住的本机任务,且距它上次被叫醒(任一事件被它的规则接收)满 2 小时 |- 去重:事件 id = `类型:任务:进入该状态的时刻`,同一状态只发一次;引擎另有 24 小时回执去重,重启后同一次状态不重发。@@ -1055,7 +1055,7 @@ Todo 在桌面与手机都只在伙伴近况(6.3.4)里展示,两端共享- 不得把 Home 根目录整体设为可写,或从 Home 内可写配置反向派生权限。- Bot 表全部只增量;旧代码打开含 Bot 表的库时按既有 migration compatibility 守卫失败关闭,不得强行降级。-- 自主跟进的观察、阈值、去重、跟进者判定和「等你」系统提醒都是程序级,不得经模型判定或依赖 prompt 自觉。+- 自主跟进的观察、阈值、去重、跟进者判定和「等你」系统提醒都是程序级;只有“本轮是否新交付最终结果”由执行任务的模型通过结构化回执判断,宿主校验当前任务、执行身份与正常结束,不将每轮结束当作最终交付。- 伙伴之间不得无限互相触发:事件只按 `followerBotId` 叫醒一个伙伴;同一任务同一状态只发一次事件,同类事件24 小时最多 6 次;伙伴推任务产生的新状态仍受同一上限约束。不得为绕过上限给事件换 id 或重置计数。- 「自动跟进所有任务」账号内唯一;不得让多个伙伴同时收全部任务事件。另一台电脑上的任务不得在本机发事件或系统提醒,@@ -1088,7 +1088,7 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘父任务异常恢复后仍投递到当前主任务;check / message / stop 都只能控制它创建的 Session 任务。伙伴负责的任务经 6.3 的工作台工具查看、继续;越权(不在负责范围、伙伴隐藏任务、非主任务调用、别的伙伴在跟)一律被宿主拒绝。-- 自主跟进:任务卡住 10 分钟 / 等你 5 分钟 / 出错 / 用量上限 / 做完后安静 20 分钟时,只有跟进者的内置「跟进」规则被叫醒一次;+- 自主跟进:任务卡住 10 分钟 / 等你 5 分钟 / 出错 / 用量上限 / 模型报告最终交付且本轮正常结束时,只有跟进者的内置「跟进」规则被叫醒一次;例行任务引擎重建后 `host:sessions` 事件源重新登记;内置规则不能删除、不能改内容、只能暂停;没人跟的本机「等你」只提醒主人一次;「自动跟进所有任务」默认关闭,恢复默认删除 override 并回到关闭;无总调度、无待跟进委派时不起扫描定时器;总调度的「一眼」看全设备任务,其它伙伴只看自己开的或接手的任务;已授权的远程控制端读「一眼」时,与远程任务列表同一口径,隐藏 / 归档伙伴开的、它的主任务与它在跟的任务一律不返回;远程任务只进「一眼」、不叫醒伙伴也不提醒;没有待处理diff --git a/packages/lizi-mcps/src/__tests__/sessionContext.test.ts b/packages/lizi-mcps/src/__tests__/sessionContext.test.tsindex 0361f24ad9..9a1a9c912b 100644--- a/packages/lizi-mcps/src/__tests__/sessionContext.test.ts+++ b/packages/lizi-mcps/src/__tests__/sessionContext.test.ts@@ -1939,3 +1939,20 @@ describe('dynamic lizi MCP session context', () => {});});});++// Unit / #7253: all harnesses use the same current-task delivery tool; ambient+// context must win over the server's captured context, and descendants cannot+// announce their parent's delivery. Existing title tests do not cover this report.+it.each([['claude-code', false], ['codex', false], ['pi', false], ['claude-code', true], ['codex', true], ['pi', true]] as const)('routes %s delivery only from the current task executor (SSH: %s)', async (agentKind, ssh) => {+ const report = vi.fn(() => ({ ok: true as const }));+ const server = createXdtHelperMcpServer({ taskDelivery: { report } }, { agentKind, workingDir: '' });+ const call = () => tools(server).call_tool.handler({ name: 'report_task_delivery', args: { final_delivery: true } });+ expect(parse(await call() as never)).toMatchObject({ ok: false, errorCode: 'NO_SESSION_CONTEXT' });+ const context = { agentKind, workingDir: '/repo', sessionId: 'current', sessionInstanceId: 'runtime-1', ...(ssh ? { remoteHostId: 'ssh-host' } : {}) };+ expect(parse(await runWithLiziMcpSessionContext(context, call) as never)).toMatchObject({ ok: true, recorded: true });+ expect(report).toHaveBeenCalledWith('current', true, 'runtime-1');+ report.mockClear();+ expect(parse(await runWithLiziMcpSessionContext({ ...context, mcpCallerKind: 'descendant' }, call) as never))+ .toMatchObject({ ok: false, errorCode: 'CAPABILITY_NOT_AVAILABLE' });+ expect(report).not.toHaveBeenCalled();+});diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 23be3cfa91..7da87cb434 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -1,3 +1,4 @@+import { registerTaskDeliveryTool, type TaskDeliveryCallbacks } from './xdt-helper/report_task_delivery.js';import { registerSessionTagTools, type SessionTagsCallback } from './xdt-helper/session_tags.js';/*** lizi_xdtHelperMcpServer.ts@@ -146,7 +147,7 @@ const CATEGORY_ENUM = ['cindy', 'auth', 'control', 'history', 'feedback', 'hando* 说明才发现。改工具的作用范围时同步改这里(测试按类目全集守护)。*/export const HELPER_CATEGORY_DESCRIPTIONS: Record<(typeof CATEGORY_ENUM)[number], string> = {- cindy: `${BRAND_NAME} 能力说明与当前任务信息;get_capabilities({key:"self-management"}) 是管理自己的任务、定时任务、项目、伙伴的工具索引。本机。`,+ cindy: `${BRAND_NAME} 能力说明与当前任务信息/交付回执(report_task_delivery);get_capabilities({key:"self-management"}) 是管理自己的任务、定时任务、项目、伙伴的工具索引。本机。`,auth: '供应商授权登录(Grok 设备码)。本机。',control: '管理任务与项目:归档/取消归档支持本机与跨电脑(deviceId::sessionId);改名、移动、标签、排队消息、插话、停止、运行设置、项目列表与增删改仅本机。',history: '按话题查找跨渠道聊天,支持伙伴归属(teammate_id)、最近活动时间与真实来源;不要默认限制当前工作目录或创建日期。查询任务、工作目录、聊天记录、任务摘要与输入队列;任务结果附带可直接引用的 sessionUrl,已知 id 要链接用 get_task_digest。任务列表、搜索、读取聊天记录、任务摘要(get_task_digest)可跨电脑(device 参数 / deviceId::sessionId);其余本机。',@@ -833,6 +834,7 @@ export interface XdtHelperMcpDeps {* set_current_session_title 会被注册; 不注入则不出现在 list_tools 里。*/setCurrentSessionTitle?: SetCurrentSessionTitleDeps['setCurrentSessionTitle'];+ taskDelivery?: TaskDeliveryCallbacks;askUserQuestionAsync?: AskUserQuestionAsyncCallback;/*** 批量 session 标题更新回调。host 注入后, control 类工具 rename_sessions 会被注册。@@ -917,6 +919,9 @@ export function createXdtHelperMcpServer(getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),execute: deps.sessionTags,});+ if (deps.taskDelivery) {+ registerTaskDeliveryTool(registry, () => resolveLiziMcpSessionContext(sessionCtx), deps.taskDelivery);+ }if (deps.setCurrentSessionTitle) {registerSetCurrentSessionTitleTool(registry, {getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),diff --git a/packages/lizi-mcps/src/xdt-helper/report_task_delivery.ts b/packages/lizi-mcps/src/xdt-helper/report_task_delivery.tsnew file mode 100644index 0000000000..12bc968f6b--- /dev/null+++ b/packages/lizi-mcps/src/xdt-helper/report_task_delivery.ts@@ -0,0 +1,28 @@+import { z } from 'zod';+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';+import type { LiziMcpSessionContext } from '../types.js';+import { errorPayload, okPayload } from './_payload.js';++export interface TaskDeliveryCallbacks {+ report(sessionId: string, finalDelivery: boolean, sessionInstanceId?: string): { ok: true } | { ok: false; errorCode: string; message: string };+}++export function registerTaskDeliveryTool(+ registry: XdtHelperToolRegistry,+ getContext: () => LiziMcpSessionContext,+ callbacks: TaskDeliveryCallbacks,+): void {+ registry.register({+ name: 'report_task_delivery',+ category: 'cindy',+ description: 'Before the final answer in each followed task turn, report whether this turn newly delivers the requested result. PR delivered for human review, merged/closed, or task goal achieved: true. Intermediate review fixes, waiting for CI, or repeated status: false. A true report followed by normal completion notifies the following teammate. Current task executor only; this neither ends the turn nor sends a message.',+ inputShape: { final_delivery: z.boolean() },+ handler: async ({ final_delivery }) => {+ const context = getContext();+ if (!context.sessionId) return errorPayload('NO_SESSION_CONTEXT', 'No current task.');+ if (context.mcpCallerKind === 'descendant') return errorPayload('CAPABILITY_NOT_AVAILABLE', 'Only the task executor can report delivery.');+ const result = callbacks.report(context.sessionId, final_delivery, context.sessionInstanceId);+ return result.ok ? okPayload({ recorded: true }) : errorPayload(result.errorCode, result.message);+ },+ });+}