Skip to content

🀯 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.

✨ feat(verify): holistic agent verify + verifyβ†’task completion bridge (#16255)

Arvin Xud6935cd13050
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 756a275adb9..b5b135f3a6e 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -28,11 +28,11 @@ import { BriefModel } from '@/database/models/brief';
import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
+import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { SystemAgentService } from '@/server/services/systemAgent';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
-import { TaskReviewService } from '@/server/services/taskReview';
import { createTaskSchedulerModule } from '@/server/services/taskScheduler';
import {
@@ -114,6 +114,13 @@ export class TaskLifecycleService {
const currentTask = await this.taskModel.findById(taskId);
+ // Whether a confirmed verify plan owns this run's delivery acceptance. Set in
+ // the 'done' branch; gates both the pause-for-review skip and (below) the
+ // creator callback β€” for verify-bound runs the callback is deferred to the
+ // verify settle path (driveTaskFromVerify) so the creator never consumes an
+ // output before verify has accepted it.
+ let verifyBound = false;
+
if (reason === 'done') {
// 1. Update topic status
if (topicId) await this.taskTopicModel.updateStatus(taskId, topicId, 'completed');
@@ -129,26 +136,12 @@ export class TaskLifecycleService {
);
}
- // 3. Auto-review (if configured) β€” Judge is the trusted accept signal:
- // when review passes, runAutoReview itself transitions the task to 'completed'.
- // Returns true if it terminated the task (completed/paused for retry/etc.).
- const reviewTerminated =
- currentTask && topicId && lastAssistantContent
- ? await this.runAutoReview(
- taskId,
- taskIdentifier,
- topicId,
- lastAssistantContent,
- currentTask,
- )
- : false;
-
- if (reviewTerminated) {
- // Review (Judge) already transitioned the task to its terminal state β€”
- // bridge the result here before the early return.
- await this.bridgeResultToCreator(params);
- return;
- }
+ // 3. Delivery acceptance now runs through Verify (LOBE-10624): the verify
+ // run settles asynchronously (agent verifier) and drives the task to its
+ // terminal state via `driveTaskFromVerify`. The legacy eval-rubric
+ // auto-review is removed; this branch only lets the task go on to the
+ // brief + post-tick transition, and the verify-bound check below makes it
+ // "let go" so verify owns the completion decision.
// 4. Synthesize a programmatic brief for the user (auto mode only).
// The agent-driven `createBrief` tool path stays the default until
@@ -181,6 +174,22 @@ export class TaskLifecycleService {
// *proposal* of completion, and the user must explicitly approve
// via the brief action to transition to 'completed'. Auto-complete
// only happens via the Judge path above.
+ // "Let go" for verify-bound runs: when a confirmed verify plan exists for
+ // this op, delivery acceptance is decided asynchronously by Verify
+ // (driveTaskFromVerify completes / pauses the task on settle), so we must
+ // NOT pause-for-review here β€” the task stays running until verify settles.
+ // Best-effort: a verify-read failure must never break the task lifecycle.
+ try {
+ const verifyRun = await new VerifyRunModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findByOperation(params.operationId);
+ verifyBound = Boolean(verifyRun?.planConfirmedAt);
+ } catch (error) {
+ log('verify-bound check failed for op=%s (non-fatal): %O', params.operationId, error);
+ }
+
if (currentTask) {
if (
currentTask.automationMode === 'schedule' &&
@@ -190,7 +199,7 @@ export class TaskLifecycleService {
await this.taskModel.updateStatus(taskId, 'completed', { completedAt: new Date() });
} else if (currentTask.automationMode) {
await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });
- } else if (this.taskModel.shouldPauseOnTopicComplete(currentTask)) {
+ } else if (!verifyBound && this.taskModel.shouldPauseOnTopicComplete(currentTask)) {
await this.taskModel.updateStatus(taskId, 'paused', { error: null });
}
}
@@ -220,7 +229,12 @@ export class TaskLifecycleService {
// racing `on-topic-complete` could observe the pre-transition status and
// silently drop the only callback for automation tasks that become terminal
// in this path (e.g. a scheduled task hitting its execution cap).
- await this.bridgeResultToCreator(params);
+ //
+ // Verify-bound runs DEFER the callback to the verify settle path
+ // (driveTaskFromVerify): the delivery isn't accepted until verify settles, so
+ // the creator must not receive/act on the output here β€” if verify later fails,
+ // the unaccepted output would already have been consumed.
+ if (!verifyBound) await this.bridgeResultToCreator(params);
// Heartbeat re-arm: re-read task state (status / context may have just
// been mutated by the branches above) and decide whether to publish the
@@ -623,129 +637,4 @@ export class TaskLifecycleService {
console.warn('[TaskLifecycle] brief synthesis failed:', e);
}
}
-
- /**
- * Run auto-review if configured.
- *
- * Acts as a "Judge" accept signal: when review passes the task transitions to
- * `completed` here; when it fails, the task is paused for retry or human action.
- *
- * @returns true if this method terminated the task lifecycle (caller should not
- * additionally pause/transition); false if review wasn't configured or
- * a non-terminal path was taken.
- */
- private async runAutoReview(
- taskId: string,
- taskIdentifier: string,
- topicId: string,
- content: string,
- currentTask: any,
- ): Promise<boolean> {
- const reviewConfig = this.taskModel.getReviewConfig(currentTask);
- if (!reviewConfig?.enabled || !reviewConfig.rubrics?.length) return false;
-
- try {
- const topicLinks = await this.taskTopicModel.findByTaskId(taskId);
- const targetTopic = topicLinks.find((t) => t.topicId === topicId);
- const iteration = (targetTopic?.reviewIteration || 0) + 1;
-
- const reviewService = new TaskReviewService(this.db, this.userId, this.workspaceId);
- const reviewResult = await reviewService.review({
- content,
- iteration,
- judge: reviewConfig.judge || {},
- rubrics: reviewConfig.rubrics,
- taskName: currentTask.name || taskIdentifier,
- });
-
- log(
- 'review result: task=%s passed=%s score=%d iteration=%d/%d',
- taskIdentifier,
- reviewResult.passed,
- reviewResult.overallScore,
- iteration,
- reviewConfig.maxIterations,
- );
-
- // Save review result to task_topics
- await this.taskTopicModel.updateReview(taskId, topicId, {
- iteration,
- passed: reviewResult.passed,
- score: reviewResult.overallScore,
- scores: reviewResult.rubricResults,
- });
-
- if (reviewResult.passed) {
- // Judge is a trusted accept signal β€” the brief is created already-resolved
- // (no actionable buttons in the UI) and the task transitions to 'completed'.
- const now = new Date();
- await this.briefModel.create({
- agentId: currentTask?.assigneeAgentId || undefined,
- priority: 'info',
- resolvedAction: 'auto-judge-pass',
- resolvedAt: now,
- readAt: now,
- summary: `Review passed (score: ${reviewResult.overallScore}%, iteration: ${iteration}). ${content.slice(0, 150)}`,
- taskId,
- title: `${taskIdentifier} review passed`,
- trigger: 'task',
- type: 'result',
- });
- await this.taskModel.updateStatus(taskId, 'completed', { error: null });
- await this.cascadeAfterAutoComplete(taskId);
- return true;
- }
-
- if (reviewConfig.autoRetry && iteration < reviewConfig.maxIterations) {
- await this.briefModel.create({
- agentId: currentTask?.assigneeAgentId || undefined,
- priority: 'normal',
- summary: `Review failed (score: ${reviewResult.overallScore}%, iteration ${iteration}/${reviewConfig.maxIterations}). Auto-retrying...`,
- taskId,
- title: `${taskIdentifier} review failed, retrying`,
- trigger: 'task',
- type: 'insight',
- });
-
- // Pause so the webhook / polling loop can pick up and re-run
- await this.taskModel.updateStatus(taskId, 'paused', { error: null });
- return true;
- }
-
- // Max iterations reached β€” surface the (failed) result for human accept/retry.
- // Type is `result` so the user's `approve` action is treated as a terminal
- // accept signal (force-pass) by BriefService.resolve. Result briefs render
- // a fixed single-button UI, so no custom actions are persisted.
- await this.briefModel.create({
- agentId: currentTask?.assigneeAgentId || undefined,
- priority: 'urgent',
- summary: `Review failed after ${iteration} iteration(s) (score: ${reviewResult.overallScore}%). Suggestions: ${reviewResult.suggestions?.join('; ') || 'none'}`,
- taskId,
- title: `${taskIdentifier} review failed β€” needs attention`,
- trigger: 'task',
- type: 'result',
- });
- await this.taskModel.updateStatus(taskId, 'paused', { error: null });
- return true;
- } catch (e) {
- console.warn('[TaskLifecycle] auto-review failed:', e);
- return false;
- }
- }
-
- /**
- * Trigger downstream task kickoff after this task auto-completes via judge.
- *
- * Lazy-imports `TaskRunnerService` to break the runner ↔ lifecycle import
- * cycle (the runner already constructs a lifecycle for its own hooks).
- */
- private async cascadeAfterAutoComplete(completedTaskId: string): Promise<void> {
- try {
- const { TaskRunnerService } = await import('@/server/services/taskRunner');
- const runner = new TaskRunnerService(this.db, this.userId, this.workspaceId);
- await runner.cascadeOnCompletion(completedTaskId);
- } catch (e) {
- console.warn('[TaskLifecycle] dependency cascade failed:', e);
- }
- }
}
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index 133b1b8df3e..d83f57c675e 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -13,6 +13,13 @@ vi.mock('@/server/services/taskScheduler', () => ({
createTaskSchedulerModule: () => fakeScheduler,
}));
+// onTopicComplete reads the op's verify run to decide whether to "let go" for
+// async Verify-driven completion (LOBE-10624). Mock it; default = no verify run.
+const verifyFindByOperation = vi.fn().mockResolvedValue(undefined);
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({ findByOperation: verifyFindByOperation })),
+}));
+
const baseTask = (overrides: Partial<TaskItem> = {}): TaskItem =>
({
automationMode: 'heartbeat',
@@ -49,6 +56,7 @@ describe('TaskLifecycleService.onTopicComplete', () => {
updateTopicStatus = vi.fn().mockResolvedValue(undefined);
createBrief = vi.fn().mockResolvedValue(undefined);
getReviewConfig = vi.fn().mockReturnValue(undefined);
+ verifyFindByOperation.mockReset().mockResolvedValue(undefined);
const taskModel = (service as any).taskModel;
taskModel.updateStatus = updateStatus;
@@ -252,16 +260,14 @@ describe('TaskLifecycleService.onTopicComplete', () => {
expect(synthesize).not.toHaveBeenCalled();
});
- it('does not call synthesizeTopicBrief when judge terminates (review enabled + passed)', async () => {
+ it('verify-bound task β†’ does NOT pause-for-review (lets Verify drive completion async)', async () => {
const task = baseTask({ automationMode: null });
findById.mockResolvedValue(task);
- // runAutoReview returns true β†’ onTopicComplete returns early before
- // reaching synthesizeTopicBrief.
- vi.spyOn(service as any, 'runAutoReview').mockResolvedValue(true);
- const synthesize = vi
- .spyOn(service as any, 'synthesizeTopicBrief')
- .mockResolvedValue(undefined);
+ // A confirmed verify run exists for this op β†’ onTopicComplete "lets go".
+ verifyFindByOperation.mockResolvedValue({ planConfirmedAt: new Date() });
+ vi.spyOn(service as any, 'synthesizeTopicBrief').mockResolvedValue(undefined);
vi.spyOn(service as any, 'generateHandoff').mockResolvedValue(undefined);
+ const bridge = vi.spyOn(service as any, 'bridgeResultToCreator').mockResolvedValue(undefined);
await service.onTopicComplete({
lastAssistantContent: 'enough content to count as substantive output',
@@ -272,7 +278,30 @@ describe('TaskLifecycleService.onTopicComplete', () => {
topicId: 'topic-1',
});
- expect(synthesize).not.toHaveBeenCalled();
+ // Did not pause β€” driveTaskFromVerify will complete/pause the task on settle.
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ // The creator callback is DEFERRED to the verify settle path, not fired here.
+ expect(bridge).not.toHaveBeenCalled();
+ });
+
+ it('non-verify-bound task β†’ fires the creator callback at onTopicComplete', async () => {
+ const task = baseTask({ automationMode: null });
+ findById.mockResolvedValue(task);
+ verifyFindByOperation.mockResolvedValue(undefined); // no verify run
+ vi.spyOn(service as any, 'synthesizeTopicBrief').mockResolvedValue(undefined);
+ vi.spyOn(service as any, 'generateHandoff').mockResolvedValue(undefined);
+ const bridge = vi.spyOn(service as any, 'bridgeResultToCreator').mockResolvedValue(undefined);
+
+ await service.onTopicComplete({
+ lastAssistantContent: 'enough content to count as substantive output',
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(bridge).toHaveBeenCalledTimes(1);
});
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/verifyResult.ts b/apps/server/src/services/toolExecution/serverRuntimes/verifyResult.ts
index ac841193024..e1ed698728d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/verifyResult.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/verifyResult.ts
@@ -6,7 +6,7 @@ import { AgentOperationModel } from '@/database/models/agentOperation';
import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
-import { maybeAutoRepair, VerifyStatusService } from '@/server/services/verify';
+import { finalizeVerifyRun, VerifyStatusService } from '@/server/services/verify';
import type { ServerRuntimeRegistration } from './types';
@@ -83,9 +83,10 @@ class VerifyResultExecutionRuntime {
await new VerifyStatusService(this.db, this.userId, this.workspaceId).recompute(
targetOperationId,
);
- // This may be the last check to resolve β€” kick auto-repair if the run failed
- // with auto_repair checks (no-op until everything has a terminal result).
- await maybeAutoRepair(this.db, this.userId, targetOperationId, this.workspaceId);
+ // This may be the last check to resolve β€” settle the run through the single
+ // finalizer (repair-aware β†’ drive the bound task on terminal). No report
+ // context here (the verifier sub-agent lacks the builder's deliverable).
+ await finalizeVerifyRun(this.db, this.userId, targetOperationId, {}, this.workspaceId);
log(
'submitted verdict %s for check %s (op %s)',
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
new file mode 100644
index 00000000000..dec946ebbcf
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -0,0 +1,129 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { driveTaskFromVerify } from '../settle';
+
+const {
+ runFindByOperation,
+ runSetMetadata,
+ opFindById,
+ taskFindById,
+ taskUpdateStatus,
+ briefCreate,
+ serviceUpdateStatus,
+ deliverMock,
+} = vi.hoisted(() => ({
+ briefCreate: vi.fn(),
+ deliverMock: vi.fn(),
+ opFindById: vi.fn(),
+ runFindByOperation: vi.fn(),
+ runSetMetadata: vi.fn(),
+ serviceUpdateStatus: vi.fn(),
+ taskFindById: vi.fn(),
+ taskUpdateStatus: vi.fn(),
+}));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({
+ findByOperation: runFindByOperation,
+ setMetadata: runSetMetadata,
+ })),
+}));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(() => ({ findById: opFindById })),
+}));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(() => ({ findById: taskFindById, updateStatus: taskUpdateStatus })),
+}));
+vi.mock('@/database/models/brief', () => ({
+ BriefModel: vi.fn(() => ({ create: briefCreate })),
+}));
+// Resolved via dynamic import inside driveTaskFromVerify (cycle break).
+vi.mock('@/server/services/task', () => ({
+ TaskService: vi.fn(() => ({ updateStatus: serviceUpdateStatus })),
+}));
+// The deferred creator callback, also resolved via dynamic import.
+vi.mock('@/server/services/taskResultBridge', () => ({
+ TaskResultBridgeService: vi.fn(() => ({ deliver: deliverMock })),
+}));
+
+const db = {} as any;
+
+describe('driveTaskFromVerify (LOBE-10624)', () => {
+ beforeEach(() => {
+ [
+ runFindByOperation,
+ runSetMetadata,
+ opFindById,
+ taskFindById,
+ taskUpdateStatus,
+ briefCreate,
+ serviceUpdateStatus,
+ deliverMock,
+ ].forEach((m) => m.mockReset());
+ opFindById.mockResolvedValue({ taskId: 'task-1', topicId: 'topic-done' });
+ taskFindById.mockResolvedValue({
+ assigneeAgentId: 'a1',
+ id: 'task-1',
+ identifier: 'T-1',
+ status: 'running',
+ });
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it('passed β†’ completes the task (with cascade), delivers the creator callback, marks done', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'passed' });
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+ expect(serviceUpdateStatus).toHaveBeenCalledWith({ id: 'task-1', status: 'completed' });
+ // Deferred creator callback fires here (not in onTopicComplete), reason 'done'.
+ expect(deliverMock).toHaveBeenCalledTimes(1);
+ expect(deliverMock.mock.calls[0][0]).toMatchObject({
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'T-1',
+ topicId: 'topic-done',
+ });
+ expect(runSetMetadata).toHaveBeenCalled();
+ });
+
+ it('failed β†’ urgent brief + pauses, delivers a failure creator callback', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+ expect(briefCreate).toHaveBeenCalled();
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: null });
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ // Creator is told it failed verification (reason 'error'), not a passed result.
+ expect(deliverMock.mock.calls[0][0]).toMatchObject({ reason: 'error', taskId: 'task-1' });
+ });
+
+ it('skips when the run has not terminally settled (verifying/repairing)', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'verifying' });
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ expect(taskUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it('skips a non-task-bound run', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'passed' });
+ opFindById.mockResolvedValue({ taskId: null });
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it('is idempotent β€” does not re-drive once taskDrivenAt is set', async () => {
+ runFindByOperation.mockResolvedValue({
+ id: 'run-1',
+ metadata: { taskDrivenAt: '2026-01-01' },
+ status: 'passed',
+ });
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ });
+
+ it('skips when the task is already terminal', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'passed' });
+ taskFindById.mockResolvedValue({ id: 'task-1', status: 'completed' });
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/holisticPlan.test.ts b/apps/server/src/services/verify/__tests__/holisticPlan.test.ts
new file mode 100644
index 00000000000..a34e66bae94
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/holisticPlan.test.ts
@@ -0,0 +1,100 @@
+import type { VerifyCheckItem } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VerifyPlanGeneratorService } from '../planGenerator';
+
+// Mock the model modules the generator constructs (LOBE-10755 holistic fallback).
+const { setPlanMock, ensureForOperationMock, getCriteriaMock, findByIdsMock } = vi.hoisted(() => ({
+ ensureForOperationMock: vi.fn(async () => ({ id: 'run-1' })),
+ findByIdsMock: vi.fn(async () => [] as any[]),
+ getCriteriaMock: vi.fn(async () => [] as any[]),
+ setPlanMock: vi.fn(async (_runId: string, _items: any[]) => {}),
+}));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({
+ ensureForOperation: ensureForOperationMock,
+ setPlan: setPlanMock,
+ })),
+}));
+vi.mock('@/database/models/verifyRubric', () => ({
+ VerifyRubricModel: vi.fn(() => ({ getCriteria: getCriteriaMock })),
+}));
+vi.mock('@/database/models/verifyCriterion', () => ({
+ VerifyCriterionModel: vi.fn(() => ({ findByIds: findByIdsMock })),
+}));
+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn(() => ({})) }));
+vi.mock('@/server/services/aiGeneration', () => ({ AiGenerationService: vi.fn(() => ({})) }));
+
+const db = {} as any;
+const lastPlan = (): VerifyCheckItem[] => setPlanMock.mock.calls.at(-1)![1] as VerifyCheckItem[];
+
+describe('generateDraftPlan β€” holistic fallback (LOBE-10755)', () => {
+ beforeEach(() => {
+ setPlanMock.mockClear();
+ getCriteriaMock.mockResolvedValue([]);
+ findByIdsMock.mockResolvedValue([]);
+ });
+
+ it('synthesizes one agent-type holistic check from the requirement when no criteria', async () => {
+ const svc = new VerifyPlanGeneratorService(db, 'user-1');
+ await svc.generateDraftPlan({
+ goal: 'do the thing',
+ holisticFallback: true,
+ operationId: 'op-1',
+ requirement: 'The UI shows the new badge',
+ });
+
+ const plan = lastPlan();
+ expect(plan).toHaveLength(1);
+ expect(plan[0]).toMatchObject({
+ description: 'The UI shows the new badge',
+ onFail: 'manual',
+ required: true,
+ verifierType: 'agent',
+ });
+ });
+
+ it('falls back to the goal when no requirement', async () => {
+ const svc = new VerifyPlanGeneratorService(db, 'user-1');
+ await svc.generateDraftPlan({
+ goal: 'fix the bug',
+ holisticFallback: true,
+ operationId: 'op-1',
+ });
+ expect(lastPlan()[0].description).toBe('fix the bug');
+ });
+
+ it('does NOT synthesize when holisticFallback is off β€” empty plan stays empty', async () => {
+ const svc = new VerifyPlanGeneratorService(db, 'user-1');
+ await svc.generateDraftPlan({ goal: 'x', holisticFallback: false, operationId: 'op-1' });
+ expect(lastPlan()).toHaveLength(0);
+ });
+
+ it('does NOT add a holistic item when criteria already produced items', async () => {
+ getCriteriaMock.mockResolvedValue([
+ {
+ description: null,
+ documentId: null,
+ id: 'c1',
+ onFail: 'manual',
+ required: true,
+ title: 'Crit 1',
+ verifierConfig: {},
+ verifierType: 'llm',
+ },
+ ]);
+ const svc = new VerifyPlanGeneratorService(db, 'user-1');
+ await svc.generateDraftPlan({
+ goal: 'x',
+ holisticFallback: true,
+ operationId: 'op-1',
+ verifyRubricId: 'rub-1',
+ });
+
+ const plan = lastPlan();
+ expect(plan).toHaveLength(1);
+ expect(plan[0].title).toBe('Crit 1');
+ expect(plan[0].verifierType).toBe('llm');
+ });
+});
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index 1b2d8af9d80..445b3956bb6 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -16,4 +16,5 @@ export {
VerifyRepairService,
} from './repairService';
export { type GenerateReportParams, VerifyReporterService } from './reporter';
+export { driveTaskFromVerify, finalizeVerifyRun } from './settle';
export { VerifyStatusService } from './statusService';
diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.ts
index a2b842b9210..eae83c3c826 100644
--- a/apps/server/src/services/verify/lifecycle.ts
+++ b/apps/server/src/services/verify/lifecycle.ts
@@ -7,8 +7,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { createVerifierAgentRunner } from './agentVerifier';
import { VerifyExecutorService } from './executor';
-import { maybeAutoRepair } from './repairService';
-import { VerifyReporterService } from './reporter';
+import { finalizeVerifyRun } from './settle';
const log = debug('lobe-server:verify-lifecycle');
@@ -83,26 +82,24 @@ export const runVerifyOnCompletion = async (
}),
});
- // Auto-repair once verification has fully resolved. For runs with only inline
- // (LLM/program) checks, everything is resolved now; runs with async agent
- // checks no-op here and re-trigger from the verifier's writeback path.
- await maybeAutoRepair(db, userId, params.operationId, workspaceId);
-
- // Generate the report only at the link tail β€” when verification settled into a
- // terminal verdict (passed/failed). A run that spawned a repair is now
- // `repairing`; its report is generated when the repair op completes, so a
- // single card lands on the final delivery instead of one per repair round.
- const settled = await new VerifyRunModel(db, userId, workspaceId).findByOperation(
+ // Settle the run: repair-aware tail, then (on terminal settle) report + drive
+ // the bound task. For inline (LLM/program) checks everything is resolved now;
+ // runs with async agent checks no-op here and re-enter the same finalizer from
+ // the verifier's writeback path (verifyResult runtime) β€” so the task is driven
+ // from exactly one place regardless of which path finished last.
+ await finalizeVerifyRun(
+ db,
+ userId,
params.operationId,
+ {
+ report: {
+ deliverable: params.deliverable,
+ goal: params.goal,
+ modelConfig: { model: op.model, provider: op.provider },
+ },
+ },
+ workspaceId,
);
- if (settled?.status === 'passed' || settled?.status === 'failed') {
- await new VerifyReporterService(db, userId, workspaceId).generateReport({
- deliverable: params.deliverable,
- goal: params.goal,
- modelConfig: { model: op.model, provider: op.provider },
- verifyRunId: settled.id,
- });
- }
} catch (error) {
log('runVerifyOnCompletion failed for op %s (non-fatal): %O', params.operationId, error);
}
diff --git a/apps/server/src/services/verify/planGenerator.ts b/apps/server/src/services/verify/planGenerator.ts
index 7a6afd9a2d0..4e5a41e25c6 100644
--- a/apps/server/src/services/verify/planGenerator.ts
+++ b/apps/server/src/services/verify/planGenerator.ts
@@ -27,10 +27,18 @@ export interface GeneratePlanParams {
enableAiGeneration?: boolean;
/** The user's task / instruction text the run must satisfy. */
goal: string;
+ /**
+ * When the run opted into verify but produced no decomposed criteria, synthesize
+ * a single agent-type holistic check (the coarse "one broad agent verify"
+ * default, LOBE-10755) instead of leaving an empty plan (β†’ verify no-op).
+ */
+ holisticFallback?: boolean;
maxAiCriteria?: number;
/** Required only when `enableAiGeneration` is true. */
modelConfig?: { model: string; provider: string };
operationId: string;
+ /** One-sentence acceptance the holistic check verifies against (falls back to `goal`). */
+ requirement?: string;
/** Ad-hoc criteria mounted on the agent (`agencyConfig.verifyCriteriaIds`). */
verifyCriteriaIds?: string[];
/** Reusable rubric mounted on the agent (`agencyConfig.verifyRubricId`). */
@@ -57,6 +65,30 @@ export interface CriterionDraft {
verifierType?: VerifyCheckItem['verifierType'];
}
+/**
+ * Synthesize a single `agent`-type holistic check from the task's acceptance
+ * requirement (or its goal). The agent verifier investigates the whole
+ * deliverable and submits one verdict β€” the coarse "one broad agent verify"
+ * default for tasks that opted into verify without decomposing into criteria
+ * (LOBE-10755). No `requiredEvidence` hard gate: the agent self-captures, so the
+ * structural gate never marks it uncertain for "missing evidence".
+ */
+const buildHolisticAgentItem = (requirement?: string, goal?: string): VerifyCheckItem => {
+ const acceptance = requirement?.trim() || goal?.trim() || 'The deliverable fulfills the task.';
+ return {
+ description: acceptance,
+ id: randomUUID(),
+ index: 0,
+ // Delegate the fail decision to the task bridge (pass→completed / fail→brief)
+ // rather than the operation-level auto-repair loop.
+ onFail: 'manual',
+ required: true,
+ title: 'Task delivery acceptance',
+ verifierConfig: {},
+ verifierType: 'agent',
+ };
+};
+
const criterionToCheckItem = (
criterion: VerifyCriterionItem,
index: number,
@@ -318,6 +350,14 @@ export class VerifyPlanGeneratorService {
}
}
+ // 4. Holistic fallback: opted into verify but nothing decomposed into
+ // criteria β€” synthesize one agent-type check over the whole deliverable
+ // so verify actually runs (instead of an empty plan β†’ no-op).
+ if (items.length === 0 && params.holisticFallback) {
+ items.push(buildHolisticAgentItem(params.requirement, params.goal));
+ log('synthesized holistic agent check for op %s', params.operationId);
+ }
+
const run = await this.runModel.ensureForOperation(params.operationId, { goal: params.goal });
await this.runModel.setPlan(run.id, items);
log('generated draft plan for op %s with %d items', params.operationId, items.length);
diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.ts
index f06320a2fd7..36aa4892615 100644
--- a/apps/server/src/services/verify/planInstantiation.ts
+++ b/apps/server/src/services/verify/planInstantiation.ts
@@ -36,10 +36,18 @@ export const instantiateVerifyPlanOnStart = async (
const taskModel = new TaskModel(db, userId, workspaceId);
const verifyConfig = await taskModel.resolveVerifyConfig(params.taskId);
- // Opt-in: a task only verifies when it configured a rubric or ad-hoc criteria
- // and hasn't disabled the gate.
+ // 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 (LOBE-10755)
+ // - no signal at all β†’ verify stays off
if (!verifyConfig || verifyConfig.enabled === false) return;
- if (!verifyConfig.verifyRubricId && !verifyConfig.verifyCriteriaIds?.length) return;
+ const hasCriteria = Boolean(
+ verifyConfig.verifyRubricId || verifyConfig.verifyCriteriaIds?.length,
+ );
+ const holistic =
+ !hasCriteria && (verifyConfig.enabled === true || Boolean(verifyConfig.requirement?.trim()));
+ if (!hasCriteria && !holistic) return;
const runModel = new VerifyRunModel(db, userId, workspaceId);
const existing = await runModel.findByOperation(params.operationId);
@@ -54,7 +62,10 @@ export const instantiateVerifyPlanOnStart = async (
// No AI proposal β€” the task's configured rubric/criteria are the plan.
enableAiGeneration: false,
goal,
+ // Fall back to a single agent-type holistic check when nothing decomposed.
+ holisticFallback: holistic,
operationId: params.operationId,
+ requirement: verifyConfig.requirement,
verifyCriteriaIds: verifyConfig.verifyCriteriaIds,
verifyRubricId: verifyConfig.verifyRubricId,
});
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
new file mode 100644
index 00000000000..ac35c4e1b17
--- /dev/null
+++ b/apps/server/src/services/verify/settle.ts
@@ -0,0 +1,136 @@
+import { DEFAULT_BRIEF_ACTIONS } from '@lobechat/types';
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { BriefModel } from '@/database/models/brief';
+import { TaskModel } from '@/database/models/task';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { maybeAutoRepair } from './repairService';
+import { VerifyReporterService } from './reporter';
+
+const log = debug('lobe-server:verify-settle');
+
+const TERMINAL_TASK_STATUS = new Set(['canceled', 'completed', 'failed']);
+
+interface ReportContext {
+ deliverable: string;
+ goal: string;
+ modelConfig: { model: string; provider: string };
+}
+
+/**
+ * Drive the bound task from a settled verify run (LOBE-10624). This is the single
+ * convergence for BOTH settle paths β€” the inline LLM/program judge
+ * (`runVerifyOnCompletion`) and the async agent-verifier writeback
+ * (`submitVerifyResult`) β€” so the task is driven from exactly one place.
+ *
+ * Once a task-bound run reaches a terminal verdict: `passed` β†’ complete the task
+ * (with cascade); `failed` β†’ raise an urgent brief + pause it for the user.
+ * Idempotent via a run-metadata marker; best-effort (never throws into verify).
+ */
+export const driveTaskFromVerify = async (
+ db: LobeChatDatabase,
+ userId: string,
+ operationId: string,
+ workspaceId?: string,
+): Promise<void> => {
+ try {
+ const runModel = new VerifyRunModel(db, userId, workspaceId);
+ const run = await runModel.findByOperation(operationId);
+ // Only act on a terminally settled run (skip pending / verifying / repairing).
+ if (run?.status !== 'passed' && run?.status !== 'failed') return;
+ if ((run.metadata as { taskDrivenAt?: string } | null)?.taskDrivenAt) return; // already drove
+
+ const op = await new AgentOperationModel(db, userId, workspaceId).findById(operationId);
+ if (!op?.taskId) return; // not a task-bound run β€” nothing to drive
+
+ const taskModel = new TaskModel(db, userId, workspaceId);
+ const task = await taskModel.findById(op.taskId);
+ if (!task || TERMINAL_TASK_STATUS.has(task.status)) return; // task already settled
+
+ if (run.status === 'passed') {
+ // Complete + cascade (checkpoint / sibling rollup / unlock downstream).
+ // Dynamic import breaks the static cycle verify β†’ TaskService β†’ aiAgent β†’
+ // agentRuntime completion β†’ verify (the same break agentVerifier uses).
+ const { TaskService } = await import('@/server/services/task');
+ await new TaskService(db, userId, workspaceId).updateStatus({
+ id: op.taskId,
+ status: 'completed',
+ });
+ log('verify passed β†’ task %s completed', op.taskId);
+ } else {
+ // Failed acceptance β†’ surface for the user (urgent brief) + pause the task.
+ await new BriefModel(db, userId, workspaceId).create({
+ actions: DEFAULT_BRIEF_ACTIONS['error'],
+ agentId: task.assigneeAgentId || undefined,
+ priority: 'urgent',
+ summary: 'Delivery did not pass verification.',
+ taskId: op.taskId,
+ title: `${task.identifier} failed verification`,
+ trigger: 'task',
+ type: 'error',
+ });
+ await taskModel.updateStatus(op.taskId, 'paused', { error: null });
+ log('verify failed β†’ task %s paused + brief', op.taskId);
+ }
+
+ // Deferred creator callback (LOBE-10625 Γ— LOBE-10624): verify-bound runs defer
+ // the taskCallback from `onTopicComplete` to HERE so the creator only sees the
+ // result once verify has accepted (passed) or rejected (failed) the delivery β€”
+ // never an unaccepted output it might act on before a later verify failure.
+ // Best-effort; must not block the idempotency marker below.
+ try {
+ const { TaskResultBridgeService } = await import('@/server/services/taskResultBridge');
+ await new TaskResultBridgeService(db, userId, workspaceId).deliver({
+ operationId,
+ reason: run.status === 'passed' ? 'done' : 'error',
+ taskId: op.taskId,
+ taskIdentifier: task.identifier,
+ topicId: op.topicId ?? undefined,
+ ...(run.status === 'failed' && { errorMessage: 'Delivery did not pass verification.' }),
+ });
+ } catch (error) {
+ log('verify-settle creator callback failed for task %s (non-fatal): %O', op.taskId, error);
+ }
+
+ await runModel.setMetadata(run.id, { taskDrivenAt: new Date().toISOString() });
+ } catch (error) {
+ log('driveTaskFromVerify failed for op %s (non-fatal): %O', operationId, error);
+ }
+};
+
+/**
+ * Single finalizer for a verification run, called from both settle paths. Runs
+ * the repair-aware tail (`maybeAutoRepair` may flip the run to `repairing`), then
+ * β€” only when the run has terminally settled β€” generates the report (when the
+ * caller has the deliverable context) and drives the bound task. Keeping repair +
+ * report + task-drive in one place means the task-drive lives in exactly one
+ * location regardless of which path completed the last check.
+ */
+export const finalizeVerifyRun = async (
+ db: LobeChatDatabase,
+ userId: string,
+ operationId: string,
+ opts: { report?: ReportContext },
+ workspaceId?: string,
+): Promise<void> => {
+ // Repair-aware: no-ops until every required check is terminal, and may spawn a
+ // repair (β†’ `repairing`), in which case finalize defers to the repair op.
+ await maybeAutoRepair(db, userId, operationId, workspaceId);
+
+ const settled = await new VerifyRunModel(db, userId, workspaceId).findByOperation(operationId);
+ if (settled?.status !== 'passed' && settled?.status !== 'failed') return;
+
+ // Report only on terminal settle (a single card on the final delivery, not one
+ // per repair round). Skipped when the caller lacks the deliverable (agent path).
+ if (opts.report) {
+ await new VerifyReporterService(db, userId, workspaceId).generateReport({
+ ...opts.report,
+ verifyRunId: settled.id,
+ });
+ }
+
+ await driveTaskFromVerify(db, userId, operationId, workspaceId);
+};