Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(verify): auto-instantiate + confirm a task's verify plan at run start (#16150)

Arvin Xu95d48afe2714
diff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
index b5c2ac80e2b..7b278524060 100644
--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts
@@ -13,7 +13,7 @@ import { buildFinalSnapshotKey } from '@/server/modules/AgentTracing';
import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
import { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';
-import { runVerifyOnCompletion } from '@/server/services/verify';
+import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';
import { hookDispatcher } from './hooks';
@@ -47,6 +47,13 @@ export class CompletionLifecycle {
private readonly messageModel: MessageModel;
private readonly agentOperationModel: AgentOperationModel;
private readonly workspaceId?: string;
+ /**
+ * In-flight verify-plan instantiations started in {@link recordStart}, keyed by
+ * operationId. `dispatchHooks` awaits the matching one before running the
+ * completion gate so a very short / no-op task run can't race past its own plan
+ * (instantiation is fire-and-forget at start and may not have settled yet).
+ */
+ private readonly verifyPlanInstantiations = new Map<string, Promise<void>>();
constructor(
private readonly serverDB: LobeChatDatabase,
@@ -69,6 +76,25 @@ export class CompletionLifecycle {
} catch (error) {
log('[%s] Failed to record operation start (non-fatal): %O', params.operationId, error);
}
+
+ // Auto-instantiate the task's verify plan at run start so the completion gate
+ // fires. Only for a top-level task operation β€” repair / verifier sub-agents
+ // (which carry a parentOperationId) get their plan from the repair path, not
+ // here. Fire-and-forget; never blocks startup. We keep the promise (instead of
+ // void-ing it) so `dispatchHooks` can await it before the completion gate runs
+ // β€” a fast run can otherwise complete first and the gate would no-op on a plan
+ // that lands moments later. (instantiateVerifyPlanOnStart never rejects.)
+ if (params.taskId && !params.parentOperationId) {
+ this.verifyPlanInstantiations.set(
+ params.operationId,
+ instantiateVerifyPlanOnStart(
+ this.serverDB,
+ this.userId,
+ { operationId: params.operationId, taskId: params.taskId },
+ this.workspaceId,
+ ),
+ );
+ }
}
/**
@@ -331,6 +357,12 @@ export class CompletionLifecycle {
// plan against the deliverable. Fire-and-forget and self-guarded β€” a run
// without an opted-in plan is a no-op, and failures never affect the run.
if (reason === 'done') {
+ // The task's verify plan is instantiated fire-and-forget at run start; a
+ // fast or no-op run can reach completion before it settles. Await the
+ // in-flight instantiation (if any) so the gate sees the confirmed plan
+ // instead of racing past it and leaving a planned run with no results/card.
+ await this.verifyPlanInstantiations.get(operationId);
+
const messages: any[] = Array.isArray(state?.messages) ? state.messages : [];
const firstUserMessage = messages.find((m) => m?.role === 'user');
const goal = firstUserMessage
@@ -393,7 +425,13 @@ export class CompletionLifecycle {
} finally {
// Keep hooks registered across an async-tool park so the eventual resume
// (same operationId) can still fire onComplete/onError.
- if (!isAsyncToolPark) hookDispatcher.unregister(operationId);
+ if (!isAsyncToolPark) {
+ hookDispatcher.unregister(operationId);
+ // The instantiation has settled (awaited above) or this op never opted in
+ // β€” drop the entry so the map doesn't grow across the service's lifetime.
+ // Kept across an async-tool park: the op resumes under the same id.
+ this.verifyPlanInstantiations.delete(operationId);
+ }
}
}
diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
index 1eb5f470c2e..0deeea2f431 100644
--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts
@@ -2,9 +2,13 @@
import { ChatErrorType } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import * as verifyServices from '@/server/services/verify';
+
import { CompletionLifecycle } from '../CompletionLifecycle';
import { hookDispatcher } from '../hooks';
+const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));
+
const buildLifecycle = () => new CompletionLifecycle({} as any, 'user-1');
describe('CompletionLifecycle.extractErrorMessage', () => {
@@ -266,6 +270,64 @@ describe('CompletionLifecycle.dispatchHooks β€” error persistence', () => {
});
});
+describe('CompletionLifecycle.dispatchHooks β€” verify plan race', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('awaits the start-time verify-plan instantiation before running the completion gate', async () => {
+ const lifecycle = buildLifecycle();
+ 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(() => {});
+
+ // Control exactly when the fire-and-forget instantiation settles.
+ let settle: () => void = () => {};
+ const instantiation = new Promise<void>((resolve) => {
+ settle = resolve;
+ });
+ const instantiateSpy = vi
+ .spyOn(verifyServices, 'instantiateVerifyPlanOnStart')
+ .mockReturnValue(instantiation);
+ const runVerifySpy = vi
+ .spyOn(verifyServices, 'runVerifyOnCompletion')
+ .mockResolvedValue(undefined);
+
+ // A top-level task op registers the (still-pending) instantiation at start.
+ await lifecycle.recordStart({ operationId: 'op-1', taskId: 'task-1' } as any);
+ expect(instantiateSpy).toHaveBeenCalledTimes(1);
+
+ // Completion fires while the plan instantiation is still in flight.
+ const doneState = { metadata: { agentId: 'a', _hooks: [] }, status: 'done' };
+ const dispatch = lifecycle.dispatchHooks('op-1', doneState, 'done');
+
+ // The gate must stay blocked on the pending instantiation, not race past it.
+ await flushMicrotasks();
+ expect(runVerifySpy).not.toHaveBeenCalled();
+
+ // Once the plan lands, the gate proceeds against the now-confirmed plan.
+ settle();
+ await dispatch;
+ expect(runVerifySpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not register an instantiation for a repair / verifier sub-op (parentOperationId set)', async () => {
+ const lifecycle = buildLifecycle();
+ const instantiateSpy = vi
+ .spyOn(verifyServices, 'instantiateVerifyPlanOnStart')
+ .mockResolvedValue(undefined);
+
+ await lifecycle.recordStart({
+ operationId: 'op-2',
+ parentOperationId: 'op-1',
+ taskId: 'task-1',
+ } as any);
+
+ expect(instantiateSpy).not.toHaveBeenCalled();
+ });
+});
+
describe('CompletionLifecycle.dispatchHooks β€” async-tool park', () => {
afterEach(() => {
vi.restoreAllMocks();
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index f682b882666..1b2d8af9d80 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -8,6 +8,7 @@ export {
export { computeFalseFlags, VerifyFeedbackService } from './feedbackService';
export { runVerifyOnCompletion } from './lifecycle';
export { type GeneratePlanParams, VerifyPlanGeneratorService } from './planGenerator';
+export { instantiateVerifyPlanOnStart } from './planInstantiation';
export {
createRepairRunner,
maybeAutoRepair,
diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.ts
new file mode 100644
index 00000000000..f06320a2fd7
--- /dev/null
+++ b/apps/server/src/services/verify/planInstantiation.ts
@@ -0,0 +1,83 @@
+import debug from 'debug';
+
+import { TaskModel } from '@/database/models/task';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { VerifyPlanGeneratorService } from './planGenerator';
+
+const log = debug('lobe-server:verify-plan-instantiation');
+
+export interface InstantiateVerifyPlanParams {
+ operationId: string;
+ taskId: string;
+}
+
+/**
+ * Auto-instantiate + auto-confirm a verify plan for a task-bound operation at run
+ * start, so the completion-time gate (`runVerifyOnCompletion`) actually fires.
+ *
+ * Without this, a task's `TaskVerifyConfig` (rubric / criteria) is never turned
+ * into a plan, so verify silently no-ops. We resolve the task's verify config
+ * (with subtask inheritance), materialize the rubric + ad-hoc criteria into a
+ * plan (no AI generation β€” the task already picked its criteria), and confirm it
+ * immediately (task scenario doesn't show a "confirm plan" step).
+ *
+ * Fire-and-forget + idempotent: never throws (verify must not affect the run),
+ * and skips when a plan already exists (recordStart can re-fire).
+ */
+export const instantiateVerifyPlanOnStart = async (
+ db: LobeChatDatabase,
+ userId: string,
+ params: InstantiateVerifyPlanParams,
+ workspaceId?: string,
+): Promise<void> => {
+ try {
+ const taskModel = new TaskModel(db, userId, workspaceId);
+ const verifyConfig = await taskModel.resolveVerifyConfig(params.taskId);
+
+ // Opt-in: a task only verifies when it configured a rubric or ad-hoc criteria
+ // and hasn't disabled the gate.
+ if (!verifyConfig || verifyConfig.enabled === false) return;
+ if (!verifyConfig.verifyRubricId && !verifyConfig.verifyCriteriaIds?.length) return;
+
+ const runModel = new VerifyRunModel(db, userId, workspaceId);
+ const existing = await runModel.findByOperation(params.operationId);
+ // Idempotent: a plan already exists for this run (re-fire, or agent/UI-built).
+ if (existing?.plan?.length) return;
+
+ const task = await taskModel.findById(params.taskId);
+ const goal = task?.instruction ?? task?.name ?? '';
+
+ const planGenerator = new VerifyPlanGeneratorService(db, userId, workspaceId);
+ await planGenerator.generateDraftPlan({
+ // No AI proposal β€” the task's configured rubric/criteria are the plan.
+ enableAiGeneration: false,
+ goal,
+ operationId: params.operationId,
+ verifyCriteriaIds: verifyConfig.verifyCriteriaIds,
+ verifyRubricId: verifyConfig.verifyRubricId,
+ });
+
+ // generateDraftPlan only sets the (draft) plan; the task scenario auto-confirms
+ // so the completion gate treats it as ready instead of a pending draft.
+ const run = await runModel.findByOperation(params.operationId);
+ if (run?.plan?.length) {
+ // Carry the task's repair/re-run cap (TaskVerifyConfig.maxIterations) onto
+ // the run so auto-repair honors it. Without this the repair path falls back
+ // to the source rubric's config or the default, dropping the task cap for
+ // ad-hoc-criteria or per-task-override tasks.
+ if (typeof verifyConfig.maxIterations === 'number') {
+ await runModel.setMetadata(run.id, { maxRepairRounds: verifyConfig.maxIterations });
+ }
+ await runModel.confirmPlan(run.id);
+ log(
+ 'instantiated + confirmed verify plan for op %s (%d items)',
+ params.operationId,
+ run.plan.length,
+ );
+ }
+ } catch (error) {
+ log('instantiateVerifyPlanOnStart failed for op %s (non-fatal): %O', params.operationId, error);
+ }
+};
diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.ts
index 49ee0e5b525..0f028361e9b 100644
--- a/apps/server/src/services/verify/repairService.ts
+++ b/apps/server/src/services/verify/repairService.ts
@@ -1,4 +1,4 @@
-import type { VerifyCheckItem } from '@lobechat/types';
+import type { VerifyCheckItem, VerifyRunMetadata } from '@lobechat/types';
import { DEFAULT_MAX_REPAIR_ROUNDS } from '@lobechat/types';
import debug from 'debug';
@@ -15,16 +15,22 @@ import { VerifyStatusService } from './statusService';
const log = debug('lobe-server:verify-repair');
/**
- * Resolve the run's repair-round cap from the rubric the plan was instantiated
- * from (live read via the plan items' `sourceRubricId`). Falls back to
- * {@link DEFAULT_MAX_REPAIR_ROUNDS} for agent-generated / rubric-less plans.
+ * Resolve the run's repair-round cap. A per-run override on the session metadata
+ * (set from the task's `TaskVerifyConfig.maxIterations`) wins, since a task with
+ * ad-hoc criteria or a per-task cap may not carry it on a rubric. Otherwise read
+ * it live from the rubric the plan was instantiated from (via the plan items'
+ * `sourceRubricId`), falling back to {@link DEFAULT_MAX_REPAIR_ROUNDS} for
+ * agent-generated / rubric-less plans.
*/
const resolveMaxRepairRounds = async (
db: LobeChatDatabase,
userId: string,
plan: VerifyCheckItem[],
+ metadata: VerifyRunMetadata | null | undefined,
workspaceId?: string,
): Promise<number> => {
+ if (typeof metadata?.maxRepairRounds === 'number') return metadata.maxRepairRounds;
+
const rubricId = plan.find((i) => i.sourceRubricId)?.sourceRubricId;
if (!rubricId) return DEFAULT_MAX_REPAIR_ROUNDS;
@@ -123,6 +129,10 @@ export const createRepairRunner = (params: {
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);
}
@@ -166,7 +176,13 @@ export const maybeAutoRepair = async (
const spawner = createRepairRunner({
agentId: op?.agentId,
db,
- maxRepairRounds: await resolveMaxRepairRounds(db, userId, plan, workspaceId),
+ maxRepairRounds: await resolveMaxRepairRounds(
+ db,
+ userId,
+ plan,
+ run.metadata as VerifyRunMetadata | null,
+ workspaceId,
+ ),
model: op?.model,
provider: op?.provider,
topicId: op?.topicId,
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index 7fca9936d95..91d520949e7 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -178,6 +178,18 @@ export class VerifyRunModel {
.where(and(eq(verifyRuns.id, runId), this.ownership()));
};
+ /**
+ * Replace the session's generic policy/extension bag (`metadata`). Used to
+ * stamp per-run knobs like the task's `maxRepairRounds` override, and to carry
+ * them onto a repair round's run so it derives the same cap.
+ */
+ setMetadata = async (runId: string, metadata: Record<string, unknown>): Promise<void> => {
+ await this.db
+ .update(verifyRuns)
+ .set({ metadata })
+ .where(and(eq(verifyRuns.id, runId), this.ownership()));
+ };
+
/** Update the denormalized rollup. Always go through the service-layer chokepoint. */
updateStatus = async (runId: string, status: VerifyRunStatus | null): Promise<void> => {
await this.db
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index 666d0ac2fe9..6e379aa0931 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -118,6 +118,22 @@ export interface VerifyRubricConfig {
maxRepairRounds?: number;
}
+/**
+ * Generic per-run extension bag (`verify_runs.metadata`) β€” cross-scenario knobs
+ * we don't model as columns. Kept open so new policy switches don't require a
+ * migration; the active scenario's input lives in `context`, not here.
+ */
+export interface VerifyRunMetadata {
+ /**
+ * Per-run override for the repair-round cap, taking precedence over the
+ * rubric's {@link VerifyRubricConfig.maxRepairRounds}. Set from a task's
+ * `TaskVerifyConfig.maxIterations` so a task with ad-hoc criteria or a per-task
+ * override honors its saved cap (the rubric may not carry it). Read at repair
+ * time via {@link DEFAULT_MAX_REPAIR_ROUNDS} fallback.
+ */
+ maxRepairRounds?: number;
+}
+
/**
* Immutable snapshot of one check item, frozen into `agent_operations.verify_plan`
* when the plan is confirmed. The resolved content (title / verifierConfig) is