π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(verify): stop Task acceptance repair rounds from failing one round behind (#20768)
Arvin Xu9ac4ae7a3150
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.tsindex 56725de1e21..0471c19fb74 100644--- a/apps/cli/src/commands/acceptanceRun.ts+++ b/apps/cli/src/commands/acceptanceRun.ts@@ -1161,7 +1161,7 @@ function withSubmitOptions(cmd: Command): Command {.option('--run <verifyRunId>', 'Target verification session (or use --operation)').option('--operation <operationId>', 'Resolve the session from an Agent Run operation id').requiredOption('--item <checkItemId>', 'Plan item id (checkItemId)')- .option('--type <type>', 'screenshot|gif|video|text|dom_snapshot|transcript')+ .option('--type <type>', 'screenshot|gif|video|audio|text|markdown|dom_snapshot|transcript').option('--file <path>', 'Local file to upload as the evidence artifact').option('--content <text>', 'Inline text payload (instead of a file)').option('--verdict <verdict>', 'passed|failed|uncertain')@@ -1174,7 +1174,10 @@ function withSubmitOptions(cmd: Command): Command {function withEvidenceUploadOptions(cmd: Command): Command {return cmd.requiredOption('--check <checkResultId>', 'Target check result id')- .requiredOption('--type <type>', 'screenshot|gif|video|text|dom_snapshot|transcript')+ .requiredOption(+ '--type <type>',+ 'screenshot|gif|video|audio|text|markdown|dom_snapshot|transcript',+ ).option('--file <path>', 'Local file to upload as the artifact').option('--file-id <id>', 'Attach an already-uploaded file without uploading it again').option('--content <text>', 'Inline text payload (instead of a file)')diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.tsindex 43ce35384c2..6d8318ff185 100644--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts@@ -2,6 +2,7 @@ import { getHTTPStatusCodeFromError } from '@trpc/server/http';import { strToU8, zipSync } from 'fflate';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as FileModelModule from '@/database/models/file';import { createTRPCErrorLogger } from '@/libs/trpc/utils/errorLogger';import { verifyRouter } from '@/server/routers/lambda/verify';import { FileService } from '@/server/services/file';@@ -13,6 +14,7 @@ const modelMocks = vi.hoisted(() => ({createRun: vi.fn(),deleteResult: vi.fn(),deleteRun: vi.fn(),+ findFileById: vi.fn(),findRunByOperation: vi.fn(),findRunById: vi.fn(),findResultById: vi.fn(),@@ -21,6 +23,7 @@ const modelMocks = vi.hoisted(() => ({generateGoalPlan: vi.fn(),getFullFileUrl: vi.fn(),getServerDB: vi.fn(async () => ({})),+ listResultsByRun: vi.fn(),updateRun: vi.fn(),upsertByCheckItem: vi.fn(),}));@@ -34,6 +37,7 @@ vi.mock('@/database/models/verifyCheckResult', () => ({return {delete: modelMocks.deleteResult,findById: modelMocks.findResultById,+ listByRun: modelMocks.listResultsByRun,upsertByCheckItem: modelMocks.upsertByCheckItem,};}),@@ -51,6 +55,16 @@ vi.mock('@/database/models/verifyRun', () => ({}),}));+// Keep the real statics (the report bundle resolves file metadata through+// `FileModel.getFileById`); only the instance lookup the write paths use is stubbed.+vi.mock('@/database/models/file', async (importOriginal) => {+ const actual = await importOriginal<typeof FileModelModule>();+ class FileModel extends actual.FileModel {+ findById = modelMocks.findFileById as unknown as actual.FileModel['findById'];+ }+ return { ...actual, FileModel };+});+vi.mock('@/database/models/verifyEvidence', () => ({VerifyEvidenceModel: vi.fn(function () {return {@@ -109,6 +123,8 @@ describe('verifyRouter', () => {beforeEach(() => {vi.clearAllMocks();modelMocks.getServerDB.mockResolvedValue({});+ modelMocks.listResultsByRun.mockResolvedValue([]);+ modelMocks.findFileById.mockResolvedValue(undefined);vi.mocked(FileService).mockImplementation(function () {return {getFullFileUrl: modelMocks.getFullFileUrl,@@ -657,6 +673,64 @@ describe('verifyRouter', () => {);});+ it('lands evidence for a repaired check on the repair round, not the settled one', async () => {+ const plan = [{ id: 'item-1', index: 0, required: true, title: 'mutation gif' }];+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'round-1', plan, status: 'failed' });+ modelMocks.listResultsByRun.mockImplementation(async (runId: string) =>+ runId === 'round-1'+ ? [{ checkItemId: 'item-1', repairOperationId: 'repair-op-2' }]+ : [{ checkItemId: 'item-1', repairOperationId: null }],+ );+ modelMocks.findRunByOperation.mockResolvedValueOnce({+ id: 'round-2',+ plan,+ status: 'planned',+ });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({+ id: 'result-2',+ verifyRunId: 'round-2',+ });+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ fileId: 'files-1', type: 'gif' }],+ verifyRunId: 'round-1',+ });++ expect(modelMocks.findRunByOperation).toHaveBeenCalledWith('repair-op-2');+ expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(+ expect.objectContaining({ checkItemId: 'item-1', verifyRunId: 'round-2' }),+ );+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(+ expect.objectContaining({ checkResultId: 'result-2', type: 'gif' }),+ );+ });++ it('stores a GIF uploaded as video as a gif, not a video', async () => {+ // Builders without a gif type labelled their GIFs `video`; the acceptance+ // page then played an animated image in a video player that failed to load.+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });+ modelMocks.findFileById.mockResolvedValueOnce({+ fileType: 'image/gif',+ id: 'files-gif',+ name: 'rename.gif',+ });+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });++ await createCaller().submitCheckEvidence({+ checkItemId: 'item-1',+ evidence: [{ fileId: 'files-gif', type: 'video' }],+ verifyRunId: 'run-1',+ });++ expect(modelMocks.findFileById).toHaveBeenCalledWith('files-gif');+ expect(modelMocks.createEvidence).toHaveBeenCalledWith(+ expect.objectContaining({ fileId: 'files-gif', type: 'gif' }),+ );+ });+it('rejects a check item that is not in the run plan instead of minting a required row', async () => {modelMocks.findRunById.mockResolvedValueOnce({id: 'run-1',diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex 1307d037090..5ecd8860d4e 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -10,6 +10,7 @@ import { AgentRuntimeErrorType } from '@lobechat/model-runtime';import type {VerifyCheckItem,VerifyCheckResultMetadata,+ VerifyEvidenceType,VerifyRunContext,VerifyRunScenario,} from '@lobechat/types';@@ -24,6 +25,7 @@ import {} 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';@@ -47,8 +49,10 @@ import { GoalCriteriaGeneratorService } from '@/server/services/goal/criteriaGenimport {AcceptanceService,createEvidenceFileResolver,+ evidenceTypeForStoredFile,finalizeVerifyRun,purgeVerifyRun,+ resolveLiveRoundForItem,VerifyExecutorService,VerifyFeedbackService,VerifyPlanGeneratorService,@@ -263,6 +267,7 @@ const verifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =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),@@ -323,6 +328,14 @@ const resolveRunByOperation = async (ctx: { runModel: VerifyRunModel }, operatioreturn 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@@ -960,6 +973,7 @@ export const verifyRouter = router({// 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(),@@ -968,8 +982,8 @@ export const verifyRouter = router({content: input.content ?? null,description: input.description ?? null,fileId: input.fileId ?? null,- metadata: normalizeEvidenceMetadata(input.metadata, input.type) ?? null,- type: input.type,+ metadata: normalizeEvidenceMetadata(input.metadata, type) ?? null,+ type,});}),@@ -1019,11 +1033,15 @@ export const verifyRouter = router({}),).mutation(async ({ ctx, input }) => {- const run = input.verifyRunId+ 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, run.userId, 'verify run');+ 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@@ -1064,7 +1082,7 @@ export const verifyRouter = router({const evidence = input.evidence?.length? await Promise.all(- input.evidence.map((e) =>+ input.evidence.map(async (e) =>ctx.evidenceModel.create({capturedAt: new Date(),capturedBy: e.capturedBy ?? null,@@ -1072,7 +1090,7 @@ export const verifyRouter = router({content: e.content ?? null,description: e.description ?? null,fileId: e.fileId ?? null,- type: e.type,+ type: await storedEvidenceType(ctx, e.type, e.fileId),}),),)diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.tsindex 9ce274bdb33..414f484ab36 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts@@ -375,6 +375,74 @@ describe('acceptanceEvidenceRuntime', () => {expect(mocks.evidenceCreateMany).not.toHaveBeenCalled();});+ it('records the gif and transcript types a criterion can require', async () => {+ // The tool only offered markdown/screenshot/text/video, so a repair turn told+ // to supply a required gif or transcript could only send the wrong type and+ // fail the structural gate again, round after round.+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });+ mocks.fileFindById.mockResolvedValue({ id: 'files_gif' });+ const runtime = acceptanceEvidenceRuntime.factory({+ operationId: 'task-op',+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.submitEvidence({+ checkItemId: 'criterion-1',+ evidence: [+ { content: 'Rename applied in the list', fileId: 'files_gif', type: 'gif' },+ { content: '$ lh task view T-1\nstatus: done', type: 'transcript' },+ ],+ });++ expect(result.success).toBe(true);+ expect(mocks.evidenceCreateMany).toHaveBeenCalledWith([+ expect.objectContaining({ fileId: 'files_gif', type: 'gif' }),+ expect.objectContaining({ type: 'transcript' }),+ ]);+ });++ it('stores a GIF cited as a screenshot as a gif', async () => {+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });+ mocks.fileFindById.mockResolvedValue({ fileType: 'image/gif', id: 'files_gif', name: 'a.gif' });+ const runtime = acceptanceEvidenceRuntime.factory({+ operationId: 'task-op',+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.submitEvidence({+ checkItemId: 'criterion-1',+ evidence: [{ content: 'Rename applied', fileId: 'files_gif', type: 'screenshot' }],+ });++ expect(result.success).toBe(true);+ expect(mocks.evidenceCreateMany).toHaveBeenCalledWith([+ expect.objectContaining({ fileId: 'files_gif', type: 'gif' }),+ ]);+ });++ it('rejects a gif with no artifact behind it', async () => {+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });+ const runtime = acceptanceEvidenceRuntime.factory({+ operationId: 'task-op',+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.submitEvidence({+ checkItemId: 'criterion-1',+ evidence: [{ content: 'recorded a gif of the rename', type: 'gif' }],+ });++ expect(result).toEqual(+ expect.objectContaining({ error: 'UNBACKED_VISUAL_EVIDENCE', success: false }),+ );+ });+it('rejects an unknown files.id before the evidence foreign key is evaluated', async () => {mocks.fileFindById.mockResolvedValue(undefined);const runtime = acceptanceEvidenceRuntime.factory({diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.tsindex 9e8e76e3dfc..712c8552b78 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts@@ -11,6 +11,7 @@ import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';import { VerifyRunModel } from '@/database/models/verifyRun';import type { LobeChatDatabase } from '@/database/type';+import { evidenceTypeForStoredFile } from '@/server/services/verify/evidenceMedium';import type { ServerRuntimeRegistration } from './types';@@ -172,7 +173,9 @@ class AcceptanceEvidenceExecutionRuntime {// with no file, which renders on the acceptance as a visual check with// nothing behind it: strictly worse than an honest text note.const unbacked = params.evidence.find(- (item) => (item.type === 'screenshot' || item.type === 'video') && !item.fileId,+ (item) =>+ (item.type === 'gif' || item.type === 'screenshot' || item.type === 'video') &&+ !item.fileId,);if (unbacked) {return {@@ -214,6 +217,7 @@ class AcceptanceEvidenceExecutionRuntime {}const fileIds = [...new Set(params.evidence.flatMap((evidence) => evidence.fileId ?? []))];+ const filesById = new Map<string, Awaited<ReturnType<FileModel['findById']>>>();if (fileIds.length > 0) {const files = await Promise.all(fileIds.map((fileId) =>@@ -228,6 +232,7 @@ class AcceptanceEvidenceExecutionRuntime {success: false,};}+ fileIds.forEach((fileId, index) => filesById.set(fileId, files[index]));}const result = await new VerifyCheckResultModel(@@ -253,7 +258,10 @@ class AcceptanceEvidenceExecutionRuntime {description: evidence.description ?? null,documentId: evidence.documentId ?? null,fileId: evidence.fileId ?? null,- type: evidence.type,+ type: evidenceTypeForStoredFile(+ evidence.type,+ evidence.fileId ? filesById.get(evidence.fileId) : undefined,+ ),})),);diff --git a/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts b/apps/server/src/services/verify/__tests__/evidenceCoverage.test.tsindex 58e2a300e59..0b8a98b669b 100644--- a/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts+++ b/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts@@ -49,6 +49,22 @@ describe('coverageGaps', () => {).toEqual([]);});+ it('accepts a same-medium substitute for the declared type', () => {+ expect(coverageGaps([{ type: 'gif' }], [{ type: 'video' }])).toEqual([]);+ expect(coverageGaps([{ type: 'video' }], [{ type: 'gif' }])).toEqual([]);+ expect(coverageGaps([{ type: 'text' }], [{ type: 'markdown' }])).toEqual([]);+ expect(coverageGaps([{ type: 'transcript' }], [{ type: 'text' }])).toEqual([]);+ expect(coverageGaps([{ type: 'markdown' }], [{ type: 'transcript' }])).toEqual([]);+ });++ it('keeps visual and structured evidence strict', () => {+ expect(coverageGaps([{ type: 'screenshot' }], [{ type: 'gif' }, { type: 'text' }])).toEqual([+ 'screenshot',+ ]);+ expect(coverageGaps([{ type: 'dom_snapshot' }], [{ type: 'text' }])).toEqual(['dom_snapshot']);+ expect(coverageGaps([{ type: 'gif' }], [{ type: 'screenshot' }])).toEqual(['gif']);+ });+it('dedupes repeated required types', () => {expect(coverageGaps([{ type: 'screenshot' }, { type: 'screenshot' }], [])).toEqual(['screenshot',diff --git a/apps/server/src/services/verify/__tests__/evidenceMedium.test.ts b/apps/server/src/services/verify/__tests__/evidenceMedium.test.tsnew file mode 100644index 00000000000..81296ddc750--- /dev/null+++ b/apps/server/src/services/verify/__tests__/evidenceMedium.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { evidenceTypeForStoredFile } from '../evidenceMedium';++describe('evidenceTypeForStoredFile', () => {+ it('stores a GIF labelled as video or screenshot as a gif', () => {+ expect(evidenceTypeForStoredFile('video', { fileType: 'image/gif', name: 'rename.gif' })).toBe(+ 'gif',+ );+ expect(evidenceTypeForStoredFile('screenshot', { fileType: 'image/gif' })).toBe('gif');+ expect(evidenceTypeForStoredFile('video', { fileType: null, name: 'Rename.GIF' })).toBe('gif');+ });++ it('keeps the declared type for anything that is not a GIF file', () => {+ expect(evidenceTypeForStoredFile('video', { fileType: 'video/mp4', name: 'rename.mp4' })).toBe(+ 'video',+ );+ expect(evidenceTypeForStoredFile('screenshot', { fileType: 'image/png' })).toBe('screenshot');+ expect(evidenceTypeForStoredFile('text', { fileType: 'image/gif' })).toBe('text');+ expect(evidenceTypeForStoredFile('video', undefined)).toBe('video');+ });+});diff --git a/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts b/apps/server/src/services/verify/__tests__/evidenceSubmission.test.tsindex 5b469f844c7..46d0b52cccb 100644--- a/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts+++ b/apps/server/src/services/verify/__tests__/evidenceSubmission.test.ts@@ -151,6 +151,7 @@ describe('startEvidenceSubmission', () => {);const call = execAgent.mock.calls[0][0];expect(call.ephemeralUserMessage).toContain('criterion-1: Model artifact exists');+ expect(call.ephemeralUserMessage).not.toContain('requires evidence type');expect(call.prompt).toBe(call.ephemeralUserMessage);expect(call.prompt.trim()).not.toBe('');expect(call.userInterventionConfig).toEqual({ approvalMode: 'headless' });@@ -162,6 +163,37 @@ describe('startEvidenceSubmission', () => {});});+ it('names the run-evidence types each criterion is gated on', async () => {+ await startEvidenceSubmission({+ db: {} as any,+ deliverable: 'artifact summary',+ goal: 'ship model',+ operation: { agentId: 'builder-agent', id: 'work-op', taskId: 't', topicId: 'tp' } as any,+ plan: [+ {+ id: 'criterion-1',+ index: 0,+ onFail: 'auto_repair',+ required: true,+ title: 'Rename works in the UI',+ verifierConfig: {+ requiredEvidence: [+ { scope: 'run_evidence', type: 'gif' },+ { type: 'transcript' },+ { scope: 'task_artifacts', type: 'markdown' },+ ],+ },+ verifierType: 'agent',+ },+ ],+ userId: 'user-1',+ });++ expect(execAgent.mock.calls[0][0].prompt).toContain(+ 'criterion-1: Rename works in the UI [requires evidence type: gif, transcript]',+ );+ });+it('rejects operations that cannot preserve builder identity and topic context', async () => {await expect(startEvidenceSubmission({diff --git a/apps/server/src/services/verify/__tests__/executor.test.ts b/apps/server/src/services/verify/__tests__/executor.test.tsindex d8ea96e6198..c9ad2bca41d 100644--- a/apps/server/src/services/verify/__tests__/executor.test.ts+++ b/apps/server/src/services/verify/__tests__/executor.test.ts@@ -204,7 +204,7 @@ describe('VerifyExecutorService', () => {'shot-check',expect.objectContaining({suggestion: expect.stringContaining(- 'lh acceptance run result submit --run run-1 --item shot-check',+ 'lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item shot-check --type screenshot',),verdict: 'uncertain',}),diff --git a/apps/server/src/services/verify/__tests__/liveRound.test.ts b/apps/server/src/services/verify/__tests__/liveRound.test.tsnew file mode 100644index 00000000000..a62b3c3d7e3--- /dev/null+++ b/apps/server/src/services/verify/__tests__/liveRound.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from 'vitest';++import { resolveLiveRoundForItem } from '../liveRound';++const plan = [{ id: 'item-1' }];++const makeModels = (+ results: Record<string, { checkItemId: string; repairOperationId?: string | null }[]>,+ runsByOperation: Record<string, { id: string; plan: unknown }>,+) => ({+ resultModel: { listByRun: vi.fn(async (runId: string) => results[runId] ?? []) },+ runModel: { findByOperation: vi.fn(async (operationId: string) => runsByOperation[operationId]) },+});++describe('resolveLiveRoundForItem', () => {+ it('keeps the named round when the item was never repaired', async () => {+ const models = makeModels({ r1: [{ checkItemId: 'item-1' }] }, {});+ const run = await resolveLiveRoundForItem(models as any, { id: 'r1', plan } as any, 'item-1');+ expect(run.id).toBe('r1');+ });++ it('follows the repair chain to the latest round of the item', async () => {+ const models = makeModels(+ {+ r1: [{ checkItemId: 'item-1', repairOperationId: 'op-2' }],+ r2: [{ checkItemId: 'item-1', repairOperationId: 'op-3' }],+ r3: [{ checkItemId: 'item-1', repairOperationId: null }],+ },+ { 'op-2': { id: 'r2', plan }, 'op-3': { id: 'r3', plan } },+ );+ const run = await resolveLiveRoundForItem(models as any, { id: 'r1', plan } as any, 'item-1');+ expect(run.id).toBe('r3');+ });++ it('only follows the repair recorded on the submitted item', async () => {+ const models = makeModels(+ { r1: [{ checkItemId: 'other', repairOperationId: 'op-2' }, { checkItemId: 'item-1' }] },+ { 'op-2': { id: 'r2', plan } },+ );+ const run = await resolveLiveRoundForItem(models as any, { id: 'r1', plan } as any, 'item-1');+ expect(run.id).toBe('r1');+ });++ it('stays put when the repair round is missing or no longer plans the item', async () => {+ const missing = makeModels({ r1: [{ checkItemId: 'item-1', repairOperationId: 'op-2' }] }, {});+ expect(+ (await resolveLiveRoundForItem(missing as any, { id: 'r1', plan } as any, 'item-1')).id,+ ).toBe('r1');++ const replanned = makeModels(+ { r1: [{ checkItemId: 'item-1', repairOperationId: 'op-2' }] },+ { 'op-2': { id: 'r2', plan: [{ id: 'item-9' }] } },+ );+ expect(+ (await resolveLiveRoundForItem(replanned as any, { id: 'r1', plan } as any, 'item-1')).id,+ ).toBe('r1');+ });++ it('stops on a cycle instead of looping', async () => {+ const models = makeModels(+ {+ r1: [{ checkItemId: 'item-1', repairOperationId: 'op-2' }],+ r2: [{ checkItemId: 'item-1', repairOperationId: 'op-1' }],+ },+ { 'op-1': { id: 'r1', plan }, 'op-2': { id: 'r2', plan } },+ );+ const run = await resolveLiveRoundForItem(models as any, { id: 'r1', plan } as any, 'item-1');+ expect(run.id).toBe('r2');+ });+});diff --git a/apps/server/src/services/verify/__tests__/repairService.test.ts b/apps/server/src/services/verify/__tests__/repairService.test.tsnew file mode 100644index 00000000000..c73925bb0ed--- /dev/null+++ b/apps/server/src/services/verify/__tests__/repairService.test.ts@@ -0,0 +1,137 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { VerifyRepairService } from '../repairService';++const m = vi.hoisted(() => ({+ findVerifyMessage: vi.fn(),+ listResults: vi.fn(),+ markRepairing: vi.fn(),+ rounds: vi.fn(),+ run: vi.fn(),+ settleFailedRepair: vi.fn(),+ updateMessage: vi.fn(),+ updateResult: vi.fn(),+}));+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn(function () {+ return { findVerifyMessageByOperationId: m.findVerifyMessage, update: m.updateMessage };+ }),+}));+vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(function () {+ return { findByOperation: m.run, listByAcceptance: m.rounds };+ }),+}));+vi.mock('@/database/models/verifyCheckResult', () => ({+ VerifyCheckResultModel: vi.fn(function () {+ return { listByRun: m.listResults, updateByCheckItem: m.updateResult };+ }),+}));+vi.mock('../statusService', () => ({+ VerifyStatusService: vi.fn(function () {+ return { markRepairing: m.markRepairing };+ }),+}));+vi.mock('../repairTerminal', () => ({ settleFailedRepair: m.settleFailedRepair }));++const item = (id: string, required = true) => ({+ id,+ index: 0,+ onFail: 'auto_repair',+ required,+ title: id,+ verifierConfig: {},+ verifierType: 'agent',+});++const round = {+ acceptanceId: 'acceptance',+ id: 'round-3',+ plan: [item('gif-check'), item('optional-video', false)],+ roundIndex: 3,+ status: 'failed',+};++const gateFailure = (checkItemId: string) => ({+ checkItemId,+ status: 'failed',+ suggestion: 'Capture and upload the missing evidence',+ verdict: 'uncertain',+});++describe('VerifyRepairService.triggerAutoRepair', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ m.run.mockResolvedValue(round);+ m.rounds.mockResolvedValue([round]);+ m.findVerifyMessage.mockResolvedValue(undefined);+ });++ it('repairs a failed required check', async () => {+ m.listResults.mockResolvedValue([gateFailure('gif-check')]);+ const spawner = vi.fn().mockResolvedValue({ repairOperationId: 'repair-op' });++ const spawned = await new VerifyRepairService({} as any, 'user').triggerAutoRepair(+ 'op-3',+ spawner,+ );++ expect(spawned).toEqual({ repairOperationId: 'repair-op' });+ expect(spawner).toHaveBeenCalledWith(expect.objectContaining({ failedItemIds: ['gif-check'] }));+ });++ it('does not spend a repair round on an optional check', async () => {+ m.listResults.mockResolvedValue([+ { checkItemId: 'gif-check', status: 'passed', verdict: 'passed' },+ gateFailure('optional-video'),+ ]);+ const spawner = vi.fn();++ const spawned = await new VerifyRepairService({} as any, 'user').triggerAutoRepair(+ 'op-3',+ spawner,+ );++ expect(spawned).toBeNull();+ expect(spawner).not.toHaveBeenCalled();+ });++ it('stops a stale chain once another round of the acceptance passed', async () => {+ m.listResults.mockResolvedValue([gateFailure('gif-check')]);+ m.rounds.mockResolvedValue([+ { id: 'round-2', roundIndex: 2, status: 'passed', userDecision: null },+ round,+ ]);+ const spawner = vi.fn();++ expect(+ await new VerifyRepairService({} as any, 'user').triggerAutoRepair('op-3', spawner),+ ).toBeNull();+ expect(spawner).not.toHaveBeenCalled();+ });++ it('stops a stale chain once a later round exists', async () => {+ m.listResults.mockResolvedValue([gateFailure('gif-check')]);+ m.rounds.mockResolvedValue([round, { id: 'round-4', roundIndex: 4, status: 'verifying' }]);+ const spawner = vi.fn();++ expect(+ await new VerifyRepairService({} as any, 'user').triggerAutoRepair('op-3', spawner),+ ).toBeNull();+ expect(spawner).not.toHaveBeenCalled();+ });++ it('still repairs after a passed round the user rejected', async () => {+ m.listResults.mockResolvedValue([gateFailure('gif-check')]);+ m.rounds.mockResolvedValue([+ { id: 'round-2', roundIndex: 2, status: 'passed', userDecision: 'reject' },+ round,+ ]);+ const spawner = vi.fn().mockResolvedValue({ repairOperationId: 'repair-op' });++ expect(+ await new VerifyRepairService({} as any, 'user').triggerAutoRepair('op-3', spawner),+ ).toEqual({ repairOperationId: 'repair-op' });+ });+});diff --git a/apps/server/src/services/verify/evidenceCoverage.ts b/apps/server/src/services/verify/evidenceCoverage.tsindex 1195880ca68..8cd4fb0a114 100644--- a/apps/server/src/services/verify/evidenceCoverage.ts+++ b/apps/server/src/services/verify/evidenceCoverage.ts@@ -12,6 +12,22 @@ export const readRequiredEvidence = (return Array.isArray(raw) ? (raw as RequiredEvidenceSpec[]) : undefined;};+/**+ * Same-medium types that also satisfy a declared requirement. The gate checks+ * that an artifact of the right medium exists; whether it proves the criterion+ * is the judge's call. Without this, a recording uploaded as `video` against a+ * `gif` requirement, or a CLI log uploaded as `text` against `transcript`,+ * failed every repair round on a label while the judge never saw the artifact.+ * `screenshot`, `dom_snapshot` and `audio` have no substitute.+ */+const SATISFIED_BY: Partial<Record<VerifyEvidenceType, VerifyEvidenceType[]>> = {+ gif: ['video'],+ markdown: ['text', 'transcript'],+ text: ['markdown', 'transcript'],+ transcript: ['text', 'markdown'],+ video: ['gif'],+};+/*** Which required evidence types are still missing for a criterion β pure, so the* structural gate is unit-testable without a database. Returns `[]` when the@@ -23,7 +39,9 @@ export const coverageGaps = (): 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));+ return [...new Set(required.map((r) => r.type))].filter(+ (t) => !present.has(t) && !SATISFIED_BY[t]?.some((alt) => present.has(alt)),+ );};/**diff --git a/apps/server/src/services/verify/evidenceMedium.ts b/apps/server/src/services/verify/evidenceMedium.tsnew file mode 100644index 00000000000..2f8bcb07f12--- /dev/null+++ b/apps/server/src/services/verify/evidenceMedium.ts@@ -0,0 +1,27 @@+import type { VerifyEvidenceType } from '@lobechat/types';++/** The stored-file fields that reveal what an artifact actually is. */+export interface EvidenceFileShape {+ fileType?: string | null;+ name?: string | null;+}++const isGifFile = (file: EvidenceFileShape): boolean =>+ file.fileType?.toLowerCase() === 'image/gif' || /\.gif$/i.test(file.name ?? '');++/**+ * The evidence type a file-backed artifact is stored under. The caller's label+ * is a claim; the file is the fact. Builders whose tools offered no `gif` type+ * uploaded their GIFs as `video` or `screenshot`: the acceptance page then+ * played an animated image in a video player that could only show a load+ * failure, and the coverage gate counted it as the wrong medium. A GIF file is+ * an animated image whatever it was labelled, so it is stored as `gif`.+ */+export const evidenceTypeForStoredFile = (+ declared: VerifyEvidenceType,+ file: EvidenceFileShape | null | undefined,+): VerifyEvidenceType => {+ if (!file) return declared;+ if ((declared === 'video' || declared === 'screenshot') && isGifFile(file)) return 'gif';+ return declared;+};diff --git a/apps/server/src/services/verify/evidenceSubmission.ts b/apps/server/src/services/verify/evidenceSubmission.tsindex e283f269cf3..e09355958ed 100644--- a/apps/server/src/services/verify/evidenceSubmission.ts+++ b/apps/server/src/services/verify/evidenceSubmission.ts@@ -9,11 +9,28 @@ import type { LobeChatDatabase } from '@/database/type';import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';import { AiAgentService } from '@/server/services/aiAgent';+import { readRequiredEvidence } from './evidenceCoverage';++// A criterion that declares evidence types fails its structural gate until+// each one is present, so the prompt has to name them: without the types, the+// evidence turn sent whatever it reached for first (markdown for a `text`+// requirement, a recording as `video` for `gif`) and failed every repair round.+const describeRequiredEvidence = (item: VerifyCheckItem): string => {+ const types = [+ ...new Set(+ (readRequiredEvidence(item.verifierConfig) ?? [])+ .filter((spec) => !spec.scope || spec.scope === 'run_evidence')+ .map((spec) => spec.type),+ ),+ ];+ return types.length > 0 ? ` [requires evidence type: ${types.join(', ')}]` : '';+};+const buildEvidencePrompt = (items: VerifyCheckItem[],): string => `The task execution is complete. Submit the evidence you produced for every Acceptance criterion below.-${items.map((item) => `- ${item.id}: ${item.title}${item.description ? ` β ${item.description}` : ''}`).join('\n')}+${items.map((item) => `- ${item.id}: ${item.title}${item.description ? ` β ${item.description}` : ''}${describeRequiredEvidence(item)}`).join('\n')}Call submitEvidence once for each criterion. This is evidence collection only: do not assign verdicts and do not redo the implementation.`;diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.tsindex a9fde2620c6..ffdd695fda3 100644--- a/apps/server/src/services/verify/executor.ts+++ b/apps/server/src/services/verify/executor.ts@@ -275,9 +275,11 @@ export class VerifyExecutorService {completedAt: new Date(),confidence: 0,status: 'failed',- // `result submit` needs a run selector; spell out this run and item so- // the recovery command can be run as-is.- suggestion: `Capture and upload the missing evidence (${missing}) via \`lh acceptance run result submit --run ${verifyRunId} --item ${item.id} --type <type> --file <path>\`.`,+ // The repair that acts on this suggestion runs as a new operation with a+ // round of its own, so the command targets the caller's operation, not+ // this run: naming this (settled) run sent every repair's evidence one+ // round behind the round its gate checks.+ suggestion: `Capture and upload the missing evidence (${missing}) to your current run via \`lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item ${item.id} --type ${gaps.length === 1 ? gaps[0] : `<${gaps.join('|')}>`} --file <path>\`.`,toulmin: { limitation: `Required evidence not provided: ${missing}.` },verdict: 'uncertain',});diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.tsindex 9f791680dad..054a9880ea5 100644--- a/apps/server/src/services/verify/index.ts+++ b/apps/server/src/services/verify/index.ts@@ -25,6 +25,7 @@ export { createVerifierAgentRunner } from './agentVerifier';export { mapWithConcurrency } from './concurrency';export { coverageGaps, readRequiredEvidence } from './evidenceCoverage';export { createEvidenceFileResolver, type EvidenceFileMeta } from './evidenceFiles';+export { evidenceTypeForStoredFile } from './evidenceMedium';export {type ExecuteVerifyParams,type VerifierAgentRunner,@@ -32,6 +33,7 @@ export {} from './executor';export { computeFalseFlags, VerifyFeedbackService } from './feedbackService';export { runVerifyOnCompletion } from './lifecycle';+export { resolveLiveRoundForItem } from './liveRound';export {isHeterogeneousVerifyProvider,resolveVerifyModelConfig,diff --git a/apps/server/src/services/verify/liveRound.ts b/apps/server/src/services/verify/liveRound.tsnew file mode 100644index 00000000000..53fbce30c87--- /dev/null+++ b/apps/server/src/services/verify/liveRound.ts@@ -0,0 +1,47 @@+import type { VerifyCheckItem } from '@lobechat/types';++import type { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';+import type { VerifyRunModel } from '@/database/models/verifyRun';+import type { VerifyRunItem } from '@/database/schemas/verify';++/** Guard against a cyclic or runaway repair chain; real chains stop at the repair cap. */+const MAX_HOPS = 20;++/**+ * Follow a check item from the round a caller named to the round that will+ * actually judge it. Once a round's failure spawns a repair, its result row+ * records `repairOperationId` and that repair owns the next round; the+ * superseded round is settled and never re-judged. A repair agent that reuses+ * the round id from its feedback would otherwise attach the evidence it was+ * asked for to the old round, leaving the new round's structural gate to fail+ * on the same missing artifact, one round behind, every time.+ *+ * Returns the input run when the item was never repaired, or when the successor+ * round is missing or no longer plans the item.+ */+export const resolveLiveRoundForItem = async (+ models: { resultModel: VerifyCheckResultModel; runModel: VerifyRunModel },+ run: VerifyRunItem,+ checkItemId: string,+): Promise<VerifyRunItem> => {+ let current = run;+ const seen = new Set([run.id]);++ for (let hop = 0; hop < MAX_HOPS; hop += 1) {+ const results = await models.resultModel.listByRun(current.id);+ const repairOperationId = results.find(+ (result) => result.checkItemId === checkItemId,+ )?.repairOperationId;+ if (!repairOperationId) return current;++ const next = await models.runModel.findByOperation(repairOperationId);+ if (!next || seen.has(next.id)) return current;+ const plan = (next.plan as VerifyCheckItem[] | null) ?? [];+ if (!plan.some((item) => item.id === checkItemId)) return current;++ seen.add(next.id);+ current = next;+ }++ return current;+};diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.tsindex 18d0d0ed211..9a4715b76ce 100644--- a/apps/server/src/services/verify/repairService.ts+++ b/apps/server/src/services/verify/repairService.ts@@ -294,11 +294,37 @@ export class VerifyRepairService {const results = await this.resultModel.listByRun(run.id);const byItem = new Map(results.map((r) => [r.checkItemId, r]));+ // An optional check never gates delivery, so it must not spend a repair+ // round either: a passing round whose only gap was an optional video kept+ // re-running the builder until the repair cap.return plan- .filter((item) => item.onFail === 'auto_repair' && isFailed(byItem.get(item.id)))+ .filter(+ (item) =>+ item.required !== false && item.onFail === 'auto_repair' && isFailed(byItem.get(item.id)),+ ).map((item) => ({ item, result: byItem.get(item.id) }));}+ /**+ * A round stops owning its acceptance once a later round exists or another+ * round has already passed. Parallel attempts of one Task (a recovered topic+ * next to a still-running repair chain) otherwise kept repairing a stale+ * round after the acceptance was delivered, and left a failed round as the+ * acceptance's latest state.+ */+ private async isSuperseded(operationId: string): Promise<boolean> {+ const run = await this.runModel.findByOperation(operationId);+ if (!run?.acceptanceId) return false;++ const rounds = await this.runModel.listByAcceptance(run.acceptanceId);+ return rounds.some(+ (round) =>+ round.id !== run.id &&+ ((round.roundIndex ?? 0) > (run.roundIndex ?? 0) ||+ (round.status === 'passed' && round.userDecision !== 'reject')),+ );+ }+/*** Trigger one round of auto-repair. Returns the repair operation id, or null* when there's nothing to repair or no spawner is available in this context.@@ -309,6 +335,10 @@ export class VerifyRepairService {): Promise<{ repairOperationId: string } | null> {const failures = await this.collectRepairable(operationId);if (failures.length === 0) return null;+ if (await this.isSuperseded(operationId)) {+ log('op %s round is superseded within its acceptance, not repairing', operationId);+ return null;+ }if (!spawner) {log('auto-repair eligible for op %s but no spawner available', operationId);return null;diff --git a/packages/builtin-tool-acceptance-evidence/src/manifest.ts b/packages/builtin-tool-acceptance-evidence/src/manifest.tsindex ef3ecf4e3a3..181dd1ecd37 100644--- a/packages/builtin-tool-acceptance-evidence/src/manifest.ts+++ b/packages/builtin-tool-acceptance-evidence/src/manifest.ts@@ -40,7 +40,17 @@ export const AcceptanceEvidenceManifest: BuiltinToolManifest = {},fileId: { description: 'An existing LobeHub artifact file id.', type: 'string' },type: {- enum: ['markdown', 'screenshot', 'text', 'video'],+ description:+ 'Use the type the criterion requires (listCriteria shows it). gif, screenshot and video must cite a fileId.',+ enum: [+ 'dom_snapshot',+ 'gif',+ 'markdown',+ 'screenshot',+ 'text',+ 'transcript',+ 'video',+ ],type: 'string',},},diff --git a/packages/builtin-tool-acceptance-evidence/src/types.ts b/packages/builtin-tool-acceptance-evidence/src/types.tsindex 7956e853b52..de82b9a65ac 100644--- a/packages/builtin-tool-acceptance-evidence/src/types.ts+++ b/packages/builtin-tool-acceptance-evidence/src/types.ts@@ -3,7 +3,8 @@ export const AcceptanceEvidenceApiName = {submitEvidence: 'submitEvidence',} as const;-export type AcceptanceEvidenceType = 'markdown' | 'screenshot' | 'text' | 'video';+export type AcceptanceEvidenceType =+ 'dom_snapshot' | 'gif' | 'markdown' | 'screenshot' | 'text' | 'transcript' | 'video';export interface SubmitAcceptanceEvidenceParams {checkItemId: string;