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(plugin): revoke task ownership on uninstall and refresh run receipts

Dash7880566e770f
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 400d4a37c8..4376381482 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1722,6 +1722,8 @@ export function setGhostSessionRevealer(reveal: ((sessionId: string) => void) |
let pluginTaskHandler: PluginTaskHandler | null = null;
export function setPluginTaskHandler(handler: PluginTaskHandler | null): void { pluginTaskHandler = handler; }
+let pluginTaskUninstaller: ((pluginId: string, remove: () => Promise<void>) => Promise<void>) | null = null;
+export function setPluginTaskUninstaller(handler: typeof pluginTaskUninstaller): void { pluginTaskUninstaller = handler; }
export function isPluginTaskAuthorized(id: string): boolean {
const ghost = findAvailableGhost(id);
@@ -6521,8 +6523,11 @@ async function uninstallGhostAndCleanupLocked(
getGhostAgentSlot().clearGhost(id);
getGhostErrandSlot().clearGhost(id);
getGhostSubscriptionGateway().dropGhost(id);
- const result = await manager.uninstall(id, { notify: false });
- if ('rejection' in result) throwUninstallError(result.rejection);
+ if (!pluginTaskUninstaller) throw new Error('Plugin task storage is not ready for uninstall');
+ await pluginTaskUninstaller(id, async () => {
+ const result = await manager.uninstall(id, { notify: false });
+ if ('rejection' in result) throwUninstallError(result.rejection);
+ });
removeGhostSecrets(id);
removeGhostKvBestEffort(
createGhostKvStore({
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
index 4cc624ed3b..df141e8aff 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskService.test.ts
@@ -11,6 +11,7 @@ import {
type PluginTaskServiceDeps,
} from '../pluginTaskService.js';
import type { PluginTaskView } from '../../../shared/pluginTasks.js';
+import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from '../sessionExecutionOwnership.js';
function fixture() {
let seq = 0;
@@ -19,6 +20,12 @@ function fixture() {
const tasks = new Map<string, PluginTaskView>();
const copy = <T>(v: T): T => structuredClone(v);
const store: PluginTaskStore = {
+ revokePlugin: async pluginId => {
+ for (const row of rows.values()) if (row.pluginId === pluginId && row.operation === 'create') {
+ row.payload = JSON.stringify({...JSON.parse(row.payload),ownershipRevoked:true});
+ row.revision++;
+ }
+ },
get: async (id) => copy(rows.get(id)),
find: async (p, op, t, k) =>
copy(
@@ -103,7 +110,112 @@ function fixture() {
};
}
+it.each(['completed','failed','cancelled','interrupted'] as const)('prefers a newly persisted %s terminal over stale inspection for getRun and listRuns', async status => {
+ for (const kind of ['getRun','listRuns'] as const) {
+ const f=fixture(),run=await f.send();
+ await f.service.accept(run.taskId,{clientId:run.inputMessageId},f.execution);
+ f.deps.inspect=async()=>{
+ await f.service.settle(run.taskId,f.execution,status,'output');
+ return {execution:null,pending:[]};
+ };
+ const result=kind==='getRun'?await f.service.getRun('p',run.runId):(await f.service.listRuns('p',run.taskId)).items[0];
+ expect(result).toMatchObject({status,outputMessageId:'output'});
+ expect(result).not.toHaveProperty('error');
+ }
+});
+
+it.each(['restore','restart'] as const)('the production cancel adapter rechecks revoked ownership after %s waits', async point => {
+ const f=fixture(),run=await f.send();
+ let release!:()=>void,entered!:()=>void,restores=0;
+ const barrier=new Promise<void>(resolve=>{release=resolve;});
+ const started=new Promise<void>(resolve=>{entered=resolve;});
+ const pause=async()=>{entered();await barrier;};
+ const remove=vi.fn(),stop=vi.fn(async()=>({ok:true,status:'stopping'}));
+ const snapshot={};
+ const deps={assertPlugin:()=>{},assertCurrent:()=>{},snapshot,
+ getCurrentDbClientSnapshot:()=>snapshot,isPluginTaskAuthorized:()=>true,
+ pluginTaskServiceForCurrentOwner:()=>f.service,PluginTaskError,
+ inputCoordinator:{ensureQueueRestored:async()=>{if(++restores===2&&point==='restore')await pause();},
+ isQueueRestored:()=>true,getQueueControlSnapshot:()=>({pendingQueue:[{clientId:run.inputMessageId}]}),remove},
+ withdrawOwnedSessionInputs,controlOwnedSessionExecution,isSameSessionExecution,
+ awaitAgentInputQueueSnapshotPersistence:async()=>{},
+ withSessionRestartLock:async(_id:string,operation:()=>Promise<void>)=>{if(point==='restart')await pause();await operation();},
+ readExecution:()=>f.execution,resetAutomaticRecoveryForExplicitStop:vi.fn(),contextOverflowRolloverHolder:null,
+ sessionControlService:{stopSessionTurn:stop}};
+ const source=readFileSync(new URL('../register.ts',import.meta.url),'utf8');
+ const start=source.indexOf(' cancel: async (pluginId, taskId, inputClientIds, execution) => {');
+ const block=source.slice(start+' cancel: '.length,source.indexOf('\n },',start)+8);
+ const js=ts.transpileModule('return ('+block+');',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
+ const cancel=new Function(...Object.keys(deps),js)(...Object.values(deps));
+ const operation=cancel('p',run.taskId,[run.inputMessageId],f.execution);
+ const result=expect(operation).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
+ await started;await f.service.withUninstall('p',async()=>{});release();await result;
+ if(point==='restore')expect(remove).not.toHaveBeenCalled();
+ expect(stop).not.toHaveBeenCalled();
+});
+
describe('plugin ordinary task receipts', () => {
+ it('retains user tasks and receipts but denies every old task capability after reinstall and restart', async () => {
+ const f = fixture(); const task = await f.create(); const run = await f.send();
+ const before = structuredClone([...f.tasks]);
+ const remove = vi.fn(async () => {});
+ await f.service.withUninstall('p',remove);
+ expect(remove).toHaveBeenCalledOnce();
+ expect([...f.tasks]).toEqual(before);
+ expect(f.rows.has(task.taskId)).toBe(true);
+ expect(f.rows.has(run.runId)).toBe(true);
+ // The new installation remains authorized under the same plugin ID.
+ const restarted = createPluginTaskService(f.deps);
+ for (const service of [f.service,restarted]) {
+ expect((await service.list('p')).items).toEqual([]);
+ const denied = [
+ () => service.get('p',task.taskId),
+ () => service.create('p',{requestKey:'create',title:'Test'}),
+ () => service.send('p',{taskId:task.taskId,requestKey:'new',expectedRevision:1,text:'hello'}),
+ () => service.getRun('p',run.runId), () => service.listRuns('p',task.taskId),
+ () => service.cancel('p',run.runId),
+ () => service.accept(task.taskId,{clientId:run.inputMessageId},f.execution),
+ () => service.assertDispatch('p',task.taskId),
+ ];
+ for (const operation of denied) await expect(operation()).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
+ }
+ const fresh = await restarted.create('p',{requestKey:'new-install',title:'Test'});
+ expect(fresh.taskId).not.toBe(task.taskId);
+ expect(f.tasks.size).toBe(2);
+ expect(f.deps.cancel).not.toHaveBeenCalled();
+ });
+ it('serializes uninstall after an admitted create and retains normal-update ownership', async () => {
+ const f = fixture(); let release!:()=>void, entered!:()=>void;
+ const barrier=new Promise<void>(resolve=>{release=resolve;});
+ const started=new Promise<void>(resolve=>{entered=resolve;});
+ f.deps.resolveRoute=async()=>{entered();await barrier;return f.route;};
+ const create=f.create(); await started;
+ let removed=false;
+ const uninstall=f.service.withUninstall('p',async()=>{removed=true;});
+ await Promise.resolve();expect(removed).toBe(false);
+ release();const task=await create;await uninstall;
+ await expect(f.service.get('p',task.taskId)).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
+ const other=fixture();const original=await other.create();
+ expect(await createPluginTaskService(other.deps).create('p',{requestKey:'create',title:'Test'})).toEqual(original);
+ });
+ it.each(['getRun','listRuns'] as const)('rechecks ownership after delayed %s observation', async kind => {
+ const f=fixture();const run=await f.send();let release!:()=>void,entered!:()=>void;
+ const barrier=new Promise<void>(resolve=>{release=resolve;});const started=new Promise<void>(resolve=>{entered=resolve;});
+ f.deps.inspect=async()=>{entered();await barrier;return {execution:null,pending:[]};};
+ const operation=kind==='getRun'?f.service.getRun('p',run.runId):f.service.listRuns('p',run.taskId);
+ const result=expect(operation).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
+ await started;await f.service.withUninstall('p',async()=>{});release();await result;
+ });
+ it('does not remove the package if durable revocation fails and keeps revocation on removal failure', async () => {
+ const f=fixture();const task=await f.create();const remove=vi.fn(async()=>{});
+ const revoke=f.deps.store.revokePlugin;
+ f.deps.store.revokePlugin=async()=>{throw Error('storage unavailable');};
+ await expect(f.service.withUninstall('p',remove)).rejects.toThrow('storage unavailable');
+ expect(remove).not.toHaveBeenCalled();
+ f.deps.store.revokePlugin=revoke;
+ await expect(f.service.withUninstall('p',async()=>{throw Error('package removal failed');})).rejects.toThrow('package removal failed');
+ await expect(f.service.get('p',task.taskId)).rejects.toMatchObject({code:'TASK_NOT_FOUND'});
+ });
it('binds isolated workspace intent to creation and idempotency', async () => {
const f = fixture();
const input = { requestKey: 'isolated', title: 'Test', isolatedWorkspace: true };
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
index 2f482cd981..e18ebdf653 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/pluginTaskStorePagination.test.ts
@@ -4,6 +4,30 @@ import { expect, it } from 'vitest';
import type { DbClient } from '../../localDb/client/DbClient.js';
import { createPluginTaskStore } from '../pluginTaskStore.js';
+it('durably revokes only create ownership while retaining plans, run results and request identities', async () => {
+ const sqlite=new Database(':memory:');
+ try {
+ sqlite.exec(`CREATE TABLE plugin_task_requests(id TEXT PRIMARY KEY, plugin_id TEXT,
+ operation TEXT, target_id TEXT, request_key TEXT, fingerprint TEXT, payload TEXT,
+ revision INTEGER, created_at INTEGER)`);
+ const db={drizzle:drizzle(sqlite)} as unknown as DbClient;
+ const store=createPluginTaskStore(db);
+ const add=sqlite.prepare('INSERT INTO plugin_task_requests VALUES (?, ?, ?, ?, ?, ?, ?, 0, 1)');
+ add.run('task','p','create','','original','hash',JSON.stringify({title:'keep',teamPlan:{items:[]}}));
+ add.run('broken','p','create','','broken-key','hash','{bad');
+ add.run('run','p','send','task','send-key','hash','{"status":"completed"}');
+ add.run('other','q','create','','other-key','hash','{}');
+ await store.revokePlugin('p');
+ const restarted=createPluginTaskStore(db);
+ const row=await restarted.find('p','create','','original');
+ expect(row).toMatchObject({id:'task',requestKey:'original',revision:1});
+ expect(JSON.parse(row!.payload)).toEqual({title:'keep',teamPlan:{items:[]},ownershipRevoked:true});
+ expect(JSON.parse((await restarted.get('broken'))!.payload)).toEqual({ownershipRevoked:true});
+ expect(await restarted.get('run')).toMatchObject({payload:'{"status":"completed"}',revision:0});
+ expect(await restarted.get('other')).toMatchObject({payload:'{}',revision:0});
+ } finally { sqlite.close(); }
+});
+
it('pages by creation time and ID without losing later records with smaller UUIDs', async () => {
const sqlite = new Database(':memory:');
try {
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
index 2802eaef9a..29b41bf0e5 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskService.ts
@@ -18,6 +18,14 @@ export interface PluginTaskReceipt {
revision: number;
createdAt: number;
}
+function ownsTaskReceipt(receipt: PluginTaskReceipt | undefined, pluginId: string): boolean {
+ if (!receipt || receipt.pluginId !== pluginId || receipt.operation !== 'create') return false;
+ try {
+ const payload = JSON.parse(receipt.payload);
+ return !!payload && typeof payload === 'object' && !Array.isArray(payload)
+ && payload.ownershipRevoked !== true;
+ } catch { return false; }
+}
export interface PluginTaskStore {
get(id: string): Promise<PluginTaskReceipt | undefined>;
find(
@@ -36,6 +44,7 @@ export interface PluginTaskStore {
forSession(taskId: string): Promise<PluginTaskReceipt[]>;
insert(row: PluginTaskReceipt): Promise<void>;
save(row: PluginTaskReceipt): Promise<void>;
+ revokePlugin(pluginId: string): Promise<void>;
}
export class PluginTaskError extends Error {
constructor(
@@ -139,10 +148,14 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
const ownTask = async (pluginId: string, taskId: string) => {
deps.assertAuthorized(pluginId);
const receipt = await deps.store.get(taskId);
- if (!receipt || receipt.pluginId !== pluginId || receipt.operation !== 'create')
+ if (!ownsTaskReceipt(receipt, pluginId))
return fail('TASK_NOT_FOUND', 'Task not found');
const view = await deps.readSession(taskId);
if (!view || view.status === 'deleted') return fail('TASK_NOT_FOUND', 'Task not found');
+ if (!ownsTaskReceipt(await deps.store.get(taskId), pluginId))
+ return fail('TASK_NOT_FOUND', 'Task not found');
+ deps.assertCurrent();
+ deps.assertAuthorized(pluginId);
return view;
};
const ownRun = async (pluginId: string, runId: string) => {
@@ -180,21 +193,31 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
const run = JSON.parse(row.payload) as PluginTaskRun;
if (terminal(run)) return run;
const observed = await deps.inspect(run.taskId);
- if (
- observed.pending.some((item) => queuedInputBelongsTo(item, (value) => ownsInput(run, value)))
- )
- return run;
- if (isSameSessionExecution(observed.execution, run.execution)) return run;
- // Lack of a terminal is not success. Never replay an ambiguously dispatched input.
- run.status = 'reconciling';
- run.error =
- 'No matching live execution or pending input; inspect the task before sending a new request.';
- return run;
+ return exclusive(async () => {
+ // Native settlement/acceptance may have committed while inspection waited.
+ // Re-read behind that same receipt queue, with uninstall ownership checked.
+ const latest = await ownRun(row.pluginId, row.id);
+ const current = JSON.parse(latest.payload) as PluginTaskRun;
+ if (terminal(current) || latest.revision !== row.revision) return current;
+ if (observed.pending.some((item) => queuedInputBelongsTo(item, (value) => ownsInput(current, value))))
+ return current;
+ if (isSameSessionExecution(observed.execution, current.execution)) return current;
+ // Lack of a terminal is not success. Never replay an ambiguously dispatched input.
+ current.status = 'reconciling';
+ current.error = 'No matching live execution or pending input; inspect the task before sending a new request.';
+ return current;
+ });
};
return {
// Host-only native lifecycle work shares send/cancel's drain. Do not use
// exclusive here: native close callbacks may enqueue receipt writes.
completeOperation,
+ /** Retain receipts and user content, but never reuse an uninstalled installation's ownership. */
+ withUninstall: (pluginId: string, remove: () => Promise<void>) => exclusive(async () => {
+ await deps.store.revokePlugin(pluginId);
+ deps.assertCurrent();
+ await remove();
+ }),
/** Account teardown awaits already accepted writes before closing this DB. */
drain: async () => {
let pending: Promise<unknown>, active: Promise<unknown>;
@@ -264,6 +287,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
const rows = await deps.store.list(pluginId, 'create', null, after, limit);
const items = [];
for (const row of rows) {
+ if (!ownsTaskReceipt(row, pluginId)) continue;
const view = await deps.readSession(row.id);
if (view && view.status !== 'deleted') items.push(view);
}
@@ -344,6 +368,7 @@ export function createPluginTaskService(deps: PluginTaskServiceDeps) {
return deps.store.list(pluginId, 'send', taskId, after, limit);
});
const items = await Promise.all(rows.map(reconcile));
+ await exclusive(() => ownTask(pluginId, taskId));
deps.assertCurrent();
deps.assertAuthorized(pluginId);
return { items, nextCursor: rows.length === limit ? rows.at(-1)!.id : null };
diff --git a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
index d028640836..f2320d8475 100644
--- a/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
+++ b/apps/desktop/src/main/maker-ipc/pluginTaskStore.ts
@@ -1,4 +1,4 @@
-import { and, asc, eq, gt, or } from 'drizzle-orm';
+import { and, asc, eq, gt, or, sql } from 'drizzle-orm';
import type { DbClient } from '../localDb/client/DbClient.js';
import { pluginTaskRequests } from '../localDb/schema.js';
import type { PluginTaskStore } from './pluginTaskService.js';
@@ -56,6 +56,13 @@ export function createPluginTaskStore(db: DbClient): PluginTaskStore {
insert: async (row) => {
await db.drizzle.insert(table).values(row);
},
+ revokePlugin: async (pluginId) => {
+ // Keep the identity/request key so reinstall cannot replay or recreate old tasks.
+ await db.drizzle.update(table).set({
+ payload: sql`json_set(CASE WHEN json_valid(${table.payload}) THEN CASE WHEN json_type(${table.payload}) = 'object' THEN ${table.payload} ELSE '{}' END ELSE '{}' END, '$.ownershipRevoked', json('true'))`,
+ revision: sql`${table.revision} + 1`,
+ }).where(and(eq(table.pluginId, pluginId), eq(table.operation, 'create')));
+ },
save: async (row) => {
const result = await db.drizzle
.update(table)
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 14c7bb6d77..f1d7f8f242 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4,7 +4,7 @@ import { PluginWriteAccessGate } from './pluginWriteAccessGate.js';
import { pluginWorkerCompletedAt } from './pluginWorkerCompletion.js';
import { createPluginTaskStore } from './pluginTaskStore.js';
import { controlOwnedSessionExecution, isSameSessionExecution, withdrawOwnedSessionInputs } from './sessionExecutionOwnership.js';
-import { setPluginTaskHandler, isPluginTaskAuthorized, getPluginTaskInstallRevision } from '../cindy-brain/index.js';
+import { setPluginTaskHandler, setPluginTaskUninstaller, isPluginTaskAuthorized, getPluginTaskInstallRevision } from '../cindy-brain/index.js';
import type { PluginTaskRoute, PluginTaskRequest } from '../../shared/pluginTasks.js';
import { createHash as pluginTaskConfigHash } from 'node:crypto';
import { finishCompanionEnvironmentRemoval } from '../bot-import/runtime.js';
@@ -10528,7 +10528,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
await inputCoordinator.ensureQueueRestored(taskId);
assertCurrent();
if (!inputCoordinator.isQueueRestored(taskId)) throw new PluginTaskError('HOST_NOT_READY', 'Task queue is restoring', true);
- await withdrawOwnedSessionInputs({ sessionId: taskId, queue: inputCoordinator, owns: value => { assertPlugin(pluginId); return inputClientIds.includes(value); }, flush: awaitAgentInputQueueSnapshotPersistence });
+ await withdrawOwnedSessionInputs({ sessionId: taskId, queue: {
+ ensureQueueRestored: async sessionId => {
+ await inputCoordinator.ensureQueueRestored(sessionId);
+ await pluginTaskServiceForCurrentOwner!().get(pluginId, taskId);
+ assertPlugin(pluginId);
+ },
+ getQueueControlSnapshot: sessionId => inputCoordinator.getQueueControlSnapshot(sessionId),
+ remove: (sessionId, clientId) => inputCoordinator.remove(sessionId, clientId),
+ }, owns: value => { assertPlugin(pluginId); return inputClientIds.includes(value); }, flush: awaitAgentInputQueueSnapshotPersistence });
assertCurrent();
if (!execution) return 'cancelled';
let stopped = false;
@@ -10536,7 +10544,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId: taskId, withSessionLock: withSessionRestartLock,
matches: () => getCurrentDbClientSnapshot() === snapshot && isPluginTaskAuthorized(pluginId) && isSameSessionExecution(readExecution(taskId), execution),
operation: async () => {
+ await pluginTaskServiceForCurrentOwner!().get(pluginId, taskId);
assertPlugin(pluginId);
+ if (!isSameSessionExecution(readExecution(taskId), execution)) { stopped = true; return; }
resetAutomaticRecoveryForExplicitStop(taskId);
contextOverflowRolloverHolder?.cancelRecovery(taskId);
const outcome = await sessionControlService.stopSessionTurn({ targetSessionId: taskId });
@@ -10795,6 +10805,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (getCurrentDbClientSnapshot() !== snapshot) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
const page = await getMessagesForHistory({ sessionIds: [request.taskId], workdir: null, fromMs: null, toMs: null,
agentKind: null, roles: null, includeRewound: false, limit: request.limit ?? 50, cursor, order: 'asc' });
+ await service.get(pluginId, request.taskId);
if (getCurrentDbClientSnapshot() !== snapshot) throw new PluginTaskError('PERMISSION_DENIED', 'Account changed');
return { items: page.items.map(({ id, clientId, role, content, createdAt }) => ({ id: clientId ?? id, role, content, createdAt })),
nextCursor: page.nextCursor ? JSON.stringify(page.nextCursor) : null };
@@ -10806,6 +10817,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
};
setPluginTaskHandler(handlePluginTask);
+ setPluginTaskUninstaller((pluginId, remove) => pluginTaskServiceForCurrentOwner!().withUninstall(pluginId, remove));
// Local task UI only. The plugin and device-link protocols have no recovery operation.
const pluginWriteAccessFromHost = async (event: Electron.IpcMainInvokeEvent, taskId: unknown, retry: boolean) => {
diff --git a/docs/dev-rules/plugin-task-api-implementation.md b/docs/dev-rules/plugin-task-api-implementation.md
index d94045cb56..62894bfdad 100644
--- a/docs/dev-rules/plugin-task-api-implementation.md
+++ b/docs/dev-rules/plugin-task-api-implementation.md
@@ -13,6 +13,7 @@
- 读取限定于本插件创建的任务;返回消息 clientId。list/listRuns 按 (createdAt, id) 排序,现有回执 ID 游标在同插件与目标内解析,不再只按随机 UUID 排序。列表是分页查询,不是增量订阅;刷新应从首页重扫,不能把游标当永久同步水位(同毫秒追加、系统时钟回退或既有回执终态更新均需刷新)。
- 取消只撤回自己的排队输入或其原生重试别名;停止前在 Session 锁内再次核对执行身份与插件权限。
- 请求跨账号切换后不能继续操作新账号数据库。禁用插件后不能继续发送或停止。
+- 用户通过插件页或市场卸载时,在删除插件包前持久撤销其旧任务归属;保留任务、消息、作答文件、成绩和回执。正常更新保留归属;卸载重装后旧任务和旧 requestKey 不再可用,新请求键可创建新任务。撤销写入失败则不删除包;删除包失败时已撤销的归属不回滚。此处不改变内置插件 orphan/audience 自动回收路径。
## 与伙伴的共用和隔离