Skip to content

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

πŸ› fix(verify): stop acceptance rounds from failing on work already proven (#20896)

Arvin Xu53dd576bddf5
diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
index 076eb72daf8..9d35a689c7f 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({
acceptanceEnsureForSubject: vi.fn(),
acceptanceUpdate: vi.fn(),
agentExec: vi.fn(),
+ carryPassedResultsForward: vi.fn(),
confirmPlan: vi.fn(),
ensureForOperation: vi.fn(),
@@ -46,6 +47,9 @@ vi.mock('../acceptanceService', async (original) => ({
}),
}));
+vi.mock('../carryForward', () => ({
+ carryPassedResultsForward: mocks.carryPassedResultsForward,
+}));
vi.mock('../planGenerator', () => ({
VerifyPlanGeneratorService: vi.fn(function () {
return {
@@ -387,6 +391,18 @@ describe('Verify acceptance lifecycle', () => {
}),
);
expect(mocks.acceptanceAttachPolicyRun).toHaveBeenCalledWith('repair-run', 'acceptance-1');
+ // Checks the repair was not asked to fix keep their earned verdict.
+ expect(mocks.carryPassedResultsForward).toHaveBeenCalledWith(
+ db,
+ 'user-1',
+ expect.objectContaining({
+ excludeItemIds: ['check-1'],
+ operationId: 'repair-operation',
+ sourceRunId: 'source-run',
+ targetRunId: 'repair-run',
+ }),
+ 'workspace-1',
+ );
});
});
diff --git a/apps/server/src/services/verify/__tests__/carryForward.db.test.ts b/apps/server/src/services/verify/__tests__/carryForward.db.test.ts
new file mode 100644
index 00000000000..bec0c3367c7
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/carryForward.db.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import type { VerifyCheckItem } from '@lobechat/types';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import { users } from '@/database/schemas';
+
+import { carryPassedResultsForward } from '../carryForward';
+import { VerifyExecutorService } from '../executor';
+
+// No stored files in this scenario; the real service only refuses to build without S3 env.
+vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));
+
+const serverDB = await getTestDB();
+const userId = 'carry-forward-db-user';
+const sourceOperationId = 'carry-forward-source-op';
+const repairOperationId = 'carry-forward-repair-op';
+
+const planItem = (id: string, index: number, title: string) =>
+ ({
+ id,
+ index,
+ required: true,
+ title,
+ verifierConfig: {},
+ verifierType: 'agent',
+ }) as VerifyCheckItem;
+
+const plan: VerifyCheckItem[] = [
+ planItem('list', 0, 'List migrated'),
+ planItem('reader', 1, 'Reader migrated'),
+ planItem('keys', 2, 'Dead keys removed'),
+];
+
+const runs = () => new VerifyRunModel(serverDB, userId);
+const results = () => new VerifyCheckResultModel(serverDB, userId);
+const evidence = () => new VerifyEvidenceModel(serverDB, userId);
+
+beforeEach(async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await new AgentOperationModel(serverDB, userId).recordStart({ operationId: sourceOperationId });
+ await new AgentOperationModel(serverDB, userId).recordStart({ operationId: repairOperationId });
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(eq(users.id, userId));
+});
+
+/**
+ * The production shape that looped T-776: round N passed two checks and
+ * failed one, the repair turn only evidenced the failed one, and every
+ * repair round then re-gated the two passing checks on zero evidence.
+ */
+describe('repair round carry-forward (database)', () => {
+ it('keeps passed checks and their evidence, and judges only the repaired check', async () => {
+ const source = await runs().ensureForOperation(sourceOperationId);
+ await runs().setPlan(source.id, plan);
+ await runs().confirmPlan(source.id);
+ for (const [item, verdict] of [
+ [plan[0], 'passed'],
+ [plan[1], 'failed'],
+ [plan[2], 'passed'],
+ ] as const) {
+ const result = await results().upsertByCheckItem({
+ checkItemId: item.id,
+ checkItemIndex: item.index,
+ checkItemTitle: item.title,
+ completedAt: new Date(),
+ status: verdict,
+ toulmin: { reasoning: `${item.title} judged ${verdict}` },
+ verdict,
+ verifierType: 'agent',
+ verifyRunId: source.id,
+ });
+ await evidence().createMany([
+ {
+ capturedAt: new Date(),
+ capturedBy: 'cli',
+ checkResultId: result.id,
+ content: `${item.id} evidence`,
+ description: `${item.id} caption`,
+ documentId: null,
+ fileId: null,
+ metadata: null,
+ type: 'text',
+ },
+ ]);
+ }
+
+ // What prepareRepairRound does for the repair operation.
+ const repair = await runs().ensureForOperation(repairOperationId);
+ await runs().setPlan(repair.id, plan);
+ await runs().confirmPlan(repair.id);
+ const carried = await carryPassedResultsForward(serverDB, userId, {
+ excludeItemIds: ['reader'],
+ operationId: repairOperationId,
+ plan,
+ sourceRoundIndex: 1,
+ sourceRunId: source.id,
+ targetRunId: repair.id,
+ });
+ expect(carried).toEqual(['list', 'keys']);
+
+ // The repair turn evidences only the check it was asked to fix.
+ const reader = await results().upsertByCheckItem({
+ checkItemId: 'reader',
+ checkItemIndex: 1,
+ checkItemTitle: 'Reader migrated',
+ verifierType: 'agent',
+ verifyRunId: repair.id,
+ });
+ await evidence().createMany([
+ {
+ capturedAt: new Date(),
+ capturedBy: 'cli',
+ checkResultId: reader.id,
+ content: 'reader fix evidence',
+ description: 'reader fixed',
+ documentId: null,
+ fileId: null,
+ metadata: null,
+ type: 'text',
+ },
+ ]);
+
+ const runVerifierAgent = vi.fn().mockResolvedValue({ verifierOperationId: null });
+ await new VerifyExecutorService(serverDB, userId).execute({
+ deliverable: 'Fixed the reader. No other code changed this round.',
+ goal: 'migrate agent documents to replica',
+ modelConfig: { model: 'gpt-4o-mini', provider: 'openai' },
+ operationId: repairOperationId,
+ runVerifierAgent,
+ });
+
+ // Only the repaired check reaches a verifier.
+ expect(runVerifierAgent).toHaveBeenCalledTimes(1);
+ expect(runVerifierAgent.mock.calls[0][0].checkItem.id).toBe('reader');
+
+ const repaired = await results().listByRun(repair.id);
+ const byItem = Object.fromEntries(repaired.map((row) => [row.checkItemId, row]));
+ for (const id of ['list', 'keys']) {
+ expect(byItem[id]).toMatchObject({ status: 'passed', verdict: 'passed' });
+ expect(byItem[id].metadata).toMatchObject({
+ carriedFrom: { roundIndex: 1, verifyRunId: source.id },
+ });
+ expect(byItem[id].toulmin?.reasoning).toContain('judged passed');
+ }
+
+ // The carried checks hold the earlier round's evidence, so the Goal review
+ // and the acceptance page still read a real artifact for each of them.
+ const repairEvidence = await evidence().listByRun(repair.id);
+ expect(
+ repairEvidence
+ .map((row) => [row.checkItemId, row.content])
+ .sort(([a], [b]) => a.localeCompare(b)),
+ ).toEqual([
+ ['keys', 'keys evidence'],
+ ['list', 'list evidence'],
+ ['reader', 'reader fix evidence'],
+ ]);
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/carryForward.test.ts b/apps/server/src/services/verify/__tests__/carryForward.test.ts
new file mode 100644
index 00000000000..31924c1c4ec
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/carryForward.test.ts
@@ -0,0 +1,152 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { carryPassedResultsForward, settledCarriedItemIds } from '../carryForward';
+
+const mocks = vi.hoisted(() => ({
+ evidenceCreateMany: vi.fn(),
+ evidenceListByCheckResult: vi.fn(),
+ resultListByRun: vi.fn(),
+ resultUpsert: vi.fn(),
+}));
+
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function () {
+ return { listByRun: mocks.resultListByRun, upsertByCheckItem: mocks.resultUpsert };
+ }),
+}));
+vi.mock('@/database/models/verifyEvidence', () => ({
+ VerifyEvidenceModel: vi.fn(function () {
+ return {
+ createMany: mocks.evidenceCreateMany,
+ listByCheckResult: mocks.evidenceListByCheckResult,
+ };
+ }),
+}));
+
+const plan = [
+ { id: 'list', index: 0, required: true, title: 'List', verifierType: 'agent' },
+ { id: 'reader', index: 1, required: true, title: 'Reader', verifierType: 'agent' },
+ { id: 'keys', index: 2, required: true, title: 'Keys', verifierType: 'agent' },
+] as never;
+
+describe('carryPassedResultsForward', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.resultUpsert.mockImplementation(async (row) => ({ id: `new-${row.checkItemId}` }));
+ mocks.evidenceCreateMany.mockResolvedValue([]);
+ });
+
+ it('copies passed results and their evidence, skipping the checks under repair', async () => {
+ mocks.resultListByRun.mockResolvedValue([
+ {
+ checkItemId: 'list',
+ confidence: 0.9,
+ id: 'old-list',
+ metadata: null,
+ status: 'passed',
+ toulmin: { reasoning: 'diffs cover all five sites' },
+ verdict: 'passed',
+ },
+ { checkItemId: 'reader', id: 'old-reader', status: 'failed', verdict: 'failed' },
+ // Passed in the source round but this repair was asked to redo it.
+ { checkItemId: 'keys', id: 'old-keys', status: 'passed', verdict: 'passed' },
+ ]);
+ mocks.evidenceListByCheckResult.mockResolvedValue([
+ {
+ checkResultId: 'old-list',
+ content: 'diff',
+ createdAt: new Date(),
+ id: 'ev-1',
+ metadata: null,
+ type: 'text',
+ },
+ ]);
+
+ const carried = await carryPassedResultsForward({} as never, 'user-1', {
+ excludeItemIds: ['keys'],
+ operationId: 'repair-op',
+ plan,
+ sourceRoundIndex: 2,
+ sourceRunId: 'run-2',
+ targetRunId: 'run-3',
+ });
+
+ expect(carried).toEqual(['list']);
+ expect(mocks.resultUpsert).toHaveBeenCalledTimes(1);
+ expect(mocks.resultUpsert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ checkItemId: 'list',
+ metadata: {
+ carriedFrom: { checkResultId: 'old-list', roundIndex: 2, verifyRunId: 'run-2' },
+ },
+ operationId: 'repair-op',
+ status: 'passed',
+ toulmin: expect.objectContaining({ reasoning: 'diffs cover all five sites' }),
+ verdict: 'passed',
+ verifyRunId: 'run-3',
+ }),
+ );
+ expect(mocks.evidenceCreateMany).toHaveBeenCalledWith([
+ {
+ checkResultId: 'new-list',
+ content: 'diff',
+ metadata: { carriedFromEvidenceId: 'ev-1' },
+ type: 'text',
+ },
+ ]);
+ });
+
+ it('does not carry a result the user rejected', async () => {
+ mocks.resultListByRun.mockResolvedValue([
+ {
+ checkItemId: 'list',
+ id: 'old',
+ status: 'passed',
+ userDecision: 'rejected',
+ verdict: 'passed',
+ },
+ ]);
+
+ expect(
+ await carryPassedResultsForward({} as never, 'user-1', {
+ operationId: 'repair-op',
+ plan,
+ sourceRunId: 'run-2',
+ targetRunId: 'run-3',
+ }),
+ ).toEqual([]);
+ expect(mocks.resultUpsert).not.toHaveBeenCalled();
+ });
+});
+
+describe('settledCarriedItemIds', () => {
+ const carried = { carriedFrom: { checkResultId: 'r', roundIndex: 1, verifyRunId: 'run-1' } };
+
+ it('settles a carried check backed only by copied evidence', () => {
+ expect(
+ settledCarriedItemIds(
+ [
+ { checkItemId: 'a', metadata: carried, status: 'passed' },
+ { checkItemId: 'b', metadata: null, status: 'pending' },
+ ],
+ [
+ { checkItemId: 'a', metadata: { carriedFromEvidenceId: 'e1' } },
+ { checkItemId: 'b', metadata: null },
+ ],
+ ),
+ ).toEqual({ reopened: [], settled: new Set(['a']) });
+ });
+
+ it('reopens a carried check the builder evidenced again', () => {
+ expect(
+ settledCarriedItemIds(
+ [{ checkItemId: 'a', metadata: carried, status: 'passed' }],
+ [
+ { checkItemId: 'a', metadata: { carriedFromEvidenceId: 'e1' } },
+ { checkItemId: 'a', metadata: null },
+ ],
+ ),
+ ).toEqual({ reopened: ['a'], settled: new Set() });
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts b/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts
index 0b8a98b669b..fb784e338e5 100644
--- a/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts
+++ b/apps/server/src/services/verify/__tests__/evidenceCoverage.test.ts
@@ -57,8 +57,12 @@ describe('coverageGaps', () => {
expect(coverageGaps([{ type: 'markdown' }], [{ type: 'transcript' }])).toEqual([]);
});
+ it('accepts a GIF recording for a screenshot requirement', () => {
+ expect(coverageGaps([{ type: 'screenshot' }], [{ type: 'gif' }, { type: 'text' }])).toEqual([]);
+ });
+
it('keeps visual and structured evidence strict', () => {
- expect(coverageGaps([{ type: 'screenshot' }], [{ type: 'gif' }, { type: 'text' }])).toEqual([
+ expect(coverageGaps([{ type: 'screenshot' }], [{ type: 'video' }, { type: 'text' }])).toEqual([
'screenshot',
]);
expect(coverageGaps([{ type: 'dom_snapshot' }], [{ type: 'text' }])).toEqual(['dom_snapshot']);
diff --git a/apps/server/src/services/verify/__tests__/executor.test.ts b/apps/server/src/services/verify/__tests__/executor.test.ts
index c9ad2bca41d..0cc9ef9f698 100644
--- a/apps/server/src/services/verify/__tests__/executor.test.ts
+++ b/apps/server/src/services/verify/__tests__/executor.test.ts
@@ -95,6 +95,93 @@ describe('VerifyExecutorService', () => {
mocks.statusRecompute.mockResolvedValue('verifying');
});
+ it('leaves a check carried into a repair round alone and judges the repaired one', async () => {
+ mocks.runEnsureForOperation.mockResolvedValue({
+ id: 'run-2',
+ plan: [
+ { id: 'carried', index: 0, required: true, title: 'List', verifierType: 'agent' },
+ { id: 'repaired', index: 1, required: true, title: 'Reader', verifierType: 'agent' },
+ ],
+ planConfirmedAt: new Date(),
+ });
+ mocks.resultListByRun.mockReset().mockResolvedValue([
+ {
+ checkItemId: 'carried',
+ metadata: { carriedFrom: { checkResultId: 'r1', roundIndex: 1, verifyRunId: 'run-1' } },
+ status: 'passed',
+ },
+ ]);
+ mocks.evidenceListByRun.mockResolvedValue([
+ {
+ checkItemId: 'carried',
+ content: 'diff',
+ metadata: { carriedFromEvidenceId: 'e1' },
+ type: 'text',
+ },
+ { checkItemId: 'repaired', content: 'fix', metadata: null, type: 'text' },
+ ]);
+ const runVerifierAgent = vi.fn().mockResolvedValue({ verifierOperationId: 'verifier-op' });
+
+ await new VerifyExecutorService({} as never, 'user-1').execute({
+ deliverable: 'Fixed the reader; no other change this round.',
+ goal: 'ship it',
+ modelConfig: { model: 'model', provider: 'provider' },
+ operationId: 'repair-op',
+ runVerifierAgent,
+ });
+
+ expect(runVerifierAgent).toHaveBeenCalledTimes(1);
+ expect(runVerifierAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ checkItem: expect.objectContaining({ id: 'repaired' }) }),
+ );
+ expect(mocks.resultUpdateByCheckItem).not.toHaveBeenCalledWith(
+ 'run-2',
+ 'carried',
+ expect.anything(),
+ );
+ });
+
+ it('judges a carried check again once the builder evidences it in the repair round', async () => {
+ mocks.runEnsureForOperation.mockResolvedValue({
+ id: 'run-2',
+ plan: [{ id: 'carried', index: 0, required: true, title: 'List', verifierType: 'agent' }],
+ planConfirmedAt: new Date(),
+ });
+ mocks.resultListByRun.mockReset().mockResolvedValue([
+ {
+ checkItemId: 'carried',
+ metadata: { carriedFrom: { checkResultId: 'r1', roundIndex: 1, verifyRunId: 'run-1' } },
+ status: 'passed',
+ },
+ ]);
+ mocks.evidenceListByRun.mockResolvedValue([
+ { checkItemId: 'carried', metadata: { carriedFromEvidenceId: 'e1' }, type: 'text' },
+ { checkItemId: 'carried', content: 'new run log', metadata: null, type: 'text' },
+ ]);
+ const runVerifierAgent = vi.fn().mockResolvedValue({ verifierOperationId: 'verifier-op' });
+
+ await new VerifyExecutorService({} as never, 'user-1').execute({
+ deliverable: 'done',
+ goal: 'ship it',
+ modelConfig: { model: 'model', provider: 'provider' },
+ operationId: 'repair-op',
+ runVerifierAgent,
+ });
+
+ expect(mocks.resultUpdateByCheckItem).toHaveBeenCalledWith(
+ 'run-2',
+ 'carried',
+ expect.objectContaining({
+ metadata: { reopenedFrom: { checkResultId: 'r1', roundIndex: 1, verifyRunId: 'run-1' } },
+ status: 'pending',
+ verdict: null,
+ }),
+ );
+ expect(runVerifierAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ checkItem: expect.objectContaining({ id: 'carried' }) }),
+ );
+ });
+
it('runs a program criterion through the verifier-agent fallback', async () => {
mocks.runEnsureForOperation.mockResolvedValue({
id: 'run-1',
diff --git a/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts b/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts
index 0436a1894fc..6a52cd4367b 100644
--- a/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts
+++ b/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts
@@ -1,5 +1,6 @@
// @vitest-environment node
import { REVIEW_PREDICT_PROMPT_VERSION } from '@lobechat/prompts';
+import sharp from 'sharp';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { LobeChatDatabase } from '@/database/type';
@@ -216,6 +217,89 @@ describe('Goal review evidence', () => {
* Regression: the inline ceiling was per frame only, so a gate review carrying
* twelve large frames could build a request body far past provider limits.
*/
+ it('keeps regions drawn on a GIF frame sheet off the original animation', async () => {
+ mocks.evidence.mockResolvedValue([
+ { fileId: 'f-gif', id: 'g1', type: 'gif' },
+ { fileId: 'f-png', id: 's1', type: 'screenshot' },
+ ]);
+ const frames = await Promise.all(
+ ['#ff0000', '#0000ff'].map((background) =>
+ sharp({ create: { background, channels: 3, height: 8, width: 8 } })
+ .png()
+ .toBuffer(),
+ ),
+ );
+ const gif = await sharp(frames, { join: { animated: true } })
+ .gif()
+ .toBuffer();
+ const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47]);
+ mocks.file.mockImplementation(async (id: string) =>
+ id === 'f-gif'
+ ? { fileType: 'image/gif', id, size: gif.length, url: 'key-gif' }
+ : { fileType: 'image/png', id, size: png.length, url: 'key-png' },
+ );
+ mocks.bytes.mockImplementation(async (url: string) =>
+ url === 'key-gif' ? new Uint8Array(gif) : png,
+ );
+ const box = { height: 0.2, width: 0.2, x: 0.1, y: 0.1 };
+ mocks.generate.mockResolvedValue({
+ action: 'reject',
+ comment: 'Spinner in frame 3',
+ regions: [
+ { ...box, comment: 'on the sheet', imageIndex: 0 },
+ { ...box, comment: 'on the screenshot', imageIndex: 1 },
+ ],
+ });
+
+ await review().predict(params);
+
+ const payload = JSON.stringify(mocks.generate.mock.calls[0][0].messages);
+ expect(payload).not.toContain('data:image/gif');
+ expect(payload).toContain('frames in playback order');
+ expect(mocks.upsert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ annotations: [{ comment: 'on the screenshot', evidenceId: 's1', rect: box }],
+ comment: 'Spinner in frame 3',
+ }),
+ );
+ });
+
+ it('still sends a GIF as a sheet after the inline budget is spent', async () => {
+ const big = 5 * 1024 * 1024;
+ const frames = await Promise.all(
+ ['#ff0000', '#0000ff'].map((background) =>
+ sharp({ create: { background, channels: 3, height: 8, width: 8 } })
+ .png()
+ .toBuffer(),
+ ),
+ );
+ const gif = await sharp(frames, { join: { animated: true } })
+ .gif()
+ .toBuffer();
+ // Three 5 MiB screenshots spend the whole 15 MiB budget before the GIF.
+ mocks.evidence.mockResolvedValue([
+ ...['s1', 's2', 's3'].map((id) => ({ fileId: id, id, type: 'screenshot' })),
+ { fileId: 'f-gif', id: 'g1', type: 'gif' },
+ ]);
+ mocks.file.mockImplementation(async (id: string) =>
+ id === 'f-gif'
+ ? { fileType: 'image/gif', id, size: gif.length, url: 'key-gif' }
+ : { fileType: 'image/png', id, size: big, url: `key-${id}` },
+ );
+ mocks.bytes.mockImplementation(async (url: string) =>
+ url === 'key-gif' ? new Uint8Array(gif) : new Uint8Array([0x89, 0x50, 0x4e, 0x47]),
+ );
+ mocks.url.mockImplementation(async ({ id }: { id: string }) => `https://x/${id}`);
+
+ await review().predict({ ...params, maxVisuals: GATE_REVIEW_MAX_VISUALS });
+
+ const payload = JSON.stringify(mocks.generate.mock.calls[0][0].messages);
+ // The sheet is budgeted first, so the last screenshot is the one linked.
+ expect(payload).toContain('https://x/s3');
+ expect(payload).not.toContain('https://x/f-gif');
+ expect(payload).toContain('frames in playback order');
+ });
+
it('links the frames past the per-request inline budget', async () => {
const size = 4 * 1024 * 1024;
const ids = ['s1', 's2', 's3', 's4', 's5'];
diff --git a/apps/server/src/services/verify/__tests__/judgePrompt.test.ts b/apps/server/src/services/verify/__tests__/judgePrompt.test.ts
index 8f73146f12e..936b77134e6 100644
--- a/apps/server/src/services/verify/__tests__/judgePrompt.test.ts
+++ b/apps/server/src/services/verify/__tests__/judgePrompt.test.ts
@@ -3,7 +3,20 @@ import { describe, expect, it } from 'vitest';
describe('buildJudgePrompt evidence injection', () => {
it('partitions traces with the current evidence-policy prompt version', () => {
- expect(VERIFY_JUDGE_PROMPT_VERSION).toBe('v2');
+ expect(VERIFY_JUDGE_PROMPT_VERSION).toBe('v3');
+ });
+
+ it('does not let a round-delta reply stand in for missing work', () => {
+ const { messages } = chainVerifyJudge({
+ deliverable: 'Round 3: no code changed, re-uploaded the screenshot.',
+ goal: 'ship it',
+ items: [{ id: 'item-1', title: 'Home renders' }],
+ mode: 'single',
+ });
+
+ expect(messages[0].content).toContain(
+ 'A statement that a round made no code change is not evidence that the work is missing',
+ );
});
it('inlines text evidence and references stored artifacts under the criterion', () => {
diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
index 97424919f78..d0d2f629cf7 100644
--- a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
@@ -15,6 +15,7 @@ const {
finalizeVerifyRun,
recordHeterogeneousDeliverableEvidence,
resolveTaskAcceptance,
+ resultListByRun,
startEvidenceSubmission,
updateStatus,
} = vi.hoisted(() => ({
@@ -28,6 +29,7 @@ const {
operationFindById: vi.fn(),
recordHeterogeneousDeliverableEvidence: vi.fn(),
resolveTaskAcceptance: vi.fn(),
+ resultListByRun: vi.fn(),
startEvidenceSubmission: vi.fn(),
updateStatus: vi.fn(),
}));
@@ -51,6 +53,11 @@ vi.mock('@/database/models/verifyEvidence', () => ({
return { listByRun: evidenceListByRun };
}),
}));
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function () {
+ return { listByRun: resultListByRun };
+ }),
+}));
vi.mock('@/database/models/document', () => ({
DocumentModel: vi.fn(function () {
return {};
@@ -112,9 +119,11 @@ describe('runVerifyOnCompletion β€” verification claim', () => {
operationFindById,
recordHeterogeneousDeliverableEvidence,
resolveTaskAcceptance,
+ resultListByRun,
startEvidenceSubmission,
updateStatus,
].forEach((m) => m.mockReset());
+ resultListByRun.mockResolvedValue([]);
resolveTaskAcceptance.mockResolvedValue({
acceptance: { id: 'acceptance-1' },
config: { enabled: true },
@@ -157,6 +166,43 @@ describe('runVerifyOnCompletion β€” verification claim', () => {
expect(execute).not.toHaveBeenCalled();
});
+ it("leaves carried checks out of a repair round's evidence turn", async () => {
+ // Fresh rows on a carried check reopen it, so asking for them would re-judge
+ // every carried check on the repair turn's own delta reply.
+ findByOperation.mockResolvedValue({
+ ...confirmedRun,
+ plan: [
+ { id: 'carried', required: true },
+ { id: 'repaired', required: true },
+ ],
+ });
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ resultListByRun.mockResolvedValue([
+ {
+ checkItemId: 'carried',
+ metadata: { carriedFrom: { checkResultId: 'r', roundIndex: 1, verifyRunId: 'run-0' } },
+ status: 'passed',
+ },
+ ]);
+ evidenceListByRun.mockResolvedValue([
+ { checkItemId: 'carried', metadata: { carriedFromEvidenceId: 'e1' }, type: 'text' },
+ ]);
+ claimEvidenceCollection.mockResolvedValue(true);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(startEvidenceSubmission).toHaveBeenCalledWith(
+ expect.objectContaining({ plan: [{ id: 'repaired', required: true }] }),
+ );
+ });
+
it('still collects when a criterion is missing a declared evidence type', async () => {
findByOperation.mockResolvedValue({
...confirmedRun,
diff --git a/apps/server/src/services/verify/__tests__/modelFrames.test.ts b/apps/server/src/services/verify/__tests__/modelFrames.test.ts
new file mode 100644
index 00000000000..1b5c786e0fc
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/modelFrames.test.ts
@@ -0,0 +1,119 @@
+import sharp from 'sharp';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { FileService } from '@/server/services/file';
+
+import {
+ isGifFrameSheet,
+ MAX_INLINE_FRAME_BYTES,
+ renderGifFrameSheet,
+ resolveModelReadableFrameUrl,
+} from '../modelFrames';
+
+const FRAME = 40;
+const COLORS = [
+ [255, 0, 0],
+ [0, 255, 0],
+ [0, 0, 255],
+ [255, 255, 0],
+];
+
+/** A 40Γ—40 animated GIF whose frames are solid red, green, blue, yellow. */
+const animatedGif = async () => {
+ const frames = await Promise.all(
+ COLORS.map(([r, g, b]) =>
+ sharp({ create: { background: { b, g, r }, channels: 3, height: FRAME, width: FRAME } })
+ .png()
+ .toBuffer(),
+ ),
+ );
+ return sharp(frames, { join: { animated: true } })
+ .gif({ delay: COLORS.map(() => 100), loop: 0 })
+ .toBuffer();
+};
+
+const pixel = async (png: Buffer, x: number, y: number) => {
+ const { data, info } = await sharp(png).raw().toBuffer({ resolveWithObject: true });
+ const offset = (y * info.width + x) * info.channels;
+ return [data[offset], data[offset + 1], data[offset + 2]];
+};
+
+describe('renderGifFrameSheet', () => {
+ it('lays every frame of an animated GIF out on one PNG, in playback order', async () => {
+ const gif = await animatedGif();
+ expect((await sharp(gif).metadata()).pages).toBe(COLORS.length);
+
+ const sheet = await renderGifFrameSheet(gif);
+ expect(sheet).toBeDefined();
+
+ const meta = await sharp(sheet!).metadata();
+ expect(meta.format).toBe('png');
+ // Four frames β†’ a 2Γ—2 grid with an 8px gap.
+ expect(meta.width).toBe(FRAME * 2 + 8);
+ expect(meta.height).toBe(FRAME * 2 + 8);
+
+ const centre = FRAME / 2;
+ const step = FRAME + 8;
+ const sampled = await Promise.all([
+ pixel(sheet!, centre, centre),
+ pixel(sheet!, step + centre, centre),
+ pixel(sheet!, centre, step + centre),
+ pixel(sheet!, step + centre, step + centre),
+ ]);
+ sampled.forEach((rgb, index) => {
+ rgb.forEach((channel, c) => expect(Math.abs(channel - COLORS[index][c])).toBeLessThan(40));
+ });
+ });
+});
+
+describe('resolveModelReadableFrameUrl', () => {
+ const fileServiceFor = (bytes: Uint8Array) =>
+ ({
+ getFileAccessUrl: vi.fn(async () => 'https://files.example/frame'),
+ getFileByteArray: vi.fn(async () => bytes),
+ }) as unknown as FileService;
+
+ it('sends a GIF as a PNG frame sheet instead of the raw animation', async () => {
+ const gif = await animatedGif();
+ const url = await resolveModelReadableFrameUrl(fileServiceFor(gif), {
+ fileType: 'image/gif',
+ id: 'file_gif',
+ size: gif.length,
+ url: 'files/recording.gif',
+ });
+
+ expect(url.startsWith('data:image/png;base64,')).toBe(true);
+ expect(isGifFrameSheet('gif', url)).toBe(true);
+ });
+
+ it('still sends a GIF as a sheet when it is past the inline limits', async () => {
+ const gif = await animatedGif();
+ const fileService = fileServiceFor(gif);
+ const url = await resolveModelReadableFrameUrl(
+ fileService,
+ // Larger than one inline frame, and the request's budget is already spent.
+ { fileType: 'image/gif', id: 'file_big', size: MAX_INLINE_FRAME_BYTES + 1, url: 'big.gif' },
+ false,
+ );
+
+ expect(isGifFrameSheet('gif', url)).toBe(true);
+ expect(fileService.getFileAccessUrl).not.toHaveBeenCalled();
+ });
+
+ it('keeps a PNG screenshot as-is', async () => {
+ const png = await sharp({
+ create: { background: '#ff0000', channels: 3, height: 4, width: 4 },
+ })
+ .png()
+ .toBuffer();
+ const url = await resolveModelReadableFrameUrl(fileServiceFor(png), {
+ fileType: 'image/png',
+ id: 'file_png',
+ size: png.length,
+ url: 'files/shot.png',
+ });
+
+ expect(url).toBe(`data:image/png;base64,${png.toString('base64')}`);
+ expect(isGifFrameSheet('screenshot', url)).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/verify/carryForward.ts b/apps/server/src/services/verify/carryForward.ts
new file mode 100644
index 00000000000..ee90201c09f
--- /dev/null
+++ b/apps/server/src/services/verify/carryForward.ts
@@ -0,0 +1,133 @@
+import type { VerifyCheckItem } from '@lobechat/types';
+
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
+import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+
+/** Where a carried result came from, stored under `metadata.carriedFrom`. */
+export interface CarriedFromMetadata {
+ checkResultId: string;
+ roundIndex: number | null;
+ verifyRunId: string;
+}
+
+const EVIDENCE_CARRY_KEY = 'carriedFromEvidenceId';
+
+export const readCarriedFrom = (
+ result: Pick<VerifyCheckResultItem, 'metadata'>,
+): CarriedFromMetadata | undefined =>
+ (result.metadata as { carriedFrom?: CarriedFromMetadata } | null)?.carriedFrom;
+
+const isCarriedEvidence = (row: { metadata?: unknown }): boolean =>
+ Boolean((row.metadata as Record<string, unknown> | null)?.[EVIDENCE_CARRY_KEY]);
+
+/**
+ * A repair round re-runs the checks it was asked to fix; the checks that
+ * already passed are not its job. They used to be planned, gated and judged
+ * again anyway, with only what the repair turn happened to capture β€” which is
+ * evidence for the failed checks β€” so a passing check landed at the structural
+ * gate with nothing, or in front of a verifier reading "no code changed this
+ * round", and the round failed on work an earlier round had already proven.
+ * Each repair then broke a different check, and the loop ran until its budget.
+ *
+ * Copy every passed result of the source round, with its evidence, into the
+ * repair round instead. The repair round still holds a complete, judged
+ * checklist, so its rollup, the acceptance union and the Goal review all read
+ * real evidence for every check.
+ */
+export const carryPassedResultsForward = async (
+ db: LobeChatDatabase,
+ userId: string,
+ params: {
+ excludeItemIds?: Iterable<string>;
+ operationId: string;
+ plan: VerifyCheckItem[];
+ sourceRoundIndex?: number | null;
+ sourceRunId: string;
+ targetRunId: string;
+ },
+ workspaceId?: string,
+): Promise<string[]> => {
+ const resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
+ const evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
+ const excluded = new Set(params.excludeItemIds);
+ const planned = new Map(params.plan.map((item) => [item.id, item]));
+
+ const sourceResults = await resultModel.listByRun(params.sourceRunId);
+ const carried: string[] = [];
+ for (const source of sourceResults) {
+ const item = planned.get(source.checkItemId);
+ if (!item || excluded.has(item.id)) continue;
+ if (source.status !== 'passed' || source.verdict !== 'passed') continue;
+ if (source.userDecision === 'rejected') continue;
+
+ const carriedFrom: CarriedFromMetadata = {
+ checkResultId: source.id,
+ roundIndex: params.sourceRoundIndex ?? null,
+ verifyRunId: params.sourceRunId,
+ };
+ const result = await resultModel.upsertByCheckItem({
+ checkItemId: item.id,
+ checkItemIndex: item.index,
+ checkItemTitle: item.title,
+ completedAt: new Date(),
+ confidence: source.confidence,
+ metadata: { ...source.metadata, carriedFrom },
+ operationId: params.operationId,
+ required: item.required,
+ startedAt: source.startedAt,
+ status: 'passed',
+ toulmin: {
+ ...source.toulmin,
+ limitation: [
+ source.toulmin?.limitation,
+ `Carried forward from round ${params.sourceRoundIndex ?? '?'}: this repair round was not asked to change it.`,
+ ]
+ .filter(Boolean)
+ .join(' '),
+ },
+ verdict: 'passed',
+ verifierType: item.verifierType,
+ verifyRunId: params.targetRunId,
+ });
+
+ const evidence = await evidenceModel.listByCheckResult(source.id);
+ await evidenceModel.createMany(
+ evidence.map(({ id, createdAt: _createdAt, ...row }) => ({
+ ...row,
+ checkResultId: result.id,
+ metadata: {
+ ...(row.metadata as Record<string, unknown> | null),
+ [EVIDENCE_CARRY_KEY]: id,
+ },
+ })),
+ );
+ carried.push(item.id);
+ }
+ return carried;
+};
+
+/**
+ * The carried results the executor should leave alone: still passed, and
+ * backed only by the evidence copied from the earlier round. A carried check
+ * the builder evidenced again in this round is judged again β€” the new artifact
+ * may show a regression the copied verdict cannot know about.
+ */
+export const settledCarriedItemIds = (
+ results: Pick<VerifyCheckResultItem, 'checkItemId' | 'metadata' | 'status'>[],
+ evidence: { checkItemId: string; metadata?: unknown }[],
+): { reopened: string[]; settled: Set<string> } => {
+ const fresh = new Set(
+ evidence.filter((row) => !isCarriedEvidence(row)).map((row) => row.checkItemId),
+ );
+ const settled = new Set<string>();
+ const reopened: string[] = [];
+ for (const result of results) {
+ if (!readCarriedFrom(result)) continue;
+ if (result.status === 'passed' && !fresh.has(result.checkItemId)) {
+ settled.add(result.checkItemId);
+ } else reopened.push(result.checkItemId);
+ }
+ return { reopened, settled };
+};
diff --git a/apps/server/src/services/verify/evidenceCoverage.ts b/apps/server/src/services/verify/evidenceCoverage.ts
index 8cd4fb0a114..4edb12c22cd 100644
--- a/apps/server/src/services/verify/evidenceCoverage.ts
+++ b/apps/server/src/services/verify/evidenceCoverage.ts
@@ -18,11 +18,16 @@ export const readRequiredEvidence = (
* 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.
+ * A GIF is a run of screenshots, and judges receive it as a frame sheet (see
+ * `renderGifFrameSheet`), so it also answers a `screenshot` requirement β€” a GIF
+ * uploaded as `screenshot` is stored as `gif`, which otherwise failed the gate
+ * on the very artifact it asked for. `dom_snapshot` and `audio` have no
+ * substitute.
*/
const SATISFIED_BY: Partial<Record<VerifyEvidenceType, VerifyEvidenceType[]>> = {
gif: ['video'],
markdown: ['text', 'transcript'],
+ screenshot: ['gif'],
text: ['markdown', 'transcript'],
transcript: ['text', 'markdown'],
video: ['gif'],
diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.ts
index ffdd695fda3..bc80fcb6d7e 100644
--- a/apps/server/src/services/verify/executor.ts
+++ b/apps/server/src/services/verify/executor.ts
@@ -29,9 +29,10 @@ import type { LobeChatDatabase } from '@/database/type';
import { AiGenerationService } from '@/server/services/aiGeneration';
import { FileService } from '@/server/services/file';
+import { settledCarriedItemIds } from './carryForward';
import { runEvidenceGaps } from './evidenceCoverage';
import { planEvidenceVerification } from './evidencePlanner';
-import { resolveModelReadableFrameUrl } from './modelFrames';
+import { GIF_FRAME_SHEET_NOTE, isGifFrameSheet, resolveModelReadableFrameUrl } from './modelFrames';
import { planItemToPendingResult } from './resultSnapshot';
import { BatchVerdictSchema, type SingleVerdict, SingleVerdictSchema } from './schema';
import { VerifyStatusService } from './statusService';
@@ -141,13 +142,13 @@ export class VerifyExecutorService {
}
const verifyRunId = run.id;
- const items = run.plan as VerifyCheckItem[];
+ const plan = run.plan as VerifyCheckItem[];
// 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 = items
+ const toCreate = plan
.filter((i) => !existingIds.has(i.id))
.map((item) => planItemToPendingResult(verifyRunId, params.operationId, item));
if (toCreate.length > 0) await this.resultModel.createMany(toCreate);
@@ -156,7 +157,24 @@ export class VerifyExecutorService {
// Load run-captured evidence once, grouped by plan item β€” feeds both the
// structural gate and the LLM judge.
- const evidenceByItem = await this.loadEvidence(verifyRunId);
+ const evidenceRows = await this.evidenceModel.listByRun(verifyRunId);
+ const evidenceByItem = await this.loadEvidence(evidenceRows);
+
+ // A repair round carries the checks it was not asked to fix (see
+ // carryPassedResultsForward). Those keep their copied verdict; one the
+ // builder evidenced again is judged again on old and new evidence together.
+ const { reopened, settled } = settledCarriedItemIds(existing, evidenceRows);
+ for (const checkItemId of reopened) {
+ const result = existing.find((row) => row.checkItemId === checkItemId);
+ const { carriedFrom, ...metadata } = (result?.metadata ?? {}) as Record<string, unknown>;
+ await this.resultModel.updateByCheckItem(verifyRunId, checkItemId, {
+ completedAt: null,
+ metadata: { ...metadata, reopenedFrom: carriedFrom },
+ status: 'pending',
+ verdict: null,
+ });
+ }
+ const items = plan.filter((item) => !settled.has(item.id));
// Structural gate (server, no LLM): an evidence-driven item missing any of
// its declared evidence types is marked uncertain up front and excluded from
@@ -207,9 +225,10 @@ export class VerifyExecutorService {
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);
+ /** Group a run's evidence rows by the plan item id they back. */
+ private async loadEvidence(
+ rows: Awaited<ReturnType<VerifyEvidenceModel['listByRun']>>,
+ ): Promise<EvidenceByItem> {
const documentIds = [
...new Set(rows.flatMap((row) => (row.documentId ? [row.documentId] : []))),
];
@@ -236,7 +255,14 @@ export class VerifyExecutorService {
if (!item.fileId || (item.type !== 'screenshot' && item.type !== 'gif')) return item;
const file = await this.fileModel.findById(item.fileId);
if (!file) return item;
- return { ...item, accessUrl: await resolveModelReadableFrameUrl(this.fileService, file) };
+ const accessUrl = await resolveModelReadableFrameUrl(this.fileService, file);
+ return {
+ ...item,
+ accessUrl,
+ description: isGifFrameSheet(item.type, accessUrl)
+ ? [item.description, GIF_FRAME_SHEET_NOTE].filter(Boolean).join(' ')
+ : item.description,
+ };
}),
);
}
diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.ts
index 7a596aafaae..d2a9b4b4a1d 100644
--- a/apps/server/src/services/verify/lifecycle.ts
+++ b/apps/server/src/services/verify/lifecycle.ts
@@ -5,11 +5,13 @@ import debug from 'debug';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { DocumentModel } from '@/database/models/document';
import { TaskModel } from '@/database/models/task';
+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 { createVerifierAgentRunner } from './agentVerifier';
+import { settledCarriedItemIds } from './carryForward';
import { runEvidenceGaps } from './evidenceCoverage';
import {
recordHeterogeneousDeliverableEvidence,
@@ -197,12 +199,20 @@ const executeVerifyLifecycle = async (
});
evidenceSubmitted = true;
} else {
+ // A repair round's carried checks already hold their evidence. Asking
+ // the evidence turn for them anyway would add fresh rows, which reopen
+ // and re-judge every carried check on the repair's own delta reply.
+ const [runResults, runEvidence] = await Promise.all([
+ new VerifyCheckResultModel(db, userId, workspaceId).listByRun(run.id),
+ new VerifyEvidenceModel(db, userId, workspaceId).listByRun(run.id),
+ ]);
+ const { settled } = settledCarriedItemIds(runResults, runEvidence);
await startEvidenceSubmission({
db,
deliverable: params.deliverable,
goal: params.goal,
operation: op,
- plan,
+ plan: plan.filter((item) => !settled.has(item.id)),
userId,
workspaceId,
});
diff --git a/apps/server/src/services/verify/modelFrames.ts b/apps/server/src/services/verify/modelFrames.ts
index 4d15ba8476e..732a44be798 100644
--- a/apps/server/src/services/verify/modelFrames.ts
+++ b/apps/server/src/services/verify/modelFrames.ts
@@ -1,4 +1,6 @@
import debug from 'debug';
+import pMap from 'p-map';
+import sharp from 'sharp';
import type { FileService } from '@/server/services/file';
@@ -44,6 +46,101 @@ const sniffImageMimeType = (bytes: Uint8Array): string | undefined => {
return 'image/webp';
};
+/** Frames sampled from an animated GIF into one sheet. */
+const GIF_SHEET_MAX_FRAMES = 9;
+/** Tile width on a multi-frame sheet; a 3Γ—3 sheet stays under ~1.5k px wide. */
+const GIF_SHEET_TILE_WIDTH = 480;
+const GIF_SHEET_GAP = 8;
+const GIF_SHEET_DECODE_CONCURRENCY = 3;
+
+/**
+ * Caption suffix for a GIF the model receives as a frame sheet, so it reads the
+ * grid as a timeline rather than as one busy screenshot.
+ */
+export const GIF_FRAME_SHEET_NOTE =
+ 'Animated recording shown as evenly spaced frames in playback order, left to right, top to bottom.';
+
+/**
+ * Ceiling on a GIF read to build its sheet. The source is only decoded, never
+ * sent, so it is not bound by the inline limits; this only keeps one huge
+ * recording from being pulled into memory.
+ */
+export const MAX_GIF_SOURCE_BYTES = 64 * 1024 * 1024;
+/** Past this a PNG sheet is re-encoded as JPEG, keeping each sheet small to inline. */
+const MAX_GIF_SHEET_PNG_BYTES = 1024 * 1024;
+
+export const isGifStoredFrame = (file: { fileType?: string | null }): boolean =>
+ file.fileType?.toLowerCase() === 'image/gif';
+
+/** Whether a frame URL is the sheet a GIF artifact was rendered into. */
+export const isGifFrameSheet = (type: string, url: string): boolean =>
+ type === 'gif' && /^data:image\/(?:png|jpeg);/.test(url);
+
+/** Bytes a data-URI frame adds to a request once decoded; 0 for a link. */
+export const inlinedFrameBytes = (url: string): number =>
+ url.startsWith('data:') ? Math.floor(((url.length - url.indexOf(',') - 1) * 3) / 4) : 0;
+
+/**
+ * Render a GIF as a PNG sheet of evenly spaced frames.
+ *
+ * Vision models cannot read an animated GIF: some providers reject the format
+ * outright and the rest look at the first frame only. A cold-start recording's
+ * first frame is the browser unloading, so a reviewer handed the raw GIF
+ * reported "no recording attached" and sent a passing delivery back for
+ * another round. A sheet shows the whole recording in one image every vision
+ * model accepts.
+ */
+export const renderGifFrameSheet = async (bytes: Uint8Array): Promise<Buffer | undefined> => {
+ const { height, pageHeight, pages = 1, width } = await sharp(bytes).metadata();
+ const frameHeight = pageHeight ?? height;
+ if (!width || !frameHeight) return;
+
+ const count = Math.min(Math.max(pages, 1), GIF_SHEET_MAX_FRAMES);
+ const indices =
+ count === 1
+ ? [0]
+ : Array.from({ length: count }, (_, i) => Math.round((i * (pages - 1)) / (count - 1)));
+ const tileWidth = count === 1 ? width : Math.min(width, GIF_SHEET_TILE_WIDTH);
+ const tileHeight = Math.max(1, Math.round((frameHeight * tileWidth) / width));
+ const columns = Math.ceil(Math.sqrt(count));
+ const rows = Math.ceil(count / columns);
+
+ // Each tile decodes the whole GIF, so keep only a few in flight at once.
+ const tiles = await pMap(
+ indices,
+ (page) =>
+ sharp(bytes, { page }).resize(tileWidth, tileHeight, { fit: 'fill' }).png().toBuffer(),
+ { concurrency: GIF_SHEET_DECODE_CONCURRENCY },
+ );
+
+ return sharp({
+ create: {
+ background: '#ffffff',
+ channels: 3,
+ height: rows * tileHeight + (rows - 1) * GIF_SHEET_GAP,
+ width: columns * tileWidth + (columns - 1) * GIF_SHEET_GAP,
+ },
+ })
+ .composite(
+ tiles.map((input, index) => ({
+ input,
+ left: (index % columns) * (tileWidth + GIF_SHEET_GAP),
+ top: Math.floor(index / columns) * (tileHeight + GIF_SHEET_GAP),
+ })),
+ )
+ .png()
+ .toBuffer();
+};
+
+const sheetDataUri = async (bytes: Uint8Array): Promise<string | undefined> => {
+ const sheet = await renderGifFrameSheet(bytes);
+ if (!sheet) return;
+ if (sheet.length <= MAX_GIF_SHEET_PNG_BYTES)
+ return `data:image/png;base64,${sheet.toString('base64')}`;
+ const jpeg = await sharp(sheet).jpeg({ quality: 80 }).toBuffer();
+ return `data:image/jpeg;base64,${jpeg.toString('base64')}`;
+};
+
/**
* The URL a judging model is given for a stored evidence frame.
*
@@ -53,6 +150,11 @@ const sniffImageMimeType = (bytes: Uint8Array): string | undefined => {
* from the provider, and the model call fails with "Error while downloading
* file" on every attempt, however many times the review is retried.
*
+ * A GIF is always sent as a frame sheet (see {@link renderGifFrameSheet}),
+ * whatever its size or the remaining inline budget: a linked GIF is no fallback,
+ * because an adapter that downloads it still drops `image/gif`. The sheet is
+ * what spends the budget, not the recording it came from.
+ *
* Falls back to the access URL when the frame is too large to inline, is not a
* recognizable image, or cannot be read.
*/
@@ -62,12 +164,28 @@ export const resolveModelReadableFrameUrl = async (
/** False once the request's inline budget is spent: link the frame instead. */
inline = true,
): Promise<string> => {
+ if (
+ isGifStoredFrame(file) &&
+ typeof file.size === 'number' &&
+ file.size <= MAX_GIF_SOURCE_BYTES
+ ) {
+ try {
+ const sheet = await sheetDataUri(await fileService.getFileByteArray(file.url));
+ if (sheet) return sheet;
+ } catch (error) {
+ log('could not render GIF %s as a frame sheet: %O', file.id, error);
+ }
+ }
if (inline && isInlineableFrameSize(file.size)) {
try {
const bytes = await fileService.getFileByteArray(file.url);
- const mimeType = file.fileType?.startsWith('image/')
- ? file.fileType
- : sniffImageMimeType(bytes);
+ const sniffed = sniffImageMimeType(bytes);
+ const mimeType = file.fileType?.startsWith('image/') ? file.fileType : sniffed;
+ if (sniffed === 'image/gif') {
+ // A GIF stored without its MIME type.
+ const sheet = await sheetDataUri(bytes);
+ if (sheet) return sheet;
+ }
if (mimeType) return `data:${mimeType};base64,${Buffer.from(bytes).toString('base64')}`;
} catch (error) {
log('could not inline frame %s, linking it instead: %O', file.id, error);
diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.ts
index 9a4715b76ce..66ecfcc512f 100644
--- a/apps/server/src/services/verify/repairService.ts
+++ b/apps/server/src/services/verify/repairService.ts
@@ -14,6 +14,7 @@ import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLi
import { AiAgentService } from '@/server/services/aiAgent';
import { AcceptanceService } from './acceptanceService';
+import { carryPassedResultsForward } from './carryForward';
import { settleFailedRepair } from './repairTerminal';
import { VerifyStatusService } from './statusService';
@@ -99,7 +100,7 @@ export const createRepairRunner = (params: {
params;
if (!agentId || !topicId) return undefined;
- return async ({ instruction, operationId, verifyMessageId }) => {
+ return async ({ failedItemIds, instruction, operationId, verifyMessageId }) => {
const operationModel = new AgentOperationModel(db, userId, workspaceId);
const round = await countRepairRounds(operationModel, operationId);
@@ -136,6 +137,25 @@ export const createRepairRunner = (params: {
sourceRun.acceptanceId,
);
}
+
+ // The repair is asked to fix the failed checks only, so the rest keep
+ // the verdict and evidence they already earned instead of being
+ // judged again on a turn that never touched them.
+ if (sourceRun) {
+ await carryPassedResultsForward(
+ repairDB,
+ userId,
+ {
+ excludeItemIds: failedItemIds,
+ operationId: repairOperationId,
+ plan,
+ sourceRoundIndex: sourceRun.roundIndex,
+ sourceRunId: sourceRun.id,
+ targetRunId: repairRun.id,
+ },
+ workspaceId,
+ );
+ }
}
});
} catch (error) {
@@ -266,6 +286,10 @@ const buildInstruction = (
return [
'The delivery checker found unresolved issues with the previous result. Fix only these, then stop:',
...lines,
+ '',
+ 'The checks not listed here already passed and are carried forward; do not re-submit their evidence.',
+ 'Submit fresh evidence for each check listed above to this run.',
+ 'Your final reply is read by the verifier as the deliverable: describe the complete delivery as it now stands (what is implemented, where, and the evidence for it), not only what changed in this turn.',
].join('\n');
};
diff --git a/apps/server/src/services/verify/reviewPredictor.ts b/apps/server/src/services/verify/reviewPredictor.ts
index 318b5ef118a..01618173e2f 100644
--- a/apps/server/src/services/verify/reviewPredictor.ts
+++ b/apps/server/src/services/verify/reviewPredictor.ts
@@ -9,6 +9,7 @@ import type { AcceptanceReviewAnnotation } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import { pickTrimmedString, toRecord } from '@lobechat/utils/object';
import debug from 'debug';
+import pMap from 'p-map';
import { DocumentModel } from '@/database/models/document';
import { FileModel } from '@/database/models/file';
@@ -20,6 +21,10 @@ import { AiGenerationService } from '@/server/services/aiGeneration';
import { FileService } from '@/server/services/file';
import {
+ GIF_FRAME_SHEET_NOTE,
+ inlinedFrameBytes,
+ isGifFrameSheet,
+ isGifStoredFrame,
isInlineableFrameSize,
MAX_INLINE_REQUEST_BYTES,
resolveModelReadableFrameUrl,
@@ -57,6 +62,9 @@ const MAX_VISUALS = 3;
*/
export const GATE_REVIEW_MAX_VISUALS = 12;
+/** GIF frame sheets rendered at once for one review request. */
+const GIF_SHEET_CONCURRENCY = 2;
+
/**
* How many checks may be judged at once when a whole acceptance is requested.
*
@@ -376,9 +384,21 @@ export class VerifyReviewPredictorService {
const files = await Promise.all(visual.map((row) => this.fileModel.findById(row.fileId!)));
- // Spend the request's inline budget in evidence order; later frames are
- // linked, so a many-frame check cannot push the body past provider limits.
- let inlineBytes = 0;
+ // A GIF has no usable link (adapters that download it still drop
+ // `image/gif`), so it is always rendered to a sheet and inlined. The sheets
+ // are resolved first and spend the budget at their own size; the remaining
+ // frames then spend what is left in evidence order, and later ones are
+ // linked so a many-frame check cannot push the body past provider limits.
+ // Each sheet downloads and decodes a whole recording, so only two at a time.
+ const gifSheets = await pMap(
+ files,
+ (file) =>
+ file && isGifStoredFrame(file)
+ ? resolveModelReadableFrameUrl(this.fileService, file)
+ : undefined,
+ { concurrency: GIF_SHEET_CONCURRENCY },
+ );
+ let inlineBytes = gifSheets.reduce((sum, url) => sum + (url ? inlinedFrameBytes(url) : 0), 0);
const inline = files.map((file) => {
const size = file?.size;
if (!isInlineableFrameSize(size) || inlineBytes + size > MAX_INLINE_REQUEST_BYTES)
@@ -391,17 +411,30 @@ export class VerifyReviewPredictorService {
visual.map(async (row, index) => {
const file = files[index];
if (!file) return null;
+ const accessUrl =
+ gifSheets[index] ??
+ (await resolveModelReadableFrameUrl(this.fileService, file, inline[index]));
+ const frameSheet = isGifFrameSheet(row.type, accessUrl);
return {
- accessUrl: await resolveModelReadableFrameUrl(this.fileService, file, inline[index]),
- description: row.description,
+ accessUrl,
+ description: frameSheet
+ ? [row.description, GIF_FRAME_SHEET_NOTE].filter(Boolean).join(' ')
+ : row.description,
evidenceId: row.id,
+ frameSheet,
};
}),
);
return resolved.filter(
- (item): item is { accessUrl: string; description: string | null; evidenceId: string } =>
- Boolean(item?.accessUrl),
+ (
+ item,
+ ): item is {
+ accessUrl: string;
+ description: string | null;
+ evidenceId: string;
+ frameSheet: boolean;
+ } => Boolean(item?.accessUrl),
);
}
@@ -413,14 +446,19 @@ export class VerifyReviewPredictorService {
* A region naming an image outside the attached set is dropped rather than
* clamped to image 0: a note pinned to the wrong screenshot is more misleading
* than no note, because the reviewer has no way to tell it moved.
+ *
+ * A GIF is shown to the model as a frame sheet, so a region drawn on it is in
+ * sheet coordinates. The page draws annotations over the original animation,
+ * where those coordinates land on unrelated content, so they are dropped; the
+ * comment still carries the finding.
*/
private toAnnotations(
regions: RawReviewPrediction['regions'],
- visuals: { evidenceId: string }[],
+ visuals: { evidenceId: string; frameSheet: boolean }[],
): AcceptanceReviewAnnotation[] {
return (regions ?? []).flatMap((region) => {
const target = visuals[region.imageIndex];
- if (!target) return [];
+ if (!target || target.frameSheet) return [];
return [
{
comment: region.comment ?? undefined,
diff --git a/packages/prompts/src/chains/verify.ts b/packages/prompts/src/chains/verify.ts
index 36b9ab8cbbb..7fb738b6fa9 100644
--- a/packages/prompts/src/chains/verify.ts
+++ b/packages/prompts/src/chains/verify.ts
@@ -3,7 +3,7 @@ import type { VerifyCheckItem, VerifyEvidenceType } from '@lobechat/types';
/** Bump when the plan-gen prompt meaningfully changes (tracing partition key). */
export const VERIFY_PLAN_PROMPT_VERSION = 'v3';
/** Bump when the judge prompt meaningfully changes. */
-export const VERIFY_JUDGE_PROMPT_VERSION = 'v2';
+export const VERIFY_JUDGE_PROMPT_VERSION = 'v3';
/** Bump when the report prompt meaningfully changes. */
export const VERIFY_REPORT_PROMPT_VERSION = 'v1';
/**
@@ -309,6 +309,7 @@ export const chainVerifyJudge = ({ goal, deliverable, items, mode }: JudgePrompt
'- suggestion: a concrete fix when the verdict is failed/uncertain.',
'Artifacts listed under "Evidence captured during the run" are primary Data only when their contents are attached or quoted. Never treat mere existence, a filename, or a caption as proof of what an artifact depicts.',
'Be skeptical: default to "uncertain" rather than "passed" when evidence is missing.',
+ "The deliverable may be a follow-up round's reply that only describes what that round changed. A statement that a round made no code change is not evidence that the work is missing: judge each criterion on its captured evidence, and treat the deliverable as the builder's account rather than a complete inventory.",
mode === 'batch'
? 'Return one verdict object per criterion, each tagged with its exact checkItemId.'
: 'Return a single verdict object for the one criterion below.',
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 04c95a75796..c0caeed8584 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -812,6 +812,12 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
taskLines.push(
`Goal loop${goalLoop.round ? ` β€” round ${goalLoop.round}${budget}` : ''}: earlier rounds did not fully meet the acceptance criteria. Focus on closing the gaps below instead of redoing finished work.`,
);
+ taskLines.push(
+ ' This round is verified on its own: evidence from earlier rounds does not carry over. Submit evidence to this run for every required criterion, not only the unresolved ones; re-upload an earlier artifact when it still shows the current behavior.',
+ );
+ taskLines.push(
+ ' Your final response is read as the deliverable. Describe the complete delivery as it now stands, not only what changed in this round β€” "no code changed this round" without that context reads as missing work.',
+ );
const reviewFeedback = [
goalLoop.rejectComment,
goalLoop.automaticReviewFeedback &&
diff --git a/packages/prompts/src/prompts/verify/index.ts b/packages/prompts/src/prompts/verify/index.ts
index 22ec0360ab5..2557ea469ce 100644
--- a/packages/prompts/src/prompts/verify/index.ts
+++ b/packages/prompts/src/prompts/verify/index.ts
@@ -83,7 +83,7 @@ ${deliverable}`
}
## Your task
-Investigate whether the deliverable satisfies this check, judging against the run goal and the judging instruction. Weight the captured evidence above as primary Data; gather more yourself only where it's missing or insufficient. When done, call \`submitVerifyResult\` exactly once with checkItemId="${checkItem.id}" and your verdict (passed / failed / uncertain) plus evidence and reasoning.`;
+Investigate whether the deliverable satisfies this check, judging against the run goal and the judging instruction. Weight the captured evidence above as primary Data; gather more yourself only where it's missing or insufficient. The deliverable may be a follow-up round's reply that only describes what that round changed: a statement that a round made no code change is not evidence that the work is missing, so check the work itself rather than reading it as an admission. When done, call \`submitVerifyResult\` exactly once with checkItemId="${checkItem.id}" and your verdict (passed / failed / uncertain) plus evidence and reasoning.`;
/**
* The send-back prompt for a rejected delivery. It points the agent at the CLI