Skip to content

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

✨ feat(verify): structural gate + evidence-aware judge + LLM reporter (#16130)

Arvin Xucc67ecb6cece
diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.ts
index cd339ff1b38..97d188bead2 100644
--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts
@@ -32,6 +32,7 @@ vi.mock('@/server/services/verify', () => ({
VerifyExecutorService: class VerifyExecutorService {},
VerifyFeedbackService: class VerifyFeedbackService {},
VerifyPlanGeneratorService: class VerifyPlanGeneratorService {},
+ VerifyReporterService: class VerifyReporterService {},
}));
vi.mock('@/server/services/file', () => ({
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index d56cab86ae3..cbdb39276e9 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -25,6 +25,7 @@ import {
VerifyExecutorService,
VerifyFeedbackService,
VerifyPlanGeneratorService,
+ VerifyReporterService,
} from '@/server/services/verify';
const verifierTypeSchema = z.enum(['program', 'agent', 'llm']);
@@ -100,6 +101,7 @@ const verifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =
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),
@@ -459,6 +461,30 @@ export const verifyRouter = router({
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: verifyProcedure
+ .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);
+ return ctx.reporterService.generateReport({
+ deliverable: input.deliverable,
+ goal: input.goal,
+ modelConfig: input.modelConfig,
+ verifyRunId: run.id,
+ });
+ }),
+
/**
* One-shot payload for the standalone report viewer: the session, its report,
* and every check result with its evidence β€” addressed purely by verifyRunId
diff --git a/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts b/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts
new file mode 100644
index 00000000000..8dc37d6908e
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { coverageGaps, readRequiredEvidence } from '../evidenceCoverage';
+
+describe('readRequiredEvidence', () => {
+ it('reads a requiredEvidence array off the verifier config', () => {
+ expect(readRequiredEvidence({ requiredEvidence: [{ type: 'screenshot' }] })).toEqual([
+ { type: 'screenshot' },
+ ]);
+ });
+
+ it('returns undefined when absent or malformed', () => {
+ expect(readRequiredEvidence({})).toBeUndefined();
+ expect(readRequiredEvidence(null)).toBeUndefined();
+ expect(readRequiredEvidence({ requiredEvidence: 'screenshot' })).toBeUndefined();
+ });
+});
+
+describe('coverageGaps', () => {
+ it('returns no gaps when the item declares no evidence requirement', () => {
+ expect(coverageGaps(undefined, [])).toEqual([]);
+ expect(coverageGaps([], [{ type: 'screenshot' }])).toEqual([]);
+ });
+
+ it('reports each required type with no matching evidence', () => {
+ expect(
+ coverageGaps([{ type: 'screenshot' }, { type: 'dom_snapshot' }], [{ type: 'screenshot' }]),
+ ).toEqual(['dom_snapshot']);
+ });
+
+ it('passes when every required type is present', () => {
+ expect(
+ coverageGaps([{ type: 'screenshot' }], [{ type: 'screenshot' }, { type: 'text' }]),
+ ).toEqual([]);
+ });
+
+ it('dedupes repeated required types', () => {
+ expect(coverageGaps([{ type: 'screenshot' }, { type: 'screenshot' }], [])).toEqual([
+ 'screenshot',
+ ]);
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/judgePrompt.test.ts b/apps/server/src/services/verify/__tests__/judgePrompt.test.ts
new file mode 100644
index 00000000000..986c3fac5a0
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/judgePrompt.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildJudgePrompt } from '../prompts';
+
+describe('buildJudgePrompt evidence injection', () => {
+ it('inlines text evidence and references stored artifacts under the criterion', () => {
+ const { system, user } = buildJudgePrompt({
+ deliverable: 'done',
+ goal: 'ship it',
+ items: [
+ {
+ evidence: [
+ { description: 'ι¦–ε±ζΈ²ζŸ“', type: 'screenshot' },
+ { content: '<div id="root">ok</div>', type: 'dom_snapshot' },
+ ],
+ id: 'item-1',
+ title: 'Home renders',
+ },
+ ],
+ mode: 'single',
+ });
+
+ expect(user).toContain('Evidence captured during the run:');
+ // stored artifact β†’ referenced by presence + caption, not inlined
+ expect(user).toContain('(screenshot) β€” ι¦–ε±ζΈ²ζŸ“ [artifact captured]');
+ // inline text β†’ quoted in full
+ expect(user).toContain('(dom_snapshot): <div id="root">ok</div>');
+ // the judge is told to weight artifacts as primary Data
+ expect(system).toContain('primary Data');
+ });
+
+ it('omits the evidence block when an item has none', () => {
+ const { user } = buildJudgePrompt({
+ deliverable: 'done',
+ goal: 'ship it',
+ items: [{ id: 'item-1', title: 'No evidence needed' }],
+ mode: 'single',
+ });
+
+ expect(user).not.toContain('Evidence captured during the run:');
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/reporter.test.ts b/apps/server/src/services/verify/__tests__/reporter.test.ts
new file mode 100644
index 00000000000..027054e1c01
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/reporter.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+
+import { countStats, rollupVerdict } from '../reportRollup';
+
+/** Minimal result-row factory β€” only the fields the rollup reads. */
+const r = (over: Partial<VerifyCheckResultItem>): VerifyCheckResultItem =>
+ ({ required: true, status: 'passed', verdict: 'passed', ...over }) as VerifyCheckResultItem;
+
+describe('rollupVerdict', () => {
+ it('fails when any required item failed (by verdict or status)', () => {
+ expect(rollupVerdict([r({}), r({ status: 'failed', verdict: 'failed' })])).toBe('failed');
+ // structural-gate row: status failed + verdict uncertain still gates as failed
+ expect(rollupVerdict([r({ status: 'failed', verdict: 'uncertain' })])).toBe('failed');
+ });
+
+ it('is uncertain when a required item is unresolved but none failed', () => {
+ expect(rollupVerdict([r({}), r({ status: 'pending', verdict: null })])).toBe('uncertain');
+ expect(rollupVerdict([r({ status: 'running', verdict: 'uncertain' })])).toBe('uncertain');
+ });
+
+ it('passes when every required item passed', () => {
+ expect(rollupVerdict([r({}), r({})])).toBe('passed');
+ });
+
+ it('ignores non-required items in the gate', () => {
+ expect(
+ rollupVerdict([r({}), r({ required: false, status: 'failed', verdict: 'failed' })]),
+ ).toBe('passed');
+ // skipped required items are not "unresolved"
+ expect(rollupVerdict([r({ status: 'skipped', verdict: null })])).toBe('passed');
+ });
+});
+
+describe('countStats', () => {
+ it('counts verdicts and totals (pending/skipped only in total)', () => {
+ expect(
+ countStats([
+ r({ verdict: 'passed' }),
+ r({ verdict: 'failed' }),
+ r({ verdict: 'uncertain' }),
+ r({ verdict: null, status: 'pending' }),
+ ]),
+ ).toEqual({ failed: 1, passed: 1, total: 4, uncertain: 1 });
+ });
+});
diff --git a/apps/server/src/services/verify/evidenceCoverage.ts b/apps/server/src/services/verify/evidenceCoverage.ts
new file mode 100644
index 00000000000..987e72fe226
--- /dev/null
+++ b/apps/server/src/services/verify/evidenceCoverage.ts
@@ -0,0 +1,27 @@
+import type { RequiredEvidenceSpec, VerifyEvidenceType } from '@lobechat/types';
+
+/**
+ * Read the (optional) evidence requirement a criterion declares on its config.
+ * Evidence-driven criteria list the artifact types they need under
+ * `verifierConfig.requiredEvidence`; everything else returns undefined.
+ */
+export const readRequiredEvidence = (
+ config: Record<string, unknown> | undefined | null,
+): RequiredEvidenceSpec[] | undefined => {
+ const raw = config?.requiredEvidence;
+ return Array.isArray(raw) ? (raw as RequiredEvidenceSpec[]) : undefined;
+};
+
+/**
+ * Which required evidence types are still missing for a criterion β€” pure, so the
+ * structural gate is unit-testable without a database. Returns `[]` when the
+ * item declares no evidence requirement (nothing to gate on).
+ */
+export const coverageGaps = (
+ required: RequiredEvidenceSpec[] | undefined,
+ evidence: { type: VerifyEvidenceType }[],
+): VerifyEvidenceType[] => {
+ if (!required?.length) return [];
+ const present = new Set(evidence.map((e) => e.type));
+ return [...new Set(required.map((r) => r.type))].filter((t) => !present.has(t));
+};
diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.ts
index 60aa339bd41..fe47a340935 100644
--- a/apps/server/src/services/verify/executor.ts
+++ b/apps/server/src/services/verify/executor.ts
@@ -1,4 +1,4 @@
-import { createHash, randomUUID } from 'node:crypto';
+import { randomUUID } from 'node:crypto';
import { TRACING_SCENARIOS } from '@lobechat/const';
import type { TracingOptions } from '@lobechat/llm-generation-tracing';
@@ -12,12 +12,14 @@ import debug from 'debug';
import { DocumentModel } from '@/database/models/document';
import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
import { VerifyRunModel } from '@/database/models/verifyRun';
-import type { NewVerifyCheckResult } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
import { AiGenerationService } from '@/server/services/aiGeneration';
-import { buildJudgePrompt, VERIFY_JUDGE_PROMPT_VERSION } from './prompts';
+import { coverageGaps, readRequiredEvidence } from './evidenceCoverage';
+import { buildJudgePrompt, type JudgeEvidence, VERIFY_JUDGE_PROMPT_VERSION } from './prompts';
+import { planItemToPendingResult } from './resultSnapshot';
import {
BATCH_VERDICT_JSON_SCHEMA,
BatchVerdictSchema,
@@ -56,15 +58,12 @@ export interface ExecuteVerifyParams {
runVerifierAgent?: VerifierAgentRunner;
}
-const hashConfig = (config: Record<string, unknown>): string =>
- createHash('sha256')
- .update(JSON.stringify(config ?? {}))
- .digest('hex')
- .slice(0, 16);
-
const verdictToStatus = (verdict: VerifyVerdict): VerifyCheckResultStatus =>
verdict === 'passed' ? 'passed' : 'failed';
+/** Group a run's evidence rows by the plan item they back, for judge injection. */
+type EvidenceByItem = Map<string, JudgeEvidence[]>;
+
const toToulmin = (v: SingleVerdict): ToulminVerdict => ({
counterEvidence: v.counterEvidence ?? undefined,
evidence: v.evidence ?? undefined,
@@ -79,6 +78,7 @@ export class VerifyExecutorService {
private readonly resultModel: VerifyCheckResultModel;
private readonly statusService: VerifyStatusService;
private readonly documentModel: DocumentModel;
+ private readonly evidenceModel: VerifyEvidenceModel;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
this.db = db;
@@ -87,6 +87,7 @@ export class VerifyExecutorService {
this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
this.statusService = new VerifyStatusService(db, userId, workspaceId);
this.documentModel = new DocumentModel(db, userId, workspaceId);
+ this.evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
}
/**
@@ -119,42 +120,85 @@ export class VerifyExecutorService {
const verifyRunId = run.id;
const items = run.plan as VerifyCheckItem[];
- // Idempotently create the pending result rows (skip ones already present).
+ // Idempotently create the pending result rows (skip ones already present β€”
+ // an item may already have a row from evidence uploaded mid-run).
const existing = await this.resultModel.listByRun(verifyRunId);
const existingIds = new Set(existing.map((r) => r.checkItemId));
- const toCreate: Omit<NewVerifyCheckResult, 'userId'>[] = items
+ const toCreate = items
.filter((i) => !existingIds.has(i.id))
- .map((item) => ({
- checkItemId: item.id,
- checkItemIndex: item.index,
- checkItemTitle: item.title,
- // Denormalized direct link to the Agent Run (canonical link is verifyRunId).
- operationId: params.operationId,
- required: item.required,
- status: 'pending' as const,
- verifierConfigHash: hashConfig(item.verifierConfig),
- verifierType: item.verifierType,
- verifyRunId,
- }));
+ .map((item) => planItemToPendingResult(verifyRunId, params.operationId, item));
if (toCreate.length > 0) await this.resultModel.createMany(toCreate);
await this.statusService.markVerifying(params.operationId);
- const llmItems = items.filter((i) => i.verifierType === 'llm');
- const agentItems = items.filter((i) => i.verifierType === 'agent');
- const programItems = items.filter((i) => i.verifierType === 'program');
+ // Load run-captured evidence once, grouped by plan item β€” feeds both the
+ // structural gate and the LLM judge.
+ const evidenceByItem = await this.loadEvidence(verifyRunId);
+
+ // Structural gate (server, no LLM): an evidence-driven item missing any of
+ // its declared evidence types is marked uncertain up front and excluded from
+ // the judges β€” we never let a required artifact-backed claim pass unseen.
+ const gapIds = await this.runStructuralGate(verifyRunId, items, evidenceByItem);
+ const gated = items.filter((i) => !gapIds.has(i.id));
+
+ const llmItems = gated.filter((i) => i.verifierType === 'llm');
+ const agentItems = gated.filter((i) => i.verifierType === 'agent');
+ const programItems = gated.filter((i) => i.verifierType === 'program');
// The three verifier kinds are independent β€” run them concurrently. LLM items
// are judged in one batched call; each agent item spawns its own sub-agent.
await Promise.all([
this.runProgramItems(verifyRunId, programItems),
- this.runLlmItems(params, verifyRunId, llmItems),
+ this.runLlmItems(params, verifyRunId, llmItems, evidenceByItem),
...agentItems.map((item) => this.runAgentItem(params, verifyRunId, item)),
]);
await this.statusService.recompute(params.operationId);
}
+ /** Load a run's evidence rows grouped by the plan item id they back. */
+ private async loadEvidence(verifyRunId: string): Promise<EvidenceByItem> {
+ const rows = await this.evidenceModel.listByRun(verifyRunId);
+ const byItem: EvidenceByItem = new Map();
+ for (const row of rows) {
+ const list = byItem.get(row.checkItemId) ?? [];
+ list.push({ content: row.content, description: row.description, type: row.type });
+ byItem.set(row.checkItemId, list);
+ }
+ return byItem;
+ }
+
+ /**
+ * Mark every evidence-driven item whose declared evidence is incomplete as
+ * `uncertain` (status `failed`, so it gates delivery and seeds repair), and
+ * return their ids so the judges skip them. Items with no `requiredEvidence`
+ * pass through untouched.
+ */
+ private async runStructuralGate(
+ verifyRunId: string,
+ items: VerifyCheckItem[],
+ evidenceByItem: EvidenceByItem,
+ ): Promise<Set<string>> {
+ const gapIds = new Set<string>();
+ for (const item of items) {
+ const required = readRequiredEvidence(item.verifierConfig);
+ const gaps = coverageGaps(required, evidenceByItem.get(item.id) ?? []);
+ if (gaps.length === 0) continue;
+
+ gapIds.add(item.id);
+ const missing = gaps.join(', ');
+ await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
+ completedAt: new Date(),
+ confidence: 0,
+ status: 'failed',
+ suggestion: `Capture and upload the missing evidence (${missing}) via \`lh verify upload-evidence\`.`,
+ toulmin: { limitation: `Required evidence not provided: ${missing}.` },
+ verdict: 'uncertain',
+ });
+ }
+ return gapIds;
+ }
+
/** Program verifiers are a v1 placeholder (no shell environment) β€” mark skipped. */
private async runProgramItems(verifyRunId: string, items: VerifyCheckItem[]): Promise<void> {
for (const item of items) {
@@ -171,13 +215,14 @@ export class VerifyExecutorService {
params: ExecuteVerifyParams,
verifyRunId: string,
items: VerifyCheckItem[],
+ evidenceByItem: EvidenceByItem,
): Promise<void> {
if (items.length === 0) return;
try {
if (params.batchLlm ?? true) {
- await this.judgeBatch(params, verifyRunId, items);
+ await this.judgeBatch(params, verifyRunId, items, evidenceByItem);
} else {
- for (const item of items) await this.judgeSingle(params, verifyRunId, item);
+ for (const item of items) await this.judgeSingle(params, verifyRunId, item, evidenceByItem);
}
} catch (error) {
log('llm judge failed for op %s: %O', params.operationId, error);
@@ -225,11 +270,13 @@ export class VerifyExecutorService {
params: ExecuteVerifyParams,
verifyRunId: string,
items: VerifyCheckItem[],
+ evidenceByItem: EvidenceByItem,
): Promise<void> {
// Batch: N verdicts share ONE tracing row (N:1).
const tracingId = randomUUID();
const promptItems = await Promise.all(
items.map(async (i) => ({
+ evidence: evidenceByItem.get(i.id),
id: i.id,
instruction: await this.resolveInstruction(i),
title: i.title,
@@ -292,13 +339,21 @@ export class VerifyExecutorService {
params: ExecuteVerifyParams,
verifyRunId: string,
item: VerifyCheckItem,
+ evidenceByItem: EvidenceByItem,
): Promise<void> {
// Per-criterion: each result gets its own tracing row (1:1).
const tracingId = randomUUID();
const { system, user } = buildJudgePrompt({
deliverable: params.deliverable,
goal: params.goal,
- items: [{ id: item.id, instruction: await this.resolveInstruction(item), title: item.title }],
+ items: [
+ {
+ evidence: evidenceByItem.get(item.id),
+ id: item.id,
+ instruction: await this.resolveInstruction(item),
+ title: item.title,
+ },
+ ],
mode: 'single',
});
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index 1ba87d3f39b..f682b882666 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -1,4 +1,5 @@
export { createVerifierAgentRunner } from './agentVerifier';
+export { coverageGaps, readRequiredEvidence } from './evidenceCoverage';
export {
type ExecuteVerifyParams,
type VerifierAgentRunner,
@@ -13,4 +14,5 @@ export {
type RepairSpawner,
VerifyRepairService,
} from './repairService';
+export { type GenerateReportParams, VerifyReporterService } from './reporter';
export { VerifyStatusService } from './statusService';
diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.ts
index d695bf8c29e..a2b842b9210 100644
--- a/apps/server/src/services/verify/lifecycle.ts
+++ b/apps/server/src/services/verify/lifecycle.ts
@@ -8,6 +8,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { createVerifierAgentRunner } from './agentVerifier';
import { VerifyExecutorService } from './executor';
import { maybeAutoRepair } from './repairService';
+import { VerifyReporterService } from './reporter';
const log = debug('lobe-server:verify-lifecycle');
@@ -86,6 +87,22 @@ export const runVerifyOnCompletion = async (
// (LLM/program) checks, everything is resolved now; runs with async agent
// checks no-op here and re-trigger from the verifier's writeback path.
await maybeAutoRepair(db, userId, params.operationId, workspaceId);
+
+ // Generate the report only at the link tail β€” when verification settled into a
+ // terminal verdict (passed/failed). A run that spawned a repair is now
+ // `repairing`; its report is generated when the repair op completes, so a
+ // single card lands on the final delivery instead of one per repair round.
+ const settled = await new VerifyRunModel(db, userId, workspaceId).findByOperation(
+ params.operationId,
+ );
+ if (settled?.status === 'passed' || settled?.status === 'failed') {
+ await new VerifyReporterService(db, userId, workspaceId).generateReport({
+ deliverable: params.deliverable,
+ goal: params.goal,
+ modelConfig: { model: op.model, provider: op.provider },
+ verifyRunId: settled.id,
+ });
+ }
} catch (error) {
log('runVerifyOnCompletion failed for op %s (non-fatal): %O', params.operationId, error);
}
diff --git a/apps/server/src/services/verify/prompts.ts b/apps/server/src/services/verify/prompts.ts
index e9cebd2cda3..b76834d70bd 100644
--- a/apps/server/src/services/verify/prompts.ts
+++ b/apps/server/src/services/verify/prompts.ts
@@ -1,9 +1,11 @@
-import type { VerifyCheckItem } from '@lobechat/types';
+import type { VerifyCheckItem, VerifyEvidenceType } from '@lobechat/types';
/** Bump when the plan-gen prompt meaningfully changes (tracing partition key). */
export const VERIFY_PLAN_PROMPT_VERSION = '1';
/** Bump when the judge prompt meaningfully changes. */
export const VERIFY_JUDGE_PROMPT_VERSION = '1';
+/** Bump when the report prompt meaningfully changes. */
+export const VERIFY_REPORT_PROMPT_VERSION = '1';
export interface PlanPromptInput {
/** Optional run context (agent role, repo, constraints). */
@@ -46,19 +48,41 @@ export const buildPlanPrompt = ({
return { system, user };
};
+/** One captured artifact, summarized for the judge. */
+export interface JudgeEvidence {
+ content?: string | null;
+ description?: string | null;
+ type: VerifyEvidenceType;
+}
+
export interface JudgePromptInput {
/** The artifacts / agent output to judge against. */
deliverable: string;
goal: string;
- /** Each item carries its resolved judging instruction (from its document, if any). */
- items: (Pick<VerifyCheckItem, 'id' | 'title'> & { instruction?: string })[];
+ /** Each item carries its resolved judging instruction + any captured evidence. */
+ items: (Pick<VerifyCheckItem, 'id' | 'title'> & {
+ evidence?: JudgeEvidence[];
+ instruction?: string;
+ })[];
/** Single mode judges one item; batch mode judges all `items`. */
mode: 'single' | 'batch';
}
+const describeEvidence = (evidence: JudgeEvidence[] | undefined): string => {
+ if (!evidence?.length) return '';
+ const lines = evidence.map((e) => {
+ const caption = e.description ? ` β€” ${e.description}` : '';
+ // Inline text is quoted in full; a stored artifact (screenshot/gif/video) is
+ // referenced by presence + caption, which is itself supporting Data.
+ const payload = e.content ? `: ${e.content}` : ' [artifact captured]';
+ return ` - (${e.type})${caption}${payload}`;
+ });
+ return `\nEvidence captured during the run:\n${lines.join('\n')}`;
+};
+
const describeItem = (item: JudgePromptInput['items'][number]) => {
const instruction = item.instruction ? `\n${item.instruction}` : '';
- return `${item.title}${instruction}`;
+ return `${item.title}${instruction}${describeEvidence(item.evidence)}`;
};
export const buildJudgePrompt = ({ goal, deliverable, items, mode }: JudgePromptInput) => {
@@ -72,6 +96,7 @@ export const buildJudgePrompt = ({ goal, deliverable, items, mode }: JudgePrompt
'- counterEvidence: evidence pointing the other way, if any (the Rebuttal).',
'- limitation: what you could not verify and why (the Rebuttal).',
'- suggestion: a concrete fix when the verdict is failed/uncertain.',
+ 'Artifacts listed under "Evidence captured during the run" are primary Data β€” weight them above the deliverable prose. An entry marked "[artifact captured]" means the screenshot/recording was taken; treat its presence and caption as supporting Data for what it depicts.',
'Be skeptical: default to "uncertain" rather than "passed" when evidence is missing.',
mode === 'batch'
? 'Return one verdict object per criterion, each tagged with its exact checkItemId.'
@@ -91,3 +116,65 @@ export const buildJudgePrompt = ({ goal, deliverable, items, mode }: JudgePrompt
return { system, user };
};
+
+export interface ReportPromptItem {
+ confidence?: number | null;
+ evidence?: JudgeEvidence[];
+ reasoning?: string | null;
+ status: string;
+ suggestion?: string | null;
+ title?: string | null;
+ verdict?: string | null;
+}
+
+export interface ReportPromptInput {
+ deliverable: string;
+ goal: string;
+ items: ReportPromptItem[];
+ /** Pre-computed rollup so the narrative never contradicts the numbers. */
+ stats: { failed: number; passed: number; total: number; uncertain: number };
+ verdict: string;
+}
+
+/**
+ * Narrative-only report prompt: the verdict + statistics are computed upstream
+ * and handed in, so the LLM writes prose around fixed numbers rather than
+ * re-deriving (and possibly contradicting) them.
+ */
+export const buildReportPrompt = ({
+ goal,
+ deliverable,
+ items,
+ stats,
+ verdict,
+}: ReportPromptInput) => {
+ const system = [
+ 'You are writing a delivery-verification report for the user who owns this task.',
+ 'The overall verdict and the pass/fail/uncertain counts are already decided and given to you β€” never contradict or recompute them.',
+ 'Write in the language of the run goal.',
+ 'Produce two fields:',
+ '- summary: 3-5 sentences for a chat notification β€” the verdict, what was checked, and the single most important finding.',
+ '- content: a full Markdown report. Use a per-criterion section with its verdict, the reasoning, the evidence that backs it, and a concrete next step for anything failed or uncertain. Reference captured artifacts where they support a claim.',
+ 'Be specific and evidence-grounded; do not invent results that are not listed below.',
+ ].join('\n');
+
+ const itemBlock = items
+ .map((i) => {
+ const head = `### ${i.title ?? 'Criterion'} β€” ${i.verdict ?? i.status}${
+ typeof i.confidence === 'number' ? ` (confidence ${i.confidence})` : ''
+ }`;
+ const reasoning = i.reasoning ? `\nReasoning: ${i.reasoning}` : '';
+ const suggestion = i.suggestion ? `\nSuggestion: ${i.suggestion}` : '';
+ return `${head}${reasoning}${suggestion}${describeEvidence(i.evidence)}`;
+ })
+ .join('\n\n');
+
+ const user = [
+ `## Run goal\n${goal}`,
+ `\n## Overall verdict\n${verdict} β€” ${stats.passed}/${stats.total} passed, ${stats.failed} failed, ${stats.uncertain} uncertain`,
+ `\n## Per-criterion results\n${itemBlock}`,
+ `\n## Deliverable\n${deliverable}`,
+ ].join('\n');
+
+ return { system, user };
+};
diff --git a/apps/server/src/services/verify/reportRollup.ts b/apps/server/src/services/verify/reportRollup.ts
new file mode 100644
index 00000000000..adec97fe4fd
--- /dev/null
+++ b/apps/server/src/services/verify/reportRollup.ts
@@ -0,0 +1,42 @@
+import type { VerifyVerdict } from '@lobechat/types';
+
+import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+
+export interface ReportStats {
+ failed: number;
+ passed: number;
+ total: number;
+ uncertain: number;
+}
+
+/**
+ * Verdict-space rollup over a run's results, mirroring `VerifyStatusService`'s
+ * gate so the report card can never disagree with the operation's verify_status.
+ * Pure (no I/O) so it's unit-testable without the model-runtime chain.
+ */
+export const rollupVerdict = (results: VerifyCheckResultItem[]): VerifyVerdict => {
+ const required = results.filter((r) => r.required);
+ const failed = (r: VerifyCheckResultItem) => r.status === 'failed' || r.verdict === 'failed';
+ const unresolved = (r: VerifyCheckResultItem) =>
+ r.verdict === 'uncertain' || (!r.verdict && r.status !== 'skipped');
+
+ if (required.some(failed)) return 'failed';
+ if (required.some(unresolved)) return 'uncertain';
+ return 'passed';
+};
+
+/** Verdict tallies for the report's statistics snapshot (pending/skipped β†’ total only). */
+export const countStats = (results: VerifyCheckResultItem[]): ReportStats => ({
+ failed: results.filter((r) => r.verdict === 'failed').length,
+ passed: results.filter((r) => r.verdict === 'passed').length,
+ total: results.length,
+ uncertain: results.filter((r) => r.verdict === 'uncertain').length,
+});
+
+/** Mean of the present confidences, rounded to the column's 0.00–1.00 scale. */
+export const meanConfidence = (results: VerifyCheckResultItem[]): number | null => {
+ const values = results.map((r) => r.confidence).filter((c): c is number => typeof c === 'number');
+ if (values.length === 0) return null;
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
+ return Math.round(mean * 100) / 100;
+};
diff --git a/apps/server/src/services/verify/reporter.ts b/apps/server/src/services/verify/reporter.ts
new file mode 100644
index 00000000000..d01cfc6c27b
--- /dev/null
+++ b/apps/server/src/services/verify/reporter.ts
@@ -0,0 +1,125 @@
+import debug from 'debug';
+
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
+import { VerifyReportModel } from '@/database/models/verifyReport';
+import type { LobeChatDatabase } from '@/database/type';
+import { AiGenerationService } from '@/server/services/aiGeneration';
+
+import { buildReportPrompt, type JudgeEvidence } from './prompts';
+import { countStats, meanConfidence, rollupVerdict } from './reportRollup';
+import { REPORT_NARRATIVE_JSON_SCHEMA, ReportNarrativeSchema } from './schema';
+
+const log = debug('lobe-server:verify-reporter');
+
+export interface GenerateReportParams {
+ deliverable: string;
+ goal: string;
+ modelConfig: { model: string; provider: string };
+ /** The verification session to summarize (the canonical run-anchor). */
+ verifyRunId: string;
+}
+
+/**
+ * Builds the LLM-authored verify report (a generated artifact) for a
+ * verification session. The verdict and statistics are computed deterministically
+ * from the session's results here; only the `summary` / `content` narrative comes
+ * from the model, so the card can never contradict the rollup. Upserts per run
+ * (regenerating overwrites in place).
+ *
+ * This is the server-side LLM reporter β€” distinct from `verify.upsertReport`,
+ * which lets a standalone harness write a report it computed itself.
+ */
+export class VerifyReporterService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly resultModel: VerifyCheckResultModel;
+ private readonly evidenceModel: VerifyEvidenceModel;
+ private readonly reportModel: VerifyReportModel;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
+ this.evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
+ this.reportModel = new VerifyReportModel(db, userId, workspaceId);
+ }
+
+ async generateReport(params: GenerateReportParams) {
+ const { verifyRunId, goal, deliverable, modelConfig } = params;
+
+ const results = await this.resultModel.listByRun(verifyRunId);
+ if (results.length === 0) {
+ log('generateReport: no results for run %s, skipping', verifyRunId);
+ return null;
+ }
+
+ const evidenceRows = await this.evidenceModel.listByRun(verifyRunId);
+ const evidenceByItem = new Map<string, JudgeEvidence[]>();
+ for (const row of evidenceRows) {
+ const list = evidenceByItem.get(row.checkItemId) ?? [];
+ list.push({ content: row.content, description: row.description, type: row.type });
+ evidenceByItem.set(row.checkItemId, list);
+ }
+
+ const verdict = rollupVerdict(results);
+ const stats = countStats(results);
+
+ const { system, user } = buildReportPrompt({
+ deliverable,
+ goal,
+ items: results.map((r) => ({
+ confidence: r.confidence,
+ evidence: evidenceByItem.get(r.checkItemId),
+ reasoning: r.toulmin?.reasoning,
+ status: r.status,
+ suggestion: r.suggestion,
+ title: r.checkItemTitle,
+ verdict: r.verdict,
+ })),
+ stats,
+ verdict,
+ });
+
+ const narrative = await this.buildNarrative(system, user, modelConfig);
+
+ return this.reportModel.upsertByRun({
+ content: narrative?.content ?? null,
+ failedChecks: stats.failed,
+ generatedBy: modelConfig.model,
+ overallConfidence: meanConfidence(results),
+ passedChecks: stats.passed,
+ reviewedByUser: false,
+ summary: narrative?.summary ?? null,
+ totalChecks: stats.total,
+ uncertainChecks: stats.uncertain,
+ verdict,
+ verifyRunId,
+ });
+ }
+
+ /** Generate the narrative, degrading to no prose (stats-only card) on failure. */
+ private async buildNarrative(
+ system: string,
+ user: string,
+ modelConfig: { model: string; provider: string },
+ ) {
+ try {
+ const ai = new AiGenerationService(this.db, this.userId);
+ const raw = await ai.generateObject({
+ messages: [
+ { content: system, role: 'system' as const },
+ { content: user, role: 'user' as const },
+ ],
+ model: modelConfig.model,
+ provider: modelConfig.provider,
+ schema: REPORT_NARRATIVE_JSON_SCHEMA,
+ });
+ const parsed = ReportNarrativeSchema.safeParse(raw);
+ return parsed.success ? parsed.data : null;
+ } catch (error) {
+ log('report narrative generation failed (non-fatal): %O', error);
+ return null;
+ }
+ }
+}
diff --git a/apps/server/src/services/verify/resultSnapshot.ts b/apps/server/src/services/verify/resultSnapshot.ts
new file mode 100644
index 00000000000..fbed62d309c
--- /dev/null
+++ b/apps/server/src/services/verify/resultSnapshot.ts
@@ -0,0 +1,41 @@
+import { createHash } from 'node:crypto';
+
+import type { VerifyCheckItem } from '@lobechat/types';
+
+import type { NewVerifyCheckResult } from '@/database/schemas/verify';
+
+/**
+ * Stable, short fingerprint of a verifier config β€” snapshotted onto the result
+ * row (the Toulmin "Backing" anchor) so a verdict records exactly which config
+ * produced it. Shared by the executor and the evidence ingestion path so a
+ * result row created by either side hashes identically.
+ */
+export const hashConfig = (config: Record<string, unknown>): string =>
+ createHash('sha256')
+ .update(JSON.stringify(config ?? {}))
+ .digest('hex')
+ .slice(0, 16);
+
+/**
+ * The initial `pending` result row for a plan item β€” the denormalized snapshot
+ * (title / required / index / verifier) frozen at the moment a result first
+ * exists for the item, whether that's the executor starting the run or an agent
+ * uploading evidence mid-run. Keyed canonically by `verifyRunId`, with the
+ * Agent Run id kept as the denormalized `operationId` link. Ownership columns
+ * are injected by the model.
+ */
+export const planItemToPendingResult = (
+ verifyRunId: string,
+ operationId: string | null,
+ item: VerifyCheckItem,
+): Omit<NewVerifyCheckResult, 'userId' | 'workspaceId'> => ({
+ checkItemId: item.id,
+ checkItemIndex: item.index,
+ checkItemTitle: item.title,
+ operationId,
+ required: item.required,
+ status: 'pending',
+ verifierConfigHash: hashConfig(item.verifierConfig),
+ verifierType: item.verifierType,
+ verifyRunId,
+});
diff --git a/apps/server/src/services/verify/schema.ts b/apps/server/src/services/verify/schema.ts
index bb169805707..d9f989c1a2d 100644
--- a/apps/server/src/services/verify/schema.ts
+++ b/apps/server/src/services/verify/schema.ts
@@ -126,3 +126,32 @@ export const BATCH_VERDICT_JSON_SCHEMA: GenerateObjectSchema = {
},
strict: false,
};
+
+// ============================================
+// Report β€” LLM narrative over a run's check results + evidence
+// ============================================
+
+/**
+ * Only the narrative is LLM-authored; the verdict + statistics are computed
+ * deterministically from the results, so the report card can never disagree with
+ * the underlying rollup.
+ */
+export const ReportNarrativeSchema = z.object({
+ content: z.string(),
+ summary: z.string(),
+});
+export type ReportNarrative = z.infer<typeof ReportNarrativeSchema>;
+
+export const REPORT_NARRATIVE_JSON_SCHEMA: GenerateObjectSchema = {
+ name: 'verify_report',
+ schema: {
+ additionalProperties: false,
+ properties: {
+ content: { type: 'string' },
+ summary: { maxLength: 600, type: 'string' },
+ },
+ required: ['summary', 'content'],
+ type: 'object',
+ },
+ strict: true,
+};
diff --git a/packages/database/src/models/verifyEvidence.ts b/packages/database/src/models/verifyEvidence.ts
index 3a0af631ded..90bea5b1759 100644
--- a/packages/database/src/models/verifyEvidence.ts
+++ b/packages/database/src/models/verifyEvidence.ts
@@ -1,13 +1,16 @@
import type { VerifyEvidence } from '@lobechat/types';
import { and, asc, eq } from 'drizzle-orm';
-import { verifyEvidence } from '../schemas/verify';
+import { verifyCheckResults, verifyEvidence } from '../schemas/verify';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
/** Caller-supplied fields when recording one evidence artifact (ownership is injected). */
type CreateVerifyEvidence = Omit<VerifyEvidence, 'id' | 'createdAt'>;
+/** An evidence row annotated with the run-stable `checkItemId` of its result. */
+export type VerifyEvidenceForRun = VerifyEvidence & { checkItemId: string };
+
export class VerifyEvidenceModel {
private readonly db: LobeChatDatabase;
private readonly userId: string;
@@ -63,6 +66,26 @@ export class VerifyEvidenceModel {
.orderBy(asc(verifyEvidence.createdAt));
};
+ /**
+ * All evidence for a whole verification session, each row carrying the
+ * `checkItemId` of the result it backs (joined through `verify_check_results`).
+ * Lets the judge and reporter group a run's artifacts by plan item in one
+ * query, oldest first.
+ */
+ listByRun = async (verifyRunId: string): Promise<VerifyEvidenceForRun[]> => {
+ const rows = await this.db
+ .select({
+ checkItemId: verifyCheckResults.checkItemId,
+ evidence: verifyEvidence,
+ })
+ .from(verifyEvidence)
+ .innerJoin(verifyCheckResults, eq(verifyEvidence.checkResultId, verifyCheckResults.id))
+ .where(and(eq(verifyCheckResults.verifyRunId, verifyRunId), this.ownership()))
+ .orderBy(asc(verifyEvidence.createdAt));
+
+ return rows.map((r) => ({ ...r.evidence, checkItemId: r.checkItemId }));
+ };
+
delete = async (id: string) => {
return this.db.delete(verifyEvidence).where(and(eq(verifyEvidence.id, id), this.ownership()));
};
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index 6aa08a27c7a..666d0ac2fe9 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -188,6 +188,21 @@ export const verifyEvidenceCapturedBy = [
] as const;
export type VerifyEvidenceCapturedBy = (typeof verifyEvidenceCapturedBy)[number];
+/**
+ * Declares that a criterion is evidence-driven: it cannot pass on the
+ * deliverable text alone β€” the run must capture and upload an artifact of each
+ * listed `type` (via `lh verify upload-evidence`). Stored under the plan item's
+ * `verifierConfig.requiredEvidence`, so adding it needs no schema change. The
+ * structural gate marks a required item `uncertain` when any listed type is
+ * missing, independent of the LLM judge.
+ */
+export interface RequiredEvidenceSpec {
+ /** What the capturer should produce β€” guidance only, not validated. */
+ hint?: string;
+ /** The evidence medium that must be present for this criterion. */
+ type: VerifyEvidenceType;
+}
+
/**
* One evidence artifact produced while judging a check. Carries existence +
* provenance only β€” no verdict logic. Verifying an evidence is itself a new