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.

♻️ refactor(server): split the 1,209-line verify router into sub-domain modules (#21103)

Arvin Xu40140b8c725a
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
deleted file mode 100644
index cba82d465d6..00000000000
--- a/apps/server/src/routers/lambda/verify.ts
+++ /dev/null
@@ -1,1209 +0,0 @@
-import { fetchAcceptanceSkillBundle } from '@lobechat/builtin-skills/acceptance';
-import {
- normalizeEvidenceMetadata,
- normalizeVerifySurface,
- verifyRunScenarios,
- verifySurfaces,
- verifyVisibilities,
-} from '@lobechat/const/verify';
-import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
-import type {
- VerifyCheckItem,
- VerifyCheckResultMetadata,
- VerifyEvidenceType,
- VerifyRunContext,
- VerifyRunScenario,
-} from '@lobechat/types';
-import { verifyCheckDefinitionSchema } from '@lobechat/types';
-import { TRPCError } from '@trpc/server';
-import { z } from 'zod';
-
-import {
- requireWorkspaceRoleWhenScoped,
- wsCompatProcedure,
-} from '@/business/server/trpc-middlewares/workspaceAuth';
-import { AgentOperationModel } from '@/database/models/agentOperation';
-import { DocumentModel } from '@/database/models/document';
-import { FileModel } from '@/database/models/file';
-import { LlmGenerationTracingModel } from '@/database/models/llmGenerationTracing';
-import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
-import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
-import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
-import { VerifyReportModel } from '@/database/models/verifyReport';
-import { VerifyRubricModel } from '@/database/models/verifyRubric';
-import { VerifyRunModel } from '@/database/models/verifyRun';
-import { publicProcedure, router } from '@/libs/trpc/lambda';
-import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
-import { FileService } from '@/server/services/file';
-import { GoalCriteriaGeneratorService } from '@/server/services/goal/criteriaGenerator';
-import {
- AcceptanceService,
- evidenceTypeForStoredFile,
- finalizeVerifyRun,
- purgeVerifyRun,
- resolveLiveRoundForItem,
- VerifyExecutorService,
- VerifyFeedbackService,
- VerifyPlanGeneratorService,
- VerifyReporterService,
-} from '@/server/services/verify';
-
-import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
-import { verifyRunReportProcedures } from './verifyRunReport';
-
-const verifierTypeSchema = z.enum(['program', 'agent', 'llm']);
-const onFailSchema = z.enum(['manual', 'auto_repair']);
-const decisionSchema = z.enum(['accepted', 'rejected', 'overridden']);
-const modelConfigSchema = z.object({ model: z.string(), provider: z.string() });
-const verdictSchema = z.enum(['passed', 'failed', 'uncertain']);
-const checkStatusSchema = z.enum([
- 'pending',
- 'running',
- 'passed',
- 'failed',
- // Verifier could not run (infra failure) β€” carries no verdict.
- 'errored',
- 'skipped',
-]);
-const runSourceSchema = z.enum(['agent', 'agent-testing']);
-const evidenceTypeSchema = z.enum([
- 'screenshot',
- 'gif',
- 'video',
- 'audio',
- 'text',
- 'markdown',
- 'dom_snapshot',
- 'transcript',
-]);
-const evidenceCapturedBySchema = z.enum(['agent-browser', 'cdp', 'cli', 'program', 'llm_judge']);
-const toulminSchema = z.object({
- counterEvidence: z.string().optional(),
- evidence: z.string().optional(),
- limitation: z.string().optional(),
- reasoning: z.string().optional(),
-});
-
-/** Derive the lifecycle status from a verdict when the caller doesn't pin one. */
-const statusForVerdict = (verdict: 'passed' | 'failed' | 'uncertain') =>
- verdict === 'passed' ? ('passed' as const) : ('failed' as const);
-
-/** Run-policy knobs persisted on a rubric (see VerifyRubricConfig). */
-const rubricConfigSchema = z.object({
- maxRepairRounds: z.number().int().min(0).max(5).optional(),
-});
-
-const checkItemSchema = z.object({
- definition: verifyCheckDefinitionSchema.optional(),
- category: z.string().optional(),
- description: z.string().optional(),
- id: z.string(),
- index: z.number(),
- onFail: onFailSchema,
- required: z.boolean(),
- sourceCriterionId: z.string().nullish(),
- sourceRubricId: z.string().nullish(),
- supersedes: z.array(z.string()).optional(),
- title: z.string(),
- verifierConfig: z.record(z.string(), z.unknown()),
- verifierType: verifierTypeSchema,
-});
-
-const verifyRunIdInputSchema = z.object({ verifyRunId: z.string() });
-const omitUndefined = <T extends Record<string, unknown>>(value: T): Partial<T> =>
- Object.fromEntries(
- Object.entries(value).filter(([, field]) => field !== undefined),
- ) as Partial<T>;
-
-// The scenario's context, rendered as the report's scope header. Shared by
-// createRun and updateRun so a re-ingest can refresh the scope in place.
-// Validated per scenario at the door (see `withScenarioContext`).
-const webUrlSchema = z
- .string()
- .url()
- .refine((value) => {
- const protocol = new URL(value).protocol;
- return protocol === 'http:' || protocol === 'https:';
- });
-
-const pullRequestContextSchema = z.object({
- number: z.union([z.number(), z.string()]).optional(),
- title: z.string().optional(),
- url: webUrlSchema.optional(),
-});
-
-/**
- * A surface, canonicalized at the door.
- *
- * Not a bare `z.enum`: `lh` is installed independently of this server, so an
- * older CLI still posts the historical spellings β€” `electron` alone accounts for
- * most of the surfaces ever written. Rejecting those would break ingest for
- * every client that hasn't upgraded, to no benefit, since they name a surface we
- * can resolve. So known spellings are normalized (`electron` β†’ `desktop`) and
- * only a value that names no surface at all is rejected β€” the column still ends
- * up with nothing but the closed set.
- */
-const surfaceSchema = z.string().transform((value, ctx) => {
- const surface = normalizeVerifySurface(value);
- if (surface) return surface;
-
- ctx.addIssue({
- code: 'custom',
- message: `"${value}" is not a product surface. Expected one of: ${verifySurfaces.join(', ')}. A test kind ("unit", "backend") or a runtime mode ("packaged build") is not a surface.`,
- });
- return z.NEVER;
-});
-
-const codingRunContextSchema = z.object({
- branch: z.string().optional(),
- commit: z.string().optional(),
- entry: z.string().optional(),
- pullRequest: pullRequestContextSchema.optional(),
- surfaces: z.array(surfaceSchema).optional(),
- testedAt: z.string().optional(),
-});
-
-/**
- * Non-coding scenarios store the scope as an open bag. The known shapes live in
- * `@lobechat/types` (`VerifyRunContext`); the server deliberately does not
- * enumerate their fields, so a new scenario β€” or a new scope field on an
- * existing one β€” never requires a server redeploy. Only `coding` gets strict
- * validation, because its scope needs canonicalization at the door (surfaces).
- */
-const genericRunContextSchema = z.record(z.string(), z.unknown());
-
-const scenarioSchema = z.enum(verifyRunScenarios);
-
-/**
- * Validate `context` by its sibling `scenario`. Absent scenario defaults to
- * `coding` (the legacy contract β€” an older `lh` posts a coding scope with no
- * scenario field), so callers setting a non-coding context MUST send `scenario`
- * in the same payload or the coding schema strips their fields. Applied as a
- * transform (not a plain union) for two reasons: the coding path canonicalizes
- * surfaces in place, and an ordered union of all-optional stripping objects
- * would silently swallow a non-coding scope into the first match.
- */
-const withScenarioContext = <T extends { context?: unknown; scenario?: VerifyRunScenario }>(
- schema: z.ZodType<T>,
-) =>
- schema.transform((value, ctx) => {
- if (value.context === undefined) return { ...value, context: undefined };
-
- const contextSchema =
- (value.scenario ?? 'coding') === 'coding' ? codingRunContextSchema : genericRunContextSchema;
- const parsed = contextSchema.safeParse(value.context);
- if (!parsed.success) {
- for (const issue of parsed.error.issues) {
- ctx.addIssue({
- code: 'custom',
- message: issue.message,
- path: ['context', ...issue.path],
- });
- }
- return z.NEVER;
- }
-
- return { ...value, context: parsed.data as VerifyRunContext };
- });
-
-const runMetadataSchema = z.record(z.string(), z.unknown());
-
-const updateRunInputSchema = verifyRunIdInputSchema.extend({
- // Every field optional β€” a re-ingest may refresh only the context/goal while
- // keeping the original title, so nothing here is required.
- value: withScenarioContext(
- z.object({
- context: z.unknown().optional(),
- goal: z.string().optional(),
- metadata: runMetadataSchema.optional(),
- plan: z.array(checkItemSchema).optional(),
- scenario: scenarioSchema.optional(),
- title: z.string().trim().min(1).max(200).optional(),
- }),
- ),
-});
-
-// Cursor-paginated report list. `cursor` is the opaque token from the previous
-// page's `nextCursor`; `q` filters by title (server-side, so it hits the whole
-// history, not just the loaded page).
-const listReportSummariesInputSchema = z
- .object({
- cursor: z.string().optional(),
- limit: z.number().int().min(1).max(100).optional(),
- q: z.string().optional(),
- })
- .optional();
-
-const uploadEvidenceInputSchema = z
- .object({
- capturedBy: evidenceCapturedBySchema.optional(),
- // Exactly one of `content` (inline text) or `fileId` (already-uploaded artifact).
- checkResultId: z.string(),
- content: z.string().min(1).optional(),
- description: z.string().optional(),
- fileId: z.string().min(1).optional(),
- metadata: z.unknown().optional(),
- type: evidenceTypeSchema,
- })
- .refine((data) => Boolean(data.content) !== Boolean(data.fileId), {
- message: 'Provide exactly one of `content` or `fileId`.',
- });
-
-const verifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
- const { ctx } = opts;
- const workspaceId = ctx.workspaceId ?? undefined;
- return opts.next({
- ctx: {
- criterionModel: new VerifyCriterionModel(ctx.serverDB, ctx.userId, workspaceId),
- documentModel: new DocumentModel(ctx.serverDB, ctx.userId, workspaceId),
- evidenceModel: new VerifyEvidenceModel(ctx.serverDB, ctx.userId, workspaceId),
- fileModel: new FileModel(ctx.serverDB, ctx.userId, workspaceId),
- executorService: new VerifyExecutorService(ctx.serverDB, ctx.userId, workspaceId),
- tracingModel: new LlmGenerationTracingModel(ctx.serverDB, ctx.userId, workspaceId),
- feedbackService: new VerifyFeedbackService(ctx.serverDB, ctx.userId, workspaceId),
- goalCriteriaGenerator: new GoalCriteriaGeneratorService(
- ctx.serverDB,
- ctx.userId,
- workspaceId,
- ),
- operationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, workspaceId),
- planGenerator: new VerifyPlanGeneratorService(ctx.serverDB, ctx.userId, workspaceId),
- reportModel: new VerifyReportModel(ctx.serverDB, ctx.userId, workspaceId),
- reporterService: new VerifyReporterService(ctx.serverDB, ctx.userId, workspaceId),
- resultModel: new VerifyCheckResultModel(ctx.serverDB, ctx.userId, workspaceId),
- rubricModel: new VerifyRubricModel(ctx.serverDB, ctx.userId, workspaceId),
- runModel: new VerifyRunModel(ctx.serverDB, ctx.userId, workspaceId),
- },
- });
-});
-
-// Writes: workspace mode requires at least the member role, gating viewers
-// out (read-only role) while personal mode passes through unrestricted.
-const verifyWriteProcedure = verifyProcedure.use(requireWorkspaceRoleWhenScoped('member'));
-
-const resolveVerifyRun = async (ctx: { runModel: VerifyRunModel }, verifyRunId: string) => {
- const run = await ctx.runModel.findById(verifyRunId);
-
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification run not found' });
- }
-
- return run;
-};
-
-const resolveCheckResult = async (
- ctx: { resultModel: VerifyCheckResultModel },
- checkResultId: string,
-) => {
- const result = await ctx.resultModel.findById(checkResultId);
-
- if (!result) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification check result not found' });
- }
-
- return result;
-};
-
-/** Resolve a run from an Agent Run operation id β€” the handle a builder has in
- * the run-start gap, before any result rows (and thus checkResultIds) exist. */
-const resolveRunByOperation = async (ctx: { runModel: VerifyRunModel }, operationId: string) => {
- const run = await ctx.runModel.findByOperation(operationId);
-
- if (!run) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'No verification run for this operation' });
- }
-
- return run;
-};
-
-/** Store a file-backed artifact under the medium of the file itself, not the caller's label. */
-const storedEvidenceType = async (
- ctx: { fileModel: FileModel },
- type: VerifyEvidenceType,
- fileId?: string | null,
-): Promise<VerifyEvidenceType> =>
- fileId ? evidenceTypeForStoredFile(type, await ctx.fileModel.findById(fileId)) : type;
-
-export const verifyRouter = router({
- // ---- criteria (reusable atomic standards) ----
- createCriterion: verifyWriteProcedure
- .input(
- z.object({
- definition: verifyCheckDefinitionSchema.optional(),
- tags: z.array(z.string()).max(50).optional(),
- description: z.string().optional(),
- documentId: z.string().optional(),
- onFail: onFailSchema.optional(),
- required: z.boolean().optional(),
- title: z.string(),
- verifierConfig: z.record(z.string(), z.unknown()).optional(),
- verifierType: verifierTypeSchema,
- }),
- )
- .mutation(async ({ ctx, input }) => ctx.criterionModel.create(input)),
-
- deleteCriterion: verifyWriteProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const criterion = await ctx.criterionModel.findById(input.id);
- // Missing row β†’ keep the delete idempotent, nothing to authorize.
- if (!criterion) return;
- assertWorkspaceRowManageable(ctx, criterion.userId, 'verify criterion');
- return ctx.criterionModel.delete(input.id);
- }),
-
- forkRubricCriteria: verifyWriteProcedure
- .input(z.object({ ids: z.array(z.string()) }))
- .mutation(async ({ ctx, input }) => ctx.criterionModel.forkRubricCriteria(input.ids)),
-
- /**
- * Resolve a specific criteria id list (e.g. the ones bound to a goal), in
- * input order. Each row carries `instruction` resolved from its linked
- * document β€” the judge rule must be inspectable and editable where the
- * criteria are shown, not an invisible value edits would silently replace.
- */
- getCriteria: verifyProcedure
- .input(z.object({ ids: z.array(z.string()) }))
- .query(async ({ ctx, input }) => {
- if (input.ids.length === 0) return [];
- const rows = await ctx.criterionModel.findByIds(input.ids);
- const documentIds = [
- ...new Set(rows.flatMap((row) => (row.documentId ? [row.documentId] : []))),
- ];
- const documents = await Promise.all(documentIds.map((id) => ctx.documentModel.findById(id)));
- const contentByDocId = new Map(
- documents.flatMap((doc) => (doc ? [[doc.id, doc.content ?? undefined] as const] : [])),
- );
- const byId = new Map(
- rows.map((row) => [
- row.id,
- {
- ...row,
- instruction: row.documentId ? contentByDocId.get(row.documentId) : undefined,
- },
- ]),
- );
- return input.ids.map((id) => byId.get(id)).filter(Boolean);
- }),
-
- listCriteria: verifyProcedure
- .input(
- z
- .object({
- search: z.string().optional(),
- tags: z.array(z.string()).optional(),
- includeArchived: z.boolean().optional(),
- })
- .optional(),
- )
- .query(async ({ ctx, input }) => ctx.criterionModel.query(input)),
-
- getCriterionResults: verifyProcedure
- .input(z.object({ id: z.string().uuid(), limit: z.number().int().min(1).max(100).optional() }))
- .query(async ({ ctx, input }) => {
- if (!(await ctx.criterionModel.findById(input.id)))
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Check asset not found' });
- return ctx.resultModel.listByCriterion(input.id, input.limit);
- }),
-
- updateCriterion: verifyWriteProcedure
- .input(
- z.object({
- id: z.string(),
- value: z.object({
- definition: verifyCheckDefinitionSchema.nullish(),
- tags: z.array(z.string()).max(50).optional(),
- archivedAt: z.coerce.date().nullish(),
- description: z.string().nullish(),
- documentId: z.string().nullish(),
- onFail: onFailSchema.optional(),
- required: z.boolean().optional(),
- title: z.string().optional(),
- verifierConfig: z.record(z.string(), z.unknown()).optional(),
- verifierType: verifierTypeSchema.optional(),
- }),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const criterion = await ctx.criterionModel.findById(input.id);
- if (!criterion) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification criterion not found' });
- }
- assertWorkspaceRowManageable(ctx, criterion.userId, 'verify criterion');
- return ctx.criterionModel.update(input.id, input.value);
- }),
-
- // ---- rubrics (named criteria groups) ----
- createRubric: verifyWriteProcedure
- .input(
- z.object({
- config: rubricConfigSchema.optional(),
- description: z.string().optional(),
- title: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => ctx.rubricModel.create(input)),
-
- deleteRubric: verifyWriteProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const rubric = await ctx.rubricModel.findById(input.id);
- // Missing row β†’ keep the delete idempotent, nothing to authorize.
- if (!rubric) return;
- assertWorkspaceRowManageable(ctx, rubric.userId, 'verify rubric');
- return ctx.rubricModel.delete(input.id);
- }),
-
- getRubric: verifyProcedure
- .input(z.object({ id: z.string() }))
- .query(async ({ ctx, input }) => ctx.rubricModel.findById(input.id)),
-
- getRubricCriteria: verifyProcedure
- .input(z.object({ rubricId: z.string() }))
- .query(async ({ ctx, input }) => ctx.rubricModel.getCriteria(input.rubricId)),
-
- listRubrics: verifyProcedure.query(async ({ ctx }) => ctx.rubricModel.query()),
-
- setRubricCriteria: verifyWriteProcedure
- .input(
- z.object({
- criteria: z.array(z.object({ criterionId: z.string(), sortOrder: z.number().optional() })),
- rubricId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const rubric = await ctx.rubricModel.findById(input.rubricId);
- if (!rubric) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification rubric not found' });
- }
- assertWorkspaceRowManageable(ctx, rubric.userId, 'verify rubric');
- return ctx.rubricModel.setCriteria(input.rubricId, input.criteria);
- }),
-
- updateRubric: verifyWriteProcedure
- .input(
- z.object({
- id: z.string(),
- value: z.object({
- config: rubricConfigSchema.optional(),
- description: z.string().nullish(),
- title: z.string().optional(),
- }),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const rubric = await ctx.rubricModel.findById(input.id);
- if (!rubric) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification rubric not found' });
- }
- assertWorkspaceRowManageable(ctx, rubric.userId, 'verify rubric');
- return ctx.rubricModel.update(input.id, input.value);
- }),
-
- // ---- per-run plan ----
- confirmPlan: verifyWriteProcedure
- .input(z.object({ operationId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const run = await ctx.runModel.ensureForOperation(input.operationId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- return ctx.runModel.confirmPlan(run.id);
- }),
-
- generateDraftPlan: verifyWriteProcedure
- .input(
- z.object({
- context: z.string().optional(),
- enableAiGeneration: z.boolean().optional(),
- goal: z.string(),
- maxAiCriteria: z.number().optional(),
- operationId: z.string(),
- verifyCriteriaIds: z.array(z.string()).optional(),
- verifyRubricId: z.string().nullish(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- // The generator ends with setPlan() on the operation's run β€” resolve it
- // and gate on the run owner before writing (same as confirmPlan).
- const run = await ctx.runModel.ensureForOperation(input.operationId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- return ctx.planGenerator.generateDraftPlan(input);
- }),
-
- /**
- * Config-time: turn a one-sentence acceptance requirement into proposed
- * criteria for the user to review/edit. Traced (TRACING_SCENARIOS.GoalCriteriaGen),
- * returns drafts only β€” nothing persisted, no operation needed.
- */
- generateCriteria: verifyWriteProcedure
- .input(
- z.object({
- context: z.string().optional(),
- goal: z.string().min(1),
- maxCriteria: z.number().int().min(1).max(8).optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.planGenerator.generateCriteria(input);
- } catch (error) {
- const errorType = (error as { errorType?: unknown } | null)?.errorType;
- if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
- const trpcError = new TRPCError({
- cause: error,
- code: 'PRECONDITION_FAILED',
- message: AgentRuntimeErrorType.InvalidProviderAPIKey,
- });
- // Runtime errors are plain payloads, so tRPC normalizes them into an Error cause.
- // Mark the normalized cause that the shared handler actually receives.
- markSilentTRPCErrorLog(trpcError.cause);
- throw trpcError;
- }
-
- throw error;
- }
- }),
-
- /** Draft the standing acceptance contract for the create-goal flow. */
- generateGoalCriteria: verifyWriteProcedure
- .input(
- z.object({
- context: z.string().optional(),
- goal: z.string().min(1),
- maxCriteria: z.number().int().min(1).max(8).optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.goalCriteriaGenerator.generate(input);
- } catch (error) {
- const errorType = (error as { errorType?: unknown } | null)?.errorType;
- if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
- const trpcError = new TRPCError({
- cause: error,
- code: 'PRECONDITION_FAILED',
- message: AgentRuntimeErrorType.InvalidProviderAPIKey,
- });
- markSilentTRPCErrorLog(trpcError.cause);
- throw trpcError;
- }
-
- throw error;
- }
- }),
-
- /** Draft the generated goal title, instruction, and standing acceptance contract. */
- generateGoalPlan: verifyWriteProcedure
- .input(
- z.object({
- context: z.string().optional(),
- goal: z.string().min(1),
- maxCriteria: z.number().int().min(1).max(8).optional(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- try {
- return await ctx.goalCriteriaGenerator.generatePlan(input);
- } catch (error) {
- const errorType = (error as { errorType?: unknown } | null)?.errorType;
- if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
- const trpcError = new TRPCError({
- cause: error,
- code: 'PRECONDITION_FAILED',
- message: AgentRuntimeErrorType.InvalidProviderAPIKey,
- });
- markSilentTRPCErrorLog(trpcError.cause);
- throw trpcError;
- }
-
- throw error;
- }
- }),
-
- /** Persist (user-edited) drafts as standalone criteria; returns their ids in order. */
- createCriteria: verifyWriteProcedure
- .input(
- z.object({
- drafts: z.array(
- z.object({
- description: z.string().optional(),
- documentId: z.string().nullable().optional(),
- instruction: z.string().optional(),
- onFail: onFailSchema.optional(),
- required: z.boolean().optional(),
- title: z.string().min(1),
- verifierConfig: z.record(z.string(), z.unknown()).optional(),
- verifierType: verifierTypeSchema.optional(),
- }),
- ),
- }),
- )
- .mutation(async ({ ctx, input }) => ctx.planGenerator.createCriteriaFromDrafts(input.drafts)),
-
- getVerifierThread: verifyProcedure
- .input(z.object({ operationId: z.string() }))
- .query(async ({ ctx, input }) => {
- // Resolve an agent verifier's sub-run to the thread it ran in, so the
- // client can open that execution trace in the portal.
- const op = await ctx.operationModel.findById(input.operationId);
- if (!op) return null;
- return { threadId: op.threadId ?? null, topicId: op.topicId ?? null };
- }),
-
- getVerifierTracing: verifyProcedure
- .input(z.object({ tracingId: z.string() }))
- .query(async ({ ctx, input }) => {
- // The model / token / latency of an LLM verifier's judgment, surfaced in
- // the result detail panel.
- const row = await ctx.tracingModel.findById(input.tracingId);
- if (!row) return null;
- return {
- inputTokens: row.inputTokens ?? null,
- latencyMs: row.latencyMs ?? null,
- model: row.model ?? null,
- outputTokens: row.outputTokens ?? null,
- provider: row.provider ?? null,
- };
- }),
-
- /**
- * Serve a pullable skill bundle (`SKILL.md` + inline resource files) by
- * identifier without authentication. Keep the legacy alias while sourcing
- * all installers from the upstream default branch (or an explicitly selected tag).
- */
- getSkillBundle: publicProcedure
- .input(
- z.object({
- identifier: z.string(),
- version: z
- .string()
- .regex(/^v?\d+\.\d+\.\d+$/)
- .optional(),
- }),
- )
- .query(async ({ input }) => {
- if (input.identifier !== 'acceptance' && input.identifier !== 'verify')
- throw new TRPCError({
- code: 'NOT_FOUND',
- message: `No pullable skill with identifier "${input.identifier}"`,
- });
- return fetchAcceptanceSkillBundle(input.version);
- }),
-
- getVerifyState: verifyProcedure
- .input(z.object({ operationId: z.string() }))
- .query(async ({ ctx, input }) => ctx.runModel.getStateByOperation(input.operationId)),
-
- skipPlan: verifyWriteProcedure
- .input(z.object({ operationId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const run = await ctx.runModel.findByOperation(input.operationId);
- if (!run) return;
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- await ctx.runModel.updateStatus(run.id, null);
- }),
-
- updateDraftItems: verifyWriteProcedure
- .input(z.object({ items: z.array(checkItemSchema), operationId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const run = await ctx.runModel.ensureForOperation(input.operationId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- return ctx.runModel.replacePlanItems(run.id, input.items);
- }),
-
- // ---- results / execution ----
- executeVerify: verifyWriteProcedure
- .input(
- z.object({
- batchLlm: z.boolean().optional(),
- deliverable: z.string(),
- goal: z.string(),
- modelConfig: modelConfigSchema,
- operationId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- // Execution writes verdicts onto the run's result rows β€” only the run
- // creator (or a workspace owner) may drive another member's session.
- const existingRun = await ctx.runModel.findByOperation(input.operationId);
- if (existingRun) assertWorkspaceRowManageable(ctx, existingRun.userId, 'verify run');
-
- await ctx.executorService.execute(input);
- // Settle the run through the SAME finalizer the completion-time gate uses
- // (runVerifyOnCompletion β†’ finalizeVerifyRun): repair-aware tail (spawn a
- // repair round on auto_repair failures), then report + drive the bound task.
- // Without this, a verify triggered via the CLI (`lh verify run`, e.g. a
- // device/agent-testing run) would write verdicts and stop β€” never auto-repair.
- await finalizeVerifyRun(
- ctx.serverDB,
- ctx.userId,
- input.operationId,
- {
- report: {
- deliverable: input.deliverable,
- goal: input.goal,
- modelConfig: input.modelConfig,
- },
- },
- ctx.workspaceId ?? undefined,
- );
- const run = await ctx.runModel.findByOperation(input.operationId);
- return run ? ctx.resultModel.listByRun(run.id) : [];
- }),
-
- listResults: verifyProcedure
- .input(z.object({ operationId: z.string() }))
- .query(async ({ ctx, input }) => {
- const run = await ctx.runModel.findByOperation(input.operationId);
- return run ? ctx.resultModel.listByRun(run.id) : [];
- }),
-
- // ---- feedback (data flywheel) ----
- submitDecision: verifyWriteProcedure
- .input(z.object({ decision: decisionSchema, resultId: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const result = await resolveCheckResult(ctx, input.resultId);
- assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
- return ctx.feedbackService.submitDecision(result.id, input.decision);
- }),
-
- // ---- ingest (standalone sessions: results / evidence / report, e.g. agent-testing) ----
- // A verification session that isn't a live Agent Run (no executor): an external
- // harness creates the run, ingests each check's verdict + evidence, and writes a
- // report β€” all keyed by verifyRunId.
- createRun: verifyWriteProcedure
- .input(
- withScenarioContext(
- z.object({
- // The active scenario's context, rendered as the report's scope header.
- context: z.unknown().optional(),
- goal: z.string().optional(),
- metadata: runMetadataSchema.optional(),
- operationId: z.string().optional(),
- // The checks the run set out to make, authored before it ran. Kept next
- // to the results so a planned-but-never-executed item stays visible.
- plan: z.array(checkItemSchema).optional(),
- scenario: scenarioSchema.optional(),
- source: runSourceSchema.optional(),
- title: z.string().optional(),
- }),
- ),
- )
- .mutation(async ({ ctx, input }) =>
- ctx.runModel.create({
- context: input.context,
- goal: input.goal,
- metadata: input.metadata,
- operationId: input.operationId,
- plan: input.plan,
- scenario: input.scenario,
- source: input.source ?? 'agent-testing',
- title: input.title,
- }),
- ),
-
- getRun: verifyProcedure
- .input(verifyRunIdInputSchema)
- .query(async ({ ctx, input }) => ctx.runModel.findById(input.verifyRunId)),
-
- // Delete a whole verification session: the run row cascades to its check
- // results (β†’ their evidence) and its report via the schema FKs, and the
- // evidence files only this run referenced are purged from storage.
- // Ownership-scoped: resolveVerifyRun 404s a run that isn't the caller's
- // before we touch it.
- deleteRun: verifyWriteProcedure.input(verifyRunIdInputSchema).mutation(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
-
- await purgeVerifyRun(
- ctx.serverDB,
- new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
- run.userId,
- run.workspaceId ?? undefined,
- run.id,
- );
- return { id: run.id, success: true };
- }),
-
- listRuns: verifyProcedure.query(async ({ ctx }) => ctx.runModel.query()),
-
- listReportSummaries: verifyProcedure
- .input(listReportSummariesInputSchema)
- .query(async ({ ctx, input }) => {
- const { items: runs, nextCursor } = await ctx.runModel.queryPage({
- cursor: input?.cursor,
- limit: input?.limit,
- q: input?.q,
- });
- const reports = await Promise.all(runs.map((run) => ctx.reportModel.findByRun(run.id)));
-
- const items = runs.map((run, index) => {
- const report = reports[index];
-
- return {
- report: report
- ? {
- createdAt: report.createdAt,
- failedChecks: report.failedChecks,
- generatedAt: report.generatedAt,
- id: report.id,
- overallConfidence: report.overallConfidence,
- passedChecks: report.passedChecks,
- reviewedByUser: report.reviewedByUser,
- summary: report.summary,
- totalChecks: report.totalChecks,
- uncertainChecks: report.uncertainChecks,
- verdict: report.verdict,
- verifyRunId: report.verifyRunId,
- }
- : null,
- run,
- };
- });
-
- return { items, nextCursor };
- }),
-
- listResultsByRun: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- return ctx.resultModel.listByRun(run.id);
- }),
-
- updateRun: verifyWriteProcedure.input(updateRunInputSchema).mutation(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
-
- const updated = await ctx.runModel.update(
- run.id,
- omitUndefined({
- context: input.value.context,
- goal: input.value.goal,
- metadata: input.value.metadata,
- plan: input.value.plan,
- scenario: input.value.scenario,
- title: input.value.title,
- }),
- );
- return { data: updated, success: true };
- }),
-
- ingestResult: verifyWriteProcedure
- .input(
- z
- .object({
- checkItemId: z.string(),
- checkItemIndex: z.number().optional(),
- checkItemTitle: z.string().optional(),
- confidence: z.number().min(0).max(1).optional(),
- metadata: z.unknown().nullish(),
- required: z.boolean().optional(),
- status: checkStatusSchema.optional(),
- // `.nullish()` (not `.optional()`) so a re-ingest can pass an explicit
- // `null` to CLEAR a prior suggestion/observation β€” `undefined` would be
- // dropped from the conflict UPDATE and leave the stale value on the row,
- // breaking the full-replace guarantee. See the ingest-report caller.
- suggestion: z.string().nullish(),
- toulmin: toulminSchema.nullish(),
- // Optional so an infra failure can be recorded as `status: 'errored'`
- // with no verdict (the verifier never produced a judgment).
- verdict: verdictSchema.optional(),
- verifierType: verifierTypeSchema.optional(),
- verifyRunId: z.string(),
- })
- // A row needs either a verdict (β†’ derives status) or an explicit status
- // (e.g. `errored`); otherwise there's nothing to record.
- .refine((v) => v.verdict !== undefined || v.status !== undefined, {
- message: 'Either a verdict or an explicit status is required.',
- path: ['verdict'],
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- // The conflict-update overwrites the run's existing result rows.
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
-
- return ctx.resultModel.upsertByCheckItem({
- checkItemId: input.checkItemId,
- checkItemIndex: input.checkItemIndex,
- checkItemTitle: input.checkItemTitle,
- completedAt: new Date(),
- confidence: input.confidence,
- metadata: input.metadata as VerifyCheckResultMetadata | null | undefined,
- required: input.required ?? true,
- // Prefer an explicit status; else derive from the verdict (the refine
- // guarantees at least one is present).
- status: input.status ?? (input.verdict ? statusForVerdict(input.verdict) : 'errored'),
- suggestion: input.suggestion,
- toulmin: input.toulmin,
- verdict: input.verdict,
- verifierType: input.verifierType ?? 'agent',
- verifyRunId: run.id,
- });
- }),
-
- // Prune one check result (ownership-scoped; its evidence cascades). The
- // re-ingest path calls this for cases a later report round dropped, so
- // updating a session in place stays a full replace and never accretes stale
- // checks. resolveCheckResult 404s a result that isn't the caller's.
- deleteResult: verifyWriteProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const result = await resolveCheckResult(ctx, input.id);
- assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
-
- await ctx.resultModel.delete(result.id);
- return { id: result.id, success: true };
- }),
-
- uploadEvidence: verifyWriteProcedure
- .input(uploadEvidenceInputSchema)
- .mutation(async ({ ctx, input }) => {
- const result = await resolveCheckResult(ctx, input.checkResultId);
- // Attaching evidence mutates another member's result β€” creator-scoped,
- // mirroring submitCheckEvidence.
- assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
- const type = await storedEvidenceType(ctx, input.type, input.fileId);
-
- return ctx.evidenceModel.create({
- capturedAt: new Date(),
- capturedBy: input.capturedBy ?? null,
- checkResultId: result.id,
- content: input.content ?? null,
- description: input.description ?? null,
- fileId: input.fileId ?? null,
- metadata: normalizeEvidenceMetadata(input.metadata, type) ?? null,
- type,
- });
- }),
-
- /**
- * Builder self-evidence contract: submit a check item's verdict AND its
- * evidence in one call. The check_result row is created lazily (idempotent
- * upsert on `(verifyRunId, checkItemId)`) so the builder doesn't need a
- * pre-existing `checkResultId` β€” solving the run-start handle gap. Evidence
- * is optional (attach mid-run) and verdict is optional (set later by review).
- */
- submitCheckEvidence: verifyWriteProcedure
- .input(
- z
- .object({
- checkItemId: z.string(),
- checkItemIndex: z.number().optional(),
- checkItemTitle: z.string().optional(),
- confidence: z.number().min(0).max(1).optional(),
- evidence: z
- .array(
- z
- .object({
- capturedBy: evidenceCapturedBySchema.optional(),
- content: z.string().min(1).optional(),
- description: z.string().optional(),
- fileId: z.string().min(1).optional(),
- type: evidenceTypeSchema,
- })
- .refine((e) => Boolean(e.content) !== Boolean(e.fileId), {
- message: 'Provide exactly one of `content` or `fileId`.',
- }),
- )
- .optional(),
- // The builder may hold only its Agent Run operationId (run-start gap);
- // either handle resolves the session.
- operationId: z.string().optional(),
- required: z.boolean().optional(),
- status: checkStatusSchema.optional(),
- suggestion: z.string().optional(),
- toulmin: toulminSchema.optional(),
- verdict: verdictSchema.optional(),
- verifierType: verifierTypeSchema.optional(),
- verifyRunId: z.string().optional(),
- })
- .refine((d) => Boolean(d.verifyRunId) || Boolean(d.operationId), {
- message: 'Provide either `verifyRunId` or `operationId`.',
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const namedRun = input.verifyRunId
- ? await resolveVerifyRun(ctx, input.verifyRunId)
- : await resolveRunByOperation(ctx, input.operationId!);
- // The idempotent upsert overwrites the run's existing result rows.
- assertWorkspaceRowManageable(ctx, namedRun.userId, 'verify run');
- // A round whose failure already spawned a repair is never judged again;
- // land the submission on the round the repair will be judged in.
- const run = await resolveLiveRoundForItem(ctx, namedRun, input.checkItemId);
- if (run.id !== namedRun.id) assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
-
- // `required` / `verifierType` / index / title are stable per plan item, so
- // hydrate them from the run plan rather than hardcoding defaults β€” otherwise
- // an evidence-only submit would flip a soft criterion to required:true on the
- // conflict-update. `status` is mutable lifecycle state: omit it when there's
- // no verdict so an existing row keeps its status (and a new row falls to the
- // DB default 'pending') instead of being reset to 'running'. drizzle omits
- // undefined fields from both the insert and the conflict-update.
- const plan = (run.plan as VerifyCheckItem[] | null) ?? [];
- const planItem = plan.find((i) => i.id === input.checkItemId);
- // A planned run owns its checklist. An unknown id used to be upserted as a
- // new row that fell to the column default `required: true`, minting a
- // phantom required check no later round ever plans or re-answers β€” and the
- // Goal review then judged its stale evidence forever. Name the valid ids
- // so the caller can resubmit under the right one.
- if (plan.length > 0 && !planItem)
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: `Check item "${input.checkItemId}" is not in this verification run's plan. Use one of: ${plan
- .map((item) => `${item.id} (${item.title})`)
- .join('; ')}`,
- });
-
- const checkResult = await ctx.resultModel.upsertByCheckItem({
- checkItemId: input.checkItemId,
- checkItemIndex: input.checkItemIndex ?? planItem?.index,
- checkItemTitle: input.checkItemTitle ?? planItem?.title,
- completedAt: input.verdict ? new Date() : undefined,
- confidence: input.confidence,
- required: input.required ?? planItem?.required,
- status: input.status ?? (input.verdict ? statusForVerdict(input.verdict) : undefined),
- suggestion: input.suggestion,
- toulmin: input.toulmin,
- verdict: input.verdict,
- verifierType: input.verifierType ?? planItem?.verifierType ?? 'agent',
- verifyRunId: run.id,
- });
-
- const evidence = input.evidence?.length
- ? await Promise.all(
- input.evidence.map(async (e) =>
- ctx.evidenceModel.create({
- capturedAt: new Date(),
- capturedBy: e.capturedBy ?? null,
- checkResultId: checkResult.id,
- content: e.content ?? null,
- description: e.description ?? null,
- fileId: e.fileId ?? null,
- type: await storedEvidenceType(ctx, e.type, e.fileId),
- }),
- ),
- )
- : [];
-
- return { checkResult, evidence };
- }),
-
- listEvidence: verifyProcedure
- .input(z.object({ checkResultId: z.string() }))
- .query(async ({ ctx, input }) => {
- const result = await resolveCheckResult(ctx, input.checkResultId);
- return ctx.evidenceModel.listByCheckResult(result.id);
- }),
-
- deleteEvidence: verifyWriteProcedure
- .input(z.object({ id: z.string() }))
- .mutation(async ({ ctx, input }) => {
- const evidence = await ctx.evidenceModel.findById(input.id);
-
- if (!evidence) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification evidence not found' });
- }
- assertWorkspaceRowManageable(ctx, evidence.userId, 'verify evidence');
-
- await ctx.evidenceModel.delete(evidence.id);
- return { id: evidence.id, success: true };
- }),
-
- upsertReport: verifyWriteProcedure
- .input(
- z.object({
- content: z.string().optional(),
- failedChecks: z.number().optional(),
- generatedBy: z.string().optional(),
- overallConfidence: z.number().min(0).max(1).optional(),
- passedChecks: z.number().optional(),
- summary: z.string().optional(),
- totalChecks: z.number().optional(),
- uncertainChecks: z.number().optional(),
- verdict: verdictSchema.optional(),
- verifyRunId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- // The upsert overwrites the run's existing report row.
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
-
- const report = await ctx.reportModel.upsertByRun({
- content: input.content ?? null,
- failedChecks: input.failedChecks ?? null,
- generatedBy: input.generatedBy ?? 'agent-testing',
- overallConfidence: input.overallConfidence ?? null,
- passedChecks: input.passedChecks ?? null,
- summary: input.summary ?? null,
- totalChecks: input.totalChecks ?? null,
- uncertainChecks: input.uncertainChecks ?? null,
- verdict: input.verdict ?? null,
- verifyRunId: run.id,
- });
-
- // A published report settles an ingested round β€” re-derive the aggregate
- // it chains onto (β†’ `delivered`, awaiting the user's decision). Best-effort:
- // the report write must not fail on a rollup hiccup.
- if (run.acceptanceId) {
- try {
- await new AcceptanceService(
- ctx.serverDB,
- ctx.userId,
- ctx.workspaceId ?? undefined,
- ).recomputeStatus(run.acceptanceId);
- } catch (error) {
- console.error('[verify:upsertReport:recomputeAcceptance]', error);
- }
- }
-
- return report;
- }),
-
- getReport: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- return ctx.reportModel.findByRun(run.id);
- }),
-
- /**
- * Server-side LLM report: generate the narrative from the session's results +
- * evidence (verdict / stats computed deterministically). Distinct from
- * `upsertReport`, which stores a report a standalone harness computed itself.
- */
- regenerateReport: verifyWriteProcedure
- .input(
- z.object({
- deliverable: z.string(),
- goal: z.string(),
- modelConfig: modelConfigSchema,
- verifyRunId: z.string(),
- }),
- )
- .mutation(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- return ctx.reporterService.generateReport({
- deliverable: input.deliverable,
- goal: input.goal,
- modelConfig: input.modelConfig,
- verifyRunId: run.id,
- });
- }),
-
- /**
- * Flip who can read this round's report page beyond its creator. Creation
- * defaults are scope-dependent (personal β†’ public, workspace β†’ private) and
- * acceptance-attached rounds inherit their aggregate; this is the deliberate
- * per-round override. Note `acceptance.setVisibility` cascades over rounds,
- * so the aggregate flip wins over earlier per-round choices.
- */
- setRunVisibility: verifyWriteProcedure
- .input(z.object({ verifyRunId: z.string(), visibility: z.enum(verifyVisibilities) }))
- .mutation(async ({ ctx, input }) => {
- const run = await resolveVerifyRun(ctx, input.verifyRunId);
- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- await ctx.runModel.setVisibility(run.id, input.visibility);
- }),
-
- ...verifyRunReportProcedures,
-});
diff --git a/apps/server/src/routers/lambda/verify/criteria.ts b/apps/server/src/routers/lambda/verify/criteria.ts
new file mode 100644
index 00000000000..d2824b6d690
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/criteria.ts
@@ -0,0 +1,184 @@
+import { verifyCheckDefinitionSchema } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { verifyProcedure, verifyWriteProcedure } from './procedures';
+import { onFailSchema, verifierTypeSchema } from './schemas';
+
+/** Run-policy knobs persisted on a rubric (see VerifyRubricConfig). */
+const rubricConfigSchema = z.object({
+ maxRepairRounds: z.number().int().min(0).max(5).optional(),
+});
+
+// A criteria list links a runtime-sized set of documents; cap the per-document reads.
+const CRITERION_DOCUMENT_LOAD_CONCURRENCY = 5;
+
+export const criteriaRouter = router({
+ // ---- criteria (reusable atomic standards) ----
+ createCriterion: verifyWriteProcedure
+ .input(
+ z.object({
+ definition: verifyCheckDefinitionSchema.optional(),
+ tags: z.array(z.string()).max(50).optional(),
+ description: z.string().optional(),
+ documentId: z.string().optional(),
+ onFail: onFailSchema.optional(),
+ required: z.boolean().optional(),
+ title: z.string(),
+ verifierConfig: z.record(z.string(), z.unknown()).optional(),
+ verifierType: verifierTypeSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ctx.criterionModel.create(input)),
+ deleteCriterion: verifyWriteProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const criterion = await ctx.criterionModel.findById(input.id);
+ // Missing row β†’ keep the delete idempotent, nothing to authorize.
+ if (!criterion) return;
+ assertWorkspaceRowManageable(ctx, criterion.userId, 'verify criterion');
+ return ctx.criterionModel.delete(input.id);
+ }),
+ forkRubricCriteria: verifyWriteProcedure
+ .input(z.object({ ids: z.array(z.string()) }))
+ .mutation(async ({ ctx, input }) => ctx.criterionModel.forkRubricCriteria(input.ids)),
+ /**
+ * Resolve a specific criteria id list (e.g. the ones bound to a goal), in
+ * input order. Each row carries `instruction` resolved from its linked
+ * document β€” the judge rule must be inspectable and editable where the
+ * criteria are shown, not an invisible value edits would silently replace.
+ */
+ getCriteria: verifyProcedure
+ .input(z.object({ ids: z.array(z.string()) }))
+ .query(async ({ ctx, input }) => {
+ if (input.ids.length === 0) return [];
+ const rows = await ctx.criterionModel.findByIds(input.ids);
+ const documentIds = [
+ ...new Set(rows.flatMap((row) => (row.documentId ? [row.documentId] : []))),
+ ];
+ const documents = await pMap(documentIds, (id) => ctx.documentModel.findById(id), {
+ concurrency: CRITERION_DOCUMENT_LOAD_CONCURRENCY,
+ });
+ const contentByDocId = new Map(
+ documents.flatMap((doc) => (doc ? [[doc.id, doc.content ?? undefined] as const] : [])),
+ );
+ const byId = new Map(
+ rows.map((row) => [
+ row.id,
+ {
+ ...row,
+ instruction: row.documentId ? contentByDocId.get(row.documentId) : undefined,
+ },
+ ]),
+ );
+ return input.ids.map((id) => byId.get(id)).filter(Boolean);
+ }),
+ listCriteria: verifyProcedure
+ .input(
+ z
+ .object({
+ search: z.string().optional(),
+ tags: z.array(z.string()).optional(),
+ includeArchived: z.boolean().optional(),
+ })
+ .optional(),
+ )
+ .query(async ({ ctx, input }) => ctx.criterionModel.query(input)),
+ getCriterionResults: verifyProcedure
+ .input(z.object({ id: z.string().uuid(), limit: z.number().int().min(1).max(100).optional() }))
+ .query(async ({ ctx, input }) => {
+ if (!(await ctx.criterionModel.findById(input.id)))
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Check asset not found' });
+ return ctx.resultModel.listByCriterion(input.id, input.limit);
+ }),
+ updateCriterion: verifyWriteProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ value: z.object({
+ definition: verifyCheckDefinitionSchema.nullish(),
+ tags: z.array(z.string()).max(50).optional(),
+ archivedAt: z.coerce.date().nullish(),
+ description: z.string().nullish(),
+ documentId: z.string().nullish(),
+ onFail: onFailSchema.optional(),
+ required: z.boolean().optional(),
+ title: z.string().optional(),
+ verifierConfig: z.record(z.string(), z.unknown()).optional(),
+ verifierType: verifierTypeSchema.optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const criterion = await ctx.criterionModel.findById(input.id);
+ if (!criterion) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification criterion not found' });
+ }
+ assertWorkspaceRowManageable(ctx, criterion.userId, 'verify criterion');
+ return ctx.criterionModel.update(input.id, input.value);
+ }),
+ // ---- rubrics (named criteria groups) ----
+ createRubric: verifyWriteProcedure
+ .input(
+ z.object({
+ config: rubricConfigSchema.optional(),
+ description: z.string().optional(),
+ title: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ctx.rubricModel.create(input)),
+ deleteRubric: verifyWriteProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const rubric = await ctx.rubricModel.findById(input.id);
+ // Missing row β†’ keep the delete idempotent, nothing to authorize.
+ if (!rubric) return;
+ assertWorkspaceRowManageable(ctx, rubric.userId, 'verify rubric');
+ return ctx.rubricModel.delete(input.id);
+ }),
+ getRubric: verifyProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => ctx.rubricModel.findById(input.id)),
+ getRubricCriteria: verifyProcedure
+ .input(z.object({ rubricId: z.string() }))
+ .query(async ({ ctx, input }) => ctx.rubricModel.getCriteria(input.rubricId)),
+ listRubrics: verifyProcedure.query(async ({ ctx }) => ctx.rubricModel.query()),
+ setRubricCriteria: verifyWriteProcedure
+ .input(
+ z.object({
+ criteria: z.array(z.object({ criterionId: z.string(), sortOrder: z.number().optional() })),
+ rubricId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const rubric = await ctx.rubricModel.findById(input.rubricId);
+ if (!rubric) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification rubric not found' });
+ }
+ assertWorkspaceRowManageable(ctx, rubric.userId, 'verify rubric');
+ return ctx.rubricModel.setCriteria(input.rubricId, input.criteria);
+ }),
+ updateRubric: verifyWriteProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ value: z.object({
+ config: rubricConfigSchema.optional(),
+ description: z.string().nullish(),
+ title: z.string().optional(),
+ }),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const rubric = await ctx.rubricModel.findById(input.id);
+ if (!rubric) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification rubric not found' });
+ }
+ assertWorkspaceRowManageable(ctx, rubric.userId, 'verify rubric');
+ return ctx.rubricModel.update(input.id, input.value);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/verify/execution.ts b/apps/server/src/routers/lambda/verify/execution.ts
new file mode 100644
index 00000000000..fc5bbc20308
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/execution.ts
@@ -0,0 +1,268 @@
+import { fetchAcceptanceSkillBundle } from '@lobechat/builtin-skills/acceptance';
+import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { publicProcedure, router } from '@/libs/trpc/lambda';
+import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';
+import { finalizeVerifyRun } from '@/server/services/verify';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { resolveCheckResult, verifyProcedure, verifyWriteProcedure } from './procedures';
+import { checkItemSchema, modelConfigSchema, onFailSchema, verifierTypeSchema } from './schemas';
+
+const decisionSchema = z.enum(['accepted', 'rejected', 'overridden']);
+
+export const executionRouter = router({
+ // ---- per-run plan ----
+ confirmPlan: verifyWriteProcedure
+ .input(z.object({ operationId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const run = await ctx.runModel.ensureForOperation(input.operationId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+ return ctx.runModel.confirmPlan(run.id);
+ }),
+ generateDraftPlan: verifyWriteProcedure
+ .input(
+ z.object({
+ context: z.string().optional(),
+ enableAiGeneration: z.boolean().optional(),
+ goal: z.string(),
+ maxAiCriteria: z.number().optional(),
+ operationId: z.string(),
+ verifyCriteriaIds: z.array(z.string()).optional(),
+ verifyRubricId: z.string().nullish(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ // The generator ends with setPlan() on the operation's run β€” resolve it
+ // and gate on the run owner before writing (same as confirmPlan).
+ const run = await ctx.runModel.ensureForOperation(input.operationId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+ return ctx.planGenerator.generateDraftPlan(input);
+ }),
+ /**
+ * Config-time: turn a one-sentence acceptance requirement into proposed
+ * criteria for the user to review/edit. Traced (TRACING_SCENARIOS.GoalCriteriaGen),
+ * returns drafts only β€” nothing persisted, no operation needed.
+ */
+ generateCriteria: verifyWriteProcedure
+ .input(
+ z.object({
+ context: z.string().optional(),
+ goal: z.string().min(1),
+ maxCriteria: z.number().int().min(1).max(8).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.planGenerator.generateCriteria(input);
+ } catch (error) {
+ const errorType = (error as { errorType?: unknown } | null)?.errorType;
+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
+ const trpcError = new TRPCError({
+ cause: error,
+ code: 'PRECONDITION_FAILED',
+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ });
+ // Runtime errors are plain payloads, so tRPC normalizes them into an Error cause.
+ // Mark the normalized cause that the shared handler actually receives.
+ markSilentTRPCErrorLog(trpcError.cause);
+ throw trpcError;
+ }
+
+ throw error;
+ }
+ }),
+ /** Draft the standing acceptance contract for the create-goal flow. */
+ generateGoalCriteria: verifyWriteProcedure
+ .input(
+ z.object({
+ context: z.string().optional(),
+ goal: z.string().min(1),
+ maxCriteria: z.number().int().min(1).max(8).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.goalCriteriaGenerator.generate(input);
+ } catch (error) {
+ const errorType = (error as { errorType?: unknown } | null)?.errorType;
+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
+ const trpcError = new TRPCError({
+ cause: error,
+ code: 'PRECONDITION_FAILED',
+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ });
+ markSilentTRPCErrorLog(trpcError.cause);
+ throw trpcError;
+ }
+
+ throw error;
+ }
+ }),
+ /** Draft the generated goal title, instruction, and standing acceptance contract. */
+ generateGoalPlan: verifyWriteProcedure
+ .input(
+ z.object({
+ context: z.string().optional(),
+ goal: z.string().min(1),
+ maxCriteria: z.number().int().min(1).max(8).optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.goalCriteriaGenerator.generatePlan(input);
+ } catch (error) {
+ const errorType = (error as { errorType?: unknown } | null)?.errorType;
+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {
+ const trpcError = new TRPCError({
+ cause: error,
+ code: 'PRECONDITION_FAILED',
+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ });
+ markSilentTRPCErrorLog(trpcError.cause);
+ throw trpcError;
+ }
+
+ throw error;
+ }
+ }),
+ /** Persist (user-edited) drafts as standalone criteria; returns their ids in order. */
+ createCriteria: verifyWriteProcedure
+ .input(
+ z.object({
+ drafts: z.array(
+ z.object({
+ description: z.string().optional(),
+ documentId: z.string().nullable().optional(),
+ instruction: z.string().optional(),
+ onFail: onFailSchema.optional(),
+ required: z.boolean().optional(),
+ title: z.string().min(1),
+ verifierConfig: z.record(z.string(), z.unknown()).optional(),
+ verifierType: verifierTypeSchema.optional(),
+ }),
+ ),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => ctx.planGenerator.createCriteriaFromDrafts(input.drafts)),
+ getVerifierThread: verifyProcedure
+ .input(z.object({ operationId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ // Resolve an agent verifier's sub-run to the thread it ran in, so the
+ // client can open that execution trace in the portal.
+ const op = await ctx.operationModel.findById(input.operationId);
+ if (!op) return null;
+ return { threadId: op.threadId ?? null, topicId: op.topicId ?? null };
+ }),
+ getVerifierTracing: verifyProcedure
+ .input(z.object({ tracingId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ // The model / token / latency of an LLM verifier's judgment, surfaced in
+ // the result detail panel.
+ const row = await ctx.tracingModel.findById(input.tracingId);
+ if (!row) return null;
+ return {
+ inputTokens: row.inputTokens ?? null,
+ latencyMs: row.latencyMs ?? null,
+ model: row.model ?? null,
+ outputTokens: row.outputTokens ?? null,
+ provider: row.provider ?? null,
+ };
+ }),
+ /**
+ * Serve a pullable skill bundle (`SKILL.md` + inline resource files) by
+ * identifier without authentication. Keep the legacy alias while sourcing
+ * all installers from the upstream default branch (or an explicitly selected tag).
+ */
+ getSkillBundle: publicProcedure
+ .input(
+ z.object({
+ identifier: z.string(),
+ version: z
+ .string()
+ .regex(/^v?\d+\.\d+\.\d+$/)
+ .optional(),
+ }),
+ )
+ .query(async ({ input }) => {
+ if (input.identifier !== 'acceptance' && input.identifier !== 'verify')
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `No pullable skill with identifier "${input.identifier}"`,
+ });
+ return fetchAcceptanceSkillBundle(input.version);
+ }),
+ getVerifyState: verifyProcedure
+ .input(z.object({ operationId: z.string() }))
+ .query(async ({ ctx, input }) => ctx.runModel.getStateByOperation(input.operationId)),
+ skipPlan: verifyWriteProcedure
+ .input(z.object({ operationId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const run = await ctx.runModel.findByOperation(input.operationId);
+ if (!run) return;
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+ await ctx.runModel.updateStatus(run.id, null);
+ }),
+ updateDraftItems: verifyWriteProcedure
+ .input(z.object({ items: z.array(checkItemSchema), operationId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const run = await ctx.runModel.ensureForOperation(input.operationId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+ return ctx.runModel.replacePlanItems(run.id, input.items);
+ }),
+ // ---- results / execution ----
+ executeVerify: verifyWriteProcedure
+ .input(
+ z.object({
+ batchLlm: z.boolean().optional(),
+ deliverable: z.string(),
+ goal: z.string(),
+ modelConfig: modelConfigSchema,
+ operationId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ // Execution writes verdicts onto the run's result rows β€” only the run
+ // creator (or a workspace owner) may drive another member's session.
+ const existingRun = await ctx.runModel.findByOperation(input.operationId);
+ if (existingRun) assertWorkspaceRowManageable(ctx, existingRun.userId, 'verify run');
+
+ await ctx.executorService.execute(input);
+ // Settle the run through the SAME finalizer the completion-time gate uses
+ // (runVerifyOnCompletion β†’ finalizeVerifyRun): repair-aware tail (spawn a
+ // repair round on auto_repair failures), then report + drive the bound task.
+ // Without this, a verify triggered via the CLI (`lh verify run`, e.g. a
+ // device/agent-testing run) would write verdicts and stop β€” never auto-repair.
+ await finalizeVerifyRun(
+ ctx.serverDB,
+ ctx.userId,
+ input.operationId,
+ {
+ report: {
+ deliverable: input.deliverable,
+ goal: input.goal,
+ modelConfig: input.modelConfig,
+ },
+ },
+ ctx.workspaceId ?? undefined,
+ );
+ const run = await ctx.runModel.findByOperation(input.operationId);
+ return run ? ctx.resultModel.listByRun(run.id) : [];
+ }),
+ listResults: verifyProcedure
+ .input(z.object({ operationId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const run = await ctx.runModel.findByOperation(input.operationId);
+ return run ? ctx.resultModel.listByRun(run.id) : [];
+ }),
+ // ---- feedback (data flywheel) ----
+ submitDecision: verifyWriteProcedure
+ .input(z.object({ decision: decisionSchema, resultId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const result = await resolveCheckResult(ctx, input.resultId);
+ assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
+ return ctx.feedbackService.submitDecision(result.id, input.decision);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts b/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts
new file mode 100644
index 00000000000..4f9221eb2fd
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts
@@ -0,0 +1,162 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as VerifyServiceModule from '@/server/services/verify';
+
+import { verifyRouter } from '.';
+
+const mocks = vi.hoisted(() => ({
+ createEvidence: vi.fn(),
+ findCriteriaByIds: vi.fn(),
+ findDocumentById: vi.fn(),
+ findFileById: vi.fn(),
+ findReportByRun: vi.fn(),
+ findRunById: vi.fn(),
+ findRunByOperation: vi.fn(),
+ listResultsByRun: vi.fn(),
+ queryRunPage: vi.fn(),
+ upsertByCheckItem: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));
+
+vi.mock('@/database/models/verifyCriterion', () => ({
+ VerifyCriterionModel: vi.fn(function () {
+ return { findByIds: mocks.findCriteriaByIds };
+ }),
+}));
+
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: vi.fn(function () {
+ return { findById: mocks.findDocumentById };
+ }),
+}));
+
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn(function () {
+ return { findById: mocks.findFileById };
+ }),
+}));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(function () {
+ return {
+ findById: mocks.findRunById,
+ findByOperation: mocks.findRunByOperation,
+ queryPage: mocks.queryRunPage,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/verifyReport', () => ({
+ VerifyReportModel: vi.fn(function () {
+ return { findByRun: mocks.findReportByRun };
+ }),
+}));
+
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function () {
+ return { listByRun: mocks.listResultsByRun, upsertByCheckItem: mocks.upsertByCheckItem };
+ }),
+}));
+
+vi.mock('@/database/models/verifyEvidence', () => ({
+ VerifyEvidenceModel: vi.fn(function () {
+ return { create: mocks.createEvidence };
+ }),
+}));
+
+vi.mock('@/server/services/verify', async (importOriginal) => ({
+ ...(await importOriginal<typeof VerifyServiceModule>()),
+ VerifyExecutorService: class VerifyExecutorService {},
+ VerifyFeedbackService: class VerifyFeedbackService {},
+ VerifyPlanGeneratorService: class VerifyPlanGeneratorService {},
+ VerifyReporterService: class VerifyReporterService {},
+}));
+
+vi.mock('@/server/services/goal/criteriaGenerator', () => ({
+ GoalCriteriaGeneratorService: class GoalCriteriaGeneratorService {},
+}));
+
+const FAN_OUT_LIMIT = 5;
+const ITEM_COUNT = 12;
+
+/**
+ * Wraps a lookup so it records the peak number of overlapping calls. Earlier
+ * items resolve later, so a result list in input order proves order is kept.
+ */
+const trackInFlight = <A extends unknown[], R>(fn: (...args: A) => R) => {
+ const state = { inFlight: 0, peak: 0 };
+ let call = 0;
+ const tracked = async (...args: A) => {
+ const delay = ITEM_COUNT - call++;
+ state.inFlight += 1;
+ state.peak = Math.max(state.peak, state.inFlight);
+ await new Promise((resolve) => setTimeout(resolve, delay));
+ state.inFlight -= 1;
+ return fn(...args);
+ };
+ return { state, tracked };
+};
+
+const ids = Array.from({ length: ITEM_COUNT }, (_, i) => `id-${i}`);
+const createCaller = () => verifyRouter.createCaller({ userId: 'fan-out-test-user' } as any);
+
+describe('verify router fan-outs', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listResultsByRun.mockResolvedValue([]);
+ });
+
+ it('getCriteria loads linked documents in order with bounded concurrency', async () => {
+ mocks.findCriteriaByIds.mockResolvedValue(ids.map((id) => ({ documentId: `doc-${id}`, id })));
+ const { state, tracked } = trackInFlight((docId: string) => ({
+ content: `content of ${docId}`,
+ id: docId,
+ }));
+ mocks.findDocumentById.mockImplementation(tracked);
+
+ const rows = await createCaller().getCriteria({ ids });
+
+ expect(rows.map((row: any) => row.instruction)).toEqual(
+ ids.map((id) => `content of doc-${id}`),
+ );
+ expect(mocks.findDocumentById).toHaveBeenCalledTimes(ITEM_COUNT);
+ expect(state.peak).toBe(FAN_OUT_LIMIT);
+ });
+
+ it('submitCheckEvidence writes evidence in order with bounded concurrency', async () => {
+ mocks.findRunById.mockResolvedValue({ id: 'run-1', plan: [] });
+ mocks.upsertByCheckItem.mockResolvedValue({ id: 'result-1' });
+ const { state, tracked } = trackInFlight((row: { content: string }) => ({
+ id: `evidence-${row.content}`,
+ }));
+ mocks.createEvidence.mockImplementation(tracked);
+
+ const res = await createCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ evidence: ids.map((id) => ({ content: id, type: 'text' as const })),
+ verifyRunId: 'run-1',
+ });
+
+ expect(res.evidence).toEqual(ids.map((id) => ({ id: `evidence-${id}` })));
+ expect(state.peak).toBe(FAN_OUT_LIMIT);
+ });
+
+ it('listReportSummaries loads reports in order with bounded concurrency', async () => {
+ mocks.queryRunPage.mockResolvedValue({
+ items: ids.map((id) => ({ id, title: id })),
+ nextCursor: undefined,
+ });
+ const { state, tracked } = trackInFlight((runId: string) => ({
+ id: `report-${runId}`,
+ summary: runId,
+ }));
+ mocks.findReportByRun.mockImplementation(tracked);
+
+ const res = await createCaller().listReportSummaries({ limit: ITEM_COUNT });
+
+ expect(res.items.map((item: any) => item.report?.id)).toEqual(ids.map((id) => `report-${id}`));
+ expect(state.peak).toBe(FAN_OUT_LIMIT);
+ });
+});
diff --git a/apps/server/src/routers/lambda/verify/index.procedures.test.ts b/apps/server/src/routers/lambda/verify/index.procedures.test.ts
new file mode 100644
index 00000000000..e5c76179b93
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/index.procedures.test.ts
@@ -0,0 +1,77 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { verifyRouter } from '.';
+
+/**
+ * Pins the router's public surface: every procedure path, its kind, and its
+ * middleware chain length (which encodes the procedure builder and its input
+ * parsers). Splitting the router across files must keep all three.
+ */
+describe('verifyRouter procedures', () => {
+ const procedures = (verifyRouter as any)._def.procedures as Record<string, any>;
+
+ it('exposes exactly the expected procedure paths', () => {
+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));
+ });
+
+ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {
+ expect(procedures[name]._def.type).toBe(type);
+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);
+ });
+});
+
+function expected(): Array<
+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]
+> {
+ return [
+ ['confirmPlan', 'mutation', 13],
+ ['createCriteria', 'mutation', 13],
+ ['createCriterion', 'mutation', 13],
+ ['createRubric', 'mutation', 13],
+ ['createRun', 'mutation', 13],
+ ['deleteCriterion', 'mutation', 13],
+ ['deleteEvidence', 'mutation', 13],
+ ['deleteResult', 'mutation', 13],
+ ['deleteRubric', 'mutation', 13],
+ ['deleteRun', 'mutation', 13],
+ ['executeVerify', 'mutation', 13],
+ ['forkRubricCriteria', 'mutation', 13],
+ ['generateCriteria', 'mutation', 13],
+ ['generateDraftPlan', 'mutation', 13],
+ ['generateGoalCriteria', 'mutation', 13],
+ ['generateGoalPlan', 'mutation', 13],
+ ['getCriteria', 'query', 12],
+ ['getCriterionResults', 'query', 12],
+ ['getReport', 'query', 12],
+ ['getReportBundle', 'query', 7],
+ ['getRubric', 'query', 12],
+ ['getRubricCriteria', 'query', 12],
+ ['getRun', 'query', 12],
+ ['getRunAcceptanceRound', 'query', 7],
+ ['getSkillBundle', 'query', 6],
+ ['getVerifierThread', 'query', 12],
+ ['getVerifierTracing', 'query', 12],
+ ['getVerifyState', 'query', 12],
+ ['ingestResult', 'mutation', 13],
+ ['listCriteria', 'query', 12],
+ ['listEvidence', 'query', 12],
+ ['listReportSummaries', 'query', 12],
+ ['listResults', 'query', 12],
+ ['listResultsByRun', 'query', 12],
+ ['listRubrics', 'query', 11],
+ ['listRuns', 'query', 11],
+ ['regenerateReport', 'mutation', 13],
+ ['setRubricCriteria', 'mutation', 13],
+ ['setRunVisibility', 'mutation', 13],
+ ['skipPlan', 'mutation', 13],
+ ['submitCheckEvidence', 'mutation', 13],
+ ['submitDecision', 'mutation', 13],
+ ['updateCriterion', 'mutation', 13],
+ ['updateDraftItems', 'mutation', 13],
+ ['updateRubric', 'mutation', 13],
+ ['updateRun', 'mutation', 13],
+ ['uploadEvidence', 'mutation', 13],
+ ['upsertReport', 'mutation', 13],
+ ];
+}
diff --git a/apps/server/src/routers/lambda/verify/index.ts b/apps/server/src/routers/lambda/verify/index.ts
new file mode 100644
index 00000000000..595f3411b52
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/index.ts
@@ -0,0 +1,19 @@
+import { mergeRouters, router } from '@/libs/trpc/lambda';
+
+import { verifyRunReportProcedures } from '../verifyRunReport';
+import { criteriaRouter } from './criteria';
+import { executionRouter } from './execution';
+import { ingestRouter } from './ingest';
+import { reportsRouter } from './reports';
+import { runsRouter } from './runs';
+
+export const verifyRouter = mergeRouters(
+ criteriaRouter,
+ executionRouter,
+ runsRouter,
+ ingestRouter,
+ reportsRouter,
+ router({
+ ...verifyRunReportProcedures,
+ }),
+);
diff --git a/apps/server/src/routers/lambda/verify/ingest.ts b/apps/server/src/routers/lambda/verify/ingest.ts
new file mode 100644
index 00000000000..b87e49f1e79
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/ingest.ts
@@ -0,0 +1,316 @@
+import { normalizeEvidenceMetadata } from '@lobechat/const/verify';
+import type {
+ VerifyCheckItem,
+ VerifyCheckResultMetadata,
+ VerifyEvidenceType,
+} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import type { FileModel } from '@/database/models/file';
+import type { VerifyRunModel } from '@/database/models/verifyRun';
+import { router } from '@/libs/trpc/lambda';
+import { evidenceTypeForStoredFile, resolveLiveRoundForItem } from '@/server/services/verify';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import {
+ resolveCheckResult,
+ resolveVerifyRun,
+ verifyProcedure,
+ verifyWriteProcedure,
+} from './procedures';
+import { verdictSchema, verifierTypeSchema } from './schemas';
+
+const checkStatusSchema = z.enum([
+ 'pending',
+ 'running',
+ 'passed',
+ 'failed',
+ // Verifier could not run (infra failure) β€” carries no verdict.
+ 'errored',
+ 'skipped',
+]);
+
+const evidenceTypeSchema = z.enum([
+ 'screenshot',
+ 'gif',
+ 'video',
+ 'audio',
+ 'text',
+ 'markdown',
+ 'dom_snapshot',
+ 'transcript',
+]);
+
+const evidenceCapturedBySchema = z.enum(['agent-browser', 'cdp', 'cli', 'program', 'llm_judge']);
+
+const toulminSchema = z.object({
+ counterEvidence: z.string().optional(),
+ evidence: z.string().optional(),
+ limitation: z.string().optional(),
+ reasoning: z.string().optional(),
+});
+
+/** Derive the lifecycle status from a verdict when the caller doesn't pin one. */
+const statusForVerdict = (verdict: 'passed' | 'failed' | 'uncertain') =>
+ verdict === 'passed' ? ('passed' as const) : ('failed' as const);
+
+const uploadEvidenceInputSchema = z
+ .object({
+ capturedBy: evidenceCapturedBySchema.optional(),
+ // Exactly one of `content` (inline text) or `fileId` (already-uploaded artifact).
+ checkResultId: z.string(),
+ content: z.string().min(1).optional(),
+ description: z.string().optional(),
+ fileId: z.string().min(1).optional(),
+ metadata: z.unknown().optional(),
+ type: evidenceTypeSchema,
+ })
+ .refine((data) => Boolean(data.content) !== Boolean(data.fileId), {
+ message: 'Provide exactly one of `content` or `fileId`.',
+ });
+
+/** Resolve a run from an Agent Run operation id β€” the handle a builder has in
+ * the run-start gap, before any result rows (and thus checkResultIds) exist. */
+const resolveRunByOperation = async (ctx: { runModel: VerifyRunModel }, operationId: string) => {
+ const run = await ctx.runModel.findByOperation(operationId);
+
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'No verification run for this operation' });
+ }
+
+ return run;
+};
+
+/** Store a file-backed artifact under the medium of the file itself, not the caller's label. */
+const storedEvidenceType = async (
+ ctx: { fileModel: FileModel },
+ type: VerifyEvidenceType,
+ fileId?: string | null,
+): Promise<VerifyEvidenceType> =>
+ fileId ? evidenceTypeForStoredFile(type, await ctx.fileModel.findById(fileId)) : type;
+
+// A submitted result carries a runtime-sized evidence list; cap the per-entry
+// file lookup + insert.
+const EVIDENCE_WRITE_CONCURRENCY = 5;
+
+export const ingestRouter = router({
+ ingestResult: verifyWriteProcedure
+ .input(
+ z
+ .object({
+ checkItemId: z.string(),
+ checkItemIndex: z.number().optional(),
+ checkItemTitle: z.string().optional(),
+ confidence: z.number().min(0).max(1).optional(),
+ metadata: z.unknown().nullish(),
+ required: z.boolean().optional(),
+ status: checkStatusSchema.optional(),
+ // `.nullish()` (not `.optional()`) so a re-ingest can pass an explicit
+ // `null` to CLEAR a prior suggestion/observation β€” `undefined` would be
+ // dropped from the conflict UPDATE and leave the stale value on the row,
+ // breaking the full-replace guarantee. See the ingest-report caller.
+ suggestion: z.string().nullish(),
+ toulmin: toulminSchema.nullish(),
+ // Optional so an infra failure can be recorded as `status: 'errored'`
+ // with no verdict (the verifier never produced a judgment).
+ verdict: verdictSchema.optional(),
+ verifierType: verifierTypeSchema.optional(),
+ verifyRunId: z.string(),
+ })
+ // A row needs either a verdict (β†’ derives status) or an explicit status
+ // (e.g. `errored`); otherwise there's nothing to record.
+ .refine((v) => v.verdict !== undefined || v.status !== undefined, {
+ message: 'Either a verdict or an explicit status is required.',
+ path: ['verdict'],
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ // The conflict-update overwrites the run's existing result rows.
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+
+ return ctx.resultModel.upsertByCheckItem({
+ checkItemId: input.checkItemId,
+ checkItemIndex: input.checkItemIndex,
+ checkItemTitle: input.checkItemTitle,
+ completedAt: new Date(),
+ confidence: input.confidence,
+ metadata: input.metadata as VerifyCheckResultMetadata | null | undefined,
+ required: input.required ?? true,
+ // Prefer an explicit status; else derive from the verdict (the refine
+ // guarantees at least one is present).
+ status: input.status ?? (input.verdict ? statusForVerdict(input.verdict) : 'errored'),
+ suggestion: input.suggestion,
+ toulmin: input.toulmin,
+ verdict: input.verdict,
+ verifierType: input.verifierType ?? 'agent',
+ verifyRunId: run.id,
+ });
+ }),
+ // Prune one check result (ownership-scoped; its evidence cascades). The
+ // re-ingest path calls this for cases a later report round dropped, so
+ // updating a session in place stays a full replace and never accretes stale
+ // checks. resolveCheckResult 404s a result that isn't the caller's.
+ deleteResult: verifyWriteProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const result = await resolveCheckResult(ctx, input.id);
+ assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
+
+ await ctx.resultModel.delete(result.id);
+ return { id: result.id, success: true };
+ }),
+ uploadEvidence: verifyWriteProcedure
+ .input(uploadEvidenceInputSchema)
+ .mutation(async ({ ctx, input }) => {
+ const result = await resolveCheckResult(ctx, input.checkResultId);
+ // Attaching evidence mutates another member's result β€” creator-scoped,
+ // mirroring submitCheckEvidence.
+ assertWorkspaceRowManageable(ctx, result.userId, 'verify result');
+ const type = await storedEvidenceType(ctx, input.type, input.fileId);
+
+ return ctx.evidenceModel.create({
+ capturedAt: new Date(),
+ capturedBy: input.capturedBy ?? null,
+ checkResultId: result.id,
+ content: input.content ?? null,
+ description: input.description ?? null,
+ fileId: input.fileId ?? null,
+ metadata: normalizeEvidenceMetadata(input.metadata, type) ?? null,
+ type,
+ });
+ }),
+ /**
+ * Builder self-evidence contract: submit a check item's verdict AND its
+ * evidence in one call. The check_result row is created lazily (idempotent
+ * upsert on `(verifyRunId, checkItemId)`) so the builder doesn't need a
+ * pre-existing `checkResultId` β€” solving the run-start handle gap. Evidence
+ * is optional (attach mid-run) and verdict is optional (set later by review).
+ */
+ submitCheckEvidence: verifyWriteProcedure
+ .input(
+ z
+ .object({
+ checkItemId: z.string(),
+ checkItemIndex: z.number().optional(),
+ checkItemTitle: z.string().optional(),
+ confidence: z.number().min(0).max(1).optional(),
+ evidence: z
+ .array(
+ z
+ .object({
+ capturedBy: evidenceCapturedBySchema.optional(),
+ content: z.string().min(1).optional(),
+ description: z.string().optional(),
+ fileId: z.string().min(1).optional(),
+ type: evidenceTypeSchema,
+ })
+ .refine((e) => Boolean(e.content) !== Boolean(e.fileId), {
+ message: 'Provide exactly one of `content` or `fileId`.',
+ }),
+ )
+ .optional(),
+ // The builder may hold only its Agent Run operationId (run-start gap);
+ // either handle resolves the session.
+ operationId: z.string().optional(),
+ required: z.boolean().optional(),
+ status: checkStatusSchema.optional(),
+ suggestion: z.string().optional(),
+ toulmin: toulminSchema.optional(),
+ verdict: verdictSchema.optional(),
+ verifierType: verifierTypeSchema.optional(),
+ verifyRunId: z.string().optional(),
+ })
+ .refine((d) => Boolean(d.verifyRunId) || Boolean(d.operationId), {
+ message: 'Provide either `verifyRunId` or `operationId`.',
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const namedRun = input.verifyRunId
+ ? await resolveVerifyRun(ctx, input.verifyRunId)
+ : await resolveRunByOperation(ctx, input.operationId!);
+ // The idempotent upsert overwrites the run's existing result rows.
+ assertWorkspaceRowManageable(ctx, namedRun.userId, 'verify run');
+ // A round whose failure already spawned a repair is never judged again;
+ // land the submission on the round the repair will be judged in.
+ const run = await resolveLiveRoundForItem(ctx, namedRun, input.checkItemId);
+ if (run.id !== namedRun.id) assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+
+ // `required` / `verifierType` / index / title are stable per plan item, so
+ // hydrate them from the run plan rather than hardcoding defaults β€” otherwise
+ // an evidence-only submit would flip a soft criterion to required:true on the
+ // conflict-update. `status` is mutable lifecycle state: omit it when there's
+ // no verdict so an existing row keeps its status (and a new row falls to the
+ // DB default 'pending') instead of being reset to 'running'. drizzle omits
+ // undefined fields from both the insert and the conflict-update.
+ const plan = (run.plan as VerifyCheckItem[] | null) ?? [];
+ const planItem = plan.find((i) => i.id === input.checkItemId);
+ // A planned run owns its checklist. An unknown id used to be upserted as a
+ // new row that fell to the column default `required: true`, minting a
+ // phantom required check no later round ever plans or re-answers β€” and the
+ // Goal review then judged its stale evidence forever. Name the valid ids
+ // so the caller can resubmit under the right one.
+ if (plan.length > 0 && !planItem)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Check item "${input.checkItemId}" is not in this verification run's plan. Use one of: ${plan
+ .map((item) => `${item.id} (${item.title})`)
+ .join('; ')}`,
+ });
+
+ const checkResult = await ctx.resultModel.upsertByCheckItem({
+ checkItemId: input.checkItemId,
+ checkItemIndex: input.checkItemIndex ?? planItem?.index,
+ checkItemTitle: input.checkItemTitle ?? planItem?.title,
+ completedAt: input.verdict ? new Date() : undefined,
+ confidence: input.confidence,
+ required: input.required ?? planItem?.required,
+ status: input.status ?? (input.verdict ? statusForVerdict(input.verdict) : undefined),
+ suggestion: input.suggestion,
+ toulmin: input.toulmin,
+ verdict: input.verdict,
+ verifierType: input.verifierType ?? planItem?.verifierType ?? 'agent',
+ verifyRunId: run.id,
+ });
+
+ const evidence = input.evidence?.length
+ ? await pMap(
+ input.evidence,
+ async (e) =>
+ ctx.evidenceModel.create({
+ capturedAt: new Date(),
+ capturedBy: e.capturedBy ?? null,
+ checkResultId: checkResult.id,
+ content: e.content ?? null,
+ description: e.description ?? null,
+ fileId: e.fileId ?? null,
+ type: await storedEvidenceType(ctx, e.type, e.fileId),
+ }),
+ { concurrency: EVIDENCE_WRITE_CONCURRENCY },
+ )
+ : [];
+
+ return { checkResult, evidence };
+ }),
+ listEvidence: verifyProcedure
+ .input(z.object({ checkResultId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const result = await resolveCheckResult(ctx, input.checkResultId);
+ return ctx.evidenceModel.listByCheckResult(result.id);
+ }),
+ deleteEvidence: verifyWriteProcedure
+ .input(z.object({ id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const evidence = await ctx.evidenceModel.findById(input.id);
+
+ if (!evidence) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification evidence not found' });
+ }
+ assertWorkspaceRowManageable(ctx, evidence.userId, 'verify evidence');
+
+ await ctx.evidenceModel.delete(evidence.id);
+ return { id: evidence.id, success: true };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/verify/procedures.ts b/apps/server/src/routers/lambda/verify/procedures.ts
new file mode 100644
index 00000000000..496342be4e8
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/procedures.ts
@@ -0,0 +1,79 @@
+import { TRPCError } from '@trpc/server';
+
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { DocumentModel } from '@/database/models/document';
+import { FileModel } from '@/database/models/file';
+import { LlmGenerationTracingModel } from '@/database/models/llmGenerationTracing';
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
+import { VerifyReportModel } from '@/database/models/verifyReport';
+import { VerifyRubricModel } from '@/database/models/verifyRubric';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { GoalCriteriaGeneratorService } from '@/server/services/goal/criteriaGenerator';
+import {
+ VerifyExecutorService,
+ VerifyFeedbackService,
+ VerifyPlanGeneratorService,
+ VerifyReporterService,
+} from '@/server/services/verify';
+
+export const verifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ return opts.next({
+ ctx: {
+ criterionModel: new VerifyCriterionModel(ctx.serverDB, ctx.userId, workspaceId),
+ documentModel: new DocumentModel(ctx.serverDB, ctx.userId, workspaceId),
+ evidenceModel: new VerifyEvidenceModel(ctx.serverDB, ctx.userId, workspaceId),
+ fileModel: new FileModel(ctx.serverDB, ctx.userId, workspaceId),
+ executorService: new VerifyExecutorService(ctx.serverDB, ctx.userId, workspaceId),
+ tracingModel: new LlmGenerationTracingModel(ctx.serverDB, ctx.userId, workspaceId),
+ feedbackService: new VerifyFeedbackService(ctx.serverDB, ctx.userId, workspaceId),
+ goalCriteriaGenerator: new GoalCriteriaGeneratorService(
+ ctx.serverDB,
+ ctx.userId,
+ workspaceId,
+ ),
+ operationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, workspaceId),
+ planGenerator: new VerifyPlanGeneratorService(ctx.serverDB, ctx.userId, workspaceId),
+ reportModel: new VerifyReportModel(ctx.serverDB, ctx.userId, workspaceId),
+ reporterService: new VerifyReporterService(ctx.serverDB, ctx.userId, workspaceId),
+ resultModel: new VerifyCheckResultModel(ctx.serverDB, ctx.userId, workspaceId),
+ rubricModel: new VerifyRubricModel(ctx.serverDB, ctx.userId, workspaceId),
+ runModel: new VerifyRunModel(ctx.serverDB, ctx.userId, workspaceId),
+ },
+ });
+});
+
+// Writes: workspace mode requires at least the member role, gating viewers
+// out (read-only role) while personal mode passes through unrestricted.
+export const verifyWriteProcedure = verifyProcedure.use(requireWorkspaceRoleWhenScoped('member'));
+
+export const resolveVerifyRun = async (ctx: { runModel: VerifyRunModel }, verifyRunId: string) => {
+ const run = await ctx.runModel.findById(verifyRunId);
+
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification run not found' });
+ }
+
+ return run;
+};
+
+export const resolveCheckResult = async (
+ ctx: { resultModel: VerifyCheckResultModel },
+ checkResultId: string,
+) => {
+ const result = await ctx.resultModel.findById(checkResultId);
+
+ if (!result) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification check result not found' });
+ }
+
+ return result;
+};
diff --git a/apps/server/src/routers/lambda/verify/reports.ts b/apps/server/src/routers/lambda/verify/reports.ts
new file mode 100644
index 00000000000..8a10e234979
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/reports.ts
@@ -0,0 +1,104 @@
+import { verifyVisibilities } from '@lobechat/const/verify';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+import { AcceptanceService } from '@/server/services/verify';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { resolveVerifyRun, verifyProcedure, verifyWriteProcedure } from './procedures';
+import { modelConfigSchema, verdictSchema, verifyRunIdInputSchema } from './schemas';
+
+export const reportsRouter = router({
+ upsertReport: verifyWriteProcedure
+ .input(
+ z.object({
+ content: z.string().optional(),
+ failedChecks: z.number().optional(),
+ generatedBy: z.string().optional(),
+ overallConfidence: z.number().min(0).max(1).optional(),
+ passedChecks: z.number().optional(),
+ summary: z.string().optional(),
+ totalChecks: z.number().optional(),
+ uncertainChecks: z.number().optional(),
+ verdict: verdictSchema.optional(),
+ verifyRunId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ // The upsert overwrites the run's existing report row.
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+
+ const report = await ctx.reportModel.upsertByRun({
+ content: input.content ?? null,
+ failedChecks: input.failedChecks ?? null,
+ generatedBy: input.generatedBy ?? 'agent-testing',
+ overallConfidence: input.overallConfidence ?? null,
+ passedChecks: input.passedChecks ?? null,
+ summary: input.summary ?? null,
+ totalChecks: input.totalChecks ?? null,
+ uncertainChecks: input.uncertainChecks ?? null,
+ verdict: input.verdict ?? null,
+ verifyRunId: run.id,
+ });
+
+ // A published report settles an ingested round β€” re-derive the aggregate
+ // it chains onto (β†’ `delivered`, awaiting the user's decision). Best-effort:
+ // the report write must not fail on a rollup hiccup.
+ if (run.acceptanceId) {
+ try {
+ await new AcceptanceService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).recomputeStatus(run.acceptanceId);
+ } catch (error) {
+ console.error('[verify:upsertReport:recomputeAcceptance]', error);
+ }
+ }
+
+ return report;
+ }),
+ getReport: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ return ctx.reportModel.findByRun(run.id);
+ }),
+ /**
+ * Server-side LLM report: generate the narrative from the session's results +
+ * evidence (verdict / stats computed deterministically). Distinct from
+ * `upsertReport`, which stores a report a standalone harness computed itself.
+ */
+ regenerateReport: verifyWriteProcedure
+ .input(
+ z.object({
+ deliverable: z.string(),
+ goal: z.string(),
+ modelConfig: modelConfigSchema,
+ verifyRunId: z.string(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+ return ctx.reporterService.generateReport({
+ deliverable: input.deliverable,
+ goal: input.goal,
+ modelConfig: input.modelConfig,
+ verifyRunId: run.id,
+ });
+ }),
+ /**
+ * Flip who can read this round's report page beyond its creator. Creation
+ * defaults are scope-dependent (personal β†’ public, workspace β†’ private) and
+ * acceptance-attached rounds inherit their aggregate; this is the deliberate
+ * per-round override. Note `acceptance.setVisibility` cascades over rounds,
+ * so the aggregate flip wins over earlier per-round choices.
+ */
+ setRunVisibility: verifyWriteProcedure
+ .input(z.object({ verifyRunId: z.string(), visibility: z.enum(verifyVisibilities) }))
+ .mutation(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+ await ctx.runModel.setVisibility(run.id, input.visibility);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/verify/runs.ts b/apps/server/src/routers/lambda/verify/runs.ts
new file mode 100644
index 00000000000..9bbe3bdbf0d
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/runs.ts
@@ -0,0 +1,259 @@
+import { normalizeVerifySurface, verifyRunScenarios, verifySurfaces } from '@lobechat/const/verify';
+import type { VerifyRunContext, VerifyRunScenario } from '@lobechat/types';
+import pMap from 'p-map';
+import { z } from 'zod';
+
+import { router } from '@/libs/trpc/lambda';
+import { FileService } from '@/server/services/file';
+import { purgeVerifyRun } from '@/server/services/verify';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { resolveVerifyRun, verifyProcedure, verifyWriteProcedure } from './procedures';
+import { checkItemSchema, verifyRunIdInputSchema } from './schemas';
+
+const runSourceSchema = z.enum(['agent', 'agent-testing']);
+
+const omitUndefined = <T extends Record<string, unknown>>(value: T): Partial<T> =>
+ Object.fromEntries(
+ Object.entries(value).filter(([, field]) => field !== undefined),
+ ) as Partial<T>;
+
+// The scenario's context, rendered as the report's scope header. Shared by
+// createRun and updateRun so a re-ingest can refresh the scope in place.
+// Validated per scenario at the door (see `withScenarioContext`).
+const webUrlSchema = z
+ .string()
+ .url()
+ .refine((value) => {
+ const protocol = new URL(value).protocol;
+ return protocol === 'http:' || protocol === 'https:';
+ });
+
+const pullRequestContextSchema = z.object({
+ number: z.union([z.number(), z.string()]).optional(),
+ title: z.string().optional(),
+ url: webUrlSchema.optional(),
+});
+
+/**
+ * A surface, canonicalized at the door.
+ *
+ * Not a bare `z.enum`: `lh` is installed independently of this server, so an
+ * older CLI still posts the historical spellings β€” `electron` alone accounts for
+ * most of the surfaces ever written. Rejecting those would break ingest for
+ * every client that hasn't upgraded, to no benefit, since they name a surface we
+ * can resolve. So known spellings are normalized (`electron` β†’ `desktop`) and
+ * only a value that names no surface at all is rejected β€” the column still ends
+ * up with nothing but the closed set.
+ */
+const surfaceSchema = z.string().transform((value, ctx) => {
+ const surface = normalizeVerifySurface(value);
+ if (surface) return surface;
+
+ ctx.addIssue({
+ code: 'custom',
+ message: `"${value}" is not a product surface. Expected one of: ${verifySurfaces.join(', ')}. A test kind ("unit", "backend") or a runtime mode ("packaged build") is not a surface.`,
+ });
+ return z.NEVER;
+});
+
+const codingRunContextSchema = z.object({
+ branch: z.string().optional(),
+ commit: z.string().optional(),
+ entry: z.string().optional(),
+ pullRequest: pullRequestContextSchema.optional(),
+ surfaces: z.array(surfaceSchema).optional(),
+ testedAt: z.string().optional(),
+});
+
+/**
+ * Non-coding scenarios store the scope as an open bag. The known shapes live in
+ * `@lobechat/types` (`VerifyRunContext`); the server deliberately does not
+ * enumerate their fields, so a new scenario β€” or a new scope field on an
+ * existing one β€” never requires a server redeploy. Only `coding` gets strict
+ * validation, because its scope needs canonicalization at the door (surfaces).
+ */
+const genericRunContextSchema = z.record(z.string(), z.unknown());
+
+const scenarioSchema = z.enum(verifyRunScenarios);
+
+/**
+ * Validate `context` by its sibling `scenario`. Absent scenario defaults to
+ * `coding` (the legacy contract β€” an older `lh` posts a coding scope with no
+ * scenario field), so callers setting a non-coding context MUST send `scenario`
+ * in the same payload or the coding schema strips their fields. Applied as a
+ * transform (not a plain union) for two reasons: the coding path canonicalizes
+ * surfaces in place, and an ordered union of all-optional stripping objects
+ * would silently swallow a non-coding scope into the first match.
+ */
+const withScenarioContext = <T extends { context?: unknown; scenario?: VerifyRunScenario }>(
+ schema: z.ZodType<T>,
+) =>
+ schema.transform((value, ctx) => {
+ if (value.context === undefined) return { ...value, context: undefined };
+
+ const contextSchema =
+ (value.scenario ?? 'coding') === 'coding' ? codingRunContextSchema : genericRunContextSchema;
+ const parsed = contextSchema.safeParse(value.context);
+ if (!parsed.success) {
+ for (const issue of parsed.error.issues) {
+ ctx.addIssue({
+ code: 'custom',
+ message: issue.message,
+ path: ['context', ...issue.path],
+ });
+ }
+ return z.NEVER;
+ }
+
+ return { ...value, context: parsed.data as VerifyRunContext };
+ });
+
+const runMetadataSchema = z.record(z.string(), z.unknown());
+
+const updateRunInputSchema = verifyRunIdInputSchema.extend({
+ // Every field optional β€” a re-ingest may refresh only the context/goal while
+ // keeping the original title, so nothing here is required.
+ value: withScenarioContext(
+ z.object({
+ context: z.unknown().optional(),
+ goal: z.string().optional(),
+ metadata: runMetadataSchema.optional(),
+ plan: z.array(checkItemSchema).optional(),
+ scenario: scenarioSchema.optional(),
+ title: z.string().trim().min(1).max(200).optional(),
+ }),
+ ),
+});
+
+// Cursor-paginated report list. `cursor` is the opaque token from the previous
+// page's `nextCursor`; `q` filters by title (server-side, so it hits the whole
+// history, not just the loaded page).
+const listReportSummariesInputSchema = z
+ .object({
+ cursor: z.string().optional(),
+ limit: z.number().int().min(1).max(100).optional(),
+ q: z.string().optional(),
+ })
+ .optional();
+
+// A report-summary page holds up to `limit` runs; cap the per-run report reads.
+const REPORT_LOAD_CONCURRENCY = 5;
+
+export const runsRouter = router({
+ // ---- ingest (standalone sessions: results / evidence / report, e.g. agent-testing) ----
+ // A verification session that isn't a live Agent Run (no executor): an external
+ // harness creates the run, ingests each check's verdict + evidence, and writes a
+ // report β€” all keyed by verifyRunId.
+ createRun: verifyWriteProcedure
+ .input(
+ withScenarioContext(
+ z.object({
+ // The active scenario's context, rendered as the report's scope header.
+ context: z.unknown().optional(),
+ goal: z.string().optional(),
+ metadata: runMetadataSchema.optional(),
+ operationId: z.string().optional(),
+ // The checks the run set out to make, authored before it ran. Kept next
+ // to the results so a planned-but-never-executed item stays visible.
+ plan: z.array(checkItemSchema).optional(),
+ scenario: scenarioSchema.optional(),
+ source: runSourceSchema.optional(),
+ title: z.string().optional(),
+ }),
+ ),
+ )
+ .mutation(async ({ ctx, input }) =>
+ ctx.runModel.create({
+ context: input.context,
+ goal: input.goal,
+ metadata: input.metadata,
+ operationId: input.operationId,
+ plan: input.plan,
+ scenario: input.scenario,
+ source: input.source ?? 'agent-testing',
+ title: input.title,
+ }),
+ ),
+ getRun: verifyProcedure
+ .input(verifyRunIdInputSchema)
+ .query(async ({ ctx, input }) => ctx.runModel.findById(input.verifyRunId)),
+ // Delete a whole verification session: the run row cascades to its check
+ // results (β†’ their evidence) and its report via the schema FKs, and the
+ // evidence files only this run referenced are purged from storage.
+ // Ownership-scoped: resolveVerifyRun 404s a run that isn't the caller's
+ // before we touch it.
+ deleteRun: verifyWriteProcedure.input(verifyRunIdInputSchema).mutation(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+
+ await purgeVerifyRun(
+ ctx.serverDB,
+ new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),
+ run.userId,
+ run.workspaceId ?? undefined,
+ run.id,
+ );
+ return { id: run.id, success: true };
+ }),
+ listRuns: verifyProcedure.query(async ({ ctx }) => ctx.runModel.query()),
+ listReportSummaries: verifyProcedure
+ .input(listReportSummariesInputSchema)
+ .query(async ({ ctx, input }) => {
+ const { items: runs, nextCursor } = await ctx.runModel.queryPage({
+ cursor: input?.cursor,
+ limit: input?.limit,
+ q: input?.q,
+ });
+ const reports = await pMap(runs, (run) => ctx.reportModel.findByRun(run.id), {
+ concurrency: REPORT_LOAD_CONCURRENCY,
+ });
+
+ const items = runs.map((run, index) => {
+ const report = reports[index];
+
+ return {
+ report: report
+ ? {
+ createdAt: report.createdAt,
+ failedChecks: report.failedChecks,
+ generatedAt: report.generatedAt,
+ id: report.id,
+ overallConfidence: report.overallConfidence,
+ passedChecks: report.passedChecks,
+ reviewedByUser: report.reviewedByUser,
+ summary: report.summary,
+ totalChecks: report.totalChecks,
+ uncertainChecks: report.uncertainChecks,
+ verdict: report.verdict,
+ verifyRunId: report.verifyRunId,
+ }
+ : null,
+ run,
+ };
+ });
+
+ return { items, nextCursor };
+ }),
+ listResultsByRun: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ return ctx.resultModel.listByRun(run.id);
+ }),
+ updateRun: verifyWriteProcedure.input(updateRunInputSchema).mutation(async ({ ctx, input }) => {
+ const run = await resolveVerifyRun(ctx, input.verifyRunId);
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+
+ const updated = await ctx.runModel.update(
+ run.id,
+ omitUndefined({
+ context: input.value.context,
+ goal: input.value.goal,
+ metadata: input.value.metadata,
+ plan: input.value.plan,
+ scenario: input.value.scenario,
+ title: input.value.title,
+ }),
+ );
+ return { data: updated, success: true };
+ }),
+});
diff --git a/apps/server/src/routers/lambda/verify/schemas.ts b/apps/server/src/routers/lambda/verify/schemas.ts
new file mode 100644
index 00000000000..9464f04c639
--- /dev/null
+++ b/apps/server/src/routers/lambda/verify/schemas.ts
@@ -0,0 +1,28 @@
+import { verifyCheckDefinitionSchema } from '@lobechat/types';
+import { z } from 'zod';
+
+export const verifierTypeSchema = z.enum(['program', 'agent', 'llm']);
+
+export const onFailSchema = z.enum(['manual', 'auto_repair']);
+
+export const modelConfigSchema = z.object({ model: z.string(), provider: z.string() });
+
+export const verdictSchema = z.enum(['passed', 'failed', 'uncertain']);
+
+export const checkItemSchema = z.object({
+ definition: verifyCheckDefinitionSchema.optional(),
+ category: z.string().optional(),
+ description: z.string().optional(),
+ id: z.string(),
+ index: z.number(),
+ onFail: onFailSchema,
+ required: z.boolean(),
+ sourceCriterionId: z.string().nullish(),
+ sourceRubricId: z.string().nullish(),
+ supersedes: z.array(z.string()).optional(),
+ title: z.string(),
+ verifierConfig: z.record(z.string(), z.unknown()),
+ verifierType: verifierTypeSchema,
+});
+
+export const verifyRunIdInputSchema = z.object({ verifyRunId: z.string() });
diff --git a/packages/trpc/src/lambda/index.ts b/packages/trpc/src/lambda/index.ts
index 721fe1c109f..debe9abcd1d 100644
--- a/packages/trpc/src/lambda/index.ts
+++ b/packages/trpc/src/lambda/index.ts
@@ -24,6 +24,13 @@ import { oidcAuth } from './middleware/oidcAuth';
*/
export const router = trpc.router;
+/**
+ * Merge sub-routers into one flat router: procedure paths are unchanged and a
+ * duplicate path throws when the router is built.
+ * @link https://trpc.io/docs/v11/merging-routers
+ */
+export const mergeRouters = trpc.mergeRouters;
+
/**
* Create an unprotected procedure
* @link https://trpc.io/docs/v11/procedures