π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(goal): gate work tasks with acceptance (#18623)
Arvin Xue41b6cb0dee4
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsnew file mode 100644index 00000000000..6ba07d54ce3--- /dev/null+++ b/apps/cli/src/commands/goal.test.ts@@ -0,0 +1,83 @@+import { Command } from 'commander';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { registerGoalCommand } from './goal';++const { mockClient } = vi.hoisted(() => ({+ mockClient: {+ goal: {+ tick: { mutate: vi.fn() },+ },+ },+}));++vi.mock('../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('../utils/logger', () => ({+ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },+}));++const createProgram = () => {+ const program = new Command();+ program.exitOverride();+ registerGoalCommand(program);+ return program;+};++const waitingResult = {+ goalId: 'goal-1',+ message: 'Task T-1 is running',+ nodeId: 'node-1',+ outcome: 'waiting_external',+ taskId: 'task-1',+};++describe('goal run command', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });++ it('prints a repeated waiting state only once', async () => {+ mockClient.goal.tick.mutate+ .mockResolvedValueOnce({ data: waitingResult })+ .mockResolvedValueOnce({ data: waitingResult })+ .mockResolvedValueOnce({+ data: { goalId: 'goal-1', message: 'Goal achieved', outcome: 'achieved' },+ });++ await createProgram().parseAsync(['node', 'test', 'goal', 'run', 'goal-1', '--poll-ms', '0']);++ const output = vi+ .mocked(console.log)+ .mock.calls.map(([value]) => String(value))+ .join('\n');+ expect(output.match(/Task T-1 is running/g)).toHaveLength(1);+ expect(output).toContain('Goal achieved');+ });++ it('compresses repeated waiting states in JSON output', async () => {+ mockClient.goal.tick.mutate+ .mockResolvedValueOnce({ data: waitingResult })+ .mockResolvedValueOnce({ data: waitingResult })+ .mockResolvedValueOnce({ data: waitingResult })+ .mockResolvedValueOnce({+ data: { goalId: 'goal-1', message: 'Goal achieved', outcome: 'achieved' },+ });++ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'run',+ 'goal-1',+ '--poll-ms',+ '10',+ '--json',+ ]);++ const result = JSON.parse(String(vi.mocked(console.log).mock.calls.at(-1)?.[0]));+ expect(result).toHaveLength(2);+ expect(result[0]).toMatchObject({ pollCount: 3, waitedMs: 30 });+ expect(result[1]).toMatchObject({ outcome: 'achieved' });+ });+});diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex a56287ac57e..41896da9f96 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -9,6 +9,18 @@ import { log } from '../utils/logger';const nodeIcon = { decision: 'β', finding: 'β', problem: 'β', work: 'β£' } as const;const terminalOutcomes = new Set(['achieved', 'waiting_human', 'no_progress', 'failed']);+interface GoalRunTickResult extends GoalTickResult {+ pollCount?: number;+ waitedMs?: number;+}++const isSameWaitingState = (previous: GoalRunTickResult | undefined, current: GoalTickResult) =>+ previous?.outcome === 'waiting_external' &&+ current.outcome === 'waiting_external' &&+ previous.message === current.message &&+ previous.nodeId === current.nodeId &&+ previous.taskId === current.taskId;+function printGraph(graph: GoalGraphSnapshot) {console.log(`\n${pc.bold(graph.goal.title)} ${pc.dim(graph.goal.id)} [${graph.goal.status}]`);if (graph.goal.requirement) console.log(`${pc.dim('Requirement:')} ${graph.goal.requirement}`);@@ -111,13 +123,23 @@ export function registerGoalCommand(program: Command) {.option('--json', 'Output tick results as JSON').action(async (id: string, options: { json?: boolean; maxTicks: string; pollMs: string }) => {const client = await getTrpcClient();- const results: GoalTickResult[] = [];+ const results: GoalRunTickResult[] = [];const maxTicks = Number.parseInt(options.maxTicks, 10);const pollMs = Number.parseInt(options.pollMs, 10);for (let index = 0; index < maxTicks; index++) {const { data } = await client.goal.tick.mutate({ id });- results.push(data);- if (!options.json) printTick(data);+ const previous = results.at(-1);+ if (isSameWaitingState(previous, data)) {+ previous.pollCount = (previous.pollCount ?? 1) + 1;+ previous.waitedMs = (previous.waitedMs ?? pollMs) + pollMs;+ } else {+ results.push(+ data.outcome === 'waiting_external'+ ? { ...data, pollCount: 1, waitedMs: pollMs }+ : data,+ );+ if (!options.json) printTick(data);+ }if (terminalOutcomes.has(data.outcome)) break;if (data.outcome === 'waiting_external') {await new Promise((resolve) => setTimeout(resolve, pollMs));@@ -125,7 +147,7 @@ export function registerGoalCommand(program: Command) {}if (options.json) outputJson(results);const last = results.at(-1);- if (last && !terminalOutcomes.has(last.outcome) && results.length === maxTicks) {+ if (last && !terminalOutcomes.has(last.outcome)) {log.warn(`Stopped after ${maxTicks} ticks; rerun to continue.`);}});diff --git a/apps/server/src/router-hono/workflows/verify/handlers/onEvidenceComplete.ts b/apps/server/src/router-hono/workflows/verify/handlers/onEvidenceComplete.tsnew file mode 100644index 00000000000..bfc1d63f658--- /dev/null+++ b/apps/server/src/router-hono/workflows/verify/handlers/onEvidenceComplete.ts@@ -0,0 +1,28 @@+import type { Context } from 'hono';++import { getServerDB } from '@/database/server';+import { runVerifyAfterEvidenceSubmission } from '@/server/services/verify/lifecycle';++interface OnEvidenceCompletePayload {+ deliverable: string;+ goal: string;+ parentOperationId: string;+ userId: string;+ workspaceId?: string;+}++export async function onEvidenceComplete(c: Context) {+ const body = (await c.req.json()) as OnEvidenceCompletePayload;+ if (!body.parentOperationId || !body.userId || typeof body.deliverable !== 'string') {+ return c.json({ error: 'Missing required fields' }, 400);+ }++ const db = await getServerDB();+ await runVerifyAfterEvidenceSubmission(+ db,+ body.userId,+ { deliverable: body.deliverable, goal: body.goal ?? '', operationId: body.parentOperationId },+ body.workspaceId,+ );+ return c.json({ success: true });+}diff --git a/apps/server/src/router-hono/workflows/verify/index.ts b/apps/server/src/router-hono/workflows/verify/index.tsindex 514f7ba8a94..aa10b1b71e5 100644--- a/apps/server/src/router-hono/workflows/verify/index.ts+++ b/apps/server/src/router-hono/workflows/verify/index.ts@@ -1,11 +1,13 @@import { Hono } from 'hono';import { qstashAuth } from '../middlewares/qstashAuth';+import { onEvidenceComplete } from './handlers/onEvidenceComplete';import { onVerifierComplete } from './handlers/onVerifierComplete';import { sweep } from './handlers/sweep';const app = new Hono();+app.post('/on-evidence-complete', qstashAuth(), onEvidenceComplete);app.post('/on-verifier-complete', qstashAuth(), onVerifierComplete);app.post('/sweep', qstashAuth(), sweep);diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex f68157f6445..ddb877b4e31 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -3,6 +3,9 @@ import { type LobeChatDatabase } from '@lobechat/database';import { getTestDB } from '@lobechat/database/test-utils';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { AcceptanceModel } from '@/database/models/acceptance';+import { TaskModel } from '@/database/models/task';+import { taskRouter } from '../../task';import {cleanupTestUser,@@ -434,6 +437,28 @@ describe('Task Router Integration', () => {});describe('verify config', () => {+ it('moves verify config supplied at task creation into Acceptance', async () => {+ const task = await caller.create({+ config: {+ model: 'test-model',+ verify: { enabled: true, maxIterations: 2, requirement: 'Ship the artifact' },+ },+ instruction: 'Test',+ });++ const storedTask = await new TaskModel(serverDB, userId).findById(task.data.id);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ task.data.id,+ );++ expect(storedTask?.config).toEqual({ model: 'test-model' });+ expect(acceptance).toMatchObject({+ config: { enabled: true, maxIterations: 2 },+ requirement: 'Ship the artifact',+ });+ });+it('should set and retrieve verify config (round-trip)', async () => {const task = await caller.create({ instruction: 'Test' });@@ -466,6 +491,22 @@ describe('Task Router Integration', () => {verifyCriteriaIds: ['c1', 'c2'],verifyRubricId: 'rub_1',});++ const storedTask = await new TaskModel(serverDB, userId).findById(task.data.id);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ task.data.id,+ );+ expect(storedTask?.config).not.toHaveProperty('verify');+ expect(acceptance).toMatchObject({+ config: {+ enabled: true,+ maxIterations: 3,+ verifierAgentId: 'agt_codex',+ verifyCriteriaIds: ['c1', 'c2'],+ verifyRubricId: 'rub_1',+ },+ });});it('should clear a saved field when passed null', async () => {@@ -497,6 +538,27 @@ describe('Task Router Integration', () => {const verify = await caller.getVerifyConfig({ id: task.data.id });expect(verify.data).toEqual({ enabled: true, maxIterations: 4 });});++ it('preserves legacy verify fields when applying a partial Acceptance patch', async () => {+ const task = await caller.create({ instruction: 'Test' });+ await new TaskModel(serverDB, userId).updateVerifyConfig(task.data.id, {+ enabled: true,+ maxIterations: 4,+ verifierAgentId: 'legacy-verifier',+ });++ await caller.updateVerifyConfig({+ id: task.data.id,+ verify: { maxIterations: 2 },+ });++ const verify = await caller.getVerifyConfig({ id: task.data.id });+ expect(verify.data).toEqual({+ enabled: true,+ maxIterations: 2,+ verifierAgentId: 'legacy-verifier',+ });+ });});describe('run idempotency', () => {diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex c5abea01426..b0f7c44652f 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -17,7 +17,6 @@ import {} from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentOperationModel } from '@/database/models/agentOperation';import { ProjectModel } from '@/database/models/project';-import { TaskModel } from '@/database/models/task';import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';import { VerifyRunModel } from '@/database/models/verifyRun';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';@@ -233,14 +232,6 @@ export const acceptanceRouter = router({await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {requirement: input.requirement,});- // A Task acceptance is instantiated from tasks.config.verify. Mirror- // edits back to that source so the next run cannot restore an older goal.- if (input.subjectType === 'task') {- const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);- const task = await taskModel.resolve(input.subjectId);- if (!task) throw new Error('Task not found in the current workspace');- await taskModel.updateVerifyConfig(task.id, { requirement: input.requirement });- }return { id: aggregate.id, requirement: input.requirement };} catch (error) {throw new TRPCError({diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex efa4e57fe33..f1404d1be25 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -1,6 +1,6 @@import { TASK_STATUSES } from '@lobechat/builtin-tool-task';import type { GoalStatus } from '@lobechat/const/goal';-import type { TaskListItem, TaskParticipant } from '@lobechat/types';+import type { TaskListItem, TaskParticipant, TaskVerifyConfig } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -21,6 +21,8 @@ import { publishResourceEvent } from '@/server/services/resourceEvents';import { TaskService } from '@/server/services/task';import { TaskLifecycleService } from '@/server/services/taskLifecycle';import { TaskRunnerService } from '@/server/services/taskRunner';+import { AcceptanceService } from '@/server/services/verify/acceptanceService';+import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';import { hasWorkspaceScopedPermission } from '@/server/services/workspacePermission';import { TransferErrorCode } from '@/types/transferError';@@ -64,6 +66,15 @@ const taskProcedureWrite = taskProcedure.use(withScopedPermission('agent:update'// Resolution happens in the model layer via model.resolve()const idInput = z.object({ id: z.string() });+const taskVerifyConfigPatchSchema = z.object({+ enabled: z.boolean().nullish(),+ maxIterations: z.number().min(1).max(10).nullish(),+ requirement: z.string().nullish(),+ verifierAgentId: z.string().nullish(),+ verifyCriteriaIds: z.array(z.string()).nullish(),+ verifyRubricId: z.string().nullish(),+});+// Priority: 0=None, 1=Urgent, 2=High, 3=Normal, 4=Lowconst createSchema = z.object({assigneeAgentId: z.string().optional(),@@ -440,7 +451,31 @@ export const taskRouter = router({create: taskProcedureWrite.input(createSchema).mutation(async ({ input, ctx }) => {try {- const task = await ctx.taskService.createTask(input);+ const parsedVerify = taskVerifyConfigPatchSchema.safeParse(input.config?.verify);+ const { verify: _legacyVerify, ...taskConfig } = input.config ?? {};+ const task = await ctx.taskService.createTask({+ ...input,+ config: parsedVerify.success ? taskConfig : input.config,+ });+ try {+ if (parsedVerify.success) {+ const { requirement, ...rawConfig } = parsedVerify.data;+ const config = Object.fromEntries(+ Object.entries(rawConfig).filter(([, value]) => value != null),+ );+ await new AcceptanceService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).ensureForSubject('task', task.id, {+ config,+ requirement: requirement ?? undefined,+ });+ }+ } catch (error) {+ await ctx.taskModel.delete(task.id).catch(() => {});+ throw error;+ }return { data: task, message: 'Task created', success: true };} catch (error) {if (error instanceof TRPCError) throw error;@@ -1008,7 +1043,16 @@ export const taskRouter = router({try {const model = ctx.taskModel;const task = await resolveOrThrow(model, input.id);- return { data: model.getVerifyConfig(task) || null, success: true };+ const resolved = await resolveTaskAcceptance(+ ctx.serverDB,+ ctx.userId,+ task.id,+ ctx.workspaceId ?? undefined,+ );+ return {+ data: resolved ? { ...resolved.config, requirement: resolved.requirement } : null,+ success: true,+ };} catch (error) {if (error instanceof TRPCError) throw error;console.error('[task:getVerifyConfig]', error);@@ -1025,16 +1069,8 @@ export const taskRouter = router({idInput.merge(z.object({// `.nullish()` lets callers clear a saved field: `null` removes it- // (JSON can't send `undefined`), omission leaves it untouched. See- // TaskModel.updateVerifyConfig.- verify: z.object({- enabled: z.boolean().nullish(),- maxIterations: z.number().min(1).max(10).nullish(),- requirement: z.string().nullish(),- verifierAgentId: z.string().nullish(),- verifyCriteriaIds: z.array(z.string()).nullish(),- verifyRubricId: z.string().nullish(),- }),+ // (JSON can't send `undefined`), omission leaves it untouched.+ verify: taskVerifyConfigPatchSchema,}),),)@@ -1042,11 +1078,42 @@ export const taskRouter = router({const { id, verify } = input;try {const model = ctx.taskModel;- const resolved = await resolveOrThrow(model, id);- const task = await model.updateVerifyConfig(resolved.id, verify);- if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ const task = await resolveOrThrow(model, id);+ const acceptanceService = new AcceptanceService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );+ const resolvedAcceptance = await resolveTaskAcceptance(+ ctx.serverDB,+ ctx.userId,+ task.id,+ ctx.workspaceId ?? undefined,+ );+ const acceptance =+ resolvedAcceptance?.acceptance ??+ (await acceptanceService.ensureForSubject('task', task.id));+ const nextConfig = { ...acceptance.config } as Record<string, unknown>;+ for (const [key, value] of Object.entries(verify)) {+ if (key === 'requirement') continue;+ if (value === null) delete nextConfig[key];+ else if (value !== undefined) nextConfig[key] = value;+ }+ const requirement =+ verify.requirement === undefined ? acceptance.requirement : verify.requirement;+ const updated = await acceptanceService.acceptanceModel.updatePolicy(acceptance.id, {+ config: nextConfig,+ requirement,+ });+ if (!updated) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance policy not found' });+ }+ const data: TaskVerifyConfig = {+ ...(nextConfig as TaskVerifyConfig),+ requirement: requirement ?? undefined,+ };return {- data: model.getVerifyConfig(task),+ data,message: 'Verify config updated',success: true,};diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex ed2e6e21bfb..318f3ad0da9 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts@@ -159,6 +159,9 @@ const agentConfigPluginsArg = () =>const disabledPluginIdsArg = () =>mockCreateServerAgentToolsEngine.mock.calls[0][1].disabledPluginIds as string[];+const generateToolsArg = () =>+ mockCreateServerAgentToolsEngine.mock.results[0].value.generateToolsDetailed.mock.calls[0][0];+const toolManifestMapArg = () =>mockCreateOperation.mock.calls[0][0].toolSet.manifestMap as Record<string, unknown>;@@ -237,6 +240,29 @@ describe('AiAgentService.execAgent - three-state plugin config (pinned/auto/disaexpect(agentConfigPluginsArg()).toEqual(['plugin-a']);});+ it('restricts an orchestration turn to the exclusive plugin set', async () => {+ mockGetAgentConfig.mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ model: 'gpt-4',+ plugins: ['plugin-a'],+ provider: 'openai',+ systemRole: 'You are a helper',+ });++ await service.execAgent({+ agentId: 'agent-1',+ exclusivePluginIds: ['evidence-only'],+ prompt: 'Submit evidence',+ } as any);++ expect(agentConfigPluginsArg()).toEqual(['evidence-only']);+ expect(generateToolsArg()).toMatchObject({+ skipDefaultTools: true,+ toolIds: ['evidence-only'],+ });+ });+it('excludes a disabled composio/lobehub-skill manifest from the activator-discovery toolManifestMap', async () => {mockGetAgentConfig.mockResolvedValue({chatConfig: {},diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 97b12db1062..f567b6b7bbf 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -413,6 +413,12 @@ interface InternalExecAgentParams extends ExecAgentParams {ephemeralUserMessage?: string;/** Eval context for injecting environment prompts into system message */evalContext?: EvalContext;+ /**+ * Restrict this orchestration turn to exactly these plugins. Unlike+ * `additionalPluginIds`, this excludes the agent's pinned and default tools+ * as well as activator-discoverable manifests.+ */+ exclusivePluginIds?: string[];/** External files to upload to S3 and attach to the user message */files?: Array<{/** Pre-downloaded buffer (from adapter/platform layer) */@@ -1357,6 +1363,7 @@ export class AiAgentService {): Promise<ExecAgentResult> {const {additionalPluginIds,+ exclusivePluginIds,agentId,slug,prompt,@@ -3090,16 +3097,18 @@ export class AiAgentService {// `additionalPluginIds` so a mentioned-but-not-pinned tool (e.g. a custom MCP// connector) is both queried for manifests and enabled by the tools engine.const isGoalTurn = isGoalPrompt(prompt);- let agentPlugins: string[] = isGoalTurn- ? [GoalIdentifier]- : [- ...new Set([- ...getActivePluginIds(agentConfig?.plugins),- ...(additionalPluginIds || []),- ...(selectedToolIds || []),- ...(hasMentionedAgents ? ['lobe-agent-management'] : []),- ]),- ];+ let agentPlugins: string[] = exclusivePluginIds+ ? [...new Set(exclusivePluginIds)]+ : isGoalTurn+ ? [GoalIdentifier]+ : [+ ...new Set([+ ...getActivePluginIds(agentConfig?.plugins),+ ...(additionalPluginIds || []),+ ...(selectedToolIds || []),+ ...(hasMentionedAgents ? ['lobe-agent-management'] : []),+ ]),+ ];// Model metadata is needed both for tool support checks and agent-management context.const { loadModels } = await import('@/business/client/model-bank/loadModels');@@ -3736,18 +3745,20 @@ export class AiAgentService {});// 5f. Generate tools and manifest map- const pluginIds = [- ...new Set([- ...agentPlugins,- ...(disableLocalSystem ? [] : [LocalSystemManifest.identifier]),- RemoteDeviceManifest.identifier,- // Include LobeHub Skills and Composio tools so they are passed to generateToolsDetailed- ...activeLobehubSkillManifests.map((m) => m.identifier),- ...activeComposioManifests.map((m) => m.identifier),- // Connector manifests are also injected as additionalManifests- ...activeConnectorManifests.map((m) => m.identifier),- ]),- ];+ const pluginIds = exclusivePluginIds+ ? agentPlugins+ : [+ ...new Set([+ ...agentPlugins,+ ...(disableLocalSystem ? [] : [LocalSystemManifest.identifier]),+ RemoteDeviceManifest.identifier,+ // Include LobeHub Skills and Composio tools so they are passed to generateToolsDetailed+ ...activeLobehubSkillManifests.map((m) => m.identifier),+ ...activeComposioManifests.map((m) => m.identifier),+ // Connector manifests are also injected as additionalManifests+ ...activeConnectorManifests.map((m) => m.identifier),+ ]),+ ];log('execAgent: agent configured plugins: %O', pluginIds);const isManualMode = agentConfig.chatConfig?.skillActivateMode === 'manual';@@ -3756,6 +3767,7 @@ export class AiAgentService {excludeDefaultToolIds: isManualMode ? manualModeExcludeToolIds : undefined,model,provider,+ skipDefaultTools: !!exclusivePluginIds,toolIds: pluginIds,});@@ -3778,6 +3790,7 @@ export class AiAgentService {// Enforced here (not as a point deletion after the seed) so the later// Skill/Composio ingest loops cannot re-add the identifier.const isManifestIngestAllowed = (identifier: string): boolean => {+ if (exclusivePluginIds && !exclusivePluginIds.includes(identifier)) return false;if (disabledPluginIdSet.has(identifier)) return false;if (!canUseDevice && isDeviceToolIdentifier(identifier)) return false;if (deviceLocked && REMOTE_DEVICE_TOOL_IDENTIFIERS.has(identifier)) return false;diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 5dae1ec35b3..b1ebad41ad4 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -2,8 +2,11 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';import { TaskModel } from '@/database/models/task';import {+ acceptances,+ agents,goalEdges,goalEvents,goalNodeDecisions,@@ -31,7 +34,9 @@ afterEach(async () => {await serverDB.delete(goalEvents);await serverDB.delete(goalNodes);await serverDB.delete(goals);+ await serverDB.delete(acceptances);await serverDB.delete(tasks);+ await serverDB.delete(agents);await serverDB.delete(users);});@@ -50,7 +55,7 @@ describe('GoalService', () => {expect(current.workVersions).toHaveLength(1);});- it('keeps long goal requirements in the task instruction without overflowing its description', async () => {+ it('keeps the overall requirement as background while making the current work authoritative', async () => {const service = new GoalService(serverDB, userId);const requirement = `Generate verified training data. ${'Detailed acceptance evidence. '.repeat(20)}`;const graph = await service.create({@@ -63,8 +68,44 @@ describe('GoalService', () => {const task = await new TaskModel(serverDB, userId).findById(created.taskId!);expect(created.outcome).toBe('advanced');- expect(task?.description).toHaveLength(255);+ expect(task?.description).toBe('Generate training data');expect(task?.instruction).toContain(requirement);+ expect(task?.instruction).toContain(+ 'Current Work contract (authoritative execution scope): Generate training data',+ );+ expect(task?.instruction).toContain('Do not implement, validate, or pre-empt any sibling');+ expect(task?.instruction).toContain(+ 'Do not invoke Acceptance skills or Acceptance CLI commands',+ );+ });++ it('gates every responsible task with a work-scoped Acceptance requirement', async () => {+ const service = new GoalService(serverDB, userId);+ const agentId = 'goal-work-verifier-agent';+ await serverDB.insert(agents).values({ id: agentId, title: 'Goal worker', userId });+ const graph = await service.create({+ agentId,+ requirement: 'Generate data, then train and evaluate a model.',+ title: 'Two-stage experiment',+ work: ['Generate isolated data'],+ });++ const created = await service.tick(graph.goal.id);+ const taskModel = new TaskModel(serverDB, userId);+ const task = await taskModel.findById(created.taskId!);+ const acceptance = await new AcceptanceModel(serverDB, userId).findBySubject(+ 'task',+ created.taskId!,+ );++ expect(taskModel.shouldPauseOnTopicComplete(task!)).toBe(false);+ expect(task?.config).not.toHaveProperty('verify');+ expect(acceptance).toMatchObject({ config: { enabled: true } });+ expect(acceptance?.config).not.toHaveProperty('verifierAgentId');+ expect(acceptance?.requirement).toContain('Verify only this Work: Generate isolated data.');+ expect(acceptance?.requirement).toContain(+ 'Ignore sibling and downstream Work deliverables; they are verified by their own Tasks.',+ );});it('advances create task -> finding -> achieved without treating task creation as completion', async () => {diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 865332c3062..e79d9f4976e 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -20,6 +20,7 @@ import { assertAgentUsableBy } from '@/database/utils/agent-access';import { TaskService } from '../task';import { TaskRunnerService } from '../taskRunner';+import { AcceptanceService } from '../verify/acceptanceService';const WORK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;const TASK_DESCRIPTION_MAX_LENGTH = 255;@@ -44,6 +45,7 @@ export interface CreateGoalNodeInput {/** Application service shared by CLI today and Graph UI/schedulers later. */export class GoalService {+ private readonly acceptanceService: AcceptanceService;private readonly goalModel: GoalModel;private readonly graphModel: GoalGraphModel;private readonly taskModel: TaskModel;@@ -56,6 +58,7 @@ export class GoalService {private readonly userId: string,private readonly workspaceId?: string,) {+ this.acceptanceService = new AcceptanceService(db, userId, workspaceId);this.goalModel = new GoalModel(db, userId, workspaceId);this.graphModel = new GoalGraphModel(db, userId, workspaceId);this.taskModel = new TaskModel(db, userId, workspaceId);@@ -264,9 +267,10 @@ export class GoalService {};}+ let acceptanceId: string | undefined;let task: TaskItem | undefined;try {- const description = frontier.description ?? graph.goal.requirement;+ const description = frontier.description ?? frontier.title;task = await this.taskService.createTask({assigneeAgentId: graph.goal.agentId ?? undefined,config: { checkpoint: { topic: { after: false } } },@@ -275,8 +279,18 @@ export class GoalService {name: frontier.title,projectId: graph.goal.projectId ?? undefined,});+ const acceptance = await this.acceptanceService.ensureForSubject('task', task.id, {+ config: { enabled: true },+ requirement: this.buildWorkAcceptanceRequirement(+ graph,+ frontier.title,+ frontier.description,+ ),+ });+ acceptanceId = acceptance.id;const bound = await this.graphModel.bindTask(goalId, frontier.id, task.id);if (!bound) {+ await this.acceptanceService.acceptanceModel.delete(acceptance.id);await this.taskModel.delete(task.id);return {goalId,@@ -286,6 +300,9 @@ export class GoalService {};}} catch (error) {+ if (acceptanceId) {+ await this.acceptanceService.acceptanceModel.delete(acceptanceId).catch(() => {});+ }if (task) {await this.taskModel.delete(task.id).catch((cleanupError) => {console.error('[GoalService.tick] failed to delete unbound task:', cleanupError);@@ -425,11 +442,32 @@ export class GoalService {description: string | null,) =>[- `Long-horizon goal: ${graph.goal.title}`,- graph.goal.requirement ? `Acceptance requirement: ${graph.goal.requirement}` : undefined,- `Current work objective: ${title}`,+ `Overall goal context (background only): ${graph.goal.title}`,+ graph.goal.requirement+ ? `Overall goal acceptance context (background only): ${graph.goal.requirement}`+ : undefined,+ `Current Work contract (authoritative execution scope): ${title}`,description,- 'Complete this work objective. Create implementation-level subtasks when useful. Return concrete evidence, key findings, and the recommended next action.',+ 'Execute only the Current Work contract. Do not implement, validate, or pre-empt any sibling or downstream Work node, even when the overall goal context describes it.',+ 'The complete requirements for this Work are included here. Do not inspect unrelated agent documents to recover requirements. Do not invoke Acceptance skills or Acceptance CLI commands during the main Work; a dedicated post-run phase will ask you to submit your evidence before an independent verifier judges it.',+ 'Create implementation-level subtasks when useful. Finish the operation once the Current Work deliverable and its concrete evidence are ready; Acceptance verification will decide whether this Task is complete.',+ 'Return the produced artifacts, evidence, key findings, and the recommended next action. Do not mark the overall Goal complete.',+ ]+ .filter(Boolean)+ .join('\n\n');++ private buildWorkAcceptanceRequirement = (+ graph: GoalGraphSnapshot,+ title: string,+ description: string | null,+ ) =>+ [+ `Verify only this Work: ${title}.`,+ description ? `Required Work outcome: ${description}` : undefined,+ graph.goal.requirement+ ? `Use this overall Goal requirement only to interpret requirements relevant to the current Work: ${graph.goal.requirement}`+ : undefined,+ 'Pass only when the current Work deliverable is complete and supported by concrete evidence. Ignore sibling and downstream Work deliverables; they are verified by their own Tasks.',].filter(Boolean).join('\n\n');diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex 2925c8320eb..d362fca6123 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -40,10 +40,16 @@ const { goalCreate, goalFindBySubject } = vi.hoisted(() => ({goalFindBySubject: vi.fn().mockResolvedValue(undefined),}));+const { resolveTaskAcceptance } = vi.hoisted(() => ({+ resolveTaskAcceptance: vi.fn(),+}));+vi.mock('@/database/models/goal', () => ({GoalModel: vi.fn(() => ({ create: goalCreate, findBySubject: goalFindBySubject })),}));+vi.mock('@/server/services/verify/taskAcceptance', () => ({ resolveTaskAcceptance }));+// AiAgentService pulls in ~14 sub-dependencies in its constructor; mock it so// the running-status branch in updateStatus doesn't drag them in.vi.mock('@/server/services/aiAgent', () => ({@@ -115,6 +121,7 @@ describe('TaskService', () => {vi.clearAllMocks();cancelScheduled.mockResolvedValue(undefined);scheduleNextTopic.mockResolvedValue('tick-new');+ resolveTaskAcceptance.mockResolvedValue(undefined);mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);(AgentModel as any).mockImplementation(() => mockAgentModel);(TaskModel as any).mockImplementation(() => mockTaskModel);@@ -185,6 +192,43 @@ describe('TaskService', () => {expect(result?.parent).toBeNull();});+ it('surfaces the effective inherited Acceptance policy', async () => {+ const task = {+ createdAt: null,+ heartbeatInterval: null,+ heartbeatTimeout: null,+ id: 'task_001',+ identifier: 'TASK-1',+ instruction: 'Do something',+ lastHeartbeatAt: null,+ parentTaskId: 'task_parent',+ priority: 'normal',+ status: 'todo',+ };+ mockTaskModel.resolve.mockResolvedValue(task);+ mockTaskModel.findAllDescendants.mockResolvedValue([]);+ mockTaskModel.getDependencies.mockResolvedValue([]);+ mockTaskTopicModel.findWithHandoff.mockResolvedValue([]);+ mockTaskModel.getComments.mockResolvedValue([]);+ mockTaskModel.getTreePinnedDocuments.mockResolvedValue({ nodeMap: {}, tree: [] });+ mockTaskModel.findByIds.mockResolvedValue([]);+ mockTaskModel.findById.mockResolvedValue(null);+ mockTaskModel.getCheckpointConfig.mockReturnValue({});+ resolveTaskAcceptance.mockResolvedValue({+ acceptance: { id: 'acceptance-child' },+ config: { enabled: true, maxIterations: 2 },+ requirement: 'Inherited contract',+ });++ const result = await new TaskService(db, userId, 'workspace-1').getTaskDetail('TASK-1');++ expect(result?.verify).toEqual({+ enabled: true,+ maxIterations: 2,+ requirement: 'Inherited contract',+ });+ });+it('should resolve parent task info when parentTaskId is set', async () => {const task = {assigneeAgentId: null,diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex 47c45c72464..9b141d21881 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -35,6 +35,7 @@ import { type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';import { type ReviewResult, TaskReviewService } from '../taskReview';import { TaskRunnerService } from '../taskRunner';import { createTaskSchedulerModule } from '../taskScheduler';+import { resolveTaskAcceptance } from '../verify/taskAcceptance';const emptyWorkspace: WorkspaceData = { nodeMap: {}, tree: [] };const UNTITLED_TOPIC_TITLE = 'Untitled';@@ -652,7 +653,7 @@ export class TaskService {// brief-type activities β the UI converges on Task Run. Briefs are therefore// not fetched/enriched here (see the omitted brief spread below). The brief// lifecycle, model and data are untouched; revert this to bring them back.- const [allDescendants, dependencies, directTopics, comments, workspace, goal] =+ const [allDescendants, dependencies, directTopics, comments, workspace, goal, acceptance] =await Promise.all([this.taskModel.findAllDescendants(task.id),this.taskModel.getDependencies(task.id),@@ -664,6 +665,9 @@ export class TaskService {new GoalModel(this.db, this.userId, this.workspaceId).findBySubject('task', task.id).catch(() => undefined),+ resolveTaskAcceptance(this.db, this.userId, task.id, this.workspaceId).catch(+ () => undefined,+ ),]);const allDescendantIds = allDescendants.map((s) => s.id);@@ -997,7 +1001,9 @@ export class TaskService {startedAt: task.startedAt ? new Date(task.startedAt).toISOString() : undefined,status: task.status,userId: task.assigneeUserId,- verify: this.taskModel.getVerifyConfig(task),+ verify: acceptance+ ? { ...acceptance.config, requirement: acceptance.requirement }+ : this.taskModel.getVerifyConfig(task),visibility: task.visibility,subtasks,activities: activities.length > 0 ? activities : undefined,diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.tsindex fefeee7f946..88a35c32b18 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts@@ -14,6 +14,7 @@ import type { LobeChatDatabase } from '@/database/type';import { extractFileIdsFromEditorData } from '@/server/services/file/extractFileIdsFromEditorData';import { resolveAttachmentMetadata } from '@/server/services/file/resolveAttachments';import { resolveGoalRoundBudget } from '@/server/services/verify/goalBudget';+import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';/** Cap on unresolved checks carried into the next round's prompt. */const MAX_GOAL_FAILED_CHECKS = 8;@@ -222,19 +223,26 @@ export async function buildTaskPrompt(const taskFiles = toFileMetas(taskFileIds);- // Delivery-acceptance (verify) context: resolve the task's verify config- // (with parent inheritance) and the referenced criteria so the builder knows+ // Delivery-acceptance context: resolve the Task's Acceptance policy and the+ // referenced criteria so the builder knows// what to self-evidence while it works. Run-time handles (verifyRunId /// checkItemId) don't exist yet at prompt-build time β the verify skill// resolves those at runtime from the builder's operationId.- const verifyConfig = await taskModel.resolveVerifyConfig(task.id).catch(() => undefined);- const verifyEnabled = !!verifyConfig && verifyConfig.enabled !== false;+ const resolvedAcceptance = await resolveTaskAcceptance(db, userId, task.id, workspaceId).catch(+ () => undefined,+ );+ const verifyConfig = resolvedAcceptance?.config;+ const verifyEnabled = !!resolvedAcceptance && verifyConfig?.enabled !== false;let verifyCriteria: Array<{required?: boolean;requiredEvidence?: Array<{ hint?: string; type: string }>;title: string;}> = [];- if (verifyEnabled && (verifyConfig.verifyRubricId || verifyConfig.verifyCriteriaIds?.length)) {+ if (+ verifyEnabled &&+ verifyConfig &&+ (verifyConfig.verifyRubricId || verifyConfig.verifyCriteriaIds?.length)+ ) {const criterionModel = new VerifyCriterionModel(db, userId, workspaceId);const rubricModel = new VerifyRubricModel(db, userId, workspaceId);const collected = (@@ -334,7 +342,7 @@ export async function buildTaskPrompt(criteria: verifyCriteria,enabled: true,maxIterations: verifyConfig?.maxIterations,- requirement: verifyConfig?.requirement,+ requirement: resolvedAcceptance?.requirement,}: undefined,subtasks: subtasks.map((s: any) => ({diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.tsnew file mode 100644index 00000000000..ad76ced5697--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts@@ -0,0 +1,90 @@+import type { SubmitAcceptanceEvidenceParams } from '@lobechat/builtin-tool-acceptance-evidence';+import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type { LobeChatDatabase } from '@/database/type';++import type { ServerRuntimeRegistration } from './types';++class AcceptanceEvidenceExecutionRuntime {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly operationId?: string,+ private readonly workspaceId?: string,+ ) {}++ submitEvidence = async (params: SubmitAcceptanceEvidenceParams) => {+ if (!this.operationId) return { error: 'NO_OPERATION', success: false };+ if (!params.checkItemId || !params.evidence?.length) {+ return { error: 'INVALID_ARGUMENTS', success: false };+ }+ if (params.evidence.some((item) => Boolean(item.content) === Boolean(item.fileId))) {+ return {+ content: 'Every evidence item must provide exactly one of content or fileId.',+ error: 'INVALID_EVIDENCE',+ success: false,+ };+ }++ const operation = await new AgentOperationModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).findById(this.operationId);+ if (!operation?.parentOperationId) return { error: 'NO_PARENT_OPERATION', success: false };++ const run = await new VerifyRunModel(this.db, this.userId, this.workspaceId).findByOperation(+ operation.parentOperationId,+ );+ const item = run?.plan?.find((candidate) => candidate.id === params.checkItemId);+ if (!run || !item) return { error: 'UNKNOWN_CRITERION', success: false };++ const result = await new VerifyCheckResultModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).upsertByCheckItem({+ checkItemId: item.id,+ checkItemIndex: item.index,+ checkItemTitle: item.title,+ operationId: operation.parentOperationId,+ required: item.required,+ verifierType: item.verifierType,+ verifyRunId: run.id,+ });++ await new VerifyEvidenceModel(this.db, this.userId, this.workspaceId).createMany(+ params.evidence.map((evidence) => ({+ capturedAt: new Date(),+ capturedBy: 'agent',+ checkResultId: result.id,+ content: evidence.content ?? null,+ description: evidence.description ?? null,+ fileId: evidence.fileId ?? null,+ type: evidence.type,+ })),+ );++ return {+ content: `Recorded ${params.evidence.length} evidence item(s) for "${item.title}".`,+ success: true,+ };+ };+}++export const acceptanceEvidenceRuntime: ServerRuntimeRegistration = {+ factory: (context) => {+ if (!context.userId || !context.serverDB) throw new Error('userId and serverDB are required');+ return new AcceptanceEvidenceExecutionRuntime(+ context.serverDB,+ context.userId,+ context.operationId,+ context.workspaceId,+ );+ },+ identifier: AcceptanceEvidenceIdentifier,+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.tsindex 621d8d93c9c..597a54c808d 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts@@ -9,6 +9,7 @@import { GoalIdentifier } from '@lobechat/builtin-tool-goal';import type { ToolExecutionContext } from '../types';+import { acceptanceEvidenceRuntime } from './acceptanceEvidence';import { activatorRuntime } from './activator';import { agentBuilderRuntime } from './agentBuilder';import { agentDocumentsRuntime } from './agentDocuments';@@ -69,6 +70,7 @@ const registerRuntimes = (runtimes: ServerRuntimeRegistration[]) => {// Register all server runtimesregisterRuntimes([+ acceptanceEvidenceRuntime,agentBuilderRuntime,webBrowsingRuntime,cloudSandboxRuntime,diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.tsindex e53caa529cc..41855cfd73c 100644--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts@@ -6,6 +6,7 @@ import { AcceptanceService } from '../acceptanceService';const mocks = vi.hoisted(() => ({attachToAcceptance: vi.fn(),findById: vi.fn(),+ findPolicyById: vi.fn(),findReportByRun: vi.fn(),findRunById: vi.fn(),ensureForSubject: vi.fn(),@@ -15,12 +16,15 @@ const mocks = vi.hoisted(() => ({setDecision: vi.fn(),taskResolve: vi.fn(),updateStatus: vi.fn(),+ updatePolicyStatus: vi.fn(),}));vi.mock('@/database/models/acceptance', () => ({AcceptanceModel: vi.fn(() => ({ensureForSubject: mocks.ensureForSubject,findById: mocks.findById,+ findPolicyById: mocks.findPolicyById,+ updatePolicyStatus: mocks.updatePolicyStatus,updateStatus: mocks.updateStatus,})),}));@@ -66,6 +70,7 @@ const acceptance = (status: string) => ({describe('AcceptanceService decision gating', () => {beforeEach(() => {vi.clearAllMocks();+ mocks.findPolicyById.mockImplementation((...args) => mocks.findById(...args));mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1 }]);});@@ -133,6 +138,21 @@ describe('AcceptanceService decision gating', () => {expect(mocks.attachToAcceptance).not.toHaveBeenCalled();});+ it('attaches a workspace task run through internal policy scope', async () => {+ mocks.findPolicyById.mockResolvedValue(acceptance('planned'));+ mocks.findRunById.mockResolvedValue({ acceptanceId: null, id: 'run-2' });+ mocks.attachToAcceptance.mockResolvedValue({+ acceptanceId: 'acc-1',+ id: 'run-2',+ roundIndex: 2,+ });++ await expect(service().attachPolicyRun('run-2', 'acc-1')).resolves.toMatchObject({+ acceptanceId: 'acc-1',+ });+ expect(mocks.attachToAcceptance).toHaveBeenCalledWith('run-2', 'acc-1', undefined);+ });+it.each(['delivered', 'errored'])('accepts a settled (%s) delivery', async (status) => {mocks.findById.mockResolvedValue(acceptance(status));diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.tsindex eb7bbe67d52..e715424ed98 100644--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts@@ -5,7 +5,7 @@ import { instantiateVerifyPlanOnStart } from '../planInstantiation';import { createRepairRunner } from '../repairService';const mocks = vi.hoisted(() => ({- acceptanceAttachRun: vi.fn(),+ acceptanceAttachPolicyRun: vi.fn(),acceptanceEnsureForSubject: vi.fn(),acceptanceUpdate: vi.fn(),agentExec: vi.fn(),@@ -17,7 +17,7 @@ const mocks = vi.hoisted(() => ({setMetadata: vi.fn(),setPlan: vi.fn(),taskFindById: vi.fn(),- taskResolveVerifyConfig: vi.fn(),+ taskAcceptanceResolve: vi.fn(),}));vi.mock('../goalLoop', () => ({@@ -27,7 +27,7 @@ vi.mock('../goalLoop', () => ({vi.mock('../acceptanceService', () => ({AcceptanceService: vi.fn(() => ({acceptanceModel: { update: mocks.acceptanceUpdate },- attachRun: mocks.acceptanceAttachRun,+ attachPolicyRun: mocks.acceptanceAttachPolicyRun,ensureForSubject: mocks.acceptanceEnsureForSubject,})),}));@@ -38,10 +38,13 @@ vi.mock('../planGenerator', () => ({})),}));+vi.mock('../taskAcceptance', () => ({+ resolveTaskAcceptance: mocks.taskAcceptanceResolve,+}));+vi.mock('@/database/models/task', () => ({TaskModel: vi.fn(() => ({findById: mocks.taskFindById,- resolveVerifyConfig: mocks.taskResolveVerifyConfig,})),}));@@ -71,9 +74,10 @@ describe('Verify acceptance lifecycle', () => {Object.values(mocks).forEach((mock) => mock.mockReset());});- it('creates and attaches the task acceptance when its verify plan is confirmed', async () => {- mocks.taskResolveVerifyConfig.mockResolvedValue({- enabled: true,+ it('attaches the verify run to the task acceptance that owns its policy', async () => {+ mocks.taskAcceptanceResolve.mockResolvedValue({+ acceptance: { id: 'acceptance-1' },+ config: { enabled: true },requirement: 'The novel is complete and coherent',});mocks.taskFindById.mockResolvedValue({@@ -83,7 +87,6 @@ describe('Verify acceptance lifecycle', () => {mocks.runFindByOperation.mockResolvedValueOnce(null).mockResolvedValueOnce({ id: 'run-1', plan });- mocks.acceptanceEnsureForSubject.mockResolvedValue({ id: 'acceptance-1' });await instantiateVerifyPlanOnStart(db,@@ -92,13 +95,21 @@ describe('Verify acceptance lifecycle', () => {'workspace-1',);- expect(mocks.acceptanceEnsureForSubject).toHaveBeenCalledWith('task', 'task-1', {- requirement: 'The novel is complete and coherent',+ expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('run-1', 'acceptance-1');+ });++ it('keeps an empty Acceptance opted out of verification', async () => {+ mocks.taskAcceptanceResolve.mockResolvedValue({+ acceptance: { id: 'acceptance-1' },+ config: {},});- expect(mocks.acceptanceUpdate).toHaveBeenCalledWith('acceptance-1', {- requirement: 'The novel is complete and coherent',++ await instantiateVerifyPlanOnStart(db, 'user-1', {+ operationId: 'operation-1',+ taskId: 'task-1',});- expect(mocks.acceptanceAttachRun).toHaveBeenCalledWith('run-1', 'acceptance-1');++ expect(mocks.generateDraftPlan).not.toHaveBeenCalled();});it('attaches an auto-repair verify run as the next round of the same acceptance', async () => {@@ -129,6 +140,6 @@ describe('Verify acceptance lifecycle', () => {expect(result).toEqual({ repairOperationId: 'repair-operation' });expect(mocks.agentExec).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-1' }));- expect(mocks.acceptanceAttachRun).toHaveBeenCalledWith('repair-run', 'acceptance-1');+ expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('repair-run', 'acceptance-1');});});diff --git a/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts b/apps/server/src/services/verify/__tests__/evidenceSubmission.test.tsnew file mode 100644index 00000000000..62542f6a3f9--- /dev/null+++ b/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts@@ -0,0 +1,77 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { startEvidenceSubmission } from '../evidenceSubmission';++const { execAgent } = vi.hoisted(() => ({ execAgent: vi.fn() }));++vi.mock('@/server/services/aiAgent', () => ({+ AiAgentService: vi.fn(() => ({ execAgent })),+}));++describe('startEvidenceSubmission', () => {+ beforeEach(() => {+ execAgent.mockReset().mockResolvedValue({ operationId: 'evidence-op' });+ });++ it('continues as the original builder in the same topic with only the evidence tool', async () => {+ const operation = {+ agentId: 'builder-agent',+ id: 'work-op',+ taskId: 'task-1',+ topicId: 'topic-1',+ } as any;++ await startEvidenceSubmission({+ db: {} as any,+ deliverable: 'artifact summary',+ goal: 'ship model',+ operation,+ plan: [+ {+ id: 'criterion-1',+ index: 0,+ onFail: 'manual',+ required: true,+ title: 'Model artifact exists',+ verifierConfig: {},+ verifierType: 'llm',+ },+ ],+ userId: 'user-1',+ });++ expect(execAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ exclusivePluginIds: ['lobe-acceptance-evidence'],+ agentId: 'builder-agent',+ appContext: { taskId: 'task-1', topicId: 'topic-1' },+ parentOperationId: 'work-op',+ suppressUserMessage: true,+ }),+ );+ const call = execAgent.mock.calls[0][0];+ expect(call.ephemeralUserMessage).toContain('criterion-1: Model artifact exists');+ expect(call.userInterventionConfig).toEqual({ approvalMode: 'headless' });+ expect(call.hooks[0].webhook.body).toMatchObject({+ deliverable: 'artifact summary',+ goal: 'ship model',+ parentOperationId: 'work-op',+ userId: 'user-1',+ });+ });++ it('rejects operations that cannot preserve builder identity and topic context', async () => {+ await expect(+ startEvidenceSubmission({+ db: {} as any,+ deliverable: '',+ goal: '',+ operation: { id: 'work-op' } as any,+ plan: [],+ userId: 'user-1',+ }),+ ).rejects.toThrow('no builder agent or topic');+ expect(execAgent).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.tsindex 0eb365d777f..769e9a0bc47 100644--- a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts@@ -1,20 +1,35 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';-import { runVerifyOnCompletion } from '../lifecycle';+import { runVerifyAfterEvidenceSubmission, runVerifyOnCompletion } from '../lifecycle';import { VERIFY_ABANDONED_MS } from '../staleness';-const { claimVerifying, execute, findByOperation, operationFindById, finalizeVerifyRun } =- vi.hoisted(() => ({- claimVerifying: vi.fn(),- execute: vi.fn(),- finalizeVerifyRun: vi.fn(),- findByOperation: vi.fn(),- operationFindById: vi.fn(),- }));+const {+ claimEvidenceCollection,+ claimVerifying,+ execute,+ findByOperation,+ operationFindById,+ finalizeVerifyRun,+ startEvidenceSubmission,+ updateStatus,+} = vi.hoisted(() => ({+ claimEvidenceCollection: vi.fn(),+ claimVerifying: vi.fn(),+ execute: vi.fn(),+ finalizeVerifyRun: vi.fn(),+ findByOperation: vi.fn(),+ operationFindById: vi.fn(),+ startEvidenceSubmission: vi.fn(),+ updateStatus: vi.fn(),+}));vi.mock('@/database/models/verifyRun', () => ({- VerifyRunModel: vi.fn(() => ({ findByOperation })),+ VerifyRunModel: vi.fn(() => ({+ claimEvidenceCollection,+ findByOperation,+ updateStatus,+ })),}));vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn(() => ({ findById: operationFindById })),@@ -35,22 +50,105 @@ vi.mock('../modelConfig', () => ({resolveVerifyModelConfig: vi.fn().mockResolvedValue({ model: 'm', provider: 'p' }),}));vi.mock('../settle', () => ({ finalizeVerifyRun }));+vi.mock('../evidenceSubmission', () => ({ startEvidenceSubmission }));+vi.mock('../taskAcceptance', () => ({+ resolveTaskAcceptance: vi.fn().mockResolvedValue({ config: { enabled: true } }),+}));const db = {} as any;const params = { deliverable: 'done', goal: 'ship it', operationId: 'op-1' };-const confirmedRun = { id: 'run-1', plan: [{ id: 'c1' }], planConfirmedAt: new Date() };+const confirmedRun = {+ id: 'run-1',+ plan: [{ id: 'c1' }],+ planConfirmedAt: new Date(),+ status: 'planned',+};describe('runVerifyOnCompletion β verification claim', () => {beforeEach(() => {- [claimVerifying, execute, finalizeVerifyRun, findByOperation, operationFindById].forEach((m) =>- m.mockReset(),- );+ [+ claimEvidenceCollection,+ claimVerifying,+ execute,+ finalizeVerifyRun,+ findByOperation,+ operationFindById,+ startEvidenceSubmission,+ updateStatus,+ ].forEach((m) => m.mockReset());findByOperation.mockResolvedValue(confirmedRun);operationFindById.mockResolvedValue({ id: 'op-1', model: 'm', provider: 'p', taskId: null });claimVerifying.mockResolvedValue(true);});+ it('starts builder evidence collection before judging a task-bound run', async () => {+ operationFindById.mockResolvedValue({+ agentId: 'builder',+ id: 'op-1',+ model: 'm',+ provider: 'p',+ taskId: 'task-1',+ topicId: 'topic-1',+ });+ claimEvidenceCollection.mockResolvedValue(true);++ await runVerifyOnCompletion(db, 'u1', params);++ expect(startEvidenceSubmission).toHaveBeenCalledWith(+ expect.objectContaining({ operation: expect.objectContaining({ id: 'op-1' }) }),+ );+ expect(claimVerifying).not.toHaveBeenCalled();+ expect(execute).not.toHaveBeenCalled();+ });++ it('does not let a redelivered task completion bypass active evidence collection', async () => {+ findByOperation.mockResolvedValue({ ...confirmedRun, status: 'collecting_evidence' });+ operationFindById.mockResolvedValue({ id: 'op-1', taskId: 'task-1' });+ claimEvidenceCollection.mockResolvedValue(false);++ await runVerifyOnCompletion(db, 'u1', params);++ expect(claimVerifying).not.toHaveBeenCalled();+ expect(execute).not.toHaveBeenCalled();+ });++ it('lets only evidence completion advance collection into verification', async () => {+ findByOperation.mockResolvedValue({ ...confirmedRun, status: 'collecting_evidence' });+ operationFindById.mockResolvedValue({+ id: 'op-1',+ model: 'm',+ provider: 'p',+ taskId: 'task-1',+ });++ await runVerifyAfterEvidenceSubmission(db, 'u1', params);++ expect(claimVerifying).toHaveBeenCalledTimes(1);+ expect(execute).toHaveBeenCalledTimes(1);+ });++ it('keeps an interrupted evidence verification retryable until it can be reclaimed', async () => {+ findByOperation.mockResolvedValue({ ...confirmedRun, status: 'verifying' });+ operationFindById.mockResolvedValue({ id: 'op-1', taskId: 'task-1' });+ claimVerifying.mockResolvedValue(false);++ await expect(runVerifyAfterEvidenceSubmission(db, 'u1', params)).rejects.toThrow(+ 'still in progress',+ );+ expect(execute).not.toHaveBeenCalled();+ });++ it('propagates evidence verification failures so the queue retries them', async () => {+ findByOperation.mockResolvedValue({ ...confirmedRun, status: 'collecting_evidence' });+ operationFindById.mockResolvedValue({ id: 'op-1', taskId: 'task-1' });+ execute.mockRejectedValue(new Error('judge unavailable'));++ await expect(runVerifyAfterEvidenceSubmission(db, 'u1', params)).rejects.toThrow(+ 'judge unavailable',+ );+ });+it('claims the run with the abandoned bound rather than reading its status', async () => {const before = Date.now();await runVerifyOnCompletion(db, 'u1', params);diff --git a/apps/server/src/services/verify/__tests__/taskAcceptance.test.ts b/apps/server/src/services/verify/__tests__/taskAcceptance.test.tsnew file mode 100644index 00000000000..3dd38cad596--- /dev/null+++ b/apps/server/src/services/verify/__tests__/taskAcceptance.test.ts@@ -0,0 +1,125 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { resolveTaskAcceptance } from '../taskAcceptance';++const mocks = vi.hoisted(() => ({+ acceptanceEnsure: vi.fn(),+ acceptanceFindPolicyBySubject: vi.fn(),+ acceptanceUpdatePolicy: vi.fn(),+ taskFindById: vi.fn(),+}));++vi.mock('@/database/models/acceptance', () => ({+ AcceptanceModel: vi.fn(() => ({+ ensureForSubject: mocks.acceptanceEnsure,+ findPolicyBySubject: mocks.acceptanceFindPolicyBySubject,+ updatePolicy: mocks.acceptanceUpdatePolicy,+ })),+}));++vi.mock('@/database/models/task', () => ({+ TaskModel: vi.fn(() => ({+ findById: mocks.taskFindById,+ getVerifyConfig: (task: { verify?: unknown }) => task.verify,+ })),+}));++const db = {} as never;++describe('resolveTaskAcceptance', () => {+ beforeEach(() => {+ Object.values(mocks).forEach((mock) => mock.mockReset());+ });++ it('uses Acceptance as the authoritative completion contract', async () => {+ mocks.acceptanceFindPolicyBySubject.mockResolvedValue({+ config: { maxIterations: 3, verifierAgentId: 'acceptance-agent' },+ id: 'acceptance-1',+ requirement: 'Acceptance requirement',+ });+ mocks.taskFindById.mockResolvedValue({ id: 'task-1', verify: { enabled: true } });++ const resolved = await resolveTaskAcceptance(db, 'user-1', 'task-1');++ expect(resolved).toMatchObject({+ acceptance: { id: 'acceptance-1' },+ config: { maxIterations: 3, verifierAgentId: 'acceptance-agent' },+ requirement: 'Acceptance requirement',+ });+ });++ it('materializes legacy task verify config into an Acceptance once', async () => {+ mocks.acceptanceFindPolicyBySubject.mockResolvedValue(null);+ mocks.taskFindById.mockResolvedValue({+ id: 'task-1',+ verify: {+ enabled: true,+ maxIterations: 2,+ requirement: 'Legacy requirement',+ verifyRubricId: 'rubric-1',+ },+ });+ mocks.acceptanceEnsure.mockResolvedValue({+ config: { enabled: true, maxIterations: 2, verifyRubricId: 'rubric-1' },+ id: 'acceptance-1',+ requirement: 'Legacy requirement',+ });++ const resolved = await resolveTaskAcceptance(db, 'user-1', 'task-1');++ expect(mocks.acceptanceEnsure).toHaveBeenCalledWith('task', 'task-1', {+ config: expect.objectContaining({+ enabled: true,+ maxIterations: 2,+ verifyRubricId: 'rubric-1',+ }),+ projectId: undefined,+ requirement: 'Legacy requirement',+ });+ expect(resolved?.acceptance.id).toBe('acceptance-1');+ });++ it('inherits the nearest parent Acceptance and snapshots it onto the child', async () => {+ mocks.taskFindById+ .mockResolvedValueOnce({ id: 'child', parentTaskId: 'parent' })+ .mockResolvedValueOnce({ id: 'parent', parentTaskId: null });+ mocks.acceptanceFindPolicyBySubject.mockResolvedValueOnce(null).mockResolvedValueOnce({+ config: { enabled: true, verifierAgentId: 'parent-verifier' },+ id: 'parent-acceptance',+ requirement: 'Parent contract',+ });+ mocks.acceptanceEnsure.mockResolvedValue({+ config: { enabled: true, verifierAgentId: 'parent-verifier' },+ id: 'child-acceptance',+ requirement: 'Parent contract',+ });++ const resolved = await resolveTaskAcceptance(db, 'user-1', 'child', 'workspace-1');++ expect(mocks.acceptanceEnsure).toHaveBeenCalledWith('task', 'child', {+ config: { enabled: true, verifierAgentId: 'parent-verifier' },+ projectId: undefined,+ requirement: 'Parent contract',+ });+ expect(resolved?.acceptance.id).toBe('child-acceptance');+ });++ it('prefers a child legacy policy over a parent Acceptance', async () => {+ mocks.acceptanceFindPolicyBySubject.mockResolvedValue(null);+ mocks.taskFindById.mockResolvedValue({+ id: 'child',+ parentTaskId: 'parent',+ verify: { enabled: true, maxIterations: 1 },+ });+ mocks.acceptanceEnsure.mockResolvedValue({+ config: { enabled: true, maxIterations: 1 },+ id: 'child-acceptance',+ });++ const resolved = await resolveTaskAcceptance(db, 'user-1', 'child');++ expect(mocks.acceptanceFindPolicyBySubject).toHaveBeenCalledTimes(1);+ expect(resolved?.config).toMatchObject({ enabled: true, maxIterations: 1 });+ });+});diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex 4d898333f17..43292d26a05 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -2,6 +2,7 @@ import { normalizeVerifySurface } from '@lobechat/const/verify';import type {AcceptanceAttachment,AcceptanceCheckReviewAction,+ AcceptanceConfig,AcceptanceRejectIntent,AcceptanceReviewAnnotation,AcceptanceStatus,@@ -475,11 +476,12 @@ export class AcceptanceService {ensureForSubject = async (subjectType: AcceptanceSubjectType,subjectId: string,- defaults?: { requirement?: string; title?: string },+ defaults?: { config?: AcceptanceConfig; requirement?: string; title?: string },): Promise<AcceptanceItem> => {await this.assertSubjectExists(subjectType, subjectId);const projectId = await this.resolveSubjectProjectId(subjectType, subjectId);return this.acceptanceModel.ensureForSubject(subjectType, subjectId, {+ config: defaults?.config,projectId,requirement: defaults?.requirement,...(subjectType === 'standalone' && defaults?.title@@ -521,6 +523,23 @@ export class AcceptanceService {const acceptance = await this.acceptanceModel.findById(acceptanceId);if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);+ return this.attachResolvedRun(runId, acceptance);+ };++ /** Attach a Task run using policy scope while preserving report visibility. */+ attachPolicyRun = async (runId: string, acceptanceId: string): Promise<VerifyRunItem> => {+ const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);+ if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);++ return this.attachResolvedRun(runId, acceptance);+ };++ private attachResolvedRun = async (+ runId: string,+ acceptance: AcceptanceItem,+ ): Promise<VerifyRunItem> => {+ const acceptanceId = acceptance.id;+// Idempotent for the re-ingest path (the CLI sidecar remembers the run):// an already-chained round keeps its index instead of being re-appended.const existing = await this.runModel.findById(runId);@@ -597,7 +616,7 @@ export class AcceptanceService {* round newer than the decision arrives.*/recomputeStatus = async (acceptanceId: string): Promise<AcceptanceStatus | null> => {- const acceptance = await this.acceptanceModel.findById(acceptanceId);+ const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);if (!acceptance) return null;if (acceptance.status === 'accepted' || acceptance.status === 'closed') {return acceptance.status;@@ -613,7 +632,7 @@ export class AcceptanceService {const report = await this.reportModel.findByRun(current.id);const status = statusFromRound(current, Boolean(report));if (status !== acceptance.status) {- await this.acceptanceModel.updateStatus(acceptanceId, status);+ await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);await this.mirrorGoalStatus(acceptance.subjectType, acceptance.subjectId, status);log('acceptance %s β %s (from round %d)', acceptanceId, status, current.roundIndex);}diff --git a/apps/server/src/services/verify/evidenceSubmission.ts b/apps/server/src/services/verify/evidenceSubmission.tsnew file mode 100644index 00000000000..05ff8c539a8--- /dev/null+++ b/apps/server/src/services/verify/evidenceSubmission.ts@@ -0,0 +1,78 @@+import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';+import type { VerifyCheckItem } from '@lobechat/types';++import type { AgentOperationItem } from '@/database/schemas/agentOperations';+import type { LobeChatDatabase } from '@/database/type';+import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';+import { AiAgentService } from '@/server/services/aiAgent';++const buildEvidencePrompt = (+ items: VerifyCheckItem[],+): string => `The task execution is complete. Submit the evidence you produced for every Acceptance criterion below.++${items.map((item) => `- ${item.id}: ${item.title}${item.description ? ` β ${item.description}` : ''}`).join('\n')}++Call submitEvidence once for each criterion. This is evidence collection only: do not assign verdicts and do not redo the implementation.`;++export const startEvidenceSubmission = async (params: {+ db: LobeChatDatabase;+ deliverable: string;+ goal: string;+ operation: AgentOperationItem;+ plan: VerifyCheckItem[];+ userId: string;+ workspaceId?: string;+}): Promise<string> => {+ const { db, deliverable, goal, operation, plan, userId, workspaceId } = params;+ if (!operation.agentId || !operation.topicId) {+ throw new Error('Task operation has no builder agent or topic for evidence submission');+ }++ const parentOperationId = operation.id;+ const hooks: AgentHook[] = [+ {+ handler: async () => {+ const { runVerifyAfterEvidenceSubmission } = await import('./lifecycle');+ await runVerifyAfterEvidenceSubmission(+ db,+ userId,+ {+ deliverable,+ goal,+ operationId: parentOperationId,+ },+ workspaceId,+ );+ },+ id: 'acceptance-evidence-on-complete',+ type: 'onComplete',+ webhook: {+ body: {+ deliverable,+ goal,+ parentOperationId,+ userId,+ ...(workspaceId ? { workspaceId } : {}),+ },+ delivery: 'qstash',+ fallback: 'none',+ url: '/api/workflows/verify/on-evidence-complete',+ },+ },+ ];++ const result = await new AiAgentService(db, userId, { workspaceId }).execAgent({+ agentId: operation.agentId,+ appContext: { taskId: operation.taskId, topicId: operation.topicId },+ autoStart: true,+ ephemeralUserMessage: buildEvidencePrompt(plan),+ exclusivePluginIds: [AcceptanceEvidenceIdentifier],+ hooks,+ parentOperationId,+ prompt: '',+ suppressUserMessage: true,+ userInterventionConfig: { approvalMode: 'headless' },+ });++ return result.operationId;+};diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.tsindex 42df7e90167..b54528e02c4 100644--- a/apps/server/src/services/verify/lifecycle.ts+++ b/apps/server/src/services/verify/lifecycle.ts@@ -7,11 +7,13 @@ import { VerifyRunModel } from '@/database/models/verifyRun';import type { LobeChatDatabase } from '@/database/type';import { createVerifierAgentRunner } from './agentVerifier';+import { startEvidenceSubmission } from './evidenceSubmission';import { VerifyExecutorService } from './executor';import { resolveVerifyModelConfig } from './modelConfig';import { finalizeVerifyRun } from './settle';import { VERIFY_ABANDONED_MS } from './staleness';import { VerifyStatusService } from './statusService';+import { resolveTaskAcceptance } from './taskAcceptance';const log = debug('lobe-server:verify-lifecycle');const MAX_TASK_DOCUMENT_CHARS = 80_000;@@ -73,11 +75,13 @@ export interface RunVerifyOnCompletionParams {* context (sub-operation forking); they are injected seams. Without a spawner* those items degrade gracefully (skipped / no repair).*/-export const runVerifyOnCompletion = async (+const executeVerifyLifecycle = async (db: LobeChatDatabase,userId: string,params: RunVerifyOnCompletionParams,workspaceId?: string,+ evidenceSubmitted = false,+ throwOnError = false,): Promise<void> => {try {const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(@@ -87,32 +91,59 @@ export const runVerifyOnCompletion = async (// Opt-in gate: only runs with a confirmed plan.if (!run?.plan?.length || !run.planConfirmedAt) return;- // Then claim it. Not a `status !== 'planned'` read: that let two completions- // landing together both start judging, and β the worse half β permanently- // shut the gate behind an attempt that entered `verifying` and then died,- // since every later attempt read the status it had already written. The- // claim is one conditional UPDATE, so exactly one caller proceeds and an- // abandoned attempt is re-enterable.+ const op = await new AgentOperationModel(db, userId, workspaceId).findById(params.operationId);+ if (!op) {+ log('op %s missing, cannot run verify', params.operationId);+ return;+ }++ if (op.taskId && !evidenceSubmitted) {+ const evidenceClaimed = await new VerifyRunModel(+ db,+ userId,+ workspaceId,+ ).claimEvidenceCollection(run.id);+ if (evidenceClaimed) {+ try {+ await startEvidenceSubmission({+ db,+ deliverable: params.deliverable,+ goal: params.goal,+ operation: op,+ plan: run.plan,+ userId,+ workspaceId,+ });+ } catch (error) {+ await new VerifyRunModel(db, userId, workspaceId).updateStatus(run.id, 'planned');+ throw error;+ }+ }+ return;+ }++ // Claim only after a task-bound builder has submitted evidence. Standalone+ // runs have no builder phase and enter verification directly.const claimed = await new VerifyStatusService(db, userId, workspaceId).claimVerifying(params.operationId,new Date(Date.now() - VERIFY_ABANDONED_MS),);- if (!claimed) return;-- const op = await new AgentOperationModel(db, userId, workspaceId).findById(params.operationId);- if (!op) {- log('op %s missing, cannot run verify', params.operationId);+ if (!claimed) {+ // A queued evidence callback that finds an unfinished judge must remain+ // retryable. A later delivery either reclaims the stale run or observes+ // its terminal status and exits normally.+ if (evidenceSubmitted && run.status === 'verifying') {+ throw new Error(`Verification for operation "${params.operationId}" is still in progress`);+ }return;}- // Task-bound runs may pin which agent verifies (TaskVerifyConfig.verifierAgentId,- // with subtask inheritance). Non-task runs leave it undefined β builtin fallback.+ // Task-bound runs may pin which agent verifies through its Acceptance policy.+ // Non-task runs leave it undefined β builtin fallback.let verifierAgentId: string | undefined;if (op.taskId) {- const verifyConfig = await new TaskModel(db, userId, workspaceId).resolveVerifyConfig(- op.taskId,- );- verifierAgentId = verifyConfig?.verifierAgentId ?? undefined;+ const resolvedAcceptance = await resolveTaskAcceptance(db, userId, op.taskId, workspaceId);+ verifierAgentId = resolvedAcceptance?.config.verifierAgentId ?? undefined;}const modelConfig = await resolveVerifyModelConfig(@@ -132,11 +163,12 @@ export const runVerifyOnCompletion = async (op.taskId,workspaceId,);+ const verificationGoal = params.goal || run.goal || '';const executor = new VerifyExecutorService(db, userId, workspaceId);await executor.execute({deliverable: resolvedDeliverable,- goal: params.goal,+ goal: verificationGoal,modelConfig,operationId: params.operationId,// `agent`-type checks run as the task-pinned verify agent (or the builtin@@ -166,7 +198,7 @@ export const runVerifyOnCompletion = async ({report: {deliverable: resolvedDeliverable,- goal: params.goal,+ goal: verificationGoal,modelConfig,},},@@ -174,5 +206,21 @@ export const runVerifyOnCompletion = async ();} catch (error) {log('runVerifyOnCompletion failed for op %s (non-fatal): %O', params.operationId, error);+ if (throwOnError) throw error;}};++export const runVerifyOnCompletion = async (+ db: LobeChatDatabase,+ userId: string,+ params: RunVerifyOnCompletionParams,+ workspaceId?: string,+): Promise<void> => executeVerifyLifecycle(db, userId, params, workspaceId, false);++/** The only entry point allowed to advance a task run out of evidence collection. */+export const runVerifyAfterEvidenceSubmission = async (+ db: LobeChatDatabase,+ userId: string,+ params: RunVerifyOnCompletionParams,+ workspaceId?: string,+): Promise<void> => executeVerifyLifecycle(db, userId, params, workspaceId, true, true);diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.tsindex 73d46d0a4d0..edea52ba560 100644--- a/apps/server/src/services/verify/planInstantiation.ts+++ b/apps/server/src/services/verify/planInstantiation.ts@@ -7,6 +7,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AcceptanceService } from './acceptanceService';import { VerifyPlanGeneratorService } from './planGenerator';+import { resolveTaskAcceptance } from './taskAcceptance';const log = debug('lobe-server:verify-plan-instantiation');@@ -19,9 +20,9 @@ export interface InstantiateVerifyPlanParams {* Auto-instantiate + auto-confirm a verify plan for a task-bound operation at run* start, so the completion-time gate (`runVerifyOnCompletion`) actually fires.*- * Without this, a task's `TaskVerifyConfig` (rubric / criteria) is never turned- * into a plan, so verify silently no-ops. We resolve the task's verify config- * (with subtask inheritance), materialize the rubric + ad-hoc criteria into a+ * Without this, a task's Acceptance policy (rubric / criteria) is never turned+ * into a plan, so verify silently no-ops. We resolve the Task's Acceptance and+ * materialize the rubric + ad-hoc criteria into a* plan (no AI generation β the task already picked its criteria), and confirm it* immediately (task scenario doesn't show a "confirm plan" step).*@@ -56,19 +57,21 @@ export const instantiateVerifyPlanOnStart = async (log('goal running transition failed for task %s (non-fatal): %O', params.taskId, error);}- const verifyConfig = await taskModel.resolveVerifyConfig(params.taskId);+ const resolvedAcceptance = await resolveTaskAcceptance(db, userId, params.taskId, workspaceId);+ if (!resolvedAcceptance) return;+ const { acceptance, config: verifyConfig, requirement } = resolvedAcceptance;// Opt-in to verify, then pick the plan shape:// - rubric / ad-hoc criteria β decomposed multi-item plan (existing path)// - else explicitly enabled OR a one-sentence acceptance requirement set// β coarse single holistic agent check// - no signal at all β verify stays off- if (!verifyConfig || verifyConfig.enabled === false) return;+ if (verifyConfig.enabled === false) return;const hasCriteria = Boolean(verifyConfig.verifyRubricId || verifyConfig.verifyCriteriaIds?.length,);const holistic =- !hasCriteria && (verifyConfig.enabled === true || Boolean(verifyConfig.requirement?.trim()));+ !hasCriteria && (verifyConfig.enabled === true || Boolean(requirement?.trim()));if (!hasCriteria && !holistic) return;const runModel = new VerifyRunModel(db, userId, workspaceId);@@ -87,7 +90,7 @@ export const instantiateVerifyPlanOnStart = async (// Fall back to a single agent-type holistic check when nothing decomposed.holisticFallback: holistic,operationId: params.operationId,- requirement: verifyConfig.requirement,+ requirement,verifyCriteriaIds: verifyConfig.verifyCriteriaIds,verifyRubricId: verifyConfig.verifyRubricId,});@@ -96,7 +99,7 @@ export const instantiateVerifyPlanOnStart = async (// so the completion gate treats it as ready instead of a pending draft.const run = await runModel.findByOperation(params.operationId);if (run?.plan?.length) {- // Carry the task's repair/re-run cap (TaskVerifyConfig.maxIterations) onto+ // Carry the Acceptance repair/re-run cap onto// the run so auto-repair honors it. Without this the repair path falls back// to the source rubric's config or the default, dropping the task cap for// ad-hoc-criteria or per-task-override tasks.@@ -110,15 +113,7 @@ export const instantiateVerifyPlanOnStart = async (// planned/verifying/repairing progress instead of waiting for an external// ingest command to create the aggregate after verification has finished.const acceptanceService = new AcceptanceService(db, userId, workspaceId);- const acceptance = await acceptanceService.ensureForSubject('task', params.taskId, {- requirement: verifyConfig.requirement?.trim() || goal,- });- // Task verify config is the source that produced this plan. Keep the- // aggregate goal in lockstep when a later run changes that source.- await acceptanceService.acceptanceModel.update(acceptance.id, {- requirement: verifyConfig.requirement?.trim() || goal,- });- await acceptanceService.attachRun(run.id, acceptance.id);+ await acceptanceService.attachPolicyRun(run.id, acceptance.id);log('instantiated + confirmed verify plan for op %s (%d items), acceptance %s',diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.tsindex b5bee57f4fa..e15d8a361ed 100644--- a/apps/server/src/services/verify/repairService.ts+++ b/apps/server/src/services/verify/repairService.ts@@ -143,7 +143,7 @@ export const createRepairRunner = (params: {// not an unrelated verification session. Attach it before it settles so// the aggregate immediately advances from "repairing" to the live round.if (sourceRun?.acceptanceId) {- await new AcceptanceService(db, userId, workspaceId).attachRun(+ await new AcceptanceService(db, userId, workspaceId).attachPolicyRun(repairRun.id,sourceRun.acceptanceId,);diff --git a/apps/server/src/services/verify/taskAcceptance.ts b/apps/server/src/services/verify/taskAcceptance.tsnew file mode 100644index 00000000000..300cdc9b757--- /dev/null+++ b/apps/server/src/services/verify/taskAcceptance.ts@@ -0,0 +1,100 @@+import type { AcceptanceConfig, TaskVerifyConfig } from '@lobechat/types';++import { AcceptanceModel } from '@/database/models/acceptance';+import { TaskModel } from '@/database/models/task';+import type { AcceptanceItem } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';++export interface ResolvedTaskAcceptance {+ acceptance: AcceptanceItem;+ config: AcceptanceConfig;+ requirement?: string;+}++const toAcceptanceConfig = (verify: TaskVerifyConfig): AcceptanceConfig => ({+ enabled: verify.enabled,+ maxIterations: verify.maxIterations,+ verifierAgentId: verify.verifierAgentId,+ verifyCriteriaIds: verify.verifyCriteriaIds,+ verifyRubricId: verify.verifyRubricId,+});++/**+ * Resolve the Acceptance that owns a Task's completion contract.+ *+ * `tasks.config.verify` is read only as a legacy compatibility source. The first+ * read materializes it into the Task's Acceptance; all new flows write the+ * Acceptance directly.+ */+export const resolveTaskAcceptance = async (+ db: LobeChatDatabase,+ userId: string,+ taskId: string,+ workspaceId?: string,+): Promise<ResolvedTaskAcceptance | undefined> => {+ const acceptanceModel = new AcceptanceModel(db, userId, workspaceId);+ const taskModel = new TaskModel(db, userId, workspaceId);+ const ownAcceptance = await acceptanceModel.findPolicyBySubject('task', taskId);+ const seen = new Set<string>();+ let currentTaskId: string | null = taskId;+ let inheritedConfig: AcceptanceConfig | undefined;+ let inheritedRequirement: string | undefined;+ let policyAcceptance: AcceptanceItem | undefined;+ let taskProjectId: string | null | undefined;++ while (currentTaskId && !seen.has(currentTaskId)) {+ seen.add(currentTaskId);+ const task = await taskModel.findById(currentTaskId);+ if (!task) break;+ if (currentTaskId === taskId) taskProjectId = task.projectId;++ const acceptance =+ currentTaskId === taskId+ ? ownAcceptance+ : await acceptanceModel.findPolicyBySubject('task', currentTaskId);+ const acceptanceConfig = acceptance?.config ?? {};+ const acceptanceRequirement = acceptance?.requirement?.trim() || undefined;+ if (Object.keys(acceptanceConfig).length > 0 || acceptanceRequirement) {+ policyAcceptance = acceptance;+ inheritedConfig = acceptanceConfig;+ inheritedRequirement = acceptanceRequirement;+ break;+ }++ const legacyVerify = taskModel.getVerifyConfig(task);+ if (legacyVerify) {+ inheritedConfig = toAcceptanceConfig(legacyVerify);+ inheritedRequirement = legacyVerify.requirement?.trim() || undefined;+ break;+ }++ currentTaskId = task.parentTaskId;+ }++ if (!inheritedConfig && !inheritedRequirement) return undefined;++ if (policyAcceptance && currentTaskId === taskId) {+ return {+ acceptance: policyAcceptance,+ config: policyAcceptance.config ?? {},+ requirement: policyAcceptance.requirement ?? undefined,+ };+ }++ const acceptance = ownAcceptance+ ? (await acceptanceModel.updatePolicy(ownAcceptance.id, {+ config: inheritedConfig ?? {},+ requirement: inheritedRequirement,+ }))!+ : await acceptanceModel.ensureForSubject('task', taskId, {+ config: inheritedConfig,+ projectId: taskProjectId,+ requirement: inheritedRequirement,+ });++ return {+ acceptance,+ config: acceptance.config ?? {},+ requirement: acceptance.requirement ?? undefined,+ };+};diff --git a/package.json b/package.jsonindex 0a2a8abaf97..6de29341230 100644--- a/package.json+++ b/package.json@@ -226,6 +226,7 @@"@lobechat/artifact-template": "workspace:*","@lobechat/builtin-agents": "workspace:*","@lobechat/builtin-skills": "workspace:*",+ "@lobechat/builtin-tool-acceptance-evidence": "workspace:*","@lobechat/builtin-tool-activator": "workspace:*","@lobechat/builtin-tool-agent-builder": "workspace:*","@lobechat/builtin-tool-agent-documents": "workspace:*",diff --git a/packages/builtin-tool-acceptance-evidence/package.json b/packages/builtin-tool-acceptance-evidence/package.jsonnew file mode 100644index 00000000000..19c66156709--- /dev/null+++ b/packages/builtin-tool-acceptance-evidence/package.json@@ -0,0 +1,12 @@+{+ "name": "@lobechat/builtin-tool-acceptance-evidence",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ }+}diff --git a/packages/builtin-tool-acceptance-evidence/src/index.ts b/packages/builtin-tool-acceptance-evidence/src/index.tsnew file mode 100644index 00000000000..ca7d4edce77--- /dev/null+++ b/packages/builtin-tool-acceptance-evidence/src/index.ts@@ -0,0 +1,7 @@+export { AcceptanceEvidenceIdentifier, AcceptanceEvidenceManifest } from './manifest';+export { systemPrompt } from './systemRole';+export {+ AcceptanceEvidenceApiName,+ type AcceptanceEvidenceType,+ type SubmitAcceptanceEvidenceParams,+} from './types';diff --git a/packages/builtin-tool-acceptance-evidence/src/manifest.ts b/packages/builtin-tool-acceptance-evidence/src/manifest.tsnew file mode 100644index 00000000000..2bf05c77848--- /dev/null+++ b/packages/builtin-tool-acceptance-evidence/src/manifest.ts@@ -0,0 +1,51 @@+import type { BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { AcceptanceEvidenceApiName } from './types';++export const AcceptanceEvidenceIdentifier = 'lobe-acceptance-evidence';++export const AcceptanceEvidenceManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ 'Submit evidence produced by your completed work for one Acceptance criterion. This records evidence only; it does not decide the verdict.',+ name: AcceptanceEvidenceApiName.submitEvidence,+ parameters: {+ properties: {+ checkItemId: {+ description: 'The exact criterion id from the evidence-submission instruction.',+ type: 'string',+ },+ evidence: {+ description: 'One or more concrete artifacts or observations produced by the work.',+ items: {+ properties: {+ content: { description: 'Inline evidence content.', type: 'string' },+ description: { description: 'What this evidence demonstrates.', type: 'string' },+ fileId: { description: 'An existing LobeHub artifact file id.', type: 'string' },+ type: {+ enum: ['markdown', 'screenshot', 'text', 'video'],+ type: 'string',+ },+ },+ required: ['type'],+ type: 'object',+ },+ type: 'array',+ },+ },+ required: ['checkItemId', 'evidence'],+ type: 'object',+ },+ },+ ],+ identifier: AcceptanceEvidenceIdentifier,+ meta: {+ avatar: 'π§Ύ',+ description: 'Submit builder-owned evidence for Acceptance criteria',+ title: 'Acceptance Evidence',+ },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/packages/builtin-tool-acceptance-evidence/src/systemRole.ts b/packages/builtin-tool-acceptance-evidence/src/systemRole.tsnew file mode 100644index 00000000000..5107327f9e9--- /dev/null+++ b/packages/builtin-tool-acceptance-evidence/src/systemRole.ts@@ -0,0 +1,8 @@+export const systemPrompt = `You are in the evidence-submission phase for work you just completed.++Your job is to cite concrete evidence already produced by your work for every Acceptance criterion. You are the builder, not the verifier:+- Submit evidence with submitEvidence for each criterion id in the instruction.+- Prefer precise command output, file paths, artifact file ids, screenshots, or concise factual notes.+- Do not decide whether a criterion passes and do not invent evidence.+- Use the conversation and artifacts from the completed task. Do not redo the task or start a new implementation.+- If evidence is missing, state that plainly in a note for that criterion.`;diff --git a/packages/builtin-tool-acceptance-evidence/src/types.ts b/packages/builtin-tool-acceptance-evidence/src/types.tsnew file mode 100644index 00000000000..29a6d698562--- /dev/null+++ b/packages/builtin-tool-acceptance-evidence/src/types.ts@@ -0,0 +1,15 @@+export const AcceptanceEvidenceApiName = {+ submitEvidence: 'submitEvidence',+} as const;++export type AcceptanceEvidenceType = 'markdown' | 'screenshot' | 'text' | 'video';++export interface SubmitAcceptanceEvidenceParams {+ checkItemId: string;+ evidence: Array<{+ content?: string;+ description?: string;+ fileId?: string;+ type: AcceptanceEvidenceType;+ }>;+}diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex dd30edd88d1..ff3b529bfb1 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -21,6 +21,7 @@"main": "./src/index.ts","dependencies": {"@icons-pack/react-simple-icons": "^13.13.0",+ "@lobechat/builtin-tool-acceptance-evidence": "workspace:*","@lobechat/builtin-tool-activator": "workspace:*","@lobechat/builtin-tool-agent-builder": "workspace:*","@lobechat/builtin-tool-agent-documents": "workspace:*",diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex 56648df9f07..c7d60962cfb 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -1,3 +1,4 @@+import { AcceptanceEvidenceManifest } from '@lobechat/builtin-tool-acceptance-evidence';import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';@@ -32,6 +33,7 @@ import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { WebOnboardingManifest } from '@lobechat/builtin-tool-web-onboarding';export const builtinToolIdentifiers: string[] = [+ AcceptanceEvidenceManifest.identifier,AgentBuilderManifest.identifier,AgentDocumentsManifest.identifier,AgentManagementManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex bdc09480308..4c523906041 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -1,3 +1,4 @@+import { AcceptanceEvidenceManifest } from '@lobechat/builtin-tool-acceptance-evidence';import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';@@ -163,6 +164,13 @@ export const runtimeManagedToolIds = [];const builtinToolRegistry: LobeBuiltinTool[] = [+ {+ discoverable: false,+ hidden: true,+ identifier: AcceptanceEvidenceManifest.identifier,+ manifest: AcceptanceEvidenceManifest,+ type: 'builtin',+ },{discoverable: false,hidden: true,diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.tsindex 17f711c6b73..fc1becb6e67 100644--- a/packages/const/src/verify.ts+++ b/packages/const/src/verify.ts@@ -59,6 +59,7 @@ export type VerifyUserDecision = (typeof verifyUserDecisions)[number];export const verifyRunStatuses = ['unverified','planned',+ 'collecting_evidence','verifying','passed','failed',@@ -323,6 +324,7 @@ export type VerifyEvidenceType = (typeof verifyEvidenceTypes)[number];/** Who / what captured an evidence artifact (provenance). */export const verifyEvidenceCapturedBy = [+ 'agent','agent-browser','cdp','cli',diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.tsindex a8c6b7b0556..983c1c9fdc0 100644--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts@@ -189,15 +189,6 @@ export class ToolNameResolver {}}- const payload: ChatToolPayload = {- apiName,- arguments: toolCall.function.arguments,- id: toolCall.id,- identifier,- thoughtSignature: toolCall.thoughtSignature,- type: (type ?? manifests[identifier]?.type ?? 'builtin') as any,- };-// Step 2: Resolve hashed apiName if neededif (apiName.startsWith(PLUGIN_SCHEMA_API_MD5_PREFIX) && manifests[identifier]) {const md5 = apiName.replace(PLUGIN_SCHEMA_API_MD5_PREFIX, '');@@ -207,10 +198,34 @@ export class ToolNameResolver {(api: LobeChatPluginApi) => this.genHash(api.name) === md5,);if (api) {- payload.apiName = api.name;+ apiName = api.name;}}+ const manifest = manifests[identifier];+ const matchedApi = manifest?.api.find((api: LobeChatPluginApi) => api.name === apiName);++ // Explicitly namespaced calls need the same current-turn allowlist check+ // as the bare-name recovery path. Topic history can contain tools from a+ // previous operation; accepting a syntactically valid old identifier here+ // would let it escape an evidence-only or otherwise restricted turn.+ if (offeredSet) {+ const directlyOffered = offeredSet.has(toolCall.function.name);+ if (!directlyOffered) {+ if (!manifest || !matchedApi) return null;+ if (!offeredSet.has(this.generate(identifier, apiName, manifest.type))) return null;+ }+ }++ const payload: ChatToolPayload = {+ apiName,+ arguments: toolCall.function.arguments,+ id: toolCall.id,+ identifier,+ thoughtSignature: toolCall.thoughtSignature,+ type: (type ?? manifest?.type ?? 'builtin') as any,+ };+return payload;}).filter(Boolean) as ChatToolPayload[];diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.tsindex 0f31e3439a9..d8f591c7dc4 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts@@ -897,6 +897,88 @@ describe('ToolNameResolver', () => {expect(result).toEqual([]);});+ it('should drop explicitly namespaced tools that were not offered this turn', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'lobe-local-system____submitEvidence' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-acceptance-evidence': {+ api: [{ description: '', name: 'submitEvidence', parameters: {} }],+ identifier: 'lobe-acceptance-evidence',+ meta: {},+ type: 'builtin' as const,+ },+ 'lobe-local-system': {+ api: [{ description: '', name: 'runCommand', parameters: {} }],+ identifier: 'lobe-local-system',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests, [+ 'lobe-acceptance-evidence____submitEvidence',+ ]);++ expect(result).toEqual([]);+ });++ it('should drop valid explicitly namespaced tools that were not offered this turn', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'lobe-local-system____runCommand' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ 'lobe-acceptance-evidence': {+ api: [{ description: '', name: 'submitEvidence', parameters: {} }],+ identifier: 'lobe-acceptance-evidence',+ meta: {},+ type: 'builtin' as const,+ },+ 'lobe-local-system': {+ api: [{ description: '', name: 'runCommand', parameters: {} }],+ identifier: 'lobe-local-system',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests, [+ 'lobe-acceptance-evidence____submitEvidence',+ ]);++ expect(result).toEqual([]);+ });++ it('should accept an explicitly offered tool when no prompt manifest is available', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'workspace____search' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const result = resolver.resolve(toolCalls, {}, ['workspace____search']);++ expect(result).toEqual([+ expect.objectContaining({+ apiName: 'search',+ id: 'call_1',+ identifier: 'workspace',+ }),+ ]);+ });+it('should treat an enabled call as unique when a disabled duplicate would have made it ambiguous', () => {const toolCalls = [{diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.tsindex e20b06076ba..348c0dcb912 100644--- a/packages/database/src/models/__tests__/acceptance.test.ts+++ b/packages/database/src/models/__tests__/acceptance.test.ts@@ -148,6 +148,36 @@ describe('AcceptanceModel', () => {expect(await otherModel.findBySubject('topic', topicId)).toBeUndefined();});+ it('shares workspace execution policies without exposing private reports', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'policy-ws', primaryOwnerId: userId, slug: 'policy-ws' })+ .returning();+ const creatorModel = new AcceptanceModel(serverDB, userId, workspace.id);+ const acceptance = await creatorModel.ensureForSubject('topic', topicId, {+ config: { enabled: true },+ });+ const collaboratorModel = new AcceptanceModel(serverDB, otherUserId, workspace.id);++ expect(await collaboratorModel.findBySubject('topic', topicId)).toBeUndefined();+ expect(await collaboratorModel.findPolicyBySubject('topic', topicId)).toMatchObject({+ id: acceptance.id,+ });+ expect(await collaboratorModel.findPolicyById(acceptance.id)).toMatchObject({+ id: acceptance.id,+ });+ await collaboratorModel.updatePolicy(acceptance.id, { requirement: 'Shared task contract' });+ await collaboratorModel.updatePolicyStatus(acceptance.id, 'verifying');+ expect((await creatorModel.findBySubject('topic', topicId))?.requirement).toBe(+ 'Shared task contract',+ );+ expect((await creatorModel.findBySubject('topic', topicId))?.status).toBe('verifying');++ expect(+ await new AcceptanceModel(serverDB, otherUserId).findPolicyBySubject('topic', topicId),+ ).toBeUndefined();+ });+it('reads many subjects statuses in one call, however old they are', async () => {const model = new AcceptanceModel(serverDB, userId);const olderTopicId = 'acceptance-test-topic-older';diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.tsindex 3b982f4dcb5..abfdb509e65 100644--- a/packages/database/src/models/__tests__/verifyRun.test.ts+++ b/packages/database/src/models/__tests__/verifyRun.test.ts@@ -74,6 +74,24 @@ describe('VerifyRunModel.claimVerifying', () => {expect(await statusOf(runId)).toBe('verifying');});+ it('advances a builder evidence run into verifying', async () => {+ const runId = await buildRun('op-claim-evidence');+ const model = new VerifyRunModel(serverDB, userId);+ await expect(model.claimEvidenceCollection(runId)).resolves.toBe(true);+ expect(await statusOf(runId)).toBe('collecting_evidence');++ await expect(model.claimVerifying(runId, staleBefore())).resolves.toBe(true);+ expect(await statusOf(runId)).toBe('verifying');+ });++ it('reserves evidence collection exactly once', async () => {+ const runId = await buildRun('op-evidence-once');+ const model = new VerifyRunModel(serverDB, userId);++ await expect(model.claimEvidenceCollection(runId)).resolves.toBe(true);+ await expect(model.claimEvidenceCollection(runId)).resolves.toBe(false);+ });+it('refuses a second claim while the first is still working', async () => {const runId = await buildRun('op-claim-2');const model = new VerifyRunModel(serverDB, userId);diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.tsindex e85c556cc7a..6f8c0b4d72d 100644--- a/packages/database/src/models/acceptance.ts+++ b/packages/database/src/models/acceptance.ts@@ -74,6 +74,39 @@ export class AcceptanceModel {});};+ /**+ * Resolve an execution policy for a subject. Unlike report-facing reads,+ * workspace policy lookup is shared by every workspace member: a private+ * Acceptance controls the shared Task even when another member executes it.+ * Personal scope remains owner-isolated.+ */+ findPolicyBySubject = async (subjectType: AcceptanceSubjectType, subjectId: string) => {+ const policyScope = buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },+ );++ return this.db.query.acceptances.findFirst({+ where: and(+ eq(acceptances.subjectType, subjectType),+ eq(acceptances.subjectId, subjectId),+ policyScope,+ ),+ });+ };++ /** Internal execution-policy lookup by id, independent of report visibility. */+ findPolicyById = async (id: string) => {+ if (!isUuid(id)) return undefined;+ const policyScope = buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },+ );+ return this.db.query.acceptances.findFirst({+ where: and(eq(acceptances.id, id), policyScope),+ });+ };+/*** The status of many subjects' acceptances in one read β for list surfaces* that must know each row's state without a request per row. Exact where the@@ -182,6 +215,38 @@ export class AcceptanceModel {return row;};+ /** Internal policy write counterpart to `findPolicyBySubject`. */+ updatePolicy = async (+ id: string,+ value: Partial<Pick<NewAcceptance, 'config' | 'requirement'>>,+ ): Promise<AcceptanceItem | undefined> => {+ const policyScope = buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },+ );+ const [row] = await this.db+ .update(acceptances)+ .set(value)+ .where(and(eq(acceptances.id, id), policyScope))+ .returning();+ return row;+ };++ /** Internal lifecycle transition counterpart to `updateStatus`. */+ updatePolicyStatus = async (id: string, status: AcceptanceStatus): Promise<void> => {+ const policyScope = buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },+ );+ await this.db+ .update(acceptances)+ .set({+ completedAt: TERMINAL_ACCEPTANCE_STATUSES.has(status) ? new Date() : null,+ status,+ })+ .where(and(eq(acceptances.id, id), policyScope));+ };+/*** Move the user-facing lifecycle state. `completedAt` is stamped when the* user's decision closes the loop (accepted / closed / rejected) and cleared when adiff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 73cb7753f6e..f43a6fbd448 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -533,7 +533,7 @@ export class VerifyRunModel {and(eq(verifyRuns.id, runId),or(- eq(verifyRuns.status, 'planned'),+ or(eq(verifyRuns.status, 'planned'), eq(verifyRuns.status, 'collecting_evidence')),and(eq(verifyRuns.status, 'verifying'), lt(verifyRuns.updatedAt, staleBefore)),),this.ownership(),@@ -544,6 +544,17 @@ export class VerifyRunModel {return claimed.length > 0;};+ /** Atomically reserve the builder-owned evidence-submission phase. */+ claimEvidenceCollection = async (runId: string): Promise<boolean> => {+ const claimed = await this.db+ .update(verifyRuns)+ .set({ status: 'collecting_evidence' })+ .where(and(eq(verifyRuns.id, runId), eq(verifyRuns.status, 'planned'), this.ownership()))+ .returning({ id: verifyRuns.id });++ return claimed.length > 0;+ };+/*** One page of runs stranded in `verifying` since before `olderThan`, across* all owners β the sweep's input (see `sweepStuckVerifyRuns`).diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.tsindex ee58c42b3fa..bd9dac275cf 100644--- a/packages/prompts/src/prompts/task/index.test.ts+++ b/packages/prompts/src/prompts/task/index.test.ts@@ -453,7 +453,9 @@ describe('buildTaskRunPrompt', () => {expect(result).toContain('login page renders (required)');expect(result).toContain('Β· evidence: screenshot β full page');expect(result).toContain('console is clean');- expect(result).toContain('lh acceptance run result submit');+ expect(result).toContain('include artifact paths, commands, and observed results');+ expect(result).toContain('an independent verifier decides whether this Task is complete');+ expect(result).not.toContain('lh acceptance run result submit');});it('should omit the verify section when verify is disabled', () => {diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.tsindex 786d6cca1b9..63aa117b99a 100644--- a/packages/prompts/src/prompts/task/index.ts+++ b/packages/prompts/src/prompts/task/index.ts@@ -634,9 +634,11 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin}}}- taskLines.push(' Use the `acceptance` skill to capture each artifact, then submit it with');taskLines.push(- ' `lh acceptance run result submit` (the skill resolves your run id and check item ids at runtime).',+ ' Produce concrete evidence while you work, and include artifact paths, commands, and observed results in your final response.',+ );+ taskLines.push(+ ' Do not judge the Acceptance. A dedicated post-run phase will ask you to submit the evidence you produced; an independent verifier decides whether this Task is complete.',);}diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex b4c1cdb1052..7d4e891bbe9 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -44,9 +44,10 @@ export interface CheckpointConfig {}/**- * Task-level delivery-acceptance (verify) gate config, persisted under- * `tasks.config.verify`. This is the authoritative source for a task run's- * verify gate β it is *not* unioned with any agent-level mount+ * Legacy Task-level delivery-acceptance gate config persisted under+ * `tasks.config.verify`. New flows persist this policy on the Task's Acceptance;+ * this shape remains for API compatibility and lazy migration. It is *not*+ * unioned with any agent-level mount* (`agencyConfig.verifyRubricId`) β the task config is authoritative and never* field-level merged with the agent-level rubric.*@@ -512,7 +513,7 @@ export interface TaskDetailData {topicCount?: number;updatedAt?: string;userId?: string | null;- /** Task-level verify (delivery-acceptance) gate config; `tasks.config.verify`. */+ /** Task Acceptance policy, exposed in the legacy TaskVerifyConfig API shape. */verify?: TaskVerifyConfig | null;/** Visibility within a workspace. 'public' is workspace-shared (default);* 'private' is only visible to the creator. Ignored in personal mode. */diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 7e4b4a5ba10..8c09fe38822 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -90,9 +90,9 @@ export interface AcceptanceVisualRender {}/**- * Acceptance policy/config snapshot. The source may be a task's `config.verify`,- * a topic-level override, or a document acceptance rule, so it lives with the- * generic aggregate rather than only in task types.+ * Acceptance policy/config snapshot. This is the authoritative policy for the+ * subject's verification lifecycle; legacy task `config.verify` values are+ * migrated here on first read.*//*** One user-authored acceptance criterion in a subject's standing checklist@@ -305,6 +305,7 @@ export interface VerifyCheckDecisionDetail {export type VerifyRunStatus =| 'unverified'| 'planned'+ | 'collecting_evidence'| 'verifying'| 'passed'| 'failed'@@ -353,7 +354,8 @@ export type VerifyEvidenceType ='screenshot' | 'gif' | 'video' | 'audio' | 'text' | 'markdown' | 'dom_snapshot' | 'transcript';/** Who / what captured an evidence artifact (provenance). */-export type VerifyEvidenceCapturedBy = 'agent-browser' | 'cdp' | 'cli' | 'program' | 'llm_judge';+export type VerifyEvidenceCapturedBy =+ 'agent' | 'agent-browser' | 'cdp' | 'cli' | 'program' | 'llm_judge';/*** Provenance of a user's acceptance decision on a verify round