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.

πŸ› fix: settle failed acceptance repairs and scope their evidence (#19685)

Arvin Xu8f2bc9ef892b
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
index b94185b3791..196b0e4d775 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.test.ts
@@ -633,6 +633,52 @@ describe('AgentRuntimeService', () => {
);
});
+ it('waits for dependent records before dispatch without losing the prepared context', async () => {
+ let release!: () => void;
+ const prepared = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const onOperationCreated = vi.fn<(operationId: string) => Promise<void>>(
+ async () => prepared,
+ );
+ const initialContext = {
+ ...mockParams.initialContext,
+ payload: {
+ assistantMessageId: 'repair-assistant',
+ parentMessageId: 'verify-card',
+ },
+ } as OperationCreationParams['initialContext'];
+ const creation = service.createOperation({
+ ...mockParams,
+ initialContext,
+ onOperationCreated,
+ });
+ try {
+ await vi.waitFor(() =>
+ expect(onOperationCreated).toHaveBeenCalledWith(mockParams.operationId),
+ );
+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();
+ } finally {
+ release();
+ }
+ await creation;
+ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ context: initialContext }),
+ );
+ });
+
+ it('does not dispatch when dependent record preparation fails', async () => {
+ await expect(
+ service.createOperation({
+ ...mockParams,
+ onOperationCreated: async () => {
+ throw new Error('Plan unavailable');
+ },
+ }),
+ ).rejects.toThrow('Plan unavailable');
+ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();
+ });
+
it('should create operation successfully with autoStart=false', async () => {
const params = { ...mockParams, autoStart: false };
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 8d348768c4a..243bf38ca82 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -1266,6 +1266,8 @@ export class AgentRuntimeService {
onInterventionPrepared?.();
}
+ await params.onOperationCreated?.(operationId);
+
throwIfAborted(signal, 'Agent execution aborted before first step scheduling');
let messageId: string | undefined;
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index ccfe455d480..24a517a45ef 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -26,7 +26,11 @@ import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
import { parseAgentSignalMarker } from '@/server/services/agentSignal/operationMarker';
import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
-import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';
+import {
+ instantiateVerifyPlanOnStart,
+ runVerifyOnCompletion,
+ settleFailedRepair,
+} from '@/server/services/verify';
import {
registerWorksForOperation,
resolveRunWorkAccessScope,
@@ -1043,6 +1047,17 @@ export class CompletionLifecycle {
);
}
+ if (reason === 'error' || reason === 'interrupted') {
+ after(async () => {
+ await settleFailedRepair(
+ this.serverDB,
+ runOrigin.userId || this.userId,
+ operationId,
+ this.workspaceId,
+ );
+ });
+ }
+
// Register entity files edited this round as `file` Works. On the
// gateway/queue path this already ran BEFORE the terminal snapshot (see
// `registerFileWorks`) and no-ops via the state marker; here it is the
diff --git a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
index 4d6ebc906b4..ed72160cb78 100644
--- a/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/completionVerifyScheduling.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import * as verifyServices from '@/server/services/verify';
@@ -23,6 +23,7 @@ vi.mock('@/server/services/workRegistration', () => ({ registerWorksForOperation
* handed to the host as post-response work instead.
*/
describe('CompletionLifecycle β€” verify gate scheduling', () => {
+ afterEach(() => vi.restoreAllMocks());
beforeEach(() => {
after.mockReset();
});
@@ -52,4 +53,48 @@ describe('CompletionLifecycle β€” verify gate scheduling', () => {
expect(runVerify).toHaveBeenCalledTimes(1);
expect(runVerify.mock.calls[0][2]).toMatchObject({ operationId: 'op-1' });
});
+ it.each(['error', 'interrupted'])(
+ 'does not wait for unfinished plan generation on %s',
+ async (reason) => {
+ const lifecycle = new CompletionLifecycle({} as any, 'user-1');
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ const dispatch = vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ let release!: () => void;
+ const pending = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ (lifecycle as any).verifyPlanInstantiations.set('top-level-op', pending);
+ let completed = false;
+ const completion = lifecycle
+ .dispatchHooks('top-level-op', { host: { hooks: [] }, origin: {}, status: reason }, reason)
+ .then(() => {
+ completed = true;
+ });
+ try {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(completed).toBe(true);
+ expect(dispatch).toHaveBeenCalled();
+ } finally {
+ release();
+ await completion;
+ }
+ },
+ );
+
+ it.each(['error', 'interrupted'])('settles an aborted repair on %s', async (reason) => {
+ const lifecycle = new CompletionLifecycle({} as any, 'user-1');
+ vi.spyOn(lifecycle as any, 'persistCompletion').mockResolvedValue(undefined);
+ vi.spyOn(hookDispatcher, 'dispatch').mockResolvedValue(undefined as any);
+ vi.spyOn(hookDispatcher, 'unregister').mockImplementation(function () {});
+ const settle = vi.spyOn(verifyServices, 'settleFailedRepair').mockResolvedValue(false);
+
+ await lifecycle.dispatchHooks(
+ 'repair-op',
+ { host: { hooks: [] }, origin: {}, status: 'error' },
+ reason,
+ );
+ await Promise.all(after.mock.calls.map(([callback]) => callback()));
+ expect(settle).toHaveBeenCalledWith(expect.anything(), 'user-1', 'repair-op', undefined);
+ });
});
diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.ts
index 398bbe17ebc..de320f08a66 100644
--- a/apps/server/src/services/agentRuntime/types.ts
+++ b/apps/server/src/services/agentRuntime/types.ts
@@ -536,6 +536,8 @@ export interface OperationCreationParams {
modelRuntimeConfig?: any;
/** Marks the source claim non-rollbackable once deterministic runtime state is durable. */
onInterventionPrepared?: () => void;
+ /** Prepare dependent records after persistence and before execution dispatch. */
+ onOperationCreated?: (operationId: string) => Promise<void>;
/** Credentials frozen for the run; see {@link FrozenCredentialFacts}. */
operationCredentials?: FrozenCredentialFacts;
operationId: string;
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
index a542461d9b8..1da3f642376 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts
@@ -301,6 +301,32 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>
const findUserMessageCreate = () =>
mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
+ it('prepares dependent records before dispatching the heterogeneous process', async () => {
+ let release!: () => void;
+ const prepared = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const onOperationCreated = vi.fn<(operationId: string) => Promise<void>>(async () => prepared);
+ const execution = service.execAgent({ agentId: 'agent-1', prompt: 'Fix', onOperationCreated });
+ try {
+ await vi.waitFor(() => expect(onOperationCreated).toHaveBeenCalledTimes(1));
+ expect(recordStartSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: onOperationCreated.mock.calls[0][0] }),
+ );
+ expect(mockDispatchAgentRun).not.toHaveBeenCalled();
+ expect(mockSpawnHeteroSandbox).not.toHaveBeenCalled();
+ } finally {
+ release();
+ }
+ const result = await execution;
+ expect(result.autoStarted).toBe(true);
+ expect(
+ mockDispatchAgentRun.mock.calls.length +
+ mockSpawnHeteroSandbox.mock.calls.length +
+ mockExecuteToolCall.mock.calls.length,
+ ).toBeGreaterThan(0);
+ });
+
it('does not dispatch a heterogeneous run when its durable operation row fails', async () => {
recordStartSpy.mockResolvedValueOnce(false);
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 57693308885..8cc75aa3e2c 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1111,6 +1111,7 @@ export class AiAgentService {
maxSteps,
memberDeviceOverride,
operationTaskId,
+ onOperationCreated: params.onOperationCreated,
parentOperationId,
pinnedHeterogeneousTopicModel: turn.pinnedHeterogeneousTopicModel,
requestTrigger: requestTriggerMetadata.trigger,
@@ -1333,6 +1334,7 @@ export class AiAgentService {
approvalSourceOperationId,
approvalSourceToolMessageIds,
autoStart,
+ onOperationCreated: params.onOperationCreated,
botContext,
botPlatformContext,
clientIp,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
index 93fbcb70f0d..401fb7a7916 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch.ts
@@ -53,7 +53,11 @@ import {
supportsCloudHeterogeneousSandbox,
} from '../helpers/heteroErrors';
import { resolveDeviceWorkingDirectoryConfig } from '../resolveDeviceWorkingDirectory';
-import type { BindTopicWorkingDirectoryParams, ExecRunContext } from '../types';
+import type {
+ BindTopicWorkingDirectoryParams,
+ ExecRunContext,
+ InternalExecAgentParams,
+} from '../types';
import { heteroOperationCapabilities } from './heteroOperationCapabilities';
const log = debug('lobe-server:ai-agent-service');
@@ -269,6 +273,7 @@ export interface HeteroDispatchInput {
localDeviceId?: string;
maxSteps?: number;
memberDeviceOverride?: Pick<LobeAgentAgencyConfig, 'boundDeviceId' | 'executionTarget'>;
+ onOperationCreated?: InternalExecAgentParams['onOperationCreated'];
operationTaskId?: string;
parentOperationId?: string;
pinnedHeterogeneousTopicModel?: HeterogeneousTopicPin;
@@ -376,6 +381,8 @@ export const dispatchHeteroAgent = async (
throw new Error('Failed to persist heterogeneous agent operation');
}
+ await input.onOperationCreated?.(operationId);
+
// Read resume session id for next-turn continuity.
const heteroService = new HeterogeneousAgentService(deps.db, deps.userId, {
workspaceId: deps.workspaceId,
diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
index af5b878f32d..57cbcafd845 100644
--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts
+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts
@@ -45,6 +45,7 @@ export interface StartOperationInput {
initialContext: OperationPrepResult['initialContext'];
initialStepCount?: number;
maxSteps?: number;
+ onOperationCreated?: InternalExecAgentParams['onOperationCreated'];
operationId: string;
operationTaskId?: string;
parentOperationId?: string;
@@ -247,6 +248,7 @@ export const startOperation = async (
trigger,
},
autoStart,
+ onOperationCreated: input.onOperationCreated,
botContext,
botPlatformContext,
deviceAccessPolicy: { canUseDevice, reason: deviceAccessReason },
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index 76e68dcb0c9..d4b0842c9a2 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -177,6 +177,8 @@ export interface InternalExecAgentParams extends ExecAgentParams {
* instead of answering itself. Mirrors the client runtime's mention wiring.
*/
mentionedAgents?: RuntimeMentionedAgent[];
+ /** Prepare dependent records after the operation is persisted, before any execution dispatch. */
+ onOperationCreated?: (operationId: string) => Promise<void>;
/** Parent message ID to continue from. Only takes effect when resume is true */
parentMessageId?: string;
queueRetries?: number;
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
index f82a83f0e04..9ce274bdb33 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
@@ -54,12 +54,22 @@ describe('acceptanceEvidenceRuntime', () => {
id: 'evidence-op',
parentOperationId: 'parent-op',
});
- mocks.runFindByOperation.mockResolvedValue({
- id: 'run-1',
- plan: [
- { id: 'criterion-1', index: 0, required: true, title: 'Document', verifierType: 'llm' },
- ],
- });
+ mocks.runFindByOperation.mockImplementation(async (operationId) =>
+ operationId === 'evidence-op'
+ ? null
+ : {
+ id: 'run-1',
+ plan: [
+ {
+ id: 'criterion-1',
+ index: 0,
+ required: true,
+ title: 'Document',
+ verifierType: 'llm',
+ },
+ ],
+ },
+ );
mocks.resultUpsert.mockResolvedValue({ id: 'result-1' });
mocks.evidenceCreateMany.mockResolvedValue([]);
mocks.evidenceListByRun.mockResolvedValue([]);
@@ -129,6 +139,34 @@ describe('acceptanceEvidenceRuntime', () => {
);
});
+ it('submits repair evidence into the repair round instead of its failed parent', async () => {
+ mocks.operationFindById.mockResolvedValue({ id: 'repair-op', parentOperationId: 'parent-op' });
+ mocks.runFindByOperation.mockImplementation(async (id) => ({
+ id: id === 'repair-op' ? 'repair-run' : 'parent-run',
+ plan: [
+ { id: 'criterion-1', index: 0, required: true, title: 'Document', verifierType: 'llm' },
+ ],
+ }));
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'repair-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+ expect(
+ (
+ await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ content: 'corrected output', type: 'text' }],
+ })
+ ).success,
+ ).toBe(true);
+ expect(mocks.resultUpsert).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'repair-op', verifyRunId: 'repair-run' }),
+ );
+ expect(mocks.runFindByOperation).not.toHaveBeenCalledWith('parent-op');
+ });
+
it('keeps writing into the parent run from the post-run evidence turn', async () => {
const runtime = acceptanceEvidenceRuntime.factory({
operationId: 'evidence-op',
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts
index eff78d4c236..9e8e76e3dfc 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts
@@ -32,8 +32,8 @@ class AcceptanceEvidenceExecutionRuntime {
* The builder now captures evidence inside the main Task run, so the plan
* hangs off the operation the tool is called from. The post-run
* evidence-submission turn is a *child* operation, and its plan still lives
- * on the parent β€” hence the parent wins when there is one. Resolving only the
- * parent (the original shape) made every in-run call fail NO_PARENT_OPERATION.
+ * on the parent. Repair operations have a parent AND their own round, so their
+ * own plan must win; otherwise repaired evidence overwrites the failed round.
*/
private resolveRunOperationId = async () => {
if (!this.operationId) return undefined;
@@ -43,7 +43,11 @@ class AcceptanceEvidenceExecutionRuntime {
this.workspaceId,
).findById(this.operationId);
if (!operation) return undefined;
- return operation.parentOperationId ?? operation.id;
+ if (!operation.parentOperationId) return operation.id;
+ const ownRun = await new VerifyRunModel(this.db, this.userId, this.workspaceId).findByOperation(
+ operation.id,
+ );
+ return ownRun ? operation.id : operation.parentOperationId;
};
listCriteria = async () => {
diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
index cb2fc9a0957..cb7e0de3936 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
@@ -1,5 +1,7 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import type * as AcceptanceServiceModule from '../acceptanceService';
import { instantiateVerifyPlanOnStart } from '../planInstantiation';
@@ -12,6 +14,7 @@ const mocks = vi.hoisted(() => ({
acceptanceEnsureForSubject: vi.fn(),
acceptanceUpdate: vi.fn(),
agentExec: vi.fn(),
+
confirmPlan: vi.fn(),
ensureForOperation: vi.fn(),
generateDraftPlan: vi.fn(),
@@ -92,10 +95,11 @@ vi.mock('@/server/services/aiAgent', () => ({
}),
}));
-const db = {} as any;
+const db = { transaction: async (callback: (tx: unknown) => Promise<void>) => callback(db) } as any;
const plan = [{ id: 'check-1', required: true }];
describe('Verify acceptance lifecycle', () => {
+ afterEach(() => vi.restoreAllMocks());
it('reuses the Goal acceptance checklist and supplemental check ids on a repair attempt', async () => {
mocks.goalFind.mockResolvedValue({ id: 'goal-1' });
mocks.taskAcceptanceResolve.mockResolvedValue({
@@ -296,9 +300,65 @@ describe('Verify acceptance lifecycle', () => {
);
});
+ it.each(['normal', 'heterogeneous'])(
+ 'does not report a spawned repair after %s preparation fails',
+ async (runtime) => {
+ mocks.operationFindById.mockResolvedValue({ parentOperationId: null });
+ mocks.runFindByOperation.mockResolvedValue({ id: 'source', plan });
+ mocks.ensureForOperation.mockResolvedValue({ id: 'repair-run' });
+ mocks.confirmPlan.mockRejectedValue(new Error('Plan write failed'));
+ const complete = vi
+ .spyOn(CompletionLifecycle.prototype, 'completeOperation')
+ .mockResolvedValue(undefined);
+ mocks.agentExec.mockImplementation(async ({ onOperationCreated }) => {
+ try {
+ await onOperationCreated('repair-op');
+ } catch (error) {
+ if (runtime === 'heterogeneous') throw error;
+ return { operationId: 'repair-op', success: false };
+ }
+ throw new Error('Unexpected dispatch');
+ });
+ const runner = createRepairRunner({
+ agentId: 'a',
+ db,
+ maxRepairRounds: 2,
+ topicId: 't',
+ userId: 'u',
+ });
+ expect(
+ await runner!({ failedItemIds: ['check-1'], instruction: 'Fix', operationId: 'source' }),
+ ).toBeNull();
+ expect(complete).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationId: 'repair-op',
+ error: { type: 'ServerAgentRuntimeError', message: 'Plan write failed' },
+ }),
+ 'error',
+ );
+ expect(mocks.acceptanceAttachPolicyRun).not.toHaveBeenCalled();
+ },
+ );
+
it('attaches an auto-repair verify run as the next round of the same acceptance', async () => {
mocks.operationFindById.mockResolvedValue({ parentOperationId: null });
- mocks.agentExec.mockResolvedValue({ operationId: 'repair-operation' });
+ let confirmed = false;
+ let attached = false;
+ let stateAtStart: boolean[] = [];
+ const start = async () => {
+ stateAtStart = [confirmed, attached];
+ };
+ mocks.agentExec.mockImplementation(async ({ onOperationCreated }) => {
+ await onOperationCreated?.('repair-operation');
+ await start();
+ return { operationId: 'repair-operation', success: true };
+ });
+ mocks.confirmPlan.mockImplementation(async () => {
+ confirmed = true;
+ });
+ mocks.acceptanceAttachPolicyRun.mockImplementation(async () => {
+ attached = true;
+ });
mocks.runFindByOperation.mockResolvedValue({
acceptanceId: 'acceptance-1',
id: 'source-run',
@@ -323,7 +383,13 @@ describe('Verify acceptance lifecycle', () => {
});
expect(result).toEqual({ repairOperationId: 'repair-operation' });
- expect(mocks.agentExec).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-1' }));
+ expect(stateAtStart).toEqual([true, true]);
+ expect(mocks.agentExec).toHaveBeenCalledWith(
+ expect.objectContaining({
+ additionalPluginIds: ['lobe-acceptance-evidence'],
+ taskId: 'task-1',
+ }),
+ );
expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('repair-run', 'acceptance-1');
});
});
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index d0d875fa6ec..47f6ccb118c 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -1,6 +1,7 @@
// @vitest-environment node
import {
ACCEPTANCE_REVIEW_ERRORED_ERROR,
+ VERIFICATION_ERRORED_ERROR,
VERIFICATION_UNJUDGEABLE_ERROR,
} from '@lobechat/const/goal';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -8,6 +9,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
import { reviewGoalDelivery } from '../goalReview';
+import { maybeAutoRepair } from '../repairService';
import { driveTaskFromVerify, finalizeVerifyRun } from '../settle';
import { attachTaskRunToAcceptance, resolveTaskAcceptance } from '../taskAcceptance';
@@ -101,6 +103,25 @@ vi.mock('@/server/services/taskResultBridge', () => ({
const db = {} as any;
describe('driveTaskFromVerify', () => {
+ it('does not overwrite a fast-failed repair when the parent finalizer resumes', async () => {
+ runFindByOperation.mockImplementation(async (id: string) => ({
+ id: id === 'repair-op' ? 'repair-run' : 'parent-run',
+ status: id === 'repair-op' ? 'errored' : 'failed',
+ }));
+ vi.mocked(maybeAutoRepair).mockImplementationOnce(async () => {
+ await driveTaskFromVerify(db, 'u1', 'repair-op');
+ return { repairOperationId: 'repair-op' };
+ });
+ await finalizeVerifyRun(db, 'u1', 'parent-op', {});
+ expect(taskUpdateStatus).toHaveBeenCalledTimes(1);
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: VERIFICATION_ERRORED_ERROR,
+ });
+ expect(deliverMock).toHaveBeenCalledTimes(1);
+ expect(runClaimTaskDrive).toHaveBeenCalledWith('repair-run');
+ expect(runClaimTaskDrive).not.toHaveBeenCalledWith('parent-run');
+ });
+
it('automatically sends a Goal delivery back when Acceptance review rejects a Verify pass', async () => {
runFindByOperation.mockResolvedValue({
id: 'run-1',
diff --git a/apps/server/src/services/verify/__tests__/repairTerminal.test.ts b/apps/server/src/services/verify/__tests__/repairTerminal.test.ts
new file mode 100644
index 00000000000..3373932b510
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/repairTerminal.test.ts
@@ -0,0 +1,143 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { settleFailedRepair } from '../repairTerminal';
+
+const m = vi.hoisted(() => ({
+ op: vi.fn(),
+ run: vi.fn(),
+ rounds: vi.fn(),
+ claim: vi.fn(),
+ write: vi.fn(),
+ recompute: vi.fn(),
+ ancestors: vi.fn(),
+ drive: vi.fn(),
+}));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(function () {
+ return { findById: m.op };
+ }),
+}));
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(function () {
+ return { findByOperation: m.run, listByAcceptance: m.rounds };
+ }),
+}));
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function () {
+ return { upsertByCheckItem: m.write };
+ }),
+}));
+vi.mock('../statusService', () => ({
+ VerifyStatusService: vi.fn(function () {
+ return { claimVerifying: m.claim, recompute: m.recompute };
+ }),
+}));
+vi.mock('../settle', () => ({
+ driveTaskFromVerify: m.drive,
+ recomputeRepairAncestors: m.ancestors,
+}));
+const db = {} as any;
+const run = {
+ id: 'repair-run',
+ acceptanceId: 'acceptance',
+ roundIndex: 2,
+ status: 'planned',
+ planConfirmedAt: new Date(),
+ plan: [
+ {
+ id: 'check',
+ index: 0,
+ required: true,
+ title: 'Report',
+ verifierType: 'llm',
+ verifierConfig: {},
+ },
+ ],
+};
+
+describe('settleFailedRepair', () => {
+ beforeEach(() => {
+ Object.values(m).forEach((mock) => mock.mockReset());
+ m.op.mockResolvedValue({
+ parentOperationId: 'parent',
+ completionReason: 'error',
+ error: { message: 'The model provider returned an empty completion.' },
+ });
+ m.run.mockImplementation(async (id) =>
+ id === 'repair' ? run : { acceptanceId: 'acceptance' },
+ );
+ m.rounds.mockResolvedValue([run]);
+ m.claim.mockResolvedValue(true);
+ });
+
+ it('turns an empty-completion repair into an infra error and settles its task and ancestors', async () => {
+ expect(await settleFailedRepair(db, 'user', 'repair', 'ws')).toBe(true);
+ expect(m.write).toHaveBeenCalledWith(
+ expect.objectContaining({
+ verifyRunId: 'repair-run',
+ checkItemId: 'check',
+ status: 'errored',
+ verdict: null,
+ toulmin: {
+ limitation:
+ 'Repair error before verification: The model provider returned an empty completion.',
+ },
+ }),
+ );
+ expect(m.recompute).toHaveBeenCalledWith('repair');
+ expect(m.ancestors).toHaveBeenCalledWith(expect.anything(), expect.anything(), 'repair');
+ expect(m.drive).toHaveBeenCalledWith(db, 'user', 'repair', 'ws');
+ });
+
+ it('recovers an interrupted repair too', async () => {
+ m.op.mockResolvedValue({ parentOperationId: 'parent', completionReason: 'interrupted' });
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(true);
+ expect(m.write.mock.calls[0][0].toulmin.limitation).toBe(
+ 'Repair interrupted before verification.',
+ );
+ });
+
+ it.each(['done', undefined])(
+ 'leaves a successful or still-live operation alone (%s)',
+ async (completionReason) => {
+ m.op.mockResolvedValue({ parentOperationId: 'parent', completionReason });
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(false);
+ expect(m.claim).not.toHaveBeenCalled();
+ },
+ );
+
+ it('leaves evidence-only children without their own plan alone', async () => {
+ m.run.mockResolvedValue(null);
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(false);
+ expect(m.drive).not.toHaveBeenCalled();
+ });
+
+ it('does not overwrite a judging or settled round', async () => {
+ m.run.mockResolvedValue({ ...run, status: 'passed' });
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(false);
+ expect(m.write).not.toHaveBeenCalled();
+ });
+
+ it('does not act after losing the lease', async () => {
+ m.claim.mockResolvedValue(false);
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(false);
+ expect(m.write).not.toHaveBeenCalled();
+ expect(m.drive).not.toHaveBeenCalled();
+ });
+
+ it('cleans up an old round without pausing a newer task attempt', async () => {
+ m.rounds.mockResolvedValue([run, { id: 'new-run', roundIndex: 3 }]);
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(true);
+ expect(m.recompute).toHaveBeenCalled();
+ expect(m.ancestors).toHaveBeenCalled();
+ expect(m.drive).not.toHaveBeenCalled();
+ });
+
+ it('collapses a late parent repairing stamp without rewriting already settled checks', async () => {
+ m.run.mockResolvedValue({ ...run, status: 'errored' });
+ expect(await settleFailedRepair(db, 'user', 'repair')).toBe(true);
+ expect(m.write).not.toHaveBeenCalled();
+ expect(m.ancestors).toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/sweep.test.ts b/apps/server/src/services/verify/__tests__/sweep.test.ts
index 6d08a17be7d..2589c975016 100644
--- a/apps/server/src/services/verify/__tests__/sweep.test.ts
+++ b/apps/server/src/services/verify/__tests__/sweep.test.ts
@@ -5,6 +5,7 @@ import { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from '../staleness';
import { sweepStuckVerifyRuns } from '../sweep';
const {
+ settleFailedRepair,
claimVerifying,
findStuckVerifying,
operationFindById,
@@ -13,6 +14,7 @@ const {
upsertByCheckItem,
finalizeVerifyRun,
} = vi.hoisted(() => ({
+ settleFailedRepair: vi.fn(),
claimVerifying: vi.fn(),
finalizeVerifyRun: vi.fn(),
findStuckVerifying: vi.fn(),
@@ -45,6 +47,7 @@ vi.mock('../statusService', () => ({
return { claimVerifying, recompute };
}),
}));
+vi.mock('../repairTerminal', () => ({ settleFailedRepair }));
vi.mock('../settle', () => ({ finalizeVerifyRun }));
const db = {} as any;
@@ -71,6 +74,7 @@ const singlePage = (runs: unknown[]) => {
describe('sweepStuckVerifyRuns', () => {
beforeEach(() => {
[
+ settleFailedRepair,
claimVerifying,
finalizeVerifyRun,
findStuckVerifying,
@@ -291,4 +295,11 @@ describe('sweepStuckVerifyRuns', () => {
expect(outcome.skipped).toBe(1);
expect(outcome.settled).toEqual(['run-newer']);
});
+ it('recovers a planned repair whose operation died before judging began', async () => {
+ singlePage([stuckRun({ status: 'planned' })]);
+ settleFailedRepair.mockResolvedValue(true);
+ expect((await sweepStuckVerifyRuns(db, { now: NOW })).abandoned).toEqual(['run-1']);
+ expect(settleFailedRepair).toHaveBeenCalledWith(db, 'u1', 'op-1', undefined);
+ expect(finalizeVerifyRun).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index 57acb3fc197..9f791680dad 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -45,6 +45,7 @@ export {
type RepairSpawner,
VerifyRepairService,
} from './repairService';
+export { settleFailedRepair } from './repairTerminal';
export { type GenerateReportParams, VerifyReporterService } from './reporter';
export {
isCurrentReviewPrediction,
diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.ts
index e15d8a361ed..18d0d0ed211 100644
--- a/apps/server/src/services/verify/repairService.ts
+++ b/apps/server/src/services/verify/repairService.ts
@@ -1,3 +1,4 @@
+import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';
import { DEFAULT_MAX_REPAIR_ROUNDS } from '@lobechat/const/verify';
import type { VerifyCheckItem, VerifyRunMetadata } from '@lobechat/types';
import debug from 'debug';
@@ -9,9 +10,11 @@ import { VerifyRubricModel } from '@/database/models/verifyRubric';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { VerifyCheckResultItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import { AiAgentService } from '@/server/services/aiAgent';
import { AcceptanceService } from './acceptanceService';
+import { settleFailedRepair } from './repairTerminal';
import { VerifyStatusService } from './statusService';
const log = debug('lobe-server:verify-repair');
@@ -105,51 +108,84 @@ export const createRepairRunner = (params: {
return null;
}
+ let preparationFailed = false;
+ const prepareRepairRound = async (repairOperationId: string) => {
+ try {
+ await db.transaction(async (tx) => {
+ const repairDB = tx as unknown as LobeChatDatabase;
+ // Re-snapshot the same plan onto the repair op's session + confirm, so the
+ // repair run re-verifies (round N+1) against its corrected deliverable.
+ const runModel = new VerifyRunModel(repairDB, userId, workspaceId);
+ const sourceRun = await runModel.findByOperation(operationId);
+ const plan = (sourceRun?.plan ?? []) as VerifyCheckItem[];
+ if (plan.length > 0) {
+ const repairRun = await runModel.ensureForOperation(repairOperationId);
+ await runModel.setPlan(repairRun.id, plan);
+ // Carry the source run's policy bag (e.g. the task's maxRepairRounds
+ // override) onto this round so its own auto-repair derives the same cap
+ // instead of falling back to the rubric/default.
+ if (sourceRun?.metadata) await runModel.setMetadata(repairRun.id, sourceRun.metadata);
+ await runModel.confirmPlan(repairRun.id);
+
+ // A repair is the next immutable round of the same business acceptance,
+ // not an unrelated verification session. Attach it before it settles so
+ // the aggregate immediately advances from "repairing" to the live round.
+ if (sourceRun?.acceptanceId) {
+ await new AcceptanceService(repairDB, userId, workspaceId).attachPolicyRun(
+ repairRun.id,
+ sourceRun.acceptanceId,
+ );
+ }
+ }
+ });
+ } catch (error) {
+ preparationFailed = true;
+ console.error('Failed to prepare repair round for %s: %O', operationId, error);
+ await new CompletionLifecycle(db, userId, workspaceId).completeOperation(
+ {
+ operationId: repairOperationId,
+ userId,
+ error: {
+ type: 'ServerAgentRuntimeError',
+ message: error instanceof Error ? error.message : String(error),
+ },
+ },
+ 'error',
+ );
+ throw error;
+ }
+ };
+
// Re-run the original agent in the same topic. The feedback lives on the
// verify message (surfaced into context by VerifyMessageProcessor), so we run
// off history instead of injecting a user turn; `instruction` is passed only
// for the operation title / logs. `verifyMessageId` parents the new turn under
// the verify card it responds to.
- const result = await new AiAgentService(db, userId, { workspaceId }).execAgent({
- agentId,
- appContext: { topicId },
- autoStart: true,
- ...(model ? { model } : {}),
- ...(verifyMessageId ? { parentMessageId: verifyMessageId } : {}),
- parentOperationId: operationId,
- prompt: instruction,
- ...(provider ? { provider } : {}),
- suppressUserMessage: true,
- ...(taskId ? { taskId } : {}),
- userInterventionConfig: { approvalMode: 'headless' },
- });
+ const result = await new AiAgentService(db, userId, { workspaceId })
+ .execAgent({
+ additionalPluginIds: [AcceptanceEvidenceIdentifier],
+ agentId,
+ appContext: { topicId },
+ autoStart: true,
+ onOperationCreated: prepareRepairRound,
+ ...(model ? { model } : {}),
+ ...(verifyMessageId ? { parentMessageId: verifyMessageId } : {}),
+ parentOperationId: operationId,
+ prompt: instruction,
+ ...(provider ? { provider } : {}),
+ suppressUserMessage: true,
+ ...(taskId ? { taskId } : {}),
+ userInterventionConfig: { approvalMode: 'headless' },
+ })
+ .catch((error) => {
+ // Heterogeneous dispatch propagates preparation errors; the normal
+ // runtime returns success:false. Neither has spawned a repair.
+ if (preparationFailed) return null;
+ throw error;
+ });
+ if (!result?.success) return null;
const repairOperationId = result.operationId;
- // Re-snapshot the same plan onto the repair op's session + confirm, so the
- // repair run re-verifies (round N+1) against its corrected deliverable.
- const runModel = new VerifyRunModel(db, userId, workspaceId);
- const sourceRun = await runModel.findByOperation(operationId);
- const plan = (sourceRun?.plan ?? []) as VerifyCheckItem[];
- if (plan.length > 0) {
- const repairRun = await runModel.ensureForOperation(repairOperationId);
- await runModel.setPlan(repairRun.id, plan);
- // Carry the source run's policy bag (e.g. the task's maxRepairRounds
- // override) onto this round so its own auto-repair derives the same cap
- // instead of falling back to the rubric/default.
- if (sourceRun?.metadata) await runModel.setMetadata(repairRun.id, sourceRun.metadata);
- await runModel.confirmPlan(repairRun.id);
-
- // A repair is the next immutable round of the same business acceptance,
- // not an unrelated verification session. Attach it before it settles so
- // the aggregate immediately advances from "repairing" to the live round.
- if (sourceRun?.acceptanceId) {
- await new AcceptanceService(db, userId, workspaceId).attachPolicyRun(
- repairRun.id,
- sourceRun.acceptanceId,
- );
- }
- }
-
log('repair op %s β†’ %s (round %d)', operationId, repairOperationId, round + 1);
return { repairOperationId };
};
@@ -168,7 +204,7 @@ export const maybeAutoRepair = async (
userId: string,
operationId: string,
workspaceId?: string,
-): Promise<void> => {
+): Promise<{ repairOperationId: string } | null | undefined> => {
const operationModel = new AgentOperationModel(db, userId, workspaceId);
const run = await new VerifyRunModel(db, userId, workspaceId).findByOperation(operationId);
const plan = (run?.plan ?? []) as VerifyCheckItem[];
@@ -210,7 +246,7 @@ export const maybeAutoRepair = async (
userId,
workspaceId,
});
- await new VerifyRepairService(db, userId, workspaceId).triggerAutoRepair(operationId, spawner);
+ return new VerifyRepairService(db, userId, workspaceId).triggerAutoRepair(operationId, spawner);
};
// `errored` = the verifier couldn't run (infra), so there's no delivery fault to
@@ -239,7 +275,11 @@ export class VerifyRepairService {
private readonly resultModel: VerifyCheckResultModel;
private readonly statusService: VerifyStatusService;
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {
this.messageModel = new MessageModel(db, userId, workspaceId);
this.runModel = new VerifyRunModel(db, userId, workspaceId);
this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
@@ -306,6 +346,9 @@ export class VerifyRepairService {
}
}
await this.statusService.markRepairing(operationId);
+ // A fast startup failure can precede the plan/parent writes above. Reconcile
+ // after both exist as well as from the completion hook.
+ await settleFailedRepair(this.db, this.userId, spawned.repairOperationId, this.workspaceId);
log('triggered auto-repair op %s β†’ %s', operationId, spawned.repairOperationId);
return spawned;
diff --git a/apps/server/src/services/verify/repairTerminal.ts b/apps/server/src/services/verify/repairTerminal.ts
new file mode 100644
index 00000000000..595f4ca9c30
--- /dev/null
+++ b/apps/server/src/services/verify/repairTerminal.ts
@@ -0,0 +1,63 @@
+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 { planItemToPendingResult } from './resultSnapshot';
+import { driveTaskFromVerify, recomputeRepairAncestors } from './settle';
+import { VerifyStatusService } from './statusService';
+
+/** Close a repair that died before it could deliver anything to the checker. */
+export const settleFailedRepair = async (
+ db: LobeChatDatabase,
+ userId: string,
+ operationId: string,
+ workspaceId?: string,
+): Promise<boolean> => {
+ const operationModel = new AgentOperationModel(db, userId, workspaceId);
+ const op = await operationModel.findById(operationId);
+ if (!op?.parentOperationId || !['error', 'interrupted'].includes(op.completionReason ?? ''))
+ return false;
+
+ const runModel = new VerifyRunModel(db, userId, workspaceId);
+ const run = await runModel.findByOperation(operationId);
+ if (!run?.planConfirmedAt || !run.plan?.length) return false;
+ const parent = await runModel.findByOperation(op.parentOperationId);
+ // Evidence/verifier children also have a parent; only a round of that same
+ // acceptance is a repair. Standalone verify rounds have no acceptance id.
+ if (!parent || parent.acceptanceId !== run.acceptanceId) return false;
+ if (run.status !== 'planned' && run.status !== 'errored') return false;
+
+ const statusService = new VerifyStatusService(db, userId, workspaceId);
+ if (run.status === 'planned') {
+ // Share the judge/sweeper lease so duplicate completion deliveries cannot
+ // overwrite results or drive the task twice.
+ if (!(await statusService.claimVerifying(operationId, new Date(0)))) return false;
+ const results = new VerifyCheckResultModel(db, userId, workspaceId);
+ const limitation = `Repair ${op.completionReason} before verification${op.error?.message ? `: ${op.error.message}` : '.'}`;
+ for (const item of run.plan) {
+ await results.upsertByCheckItem({
+ ...planItemToPendingResult(run.id, operationId, item),
+ checkItemId: item.id,
+ verifyRunId: run.id,
+ completedAt: new Date(),
+ status: 'errored',
+ suggestion: 'Retry the task to resume the repair.',
+ toulmin: { limitation },
+ verdict: null,
+ });
+ }
+ await statusService.recompute(operationId);
+ }
+
+ // Also repeat this on an already-errored round: the child can finish before
+ // its spawner stamps the parent `repairing`.
+ await recomputeRepairAncestors(operationModel, statusService, operationId);
+ if (run.acceptanceId) {
+ const rounds = await runModel.listByAcceptance(run.acceptanceId);
+ if (rounds.some((round) => (round.roundIndex ?? 0) > (run.roundIndex ?? 0))) return true;
+ }
+ // Infrastructure failure, not a rejected delivery: do not auto-repair again.
+ await driveTaskFromVerify(db, userId, operationId, workspaceId);
+ return true;
+};
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index 4ae89dddfcf..1a985397a37 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -281,7 +281,10 @@ export const finalizeVerifyRun = async (
): 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 repair = await maybeAutoRepair(db, userId, operationId, workspaceId);
+ // The child owns settlement even when it failed before the spawn returned
+ // and already recomputed this parent from repairing back to failed.
+ if (repair) return;
const settled = await new VerifyRunModel(db, userId, workspaceId).findByOperation(operationId);
if (settled?.status !== 'passed' && settled?.status !== 'failed' && settled?.status !== 'errored')
diff --git a/apps/server/src/services/verify/sweep.ts b/apps/server/src/services/verify/sweep.ts
index 2ff7d10c36d..fecbe6b8ecb 100644
--- a/apps/server/src/services/verify/sweep.ts
+++ b/apps/server/src/services/verify/sweep.ts
@@ -7,6 +7,7 @@ import { VerifyRunModel } from '@/database/models/verifyRun';
import type { VerifyRunItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
+import { settleFailedRepair } from './repairTerminal';
import { planItemToPendingResult } from './resultSnapshot';
import { finalizeVerifyRun } from './settle';
import { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from './staleness';
@@ -38,7 +39,8 @@ export interface VerifySweepOutcome {
}
/**
- * Recover verification runs stranded in `verifying`.
+ * Recover verification runs stranded in `verifying` and planned repairs whose
+ * operation has already failed or been interrupted.
*
* Entering `verifying` is a durable write; the judging that leaves it runs as
* post-response work, so any host-level interruption β€” instance recycled,
@@ -119,6 +121,11 @@ const recoverRun = async (
): Promise<'abandoned' | 'settled' | 'skipped'> => {
const operationId = run.operationId;
if (!operationId) return 'skipped';
+ if (run.status === 'planned') {
+ return (await settleFailedRepair(db, run.userId, operationId, run.workspaceId ?? undefined))
+ ? 'abandoned'
+ : 'skipped';
+ }
const workspaceId = run.workspaceId ?? undefined;
const plan = (run.plan ?? []) as VerifyCheckItem[];
diff --git a/packages/database/src/models/__tests__/verifyRun.test.ts b/packages/database/src/models/__tests__/verifyRun.test.ts
index e2d826a689a..66b14d363cc 100644
--- a/packages/database/src/models/__tests__/verifyRun.test.ts
+++ b/packages/database/src/models/__tests__/verifyRun.test.ts
@@ -3,7 +3,7 @@ import { eq, sql } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { acceptances, users, verifyRuns } from '../../schemas';
+import { acceptances, agentOperations, users, verifyRuns } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentOperationModel } from '../agentOperation';
import { VerifyRunModel } from '../verifyRun';
@@ -224,6 +224,38 @@ describe('VerifyRunModel.findStuckVerifying', () => {
expect(restIds).toContain(interloper);
});
+ it('finds dead planned repairs but excludes live, successful and unconfirmed rounds', async () => {
+ const states = [
+ ['dead', 'error', true],
+ ['interrupted', 'interrupted', true],
+ ['live', null, true],
+ ['done', 'done', true],
+ ['draft', 'error', false],
+ ] as const;
+ const ids: Record<string, string> = {};
+ for (const [name, completionReason, confirmed] of states) {
+ const operationId = `op-planned-${name}`;
+ ids[name] = await buildRun(operationId);
+ if (confirmed) await new VerifyRunModel(serverDB, userId).confirmPlan(ids[name]);
+ await serverDB
+ .update(agentOperations)
+ .set({
+ completionReason,
+ parentOperationId: 'parent-operation',
+ })
+ .where(eq(agentOperations.id, operationId));
+ await backdate(ids[name], 10 * 60 * 1000);
+ }
+ const stuck = await VerifyRunModel.findStuckVerifying(
+ serverDB,
+ new Date(Date.now() - 5 * 60 * 1000),
+ { limit: 500 },
+ );
+ const found = stuck.map((run) => run.id);
+ expect(found).toEqual(expect.arrayContaining([ids.dead, ids.interrupted]));
+ for (const name of ['live', 'done', 'draft']) expect(found).not.toContain(ids[name]);
+ });
+
it('ignores operation-less rounds β€” there is no rollup to address', async () => {
const run = await new VerifyRunModel(serverDB, userId).create({ status: 'verifying' });
await backdate(run.id, 10 * 60 * 1000);
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index cb40d3e324b..895af643367 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -629,7 +629,8 @@ export class VerifyRunModel {
};
/**
- * One page of runs stranded in `verifying` since before `olderThan`, across
+ * One page of runs stranded in `verifying`, or confirmed `planned` rounds
+ * whose child operation aborted, since before `olderThan`, across
* all owners β€” the sweep's input (see `sweepStuckVerifyRuns`).
*
* No per-user scope, like `TaskModel.findStuckTasks`: this backs a global
@@ -664,7 +665,17 @@ export class VerifyRunModel {
const updatedAtMs = sql`date_trunc('milliseconds', ${verifyRuns.updatedAt})`;
const conditions = [
- eq(verifyRuns.status, 'verifying'),
+ or(
+ eq(verifyRuns.status, 'verifying'),
+ and(
+ eq(verifyRuns.status, 'planned'),
+ isNotNull(verifyRuns.planConfirmedAt),
+ sql`exists (select 1 from ${agentOperations}
+ where ${agentOperations.id} = ${verifyRuns.operationId}
+ and ${agentOperations.parentOperationId} is not null
+ and ${agentOperations.completionReason} in ('error', 'interrupted'))`,
+ ),
+ )!,
lt(verifyRuns.updatedAt, olderThan),
isNotNull(verifyRuns.operationId),
];