π€― 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
π fix(verify): judge a finished run outside its completion request (#22650)
Arvin Xu6e40ef466b88
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.tsindex a336722177f..2e807244be6 100644--- a/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts+++ b/apps/server/src/router-hono/agent/handlers/__tests__/runStep.test.ts@@ -38,6 +38,7 @@ const mockFinalizeAbandoned = vi.hoisted(() => vi.fn());const mockSettleStaleRunning = vi.hoisted(() => vi.fn());const mockResumeAbandonedParent = vi.hoisted(() => vi.fn());const mockScheduleOpportunisticStaleSweep = vi.hoisted(() => vi.fn());+const mockScheduleOpportunisticVerifySweep = vi.hoisted(() => vi.fn());// Lets a test force the step-boundary flush to report a timeout; undefined// means use the real implementation.const flushOverride = vi.hoisted(() => ({ settled: undefined as boolean | undefined }));@@ -79,6 +80,7 @@ vi.mock('@/server/services/agentRuntime', () => ({return { finalizeAbandoned: mockFinalizeAbandoned };}),scheduleOpportunisticStaleSweep: mockScheduleOpportunisticStaleSweep,+ scheduleOpportunisticVerifySweep: mockScheduleOpportunisticVerifySweep,}));vi.mock('@/database/core/db-adaptor', () => ({@@ -376,6 +378,7 @@ describe('runStep handler', () => {expect(res.status).toBe(200);expect(mockScheduleOpportunisticStaleSweep).toHaveBeenCalledTimes(1);+ expect(mockScheduleOpportunisticVerifySweep).toHaveBeenCalledTimes(1);});it('opts the AiAgentService into visitor rows when metadata carries streamOwnerUserId', async () => {diff --git a/apps/server/src/router-hono/agent/handlers/runStep.ts b/apps/server/src/router-hono/agent/handlers/runStep.tsindex 191a2a25a65..221eb9206f5 100644--- a/apps/server/src/router-hono/agent/handlers/runStep.ts+++ b/apps/server/src/router-hono/agent/handlers/runStep.ts@@ -12,6 +12,7 @@ import {type AgentExecutionResult,type AgentStepContinuation,scheduleOpportunisticStaleSweep,+ scheduleOpportunisticVerifySweep,} from '@/server/services/agentRuntime';import { AiAgentService } from '@/server/services/aiAgent';import { runWithInvocationDeadline } from '@/server/utils/invocationDeadline';@@ -234,6 +235,9 @@ export async function runStep(c: Context): Promise<Response> {// inactivity watchdog. Fire-and-forget: it is background repair and must// not add latency to, or fail, this delivery.scheduleOpportunisticStaleSweep();+ // Same for verification rounds stranded in `verifying`: their sweep route+ // expects a QStash Schedule no deployment registers.+ scheduleOpportunisticVerifySweep();// Get userId from operation metadata stored in Redisconst coordinator = new AgentRuntimeCoordinator();diff --git a/apps/server/src/router-hono/workflows/verify/handlers/onOperationComplete.ts b/apps/server/src/router-hono/workflows/verify/handlers/onOperationComplete.tsnew file mode 100644index 00000000000..10ba05fc9b2--- /dev/null+++ b/apps/server/src/router-hono/workflows/verify/handlers/onOperationComplete.ts@@ -0,0 +1,26 @@+import type { Context } from 'hono';++import { getServerDB } from '@/database/server';+import type { VerifyOnOperationCompletePayload } from '@/server/services/verify';+import { runVerifyOnCompletionFromQueue } from '@/server/services/verify/lifecycle';++/**+ * QStash delivery of the completion-time verify gate (see+ * `scheduleVerifyOnCompletion`). A thrown gate surfaces as a 5xx so QStash+ * redelivers it.+ */+export async function onOperationComplete(c: Context) {+ const body = (await c.req.json()) as VerifyOnOperationCompletePayload;+ if (!body.operationId || !body.userId || typeof body.deliverable !== 'string') {+ return c.json({ error: 'Missing required fields' }, 400);+ }++ const db = await getServerDB();+ await runVerifyOnCompletionFromQueue(+ db,+ body.userId,+ { deliverable: body.deliverable, goal: body.goal ?? '', operationId: body.operationId },+ body.workspaceId,+ );+ return c.json({ success: true });+}diff --git a/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts b/apps/server/src/router-hono/workflows/verify/handlers/sweep.tsindex 294f7339a19..686a74b0dd5 100644--- a/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts+++ b/apps/server/src/router-hono/workflows/verify/handlers/sweep.ts@@ -21,9 +21,10 @@ export async function sweep(c: Context) {const outcome = await sweepStuckVerifyRuns(db);log(- 'Verify sweep: settled=%d abandoned=%d released=%d skipped=%d',+ 'Verify sweep: settled=%d abandoned=%d redriven=%d released=%d skipped=%d',outcome.settled.length,outcome.abandoned.length,+ outcome.redriven.length,outcome.released.length,outcome.skipped,);diff --git a/apps/server/src/router-hono/workflows/verify/index.ts b/apps/server/src/router-hono/workflows/verify/index.tsindex aa10b1b71e5..d5bb9aeb058 100644--- a/apps/server/src/router-hono/workflows/verify/index.ts+++ b/apps/server/src/router-hono/workflows/verify/index.ts@@ -2,12 +2,14 @@ import { Hono } from 'hono';import { qstashAuth } from '../middlewares/qstashAuth';import { onEvidenceComplete } from './handlers/onEvidenceComplete';+import { onOperationComplete } from './handlers/onOperationComplete';import { onVerifierComplete } from './handlers/onVerifierComplete';import { sweep } from './handlers/sweep';const app = new Hono();app.post('/on-evidence-complete', qstashAuth(), onEvidenceComplete);+app.post('/on-operation-complete', qstashAuth(), onOperationComplete);app.post('/on-verifier-complete', qstashAuth(), onVerifierComplete);app.post('/sweep', qstashAuth(), sweep);diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.tsindex 3d959339726..11601c135dc 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.assistantMessage.test.ts@@ -46,7 +46,7 @@ describe('CompletionLifecycle.dispatchHooks β lastAssistantContent DB recoveryconst setupSpies = (lifecycle: CompletionLifecycle) => {vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);- vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);+ vi.spyOn(verifyServices, 'scheduleVerifyOnCompletion').mockResolvedValue(undefined);vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});vi.spyOn(console, 'warn').mockImplementation(function () {});return vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.tsindex 6b478e3553d..894b82fc145 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.completion.test.ts@@ -50,7 +50,7 @@ describe('CompletionLifecycle.dispatchHooks β verify plan race', () => {.spyOn(verifyServices, 'instantiateVerifyPlanOnStart').mockReturnValue(instantiation);const runVerifySpy = vi- .spyOn(verifyServices, 'runVerifyOnCompletion')+ .spyOn(verifyServices, 'scheduleVerifyOnCompletion').mockResolvedValue(undefined);// A top-level task op registers the (still-pending) instantiation at start.@@ -207,7 +207,7 @@ describe('CompletionLifecycle.dispatchHooks β completion notification', () =>vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});- vi.spyOn(verifyServices, 'runVerifyOnCompletion').mockResolvedValue(undefined);+ vi.spyOn(verifyServices, 'scheduleVerifyOnCompletion').mockResolvedValue(undefined);// The recall gate falls back to the op row when metadata carries no trigger.(lifecycle as any).agentOperationModel = { findById: vi.fn(async () => null) };};diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.tsindex 8364f811aca..d3d8efe27aa 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.ts@@ -13,7 +13,7 @@ import { formatErrorForState } from '@/server/modules/AgentRuntime/formatErrorFoimport {instantiateVerifyPlanOnStart,releaseUndeliveredRound,- runVerifyOnCompletion,+ scheduleVerifyOnCompletion,settleFailedRepair,} from '@/server/services/verify';import { after } from '@/server/utils/scheduleAfterResponse';@@ -262,6 +262,11 @@ export class CompletionLifecycle {const messageModel = new MessageModel(this.serverDB, userId, undefined, undefined, {includeShareVisitor: this.includeShareVisitor,});+ // One card per run. A producer that retries its terminal call (a+ // heterogeneous `heteroFinish` the edge timed out) re-enters here for+ // the same operation, and each pass used to stack another card.+ if (await messageModel.findVerifyMessageByOperationId(operationId, op.topicId)) return;+await messageModel.create({agentId: op.agentId ?? undefined,content: '',@@ -510,24 +515,20 @@ export class CompletionLifecycle {metadata?.assistantMessageId,runOrigin.userId || this.userId,);- // `after`, not a bare `void`: judging is minutes of LLM calls and the- // step handler must not wait for it, but a detached promise has nobody- // keeping it scheduled β on the serverless path the instance is free to- // stop running it the moment this response returns. That is not merely a- // lost verification: entering `verifying` is a durable write, so a run- // cut off mid-judge stays `verifying` forever. `after` hands the work to- // the host as post-response work instead (no-op fallback off Next).- after(() =>- runVerifyOnCompletion(- this.serverDB,- runOrigin.userId || this.userId,- {- deliverable: event.lastAssistantContent ?? '',- goal,- operationId,- },- this.workspaceId,- ),+ // Judging is minutes of LLM calls and must not ride this request:+ // entering `verifying` is a durable write, so a gate cut off with the+ // request (proxy timeout, function limit) leaves the round claimed and+ // never judged. The gate runs in its own QStash delivery instead, which+ // also collapses a producer's retried completions into one gate.+ await scheduleVerifyOnCompletion(+ this.serverDB,+ runOrigin.userId || this.userId,+ {+ deliverable: event.lastAssistantContent ?? '',+ goal,+ operationId,+ },+ this.workspaceId,);}diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle/index.verifyCard.test.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.verifyCard.test.tsnew file mode 100644index 00000000000..86e3bfb8e2f--- /dev/null+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle/index.verifyCard.test.ts@@ -0,0 +1,63 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { CompletionLifecycle } from '.';++const { createMessage, findOperation, findRun, findVerifyCard } = vi.hoisted(() => ({+ createMessage: vi.fn(),+ findOperation: vi.fn(),+ findRun: vi.fn(),+ findVerifyCard: vi.fn(),+}));++vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(function () {+ return { findByOperation: findRun };+ }),+}));+vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn(function () {+ return { findById: findOperation };+ }),+}));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn(function () {+ return { create: createMessage, findVerifyMessageByOperationId: findVerifyCard };+ }),+}));++const createVerifyMessage = (lifecycle: CompletionLifecycle) =>+ (lifecycle as any).createVerifyMessage('op-1', 'msg-final', 'user-1') as Promise<void>;++describe('CompletionLifecycle.createVerifyMessage', () => {+ beforeEach(() => {+ [createMessage, findOperation, findRun, findVerifyCard].forEach((m) => m.mockReset());+ findRun.mockResolvedValue({ plan: [{ id: 'c1' }] });+ findOperation.mockResolvedValue({ agentId: 'agt-1', id: 'op-1', topicId: 'tpc-1' });+ findVerifyCard.mockResolvedValue(undefined);+ });++ it('creates the delivery-checker card for a run with a plan', async () => {+ await createVerifyMessage(new CompletionLifecycle({} as any, 'user-1'));++ expect(findVerifyCard).toHaveBeenCalledWith('op-1', 'tpc-1');+ expect(createMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ metadata: { verifyOperationId: 'op-1' },+ parentId: 'msg-final',+ role: 'verify',+ topicId: 'tpc-1',+ }),+ );+ });++ it('does not stack a second card when the completion is delivered again', async () => {+ // A heteroFinish the edge timed out is retried by the CLI up to 7 times;+ // each retry used to add one more card to the conversation.+ findVerifyCard.mockResolvedValue({ id: 'msg-card', role: 'verify' });++ await createVerifyMessage(new CompletionLifecycle({} as any, 'user-1'));++ expect(createMessage).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.tsindex 48bbdb4e511..1279c1376cf 100644--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts@@ -15,12 +15,11 @@ vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({vi.mock('@/server/services/workRegistration', () => ({ registerWorksForOperation: vi.fn() }));/**- * Regression: the completion-time verify gate used to be launched with a bare- * `void`. Nobody held that promise, so on the serverless path the instance was- * free to stop scheduling it as soon as the step response returned β and since- * entering `verifying` is a durable write, a run cut off mid-judge stayed- * `verifying` forever (acceptance and goal card stuck with it). It must be- * handed to the host as post-response work instead.+ * Regression: the completion-time verify gate used to run as post-response work+ * of the completing request. A heterogeneous `heteroFinish` past the 120 s edge+ * timeout took the gate down with it after it had claimed `verifying`, so the+ * round was never judged. The gate is handed to `scheduleVerifyOnCompletion`,+ * which runs it in its own QStash delivery.*/describe('CompletionLifecycle β verify gate scheduling', () => {afterEach(() => vi.restoreAllMocks());@@ -28,15 +27,16 @@ describe('CompletionLifecycle β verify gate scheduling', () => {after.mockReset();});- it('schedules the verify gate as post-response work, not a detached promise', async () => {+ it('hands the verify gate to its own delivery instead of this request', async () => {const lifecycle = new CompletionLifecycle({} as any, 'user-1');vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);vi.spyOn(lifecycle as any, 'createVerifyMessage').mockResolvedValue(undefined);vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});- const runVerify = vi- .spyOn(verifyServices, 'runVerifyOnCompletion')+ const schedule = vi+ .spyOn(verifyServices, 'scheduleVerifyOnCompletion').mockResolvedValue(undefined);+ const runVerify = vi.spyOn(verifyServices, 'runVerifyOnCompletion');await lifecycle.dispatchHooks('op-1',@@ -44,14 +44,11 @@ describe('CompletionLifecycle β verify gate scheduling', () => {'done',);- // Handed over, and not started behind the scheduler's back.- expect(after).toHaveBeenCalledTimes(1);+ expect(schedule).toHaveBeenCalledTimes(1);+ expect(schedule.mock.calls[0][2]).toMatchObject({ operationId: 'op-1' });+ // Not judged on this request, nor queued behind its response.expect(runVerify).not.toHaveBeenCalled();-- // What was handed over is the gate itself.- await after.mock.calls[0][0]();- expect(runVerify).toHaveBeenCalledTimes(1);- expect(runVerify.mock.calls[0][2]).toMatchObject({ operationId: 'op-1' });+ expect(after).not.toHaveBeenCalled();});it.each(['error', 'interrupted'])('does not wait for unfinished plan generation on %s',diff --git a/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.ts b/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.tsindex 486d5525123..10dd938c9ca 100644--- a/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/opportunisticSweep.test.ts@@ -4,8 +4,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import {OPPORTUNISTIC_SWEEP_INTERVAL_MS,OPPORTUNISTIC_SWEEP_SLOT_KEY,+ OPPORTUNISTIC_VERIFY_SWEEP_INTERVAL_MS,+ OPPORTUNISTIC_VERIFY_SWEEP_SLOT_KEY,runOpportunisticSweep,scheduleOpportunisticStaleSweep,+ scheduleOpportunisticVerifySweep,} from '../opportunisticSweep';const sweepMock = vi.fn().mockResolvedValue({ abandoned: 0, redriven: 1 });@@ -15,6 +18,11 @@ vi.mock('../StaleOperationReaper', () => ({}),}));+const verifySweepMock = vi.fn().mockResolvedValue({ abandoned: [], redriven: [], settled: [] });+vi.mock('@/server/services/verify/sweep', () => ({+ sweepStuckVerifyRuns: (...args: any[]) => verifySweepMock(...args),+}));+const getServerDBMock = vi.fn().mockResolvedValue({ db: 'server' });vi.mock('@/database/core/db-adaptor', () => ({getServerDB: (...args: any[]) => getServerDBMock(...args),@@ -151,3 +159,55 @@ describe('scheduleOpportunisticStaleSweep', () => {expect(sweepMock).not.toHaveBeenCalled();});});++describe('scheduleOpportunisticVerifySweep', () => {+ beforeEach(() => {+ afterQueue.length = 0;+ verifySweepMock.mockReset().mockResolvedValue({ abandoned: [], redriven: [], settled: [] });+ redisSetMock.mockReset().mockResolvedValue('OK');+ redisClient = { set: redisSetMock };+ });++ const flush = async () => {+ const pending = [...afterQueue];+ afterQueue.length = 0;+ await Promise.all(pending.map((work) => work()));+ };++ it('claims its own slot and sweeps stranded verification rounds', async () => {+ // Its route expects a QStash Schedule no deployment registers, so the step+ // path is the only thing that ever runs this sweep.+ scheduleOpportunisticVerifySweep();+ await flush();++ expect(redisSetMock).toHaveBeenCalledWith(+ OPPORTUNISTIC_VERIFY_SWEEP_SLOT_KEY,+ expect.any(String),+ 'PX',+ OPPORTUNISTIC_VERIFY_SWEEP_INTERVAL_MS,+ 'NX',+ );+ expect(OPPORTUNISTIC_VERIFY_SWEEP_SLOT_KEY).not.toBe(OPPORTUNISTIC_SWEEP_SLOT_KEY);+ expect(verifySweepMock).toHaveBeenCalledWith({ db: 'server' });+ });++ it('skips the sweep while its slot TTL is still held', async () => {+ redisSetMock.mockResolvedValue(null);++ scheduleOpportunisticVerifySweep();+ await flush();++ expect(verifySweepMock).not.toHaveBeenCalled();+ });++ it('never rejects when the sweep throws', async () => {+ verifySweepMock.mockRejectedValue(new Error('pg down'));+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ scheduleOpportunisticVerifySweep();++ await expect(flush()).resolves.toBeUndefined();+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });+});diff --git a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts b/apps/server/src/services/agentRuntime/hooks/httpWebhook.tsindex 4243e8dd0bf..a90aaeeb7c5 100644--- a/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts+++ b/apps/server/src/services/agentRuntime/hooks/httpWebhook.ts@@ -8,6 +8,7 @@ import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';import { QstashError } from '@upstash/qstash';import { OtelQstashClient } from '@/libs/qstash';+import { toQStashDeduplicationId } from '@/libs/qstash/deduplicationId';import type { AgentHookWebhook } from './types';@@ -145,6 +146,10 @@ async function readControlBody(response: Response, signal: AbortSignal): Promiseexport async function deliverWebhook(webhook: AgentHookWebhook,payload: Record<string, unknown>,+ options: {+ /** Logical id QStash drops repeats of; encoded at the provider boundary. */+ deduplicationId?: string;+ } = {},): Promise<void> {const parsed = agentHookWebhookSchema.safeParse(webhook);if (!parsed.success || webhook.responseHandling === 'toolCall')@@ -162,6 +167,9 @@ export async function deliverWebhook(const client = new OtelQstashClient({ token: process.env.QSTASH_TOKEN });await client.publishJSON({body: payload,+ ...(options.deduplicationId && {+ deduplicationId: toQStashDeduplicationId(options.deduplicationId),+ }),headers: {...headers,...(isApplicationOrigin(url) &&diff --git a/apps/server/src/services/agentRuntime/opportunisticSweep.ts b/apps/server/src/services/agentRuntime/opportunisticSweep.tsindex 15ad77be9d2..5c6deb197f2 100644--- a/apps/server/src/services/agentRuntime/opportunisticSweep.ts+++ b/apps/server/src/services/agentRuntime/opportunisticSweep.ts@@ -3,6 +3,7 @@ import debug from 'debug';import { getServerDB } from '@/database/core/db-adaptor';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { recoverChannels } from '@/server/services/channel/recover';+import { sweepStuckVerifyRuns } from '@/server/services/verify/sweep';import { after } from '@/server/utils/scheduleAfterResponse';import { StaleOperationReaper } from './StaleOperationReaper';@@ -26,6 +27,16 @@ export const OPPORTUNISTIC_SWEEP_INTERVAL_MS = 60_000;*/export const OPPORTUNISTIC_SWEEP_SLOT_KEY = 'agent_runtime:stale_sweep:slot';+/**+ * Spacing between two opportunistic verify sweeps, cluster-wide. The verify+ * sweep acts on rounds stalled for minutes (its shortest bound is five), so a+ * tighter tick would only repeat the same scan.+ */+export const OPPORTUNISTIC_VERIFY_SWEEP_INTERVAL_MS = 5 * 60_000;++/** The Redis slot that decides which caller runs the verify sweep. */+export const OPPORTUNISTIC_VERIFY_SWEEP_SLOT_KEY = 'agent_runtime:verify_sweep:slot';+export interface OpportunisticSweepDeps {/** Resolves true for exactly one caller per interval, cluster-wide. */claim: () => Promise<boolean>;@@ -68,6 +79,39 @@ export async function runOpportunisticSweep({return true;}+/**+ * Claim `slotKey` for `intervalMs` and, on a win, run `sweep` as post-response+ * work. Deliberately not awaited by the caller: background repair must never+ * add latency to, or fail, the step delivery that carries it; that is also why+ * it does not join the step loop's `runWithScheduledWorkScope` (whose boundary+ * flush would then wait on it).+ */+const scheduleSlottedSweep = (+ name: string,+ slotKey: string,+ intervalMs: number,+ sweep: () => Promise<void>,+): void => {+ const redis = getAgentRuntimeRedisClient();+ if (!redis) return;++ after(() =>+ runOpportunisticSweep({+ claim: async () => {+ const claimed = await redis.set(slotKey, String(Date.now()), 'PX', intervalMs, 'NX');++ return claimed === 'OK';+ },+ onError: (error, phase) => {+ // A failed tick is invisible by design (the delivery that hosted it+ // succeeded), so log it loudly enough to be found from the timeline.+ console.error(`[${name}] ${phase} failed: %O`, error);+ },+ sweep,+ }),+ );+};+/*** Recover operations whose executing host died mid-step, without depending on a* scheduler being configured.@@ -99,35 +143,39 @@ export async function runOpportunisticSweep({* `runWithScheduledWorkScope` (whose boundary flush would then wait on it).*/export const scheduleOpportunisticStaleSweep = (): void => {- const redis = getAgentRuntimeRedisClient();- if (!redis) return;-- after(() =>- runOpportunisticSweep({- claim: async () => {- const claimed = await redis.set(- OPPORTUNISTIC_SWEEP_SLOT_KEY,- String(Date.now()),- 'PX',- OPPORTUNISTIC_SWEEP_INTERVAL_MS,- 'NX',- );+ scheduleSlottedSweep(+ 'opportunistic-sweep',+ OPPORTUNISTIC_SWEEP_SLOT_KEY,+ OPPORTUNISTIC_SWEEP_INTERVAL_MS,+ async () => {+ const db = await getServerDB();+ const [result] = await Promise.all([+ new StaleOperationReaper(db).sweep(),+ recoverChannels(db),+ ]);+ log('sweep: %O', result);+ },+ );+};- return claimed === 'OK';- },- onError: (error, phase) => {- // A failed tick is invisible by design (the delivery that hosted it- // succeeded), so log it loudly enough to be found from the timeline.- console.error(`[opportunistic-sweep] ${phase} failed: %O`, error);- },- sweep: async () => {- const db = await getServerDB();- const [result] = await Promise.all([- new StaleOperationReaper(db).sweep(),- recoverChannels(db),- ]);- log('sweep: %O', result);- },- }),+/**+ * Recover verification rounds stranded in `verifying` (see+ * `sweepStuckVerifyRuns`), on the same always-exercised path as the stale+ * operation sweep.+ *+ * Its dedicated route, `/api/workflows/verify/sweep`, expects a QStash+ * Schedule that no deployment registers, so a round whose judging died after+ * claiming `verifying` stayed there for good, and with it the acceptance and+ * the task waiting on its verdict.+ */+export const scheduleOpportunisticVerifySweep = (): void => {+ scheduleSlottedSweep(+ 'opportunistic-verify-sweep',+ OPPORTUNISTIC_VERIFY_SWEEP_SLOT_KEY,+ OPPORTUNISTIC_VERIFY_SWEEP_INTERVAL_MS,+ async () => {+ const result = await sweepStuckVerifyRuns(await getServerDB());+ log('verify sweep: %O', result);+ },);};diff --git a/apps/server/src/services/verify/__tests__/completionDispatch.test.ts b/apps/server/src/services/verify/__tests__/completionDispatch.test.tsnew file mode 100644index 00000000000..6af5c29a892--- /dev/null+++ b/apps/server/src/services/verify/__tests__/completionDispatch.test.ts@@ -0,0 +1,87 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ scheduleVerifyOnCompletion,+ VERIFY_ON_OPERATION_COMPLETE_PATH,+} from '../completionDispatch';++const { after, deliverWebhook, findByOperation, isQueueMode, runVerifyOnCompletion } = vi.hoisted(+ () => ({+ after: vi.fn(),+ deliverWebhook: vi.fn(),+ findByOperation: vi.fn(),+ isQueueMode: vi.fn(),+ runVerifyOnCompletion: vi.fn(),+ }),+);++vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after }));+vi.mock('@/server/services/agentRuntime/hooks/httpWebhook', () => ({ deliverWebhook }));+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: isQueueMode }));+vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(function () {+ return { findByOperation };+ }),+}));+vi.mock('../lifecycle', () => ({ runVerifyOnCompletion }));++const db = {} as any;+const params = { deliverable: 'final reply', goal: 'the task', operationId: 'op-1' };+const confirmedRun = { plan: [{ id: 'c1' }], planConfirmedAt: new Date() };++describe('scheduleVerifyOnCompletion', () => {+ beforeEach(() => {+ [after, deliverWebhook, findByOperation, isQueueMode, runVerifyOnCompletion].forEach((m) =>+ m.mockReset(),+ );+ isQueueMode.mockReturnValue(true);+ findByOperation.mockResolvedValue(confirmedRun);+ deliverWebhook.mockResolvedValue(undefined);+ });++ it('publishes the gate to its own QStash delivery, deduplicated per operation', async () => {+ // A producer that retries its terminal call reaches this once per retry;+ // the deduplication id is what keeps that from starting one gate each.+ await scheduleVerifyOnCompletion(db, 'u1', params, 'ws-1');++ expect(deliverWebhook).toHaveBeenCalledWith(+ { delivery: 'qstash', fallback: 'none', url: VERIFY_ON_OPERATION_COMPLETE_PATH },+ { ...params, userId: 'u1', workspaceId: 'ws-1' },+ { deduplicationId: 'verify-completion:op-1' },+ );+ // Nothing rides the completing request.+ expect(after).not.toHaveBeenCalled();+ });++ it('publishes nothing for a run without a confirmed plan', async () => {+ findByOperation.mockResolvedValue({ plan: [{ id: 'c1' }], planConfirmedAt: null });++ await scheduleVerifyOnCompletion(db, 'u1', params);++ expect(deliverWebhook).not.toHaveBeenCalled();+ expect(after).not.toHaveBeenCalled();+ });++ it('judges in-band when the publish fails', async () => {+ deliverWebhook.mockRejectedValue(new Error('qstash down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ await expect(scheduleVerifyOnCompletion(db, 'u1', params)).resolves.toBeUndefined();++ expect(after).toHaveBeenCalledTimes(1);+ await after.mock.calls[0][0]();+ expect(runVerifyOnCompletion).toHaveBeenCalledWith(db, 'u1', params, undefined);+ });++ it('stays post-response work without a queue runtime', async () => {+ isQueueMode.mockReturnValue(false);++ await scheduleVerifyOnCompletion(db, 'u1', params);++ expect(deliverWebhook).not.toHaveBeenCalled();+ expect(after).toHaveBeenCalledTimes(1);+ await after.mock.calls[0][0]();+ expect(runVerifyOnCompletion).toHaveBeenCalledWith(db, 'u1', params, undefined);+ });+});diff --git a/apps/server/src/services/verify/__tests__/sweep.test.ts b/apps/server/src/services/verify/__tests__/sweep.test.tsindex b36926d049d..510d773abed 100644--- a/apps/server/src/services/verify/__tests__/sweep.test.ts+++ b/apps/server/src/services/verify/__tests__/sweep.test.ts@@ -9,19 +9,29 @@ const {settleFailedRepair,claimVerifying,findStuckVerifying,+ listByAcceptance,+ messageFindById,operationFindById,recompute,+ recordVerifierRedrive,+ redriveClaimedVerification,resultListByRun,upsertByCheckItem,finalizeVerifyRun,+ findVerifyMessageByOperationId,} = vi.hoisted(() => ({releaseUndeliveredRound: vi.fn(),settleFailedRepair: vi.fn(),claimVerifying: vi.fn(),finalizeVerifyRun: vi.fn(),findStuckVerifying: vi.fn(),+ findVerifyMessageByOperationId: vi.fn(),+ listByAcceptance: vi.fn(),+ messageFindById: vi.fn(),operationFindById: vi.fn(),recompute: vi.fn(),+ recordVerifierRedrive: vi.fn(),+ redriveClaimedVerification: vi.fn(),resultListByRun: vi.fn(),upsertByCheckItem: vi.fn(),}));@@ -29,7 +39,7 @@ const {vi.mock('@/database/models/verifyRun', () => ({VerifyRunModel: Object.assign(vi.fn(function () {- return {};+ return { listByAcceptance, recordVerifierRedrive };}),{ findStuckVerifying },),@@ -49,6 +59,12 @@ vi.mock('../statusService', () => ({return { claimVerifying, recompute };}),}));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn(function () {+ return { findById: messageFindById, findVerifyMessageByOperationId };+ }),+}));+vi.mock('../lifecycle', () => ({ redriveClaimedVerification }));vi.mock('../repairTerminal', () => ({ settleFailedRepair }));vi.mock('../undeliveredRound', () => ({ releaseUndeliveredRound }));vi.mock('../settle', () => ({ finalizeVerifyRun }));@@ -82,8 +98,13 @@ describe('sweepStuckVerifyRuns', () => {claimVerifying,finalizeVerifyRun,findStuckVerifying,+ findVerifyMessageByOperationId,+ listByAcceptance,+ messageFindById,operationFindById,recompute,+ recordVerifierRedrive,+ redriveClaimedVerification,resultListByRun,upsertByCheckItem,].forEach((m) => m.mockReset());@@ -299,6 +320,79 @@ describe('sweepStuckVerifyRuns', () => {expect(outcome.skipped).toBe(1);expect(outcome.settled).toEqual(['run-newer']);});+ describe('a round whose judging never started a verifier', () => {+ // The production shape: the completion gate claimed `verifying`, then died+ // before any verifier spawned, so every check is pending with no verifier.+ const neverJudged = (overrides?: Partial<Record<string, unknown>>) =>+ stuckRun({+ acceptanceId: 'acc-1',+ roundIndex: 3,+ updatedAt: new Date(NOW.getTime() - VERIFY_ABANDONED_MS - 1000),+ ...overrides,+ });++ beforeEach(() => {+ resultListByRun.mockResolvedValue([+ { checkItemId: 'c1', status: 'pending', verifierOperationId: null, verdict: null },+ { checkItemId: 'c2', status: 'pending', verifierOperationId: null, verdict: null },+ ]);+ operationFindById.mockResolvedValue({ id: 'op-1', status: 'done' });+ listByAcceptance.mockResolvedValue([{ roundIndex: 2 }, { roundIndex: 3 }]);+ findVerifyMessageByOperationId.mockResolvedValue({ id: 'card-7', parentId: 'msg-final' });+ messageFindById.mockResolvedValue({ content: 'final delivery', id: 'msg-final' });+ });++ it('judges the latest round again with the final reply instead of closing it', async () => {+ singlePage([neverJudged()]);++ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });++ expect(outcome.redriven).toEqual(['run-1']);+ expect(outcome.abandoned).toEqual([]);+ expect(recordVerifierRedrive).toHaveBeenCalledWith('run-1', NOW);+ expect(redriveClaimedVerification).toHaveBeenCalledWith(+ db,+ 'u1',+ { deliverable: 'final delivery', operationId: 'op-1' },+ undefined,+ );+ // The redriven judge owns the ending; nothing is stamped errored.+ expect(upsertByCheckItem).not.toHaveBeenCalled();+ expect(finalizeVerifyRun).not.toHaveBeenCalled();+ });++ it('closes it as errored once it was already re-driven', async () => {+ singlePage([neverJudged({ metadata: { verifierRedrivenAt: '2026-08-09T23:00:00Z' } })]);++ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });++ expect(outcome.abandoned).toEqual(['run-1']);+ expect(redriveClaimedVerification).not.toHaveBeenCalled();+ });++ it('closes a superseded round without driving the task', async () => {+ // r2 and r3 both stranded: r2 must not pause the task r3 is about to judge.+ singlePage([neverJudged({ roundIndex: 2 })]);++ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });++ expect(outcome.abandoned).toEqual(['run-1']);+ expect(redriveClaimedVerification).not.toHaveBeenCalled();+ expect(recompute).toHaveBeenCalledWith('op-1');+ expect(finalizeVerifyRun).not.toHaveBeenCalled();+ });++ it('closes it when the builder run did not finish successfully', async () => {+ singlePage([neverJudged()]);+ operationFindById.mockResolvedValue({ id: 'op-1', status: 'error' });++ const outcome = await sweepStuckVerifyRuns(db, { now: NOW });++ expect(outcome.abandoned).toEqual(['run-1']);+ expect(redriveClaimedVerification).not.toHaveBeenCalled();+ });+ });+it('recovers a planned repair whose operation died before judging began', async () => {singlePage([stuckRun({ status: 'planned' })]);settleFailedRepair.mockResolvedValue(true);diff --git a/apps/server/src/services/verify/completionDispatch.ts b/apps/server/src/services/verify/completionDispatch.tsnew file mode 100644index 00000000000..88043533316--- /dev/null+++ b/apps/server/src/services/verify/completionDispatch.ts@@ -0,0 +1,78 @@+import debug from 'debug';++import { VerifyRunModel } from '@/database/models/verifyRun';+import type { LobeChatDatabase } from '@/database/type';+import { deliverWebhook } from '@/server/services/agentRuntime/hooks/httpWebhook';+import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';+import { after } from '@/server/utils/scheduleAfterResponse';++import { runVerifyOnCompletion, type RunVerifyOnCompletionParams } from './lifecycle';++const log = debug('lobe-server:verify-completion-dispatch');++export const VERIFY_ON_OPERATION_COMPLETE_PATH = '/api/workflows/verify/on-operation-complete';++export interface VerifyOnOperationCompletePayload extends RunVerifyOnCompletionParams {+ userId: string;+ workspaceId?: string;+}++/**+ * Start the completion-time verify gate in its own invocation.+ *+ * It used to ride the completing request as post-response work. That request+ * can outlive its proxy (a heterogeneous `heteroFinish` past the 120 s edge+ * timeout) or its function, and the gate dies with it after it has already+ * claimed `verifying` β before any verifier exists. The producer then retries+ * the same completion, every retry meets the claim it cannot take over, and+ * the round is never judged. Published to QStash instead, the gate gets its own+ * function budget and redelivery, and the deduplication id collapses those+ * retried completions into one gate.+ *+ * Without a queue runtime (self-hosted local mode) there is no QStash, so the+ * gate stays post-response work. A failed publish falls back the same way:+ * judging late in-band beats not judging. Runs without a confirmed plan publish+ * nothing β the gate would only read the plan and return. Never throws.+ */+export const scheduleVerifyOnCompletion = async (+ db: LobeChatDatabase,+ userId: string,+ params: RunVerifyOnCompletionParams,+ workspaceId?: string,+): Promise<void> => {+ const runInBand = () => after(() => runVerifyOnCompletion(db, userId, params, workspaceId));++ if (!isQueueAgentRuntimeEnabled()) {+ runInBand();+ return;+ }++ try {+ const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(+ params.operationId,+ );+ if (!run?.plan?.length || !run.planConfirmedAt) return;+ } catch (error) {+ // Unknown is not "no plan": let the gate read it again in-band.+ log('plan lookup failed for op %s: %O', params.operationId, error);+ runInBand();+ return;+ }++ const payload: VerifyOnOperationCompletePayload = {+ ...params,+ userId,+ ...(workspaceId ? { workspaceId } : {}),+ };+ try {+ await deliverWebhook(+ { delivery: 'qstash', fallback: 'none', url: VERIFY_ON_OPERATION_COMPLETE_PATH },+ payload as unknown as Record<string, unknown>,+ { deduplicationId: `verify-completion:${params.operationId}` },+ );+ } catch (error) {+ console.error('[verify] publishing the completion gate failed, judging in-band: %O', error);+ log('publish failed for op %s, falling back to post-response work', params.operationId);+ runInBand();+ }+};diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.tsindex 550f31e0e8d..1077e08da80 100644--- a/apps/server/src/services/verify/index.ts+++ b/apps/server/src/services/verify/index.ts@@ -22,6 +22,11 @@ export {buildCheckReviewOverlay,} from './acceptanceService';export { createVerifierAgentRunner } from './agentVerifier';+export {+ scheduleVerifyOnCompletion,+ VERIFY_ON_OPERATION_COMPLETE_PATH,+ type VerifyOnOperationCompletePayload,+} from './completionDispatch';export { mapWithConcurrency } from './concurrency';export { coverageGaps, readRequiredEvidence } from './evidenceCoverage';export {diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.tsindex d2a9b4b4a1d..24d1606e53e 100644--- a/apps/server/src/services/verify/lifecycle.ts+++ b/apps/server/src/services/verify/lifecycle.ts@@ -64,6 +64,112 @@ export const resolveVerificationDeliverable = async (.join('\n\n');};+type VerifiedOperation = NonNullable<Awaited<ReturnType<AgentOperationModel['findById']>>>;++/**+ * Judge a run whose `verifying` lease the caller already holds, then settle it.+ * Shared by the completion-time gate and the stuck-run sweep's re-drive, so both+ * spawn verifiers and drive the task the same way.+ */+const judgeClaimedRun = async (+ db: LobeChatDatabase,+ userId: string,+ params: {+ deliverable: string;+ goal: string;+ operation: VerifiedOperation;+ verifierAgentId?: string;+ },+ workspaceId?: string,+): Promise<void> => {+ const { goal, operation: op, verifierAgentId } = params;++ const modelConfig = await resolveVerifyModelConfig(+ db,+ userId,+ {+ parentModel: op.model,+ parentProvider: op.provider,+ verifierAgentId,+ },+ workspaceId,+ );+ const resolvedDeliverable = await resolveVerificationDeliverable(+ db,+ userId,+ params.deliverable,+ op.taskId,+ workspaceId,+ );++ const executor = new VerifyExecutorService(db, userId, workspaceId);+ await executor.execute({+ deliverable: resolvedDeliverable,+ goal,+ modelConfig,+ operationId: op.id,+ // `agent`-type checks run as the task-pinned verify agent (or the builtin+ // one), which writes its verdict back via the submitVerifyResult tool.+ runVerifierAgent: createVerifierAgentRunner({+ db,+ deliverable: resolvedDeliverable,+ model: modelConfig.model,+ provider: modelConfig.provider,+ taskId: op.taskId,+ topicId: op.topicId,+ userId,+ verifierAgentId,+ workspaceId,+ }),+ });++ // 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,+ op.id,+ { report: { deliverable: resolvedDeliverable, goal, modelConfig } },+ workspaceId,+ );+};++/**+ * Judge again a round whose first attempt claimed `verifying` and then died+ * before any verifier started. The caller must already hold the `verifying`+ * lease (the sweep claims it), so this skips the completion gate's claim and+ * evidence phase: the builder's evidence is already on the round.+ */+export const redriveClaimedVerification = async (+ db: LobeChatDatabase,+ userId: string,+ params: { deliverable: string; operationId: string },+ workspaceId?: string,+): Promise<void> => {+ const op = await new AgentOperationModel(db, userId, workspaceId).findById(params.operationId);+ if (!op) throw new Error(`Operation "${params.operationId}" not found`);++ const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(op.id);+ const acceptance = op.taskId+ ? await resolveTaskAcceptance(db, userId, op.taskId, workspaceId)+ : undefined;++ await judgeClaimedRun(+ db,+ userId,+ {+ deliverable: params.deliverable,+ goal: run?.goal ?? '',+ operation: op,+ verifierAgentId: acceptance?.config.verifierAgentId ?? undefined,+ },+ workspaceId,+ );+};+export interface RunVerifyOnCompletionParams {/** The run's final output / artifacts, judged against the plan. */deliverable: string;@@ -241,63 +347,14 @@ const executeVerifyLifecycle = async (return;}- const verifierAgentId = resolvedAcceptance?.config.verifierAgentId ?? undefined;-- const modelConfig = await resolveVerifyModelConfig(+ await judgeClaimedRun(db,userId,{- parentModel: op.model,- parentProvider: op.provider,- verifierAgentId,- },- workspaceId,- );- const resolvedDeliverable = await resolveVerificationDeliverable(- db,- userId,- params.deliverable,- op.taskId,- workspaceId,- );- const verificationGoal = params.goal || run.goal || '';-- const executor = new VerifyExecutorService(db, userId, workspaceId);- await executor.execute({- deliverable: resolvedDeliverable,- goal: verificationGoal,- modelConfig,- operationId: params.operationId,- // `agent`-type checks run as the task-pinned verify agent (or the builtin- // one), which writes its verdict back via the submitVerifyResult tool.- runVerifierAgent: createVerifierAgentRunner({- db,- deliverable: resolvedDeliverable,- model: modelConfig.model,- provider: modelConfig.provider,- taskId: op.taskId,- topicId: op.topicId,- userId,- verifierAgentId,- workspaceId,- }),- });-- // 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: resolvedDeliverable,- goal: verificationGoal,- modelConfig,- },+ deliverable: params.deliverable,+ goal: params.goal || run.goal || '',+ operation: op,+ verifierAgentId: resolvedAcceptance?.config.verifierAgentId ?? undefined,},workspaceId,);@@ -314,6 +371,19 @@ export const runVerifyOnCompletion = async (workspaceId?: string,): Promise<void> => executeVerifyLifecycle(db, userId, params, workspaceId, false);+/**+ * The completion gate as delivered by QStash (see `scheduleVerifyOnCompletion`).+ * Unlike the in-band form it rethrows, so a gate that failed β or found its+ * claim still held by an attempt that may have died β is redelivered instead of+ * reported as done.+ */+export const runVerifyOnCompletionFromQueue = async (+ db: LobeChatDatabase,+ userId: string,+ params: RunVerifyOnCompletionParams,+ workspaceId?: string,+): Promise<void> => executeVerifyLifecycle(db, userId, params, workspaceId, false, true);+/** The only entry point allowed to advance a task run out of evidence collection. */export const runVerifyAfterEvidenceSubmission = async (db: LobeChatDatabase,diff --git a/apps/server/src/services/verify/sweep.ts b/apps/server/src/services/verify/sweep.tsindex 47212b79274..4de2a8fb611 100644--- a/apps/server/src/services/verify/sweep.ts+++ b/apps/server/src/services/verify/sweep.ts@@ -3,11 +3,13 @@ import { isAgentOperationInFlight } from '@lobechat/types';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';+import { MessageModel } from '@/database/models/message';import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';import { VerifyRunModel } from '@/database/models/verifyRun';import type { VerifyRunItem } from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';+import { redriveClaimedVerification } from './lifecycle';import { settleFailedRepair } from './repairTerminal';import { planItemToPendingResult } from './resultSnapshot';import { finalizeVerifyRun } from './settle';@@ -26,6 +28,8 @@ const SWEEP_MAX_RUNS = 1000;export interface VerifySweepOutcome {/** Runs whose outstanding checks were closed as `errored` before the rollup. */abandoned: string[];+ /** Runs whose judging never started a verifier and was started again. */+ redriven: string[];/** Task rounds taken off their acceptance because the run never delivered. */released: string[];/** Runs whose checks had all landed and only needed the missing rollup. */@@ -56,6 +60,14 @@ export interface VerifySweepOutcome {* carry no verdict and never will, so after {@link VERIFY_ABANDONED_MS} they* are closed as `errored` (an infra failure, not a delivery judgment, so they* neither gate delivery nor seed auto-repair) and the rollup follows.+ * - **no verifier ever started** β the attempt died between claiming+ * `verifying` and spawning its verifiers, so the builder's evidence was never+ * judged at all. Closing it as `errored` would end the round without a+ * verdict, so the latest round of a successful run is judged again, once+ * (see {@link canRedrive}). A second stall falls back to `errored`.+ *+ * A round a later round of its acceptance superseded only gets its rollup; the+ * task is driven by the latest round alone.** A check bound to a verifier operation that is still live keeps the whole run* out of the sweep however old it is β an agent verifier is a full sub-agent run@@ -71,7 +83,13 @@ export const sweepStuckVerifyRuns = async (const now = options?.now ?? new Date();const pageSize = options?.pageSize ?? SWEEP_PAGE_SIZE;const staleBefore = new Date(now.getTime() - VERIFY_ROLLUP_GRACE_MS);- const outcome: VerifySweepOutcome = { abandoned: [], released: [], settled: [], skipped: 0 };+ const outcome: VerifySweepOutcome = {+ abandoned: [],+ redriven: [],+ released: [],+ settled: [],+ skipped: 0,+ };// Walk the whole stranded set, not just its oldest page: rows the sweep leaves// alone keep their timestamp, so a single fixed-size read would return the same@@ -115,7 +133,7 @@ const recoverRun = async (db: LobeChatDatabase,run: VerifyRunItem,now: Date,-): Promise<'abandoned' | 'released' | 'settled' | 'skipped'> => {+): Promise<'abandoned' | 'redriven' | 'released' | 'settled' | 'skipped'> => {const operationId = run.operationId;if (!operationId) return 'skipped';const workspaceId = run.workspaceId ?? undefined;@@ -141,10 +159,13 @@ const recoverRun = async (return !result || PENDING_RESULT_STATUSES.has(result.status);});+ const operationModel = new AgentOperationModel(db, run.userId, workspaceId);+ const latest = await isLatestRound(db, run);+ let redrive = false;+if (outstanding.length > 0) {if (now.getTime() - run.updatedAt.getTime() < VERIFY_ABANDONED_MS) return 'skipped';- const operationModel = new AgentOperationModel(db, run.userId, workspaceId);for (const item of outstanding) {const verifierOperationId = byItem.get(item.id)?.verifierOperationId;if (!verifierOperationId) continue;@@ -155,6 +176,8 @@ const recoverRun = async (// A still-live verifier (parked ones included) can still produce a verdict.if (verifierOp && isAgentOperationInFlight(verifierOp.status)) return 'skipped';}++ redrive = latest && (await canRedrive(run, outstanding, byItem, operationModel));}// Committed to acting β take the lease first. Everything below has side effects@@ -176,6 +199,22 @@ const recoverRun = async ()return 'skipped';+ if (redrive) {+ // Stamped before judging so a re-drive that dies the same way is not+ // re-driven forever: the next tick sees the stamp and closes it as errored.+ await new VerifyRunModel(db, run.userId, workspaceId).recordVerifierRedrive(run.id, now);+ const builder = await operationModel.findById(operationId);+ const deliverable = await resolveFinalDeliverable(+ db,+ run.userId,+ { operationId, topicId: builder?.topicId ?? undefined },+ workspaceId,+ );+ await redriveClaimedVerification(db, run.userId, { deliverable, operationId }, workspaceId);+ log('re-drove run %s (op %s): no verifier had started', run.id, operationId);+ return 'redriven';+ }+if (outstanding.length > 0) {await Promise.all(outstanding.map((item) =>@@ -200,10 +239,61 @@ const recoverRun = async (await statusService.recompute(operationId);// No report context β the sweep holds no deliverable. The task is still driven,- // which is the whole point: the goal has been waiting on this verdict.- await finalizeVerifyRun(db, run.userId, operationId, {}, workspaceId);+ // which is the whole point: the goal has been waiting on this verdict. Not for+ // a superseded round, though: its task now waits on the later round, and+ // driving it from here would pause the task under that round's feet.+ if (latest) await finalizeVerifyRun(db, run.userId, operationId, {}, workspaceId);const action = outstanding.length > 0 ? 'abandoned' : 'settled';log('recovered run %s (op %s) as %s', run.id, operationId, action);return action;};++/** Whether no later round of the same acceptance superseded this one. */+const isLatestRound = async (db: LobeChatDatabase, run: VerifyRunItem): Promise<boolean> => {+ if (!run.acceptanceId) return true;+ const rounds = await new VerifyRunModel(+ db,+ run.userId,+ run.workspaceId ?? undefined,+ ).listByAcceptance(run.acceptanceId);+ return rounds.every((round) => (round.roundIndex ?? 0) <= (run.roundIndex ?? 0));+};++/**+ * Whether a stalled latest round should be judged again rather than closed as+ * errored. Only when nothing was ever judged (no outstanding check reached a+ * verifier), the builder run finished successfully, and the round was not+ * re-driven before.+ */+const canRedrive = async (+ run: VerifyRunItem,+ outstanding: VerifyCheckItem[],+ byItem: Map<string, { verifierOperationId: string | null }>,+ operationModel: AgentOperationModel,+): Promise<boolean> => {+ if (run.metadata?.verifierRedrivenAt) return false;+ if (outstanding.some((item) => byItem.get(item.id)?.verifierOperationId)) return false;++ const builder = await operationModel.findById(run.operationId!);+ return builder?.status === 'done';+};++/**+ * The builder's final reply, read back the way the completion gate received it:+ * the run's delivery-checker card hangs off the assistant message that+ * completion carried.+ */+const resolveFinalDeliverable = async (+ db: LobeChatDatabase,+ userId: string,+ { operationId, topicId }: { operationId: string; topicId?: string },+ workspaceId?: string,+): Promise<string> => {+ const messageModel = new MessageModel(db, userId, workspaceId);+ const card = await messageModel.findVerifyMessageByOperationId(operationId, topicId);+ if (!card?.parentId) return '';++ const reply = await messageModel.findById(card.parentId);+ return typeof reply?.content === 'string' ? reply.content : '';+};diff --git a/packages/database/src/models/__tests__/messages/message.verifyLookup.test.ts b/packages/database/src/models/__tests__/messages/message.verifyLookup.test.tsindex 699d4fbb7c4..31ec2a81428 100644--- a/packages/database/src/models/__tests__/messages/message.verifyLookup.test.ts+++ b/packages/database/src/models/__tests__/messages/message.verifyLookup.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { users } from '../../../schemas';+import { topics, users } from '../../../schemas';import type { LobeChatDatabase } from '../../../type';import { MessageModel } from '../../message';@@ -59,6 +59,26 @@ describe('MessageModel.findVerifyMessageByOperationId', () => {expect(found).toBeUndefined();});+ it('narrows the lookup to the given topic', async () => {+ await serverDB.insert(topics).values([+ { id: 'verify-lookup-tpc-a', userId },+ { id: 'verify-lookup-tpc-b', userId },+ ]);+ const card = await messageModel.create({+ content: '',+ metadata: { verifyOperationId: 'op-4' },+ role: 'verify',+ topicId: 'verify-lookup-tpc-a',+ });++ expect(+ (await messageModel.findVerifyMessageByOperationId('op-4', 'verify-lookup-tpc-a'))?.id,+ ).toBe(card.id);+ expect(+ await messageModel.findVerifyMessageByOperationId('op-4', 'verify-lookup-tpc-b'),+ ).toBeUndefined();+ });+it('is scoped to the owning user', async () => {await messageModel.create({content: '',diff --git a/packages/database/src/models/message/lookup.ts b/packages/database/src/models/message/lookup.tsindex 965494c419e..ed7c43a8a40 100644--- a/packages/database/src/models/message/lookup.ts+++ b/packages/database/src/models/message/lookup.ts@@ -182,11 +182,15 @@ export class MessageLookupQueries extends MessageScope {* Resolve the `role='verify'` delivery-checker card for an Agent Run (created* with `metadata.verifyOperationId = operationId`). Used by auto-repair to* persist the failure feedback onto the card it belongs to.+ *+ * Pass the run's `topicId` when known: it keeps the JSONB predicate inside+ * the topic's own (indexed) rows instead of every row the user owns.*/- findVerifyMessageByOperationId = async (operationId: string) => {+ findVerifyMessageByOperationId = async (operationId: string, topicId?: string) => {return this.db.query.messages.findFirst({where: and(this.ownership(),+ topicId ? eq(messages.topicId, topicId) : undefined,eq(messages.role, 'verify'),sql`${messages.metadata}->>'verifyOperationId' = ${operationId}`,),diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 3609291d876..efb00da53a8 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -636,6 +636,16 @@ export class VerifyRunModel {.where(and(eq(verifyRuns.id, runId), this.ownership()));};+ /** Stamp the sweep's one re-drive of this round without clobbering the rest of `metadata`. */+ recordVerifierRedrive = async (runId: string, at: Date): Promise<void> => {+ await this.db+ .update(verifyRuns)+ .set({+ metadata: sql`coalesce(${verifyRuns.metadata}, '{}'::jsonb) || jsonb_build_object('verifierRedrivenAt', ${at.toISOString()}::text)`,+ })+ .where(and(eq(verifyRuns.id, runId), this.ownership()));+ };+setMetadata = async (runId: string, metadata: Record<string, unknown>): Promise<void> => {await this.db.update(verifyRuns)diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex c43f0d1bd89..2e24e5200a1 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -712,6 +712,12 @@ export interface VerifyRunMetadata {* and never absorbs another flow, even while it holds no results yet.*/replayOfRunId?: string;+ /**+ * When the stuck-run sweep re-drove this round's judging after its first+ * attempt died before any verifier started. A round is re-driven at most+ * once; a second stall is closed as `errored`.+ */+ verifierRedrivenAt?: string;}export type VerifyVisualizationValue = boolean | null | number | string;