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(cli): handle acceptance evidence quota failures (#19870)

AmAzing-c28d6f3213dd
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 8567432eb23..5904cd88ccf 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -30,7 +30,6 @@ the next free number of that prefix.
- **L-E6** When the Task requires a durable document, create and pin the real artifact; evidence explains a verdict, it is not the deliverable.
- **L-E9** Check the acceptance's status before ingest; new scoped work on an accepted acceptance goes to a new subject.
- **L-E10** After any Agent assignment or Task edit, verify the persisted provider/model and the first completed message's metadata before judging quality.
-- **L-E11** Reconcile the evidence count in `result.json` against the ingest JSON; any `[WARN] evidence upload failed` is a failed publish β€” republish a fresh round.
- **L-E13** Uncommitted work on a branch that owns a PR: decide provenance explicitly (open the real PR, or say in `report.md` there is none) and re-read `branch`/`commit` at publish time.
- **L-E14** After an insertion affordance, continue the user's action in the same case and assert node order in persisted `editor_data`; send the payload through the same entry point.
- **L-E15** A conversation-branch regression is verified by sending the next message through the real composer: DB row, parent on the active spine, render before and after cold reload.
@@ -155,20 +154,6 @@ fallback.
provider/model and the first completed assistant message metadata; attach the
runtime identity to the round.
-### L-E11 β€” Declaring an ingest done without reconciling its evidence count
-
-`since 2026-07-31` Β· `holds-while: ingest exits 0 after "[WARN] evidence upload failed, skipping <file>"`
-
-**Trap:** the success JSON shows an `acceptanceId` and a round index, the WARN
-above it is read as noise. One skipped half of a `comparison` pair renders alone
-β€” a lone `before` reads as "the fix never landed".
-
-**Rule:** count evidence items in `result.json` against the ingest JSON's
-`evidence` field; any WARN is a failed publish. Do not retro-attach with
-`acceptance run evidence upload` (no `comparison` metadata β†’ unpaired). Publish
-a fresh round with the complete set and say in `report.md` that it republishes
-the same observations.
-
### L-E13 β€” Publishing uncommitted work onto the branch's unrelated PR
`since 2026-08-10` Β· `holds-while: ingest resolves the PR from branch when pullRequest is absent OR null`
diff --git a/apps/cli/src/commands/acceptanceEvidence.ts b/apps/cli/src/commands/acceptanceEvidence.ts
new file mode 100644
index 00000000000..702a8575090
--- /dev/null
+++ b/apps/cli/src/commands/acceptanceEvidence.ts
@@ -0,0 +1,100 @@
+import { access } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { TrpcClient } from '../api/client';
+import { log } from '../utils/logger';
+import { uploadLocalFile } from '../utils/uploadLocalFile';
+import type { EvidenceType } from './verifyHelpers';
+import {
+ evidenceDescriptionForFile,
+ evidenceTypeForFile,
+ inlineTextEvidenceForFile,
+ reportEvidence,
+} from './verifyHelpers';
+
+export interface FailedReportEvidence {
+ checkResultId: string;
+ error: string;
+ fileId?: string;
+ path: string;
+ reason: 'file_missing' | 'storage_quota' | 'upload_failed';
+ /** Arguments for lh via a process API with shell disabled, including subcommands. */
+ retryArgs: string[];
+ retryCommand: string;
+ retryCommandShell: 'posix';
+ type: EvidenceType;
+}
+
+/** Upload and attach independently: a failed artifact must not discard the report. */
+export async function uploadReportEvidence(
+ client: TrpcClient,
+ params: { checkResultId: string; dir: string; evidence: unknown },
+) {
+ const failedEvidence: FailedReportEvidence[] = [];
+ const types = new Set<EvidenceType>();
+ let count = 0;
+ let inlined = 0;
+ for (const input of reportEvidence(params.evidence)) {
+ const absolutePath = path.resolve(params.dir, input.path);
+ const type = evidenceTypeForFile(absolutePath);
+ const description = evidenceDescriptionForFile(input.description, absolutePath);
+ const metadata = input.comparison ? { comparison: input.comparison } : undefined;
+ let fileId: string | undefined;
+ let missing = false;
+ try {
+ try {
+ await access(absolutePath);
+ } catch (error) {
+ missing = (error as NodeJS.ErrnoException).code === 'ENOENT';
+ throw error;
+ }
+ const content = inlineTextEvidenceForFile(absolutePath, type);
+ if (content === undefined) fileId = (await uploadLocalFile(client, absolutePath)).id;
+ await client.verify.uploadEvidence.mutate({
+ capturedBy: 'cli',
+ checkResultId: params.checkResultId,
+ content,
+ description,
+ fileId,
+ metadata,
+ type,
+ });
+ types.add(type);
+ count += 1;
+ if (content !== undefined) inlined += 1;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ const reason = missing
+ ? 'file_missing'
+ : message.includes('storage_block:')
+ ? 'storage_quota'
+ : 'upload_failed';
+ // Reuse an uploaded file if only attachment failed. Retrying must not
+ // consume another logical file's worth of the user's storage quota.
+ const args = [
+ '--check',
+ params.checkResultId,
+ '--type',
+ type,
+ ...(fileId ? ['--file-id', fileId] : ['--file', absolutePath]),
+ '--desc',
+ description,
+ ...(metadata ? ['--metadata', JSON.stringify(metadata)] : []),
+ ];
+ const retryCommand = `lh acceptance run evidence upload ${args.map((arg) => `'${arg.replaceAll("'", "'\\''")}'`).join(' ')}`;
+ failedEvidence.push({
+ checkResultId: params.checkResultId,
+ error: message,
+ fileId,
+ path: absolutePath,
+ reason,
+ retryArgs: ['acceptance', 'run', 'evidence', 'upload', ...args],
+ retryCommand,
+ retryCommandShell: 'posix',
+ type,
+ });
+ log.warn(`evidence not published: ${path.basename(absolutePath)}: ${message}`);
+ }
+ }
+ return { count, failedEvidence, inlined, types };
+}
diff --git a/apps/cli/src/commands/acceptanceRun.test.ts b/apps/cli/src/commands/acceptanceRun.test.ts
new file mode 100644
index 00000000000..9aeaf504c98
--- /dev/null
+++ b/apps/cli/src/commands/acceptanceRun.test.ts
@@ -0,0 +1,491 @@
+import { execFile } from 'node:child_process';
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTrpcClient } from '../api/client';
+import { log } from '../utils/logger';
+import { uploadLocalFile } from '../utils/uploadLocalFile';
+import { attachAcceptanceRunCommands } from './acceptanceRun';
+
+vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));
+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.lobehub.com' }));
+vi.mock('../utils/uploadLocalFile', () => ({ uploadLocalFile: vi.fn() }));
+
+describe('acceptance publication with missing evidence', () => {
+ const client = {
+ acceptance: {
+ attachRun: { mutate: vi.fn() },
+ ensure: { mutate: vi.fn() },
+ },
+ verify: {
+ createRun: { mutate: vi.fn() },
+ ingestResult: { mutate: vi.fn() },
+ uploadEvidence: { mutate: vi.fn() },
+ upsertReport: { mutate: vi.fn() },
+ },
+ };
+ let dir: string;
+ let printed: string[];
+ let originalExitCode: typeof process.exitCode;
+
+ beforeEach(async () => {
+ vi.resetAllMocks();
+ originalExitCode = process.exitCode;
+ process.exitCode = undefined;
+ printed = [];
+ vi.spyOn(console, 'log').mockImplementation((line) => printed.push(String(line)));
+ vi.spyOn(log, 'warn').mockImplementation(() => {});
+ vi.mocked(getTrpcClient).mockResolvedValue(
+ client as unknown as Awaited<ReturnType<typeof getTrpcClient>>,
+ );
+ vi.mocked(uploadLocalFile).mockResolvedValue({ id: 'file-1', url: 'https://files.test/1' });
+ client.acceptance.ensure.mutate.mockResolvedValue({ id: 'acceptance-1' });
+ client.acceptance.attachRun.mutate.mockResolvedValue({ id: 'run-1', roundIndex: 2 });
+ client.verify.createRun.mutate.mockResolvedValue({ id: 'run-1' });
+ client.verify.ingestResult.mutate.mockImplementation(async (input) => ({
+ id: `result-${input.checkItemId}`,
+ }));
+ client.verify.uploadEvidence.mutate.mockResolvedValue({ id: 'evidence-1' });
+ dir = await mkdtemp(path.join(tmpdir(), 'lh-evidence-'));
+ await writeFile(path.join(dir, "screen's shot.png"), 'image fixture');
+ await writeFile(path.join(dir, 'output.txt'), 'Observed the expected response.');
+ });
+
+ afterEach(async () => {
+ process.exitCode = originalExitCode;
+ vi.restoreAllMocks();
+ await rm(dir, { force: true, recursive: true });
+ });
+
+ const run = async (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ attachAcceptanceRunCommands(program.command('acceptance'));
+ await program.parseAsync(['node', 'lh', 'acceptance', 'run', ...args]);
+ };
+
+ const report = async (requiredEvidence: string[], evidence: string[], verdict = 'passed') => {
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [{ evidence, id: 'screen', name: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ', status: verdict }],
+ plan: [{ id: 'screen', requiredEvidence, title: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ' }],
+ summary: { passed: 1, total: 1, verdict },
+ title: 'ε€„η†η»“ζžœε±•η€Ί',
+ }),
+ );
+ };
+
+ const result = () => JSON.parse(printed.at(-1)!);
+ const finalCheck = () => client.verify.ingestResult.mutate.mock.calls.at(-1)![0];
+ const finalReport = () => client.verify.upsertReport.mutate.mock.calls.at(-1)![0];
+
+ it('publishes partial JSON and downgrades a pass when quota blocks required screenshots', async () => {
+ vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));
+ await report(['screenshot', 'text'], ["screen's shot.png", 'output.txt']);
+ const original = await readFile(path.join(dir, 'result.json'), 'utf8');
+
+ await run('ingest', dir, '--json');
+
+ expect(process.exitCode).toBe(1);
+ expect(result()).toMatchObject({
+ acceptanceUrl: 'https://app.lobehub.com/acceptance/acceptance-1',
+ evidence: 1,
+ failedEvidence: [
+ { checkItemId: 'screen', checkResultId: 'result-screen', reason: 'storage_quota' },
+ ],
+ inlined: 1,
+ missingEvidence: [{ checkItemId: 'screen', types: ['screenshot'] }],
+ publicationStatus: 'partial',
+ roundUrl: 'https://app.lobehub.com/acceptance/acceptance-1?r=2',
+ });
+ expect(result().failedEvidence[0].retryCommand).toContain('evidence upload');
+ expect(finalCheck()).toMatchObject({
+ verdict: 'uncertain',
+ toulmin: { limitation: expect.stringContaining('screenshot') },
+ });
+ expect(finalReport()).toMatchObject({
+ passedChecks: 0,
+ totalChecks: 1,
+ uncertainChecks: 1,
+ verdict: 'uncertain',
+ });
+ expect(await readFile(path.join(dir, 'result.json'), 'utf8')).toBe(original);
+ });
+
+ it('does not downgrade a pass when only an optional medium failed', async () => {
+ vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));
+ await report(['text'], ['output.txt', "screen's shot.png"]);
+
+ await run('ingest', dir, '--json');
+
+ expect(process.exitCode).toBe(1);
+ expect(result()).toMatchObject({ missingEvidence: [], publicationStatus: 'partial' });
+ expect(finalCheck().verdict).toBe('passed');
+ expect(finalReport().verdict).toBe('passed');
+ });
+
+ it('counts only attached evidence, but accepts another successful file of the same required type', async () => {
+ await writeFile(path.join(dir, 'second.png'), 'another image');
+ vi.mocked(uploadLocalFile).mockRejectedValueOnce(new Error('storage_block:upgrade_required'));
+ await report(['screenshot'], ["screen's shot.png", 'second.png']);
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({
+ evidence: 1,
+ missingEvidence: [],
+ publicationStatus: 'partial',
+ });
+ expect(finalCheck().verdict).toBe('passed');
+ });
+
+ it.each(['failed', 'uncertain'])(
+ 'preserves an existing %s verdict with missing evidence',
+ async (verdict) => {
+ await report(['screenshot'], ['missing.png'], verdict);
+
+ await run('ingest', dir, '--json');
+
+ expect(result().failedEvidence[0].reason).toBe('file_missing');
+ expect(finalCheck().verdict).toBe(verdict);
+ expect(finalReport().verdict).toBe(verdict);
+ expect(process.exitCode).toBe(1);
+ },
+ );
+
+ it('reports missing required evidence even when no upload was attempted', async () => {
+ await report(['screenshot'], []);
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({
+ failedEvidence: [],
+ missingEvidence: [{ checkItemId: 'screen', types: ['screenshot'] }],
+ publicationStatus: 'partial',
+ });
+ expect(finalReport().verdict).toBe('uncertain');
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('prints the saved report link and recovery advice without --open', async () => {
+ vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));
+ await report(['screenshot'], ["screen's shot.png"]);
+
+ await run('ingest', dir);
+
+ expect(printed.join('\n')).toContain('Partially published');
+ expect(printed.join('\n')).toContain('https://app.lobehub.com/acceptance/acceptance-1?r=2');
+ expect(printed.join('\n')).toContain('evidence upload');
+ expect(printed.join('\n')).toContain('POSIX shell');
+ expect(printed.join('\n')).toContain('retryArgs');
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('personal file storage quota'));
+ expect(process.exitCode).toBe(1);
+ });
+
+ it.each(['passed', 'failed'])(
+ 'accounts for an unexecuted check alongside a %s case',
+ async (verdict) => {
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [{ id: 'response', name: 'ζ”Άεˆ°ε›žε€', status: verdict, evidence: ['output.txt'] }],
+ plan: [
+ { id: 'response', title: 'ζ”Άεˆ°ε›žε€', requiredEvidence: ['text'] },
+ {
+ id: 'screen',
+ title: '画青展瀺',
+ requiredEvidence: ['screenshot', 'text', 'screenshot'],
+ },
+ ],
+ summary: { passed: 2, total: 2, verdict: 'passed' },
+ }),
+ );
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({
+ cases: 1,
+ missingEvidence: [{ checkItemId: 'screen', types: ['screenshot', 'text'] }],
+ publicationStatus: 'partial',
+ unexecuted: ['screen'],
+ });
+ expect(finalReport()).toMatchObject({
+ failedChecks: verdict === 'failed' ? 1 : 0,
+ passedChecks: verdict === 'passed' ? 1 : 0,
+ totalChecks: 2,
+ uncertainChecks: 1,
+ verdict: verdict === 'failed' ? 'failed' : 'uncertain',
+ });
+ expect(client.verify.ingestResult.mutate).toHaveBeenCalledTimes(1);
+ expect(process.exitCode).toBe(1);
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('new round'));
+ },
+ );
+
+ it('keeps an entirely unexecuted required-evidence plan uncertain', async () => {
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [],
+ plan: [{ id: 'screen', title: '画青展瀺', requiredEvidence: ['screenshot'] }],
+ summary: { passed: 1, total: 1, verdict: 'passed' },
+ }),
+ );
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({ publicationStatus: 'partial', unexecuted: ['screen'] });
+ expect(finalReport()).toMatchObject({
+ passedChecks: 0,
+ totalChecks: 1,
+ uncertainChecks: 1,
+ verdict: 'uncertain',
+ });
+ expect(client.verify.ingestResult.mutate).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('accounts for draft-only checks and incoming checks using the folded plan', async () => {
+ client.acceptance.attachRun.mutate.mockResolvedValue({
+ id: 'draft-run',
+ plan: [
+ {
+ id: 'draft-response',
+ verifierConfig: { requiredEvidence: [{ type: 'text' }] },
+ },
+ {
+ id: 'draft-screen',
+ verifierConfig: { requiredEvidence: [{ type: 'screenshot' }] },
+ },
+ { id: 'response', verifierConfig: { requiredEvidence: [{ type: 'text' }] } },
+ ],
+ roundIndex: 1,
+ });
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [
+ { evidence: ['output.txt'], id: 'draft-response', name: 'θ‰η¨Ώε›žε€', status: 'passed' },
+ { evidence: ['output.txt'], id: 'response', name: 'ζ”Άεˆ°ε›žε€', status: 'passed' },
+ ],
+ plan: [{ id: 'response', requiredEvidence: ['text'], title: 'ζ”Άεˆ°ε›žε€' }],
+ summary: { passed: 2, total: 2, verdict: 'passed' },
+ }),
+ );
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({
+ cases: 2,
+ missingEvidence: [{ checkItemId: 'draft-screen', types: ['screenshot'] }],
+ planItems: 3,
+ publicationStatus: 'partial',
+ unexecuted: ['draft-screen'],
+ unplanned: [],
+ verifyRunId: 'draft-run',
+ });
+ expect(finalReport()).toMatchObject({
+ failedChecks: 0,
+ passedChecks: 2,
+ totalChecks: 3,
+ uncertainChecks: 1,
+ verdict: 'uncertain',
+ verifyRunId: 'draft-run',
+ });
+ expect(
+ client.verify.ingestResult.mutate.mock.calls.map(([input]) => input.checkItemId),
+ ).toEqual(['draft-response', 'response']);
+ expect(process.exitCode).toBe(1);
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining('new round'));
+ });
+
+ it.each([false, true])(
+ 'uses the draft evidence requirement for a shared check (screenshot present: %s)',
+ async (hasScreenshot) => {
+ client.acceptance.attachRun.mutate.mockResolvedValue({
+ id: 'draft-run',
+ plan: [{ id: 'screen', verifierConfig: { requiredEvidence: [{ type: 'screenshot' }] } }],
+ roundIndex: 1,
+ });
+ await report(['text'], hasScreenshot ? ["screen's shot.png"] : ['output.txt']);
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({
+ missingEvidence: hasScreenshot ? [] : [{ checkItemId: 'screen', types: ['screenshot'] }],
+ publicationStatus: hasScreenshot ? 'complete' : 'partial',
+ unexecuted: [],
+ unplanned: [],
+ });
+ expect(finalCheck()).toMatchObject({
+ verdict: hasScreenshot ? 'passed' : 'uncertain',
+ verifyRunId: 'draft-run',
+ });
+ expect(finalReport()).toMatchObject({
+ passedChecks: hasScreenshot ? 1 : 0,
+ totalChecks: 1,
+ uncertainChecks: hasScreenshot ? undefined : 1,
+ verdict: hasScreenshot ? 'passed' : 'uncertain',
+ });
+ expect(process.exitCode).toBe(hasScreenshot ? undefined : 1);
+ },
+ );
+
+ it('exposes shell-independent upload arguments without escaping path or description', async () => {
+ const description = `User's "input" $HOME %TEMP% & | \`literal\``;
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [
+ {
+ id: 'screen',
+ name: '画青展瀺',
+ status: 'passed',
+ evidence: [{ path: "screen's shot.png", description }],
+ },
+ ],
+ plan: [{ id: 'screen', title: '画青展瀺', requiredEvidence: ['screenshot'] }],
+ }),
+ );
+ vi.mocked(uploadLocalFile).mockRejectedValueOnce(new Error('storage_block:upgrade_required'));
+ await run('ingest', dir, '--json');
+ const failure = result().failedEvidence[0];
+ expect(failure.retryCommandShell).toBe('posix');
+ expect(failure.retryArgs).toEqual([
+ 'acceptance',
+ 'run',
+ 'evidence',
+ 'upload',
+ '--check',
+ 'result-screen',
+ '--type',
+ 'screenshot',
+ '--file',
+ path.join(dir, "screen's shot.png"),
+ '--desc',
+ description,
+ ]);
+
+ const program = new Command();
+ attachAcceptanceRunCommands(program.command('acceptance'));
+ await program.parseAsync(['node', 'lh', ...failure.retryArgs]);
+ expect(client.verify.uploadEvidence.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ description, fileId: 'file-1' }),
+ );
+ expect(uploadLocalFile).toHaveBeenLastCalledWith(client, path.join(dir, "screen's shot.png"));
+ });
+
+ it('finishes a complete publication with no failure exit code', async () => {
+ await report(['screenshot', 'text'], ["screen's shot.png", 'output.txt']);
+
+ await run('ingest', dir, '--json');
+
+ expect(result()).toMatchObject({
+ evidence: 2,
+ failedEvidence: [],
+ inlined: 1,
+ missingEvidence: [],
+ publicationStatus: 'complete',
+ });
+ expect(finalCheck().verdict).toBe('passed');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('retries only the failed attachment, reusing its file and preserving its caption and comparison', async () => {
+ const description = "Before: user's input $(printf should-not-expand)";
+ const comparison = { id: 'input', role: 'before' };
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [
+ {
+ evidence: [{ comparison, description, path: "screen's shot.png" }, 'output.txt'],
+ id: 'screen',
+ name: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ',
+ status: 'passed',
+ },
+ ],
+ plan: [
+ { id: 'screen', requiredEvidence: ['screenshot', 'text'], title: 'η”¨ζˆ·θƒ½ηœ‹εˆ°ε€„η†η»“ζžœ' },
+ ],
+ }),
+ );
+ client.verify.uploadEvidence.mutate.mockRejectedValueOnce(new Error('attachment unavailable'));
+ await run('ingest', dir, '--json');
+ const failure = result().failedEvidence[0];
+ expect(failure).toMatchObject({ fileId: 'file-1', reason: 'upload_failed' });
+ expect(failure.retryArgs).toEqual([
+ 'acceptance',
+ 'run',
+ 'evidence',
+ 'upload',
+ '--check',
+ 'result-screen',
+ '--type',
+ 'screenshot',
+ '--file-id',
+ 'file-1',
+ '--desc',
+ description,
+ '--metadata',
+ JSON.stringify({ comparison }),
+ ]);
+ expect(finalCheck().verdict).toBe('uncertain');
+ const originalReport = finalReport();
+ const checkWrites = client.verify.ingestResult.mutate.mock.calls.length;
+
+ // Parse with a real POSIX shell: spaces, quotes and command substitutions
+ // in a caption must survive verbatim rather than changing the command.
+ const { stdout } = await promisify(execFile)('sh', [
+ '-c',
+ failure.retryCommand.replace('lh acceptance run evidence upload', 'printf "%s\\0"'),
+ ]);
+ await run('evidence', 'upload', ...stdout.split('\0').filter(Boolean));
+
+ expect(uploadLocalFile).toHaveBeenCalledTimes(1);
+ expect(client.verify.createRun.mutate).toHaveBeenCalledTimes(1);
+ expect(client.verify.ingestResult.mutate).toHaveBeenCalledTimes(checkWrites);
+ expect(client.verify.upsertReport.mutate).toHaveBeenCalledTimes(1);
+ expect(finalReport()).toEqual(originalReport);
+ expect(client.verify.uploadEvidence.mutate.mock.calls.at(-1)![0]).toMatchObject({
+ capturedBy: 'cli',
+ checkResultId: 'result-screen',
+ description,
+ fileId: 'file-1',
+ metadata: { comparison },
+ type: 'screenshot',
+ });
+ });
+
+ it('recounts mixed checks without converting an observed failure into uncertainty', async () => {
+ vi.mocked(uploadLocalFile).mockRejectedValue(new Error('storage_block:upgrade_required'));
+ await writeFile(
+ path.join(dir, 'result.json'),
+ JSON.stringify({
+ cases: [
+ { evidence: ["screen's shot.png"], id: 'screen', name: '画青展瀺', status: 'passed' },
+ { evidence: ['output.txt'], id: 'response', name: 'ζ”Άεˆ°ε›žε€', status: 'passed' },
+ { id: 'cancel', name: 'ε–ζΆˆζ“δ½œ', status: 'failed' },
+ ],
+ plan: [{ id: 'screen', requiredEvidence: ['screenshot'], title: '画青展瀺' }],
+ summary: { failed: 1, passed: 2, total: 3, verdict: 'failed' },
+ }),
+ );
+
+ await run('ingest', dir, '--json');
+
+ expect(finalReport()).toMatchObject({
+ failedChecks: 1,
+ passedChecks: 1,
+ totalChecks: 3,
+ uncertainChecks: 1,
+ verdict: 'failed',
+ });
+ });
+});
diff --git a/apps/cli/src/commands/acceptanceRun.ts b/apps/cli/src/commands/acceptanceRun.ts
index 69bc6ce48c7..452eee25c75 100644
--- a/apps/cli/src/commands/acceptanceRun.ts
+++ b/apps/cli/src/commands/acceptanceRun.ts
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
import path from 'node:path';
import { acceptanceSubjectTypes } from '@lobechat/const/verify';
+import type { VerifyAgentPlanConfig, VerifyCheckItem } from '@lobechat/types';
import type { Command } from 'commander';
import pc from 'picocolors';
@@ -15,12 +16,14 @@ import { log } from '../utils/logger';
import type { LinkResult } from '../utils/skillWiring';
import { linkHarnessSkills } from '../utils/skillWiring';
import { uploadLocalFile } from '../utils/uploadLocalFile';
+import type { FailedReportEvidence } from './acceptanceEvidence';
+import { uploadReportEvidence } from './acceptanceEvidence';
import {
type Decision,
DECISIONS,
deriveReportVerdict,
evidenceDescriptionForFile,
- evidenceTypeForFile,
+ type EvidenceType,
genericContextFromResult,
inlineTextEvidenceForFile,
interactionCostFromReportDir,
@@ -31,7 +34,6 @@ import {
printResults,
pullRequestFromBranch,
pullRequestFromResult,
- reportEvidence,
scenarioFromResult,
screenProgrammaticTestChecks,
subjectFromEnv,
@@ -425,17 +427,20 @@ interface EvidenceUploadOptions {
content?: string;
desc?: string;
file?: string;
+ fileId?: string;
json?: boolean | string;
+ metadata?: string;
type: string;
}
async function evidenceUploadAction(options: EvidenceUploadOptions): Promise<void> {
- if (Boolean(options.file) === Boolean(options.content)) {
- log.error('Provide exactly one of --file or --content');
+ if ([options.file, options.content, options.fileId].filter(Boolean).length !== 1) {
+ log.error('Provide exactly one of --file, --file-id or --content');
process.exit(1);
}
+ const metadata: unknown = options.metadata ? JSON.parse(options.metadata) : undefined;
const client = await getTrpcClient();
- let fileId: string | undefined;
+ let fileId = options.fileId;
let inlineContent = options.content;
if (options.file) {
inlineContent = inlineTextEvidenceForFile(options.file, options.type);
@@ -450,6 +455,7 @@ async function evidenceUploadAction(options: EvidenceUploadOptions): Promise<voi
content: inlineContent,
description: evidenceDescriptionForFile(options.desc, options.file),
fileId,
+ metadata,
type: options.type as any,
});
if (options.json !== undefined) {
@@ -662,7 +668,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
// What the run set out to check, written before it ran. Paired with the
// results by `id`, so the report can show a planned item that never ran.
- let plan = planFromResult(result, droppedIds);
+ let plan: VerifyCheckItem[] | undefined = planFromResult(result, droppedIds);
const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
const title = options.title ?? result.title;
@@ -798,6 +804,8 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
// returns, which is the draft round when this run was folded into one.
const acceptanceId = acceptance.id;
const attached = await client.acceptance.attachRun.mutate({ acceptanceId, verifyRunId: run.id });
+ // Folding preserves the draft's checks and their evidence requirements.
+ plan = attached?.plan ?? plan;
const runId = attached?.id ?? run.id;
if (runId !== run.id)
console.log(pc.dim(`Folded into the acceptance's draft round ${attached.roundIndex ?? ''}`));
@@ -816,11 +824,14 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
const seenCheckItemIds = new Set<string>();
let evidenceCount = 0;
let inlined = 0;
+ const failedEvidence: (FailedReportEvidence & { checkItemId: string })[] = [];
+ const missingEvidence: { checkItemId: string; types: EvidenceType[] }[] = [];
+ const publishedVerdicts: Verdict[] = [];
for (const [index, { case: c, checkItemId }] of cases.entries()) {
seenCheckItemIds.add(checkItemId);
const verdict = toVerdict(c.result ?? c.status ?? c.verdict);
const observation = c.keyObservation ?? c.observation ?? c.note;
- const checkResult = await client.verify.ingestResult.mutate({
+ const checkInput = {
checkItemId,
checkItemIndex: index,
checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,
@@ -833,43 +844,49 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,
toulmin: typeof observation === 'string' ? { evidence: observation } : null,
verdict,
- verifierType: 'agent',
+ verifierType: 'agent' as const,
verifyRunId: runId,
+ };
+ const checkResult = await client.verify.ingestResult.mutate(checkInput);
+ const uploaded = await uploadReportEvidence(client, {
+ checkResultId: checkResult.id,
+ dir,
+ evidence: c.evidence,
});
-
- for (const evidenceInput of reportEvidence(c.evidence)) {
- const rel = evidenceInput.path;
- const abs = path.isAbsolute(rel) ? rel : path.join(dir, rel);
- if (!existsSync(abs)) {
- log.warn(`evidence not found, skipping: ${rel}`);
- continue;
- }
- try {
- const type = evidenceTypeForFile(abs);
- const inlineContent = inlineTextEvidenceForFile(abs, type);
- const file = inlineContent === undefined ? await uploadLocalFile(client, abs) : undefined;
- await client.verify.uploadEvidence.mutate({
- capturedBy: 'cli',
- checkResultId: checkResult.id,
- // The filename, not the case title β€” the title already heads the
- // check card, so reusing it here just triples the same text.
- content: inlineContent,
- description: evidenceDescriptionForFile(evidenceInput.description, abs),
- fileId: file?.id,
- metadata: evidenceInput.comparison ? { comparison: evidenceInput.comparison } : undefined,
- type,
- });
- evidenceCount += 1;
- if (inlineContent !== undefined) inlined += 1;
- } catch (e) {
- // A stub/unreachable storage bucket (common in local dev) fails the
- // file PUT β€” don't abort the whole ingest over one artifact; the
- // session, results, and report are the deliverable.
- log.warn(`evidence upload failed, skipping ${path.basename(abs)}: ${String(e)}`);
- }
+ evidenceCount += uploaded.count;
+ inlined += uploaded.inlined;
+ failedEvidence.push(...uploaded.failedEvidence.map((failure) => ({ ...failure, checkItemId })));
+ const config = plan?.find((item) => item.id === checkItemId)?.verifierConfig as
+ VerifyAgentPlanConfig | undefined;
+ const required = config?.requiredEvidence;
+ const gaps = [...new Set(required?.map((spec) => spec.type) ?? [])].filter(
+ (type) => !uploaded.types.has(type),
+ );
+ const publishedVerdict = gaps.length > 0 && verdict === 'passed' ? 'uncertain' : verdict;
+ publishedVerdicts.push(publishedVerdict);
+ if (gaps.length > 0) {
+ missingEvidence.push({ checkItemId, types: gaps });
+ const limitation = `Required evidence not published: ${gaps.join(', ')}.`;
+ log.warn(`${checkItemId}: ${limitation}`);
+ await client.verify.ingestResult.mutate({
+ ...checkInput,
+ toulmin: { ...checkInput.toulmin, limitation },
+ verdict: publishedVerdict,
+ });
}
}
+ const unexecuted = plan?.filter((item) => !seenCheckItemIds.has(item.id)) ?? [];
+ for (const item of unexecuted) {
+ const config = item.verifierConfig as VerifyAgentPlanConfig;
+ const types = [...new Set(config.requiredEvidence?.map((spec) => spec.type) ?? [])];
+ if (types.length === 0) continue;
+ missingEvidence.push({ checkItemId: item.id, types });
+ // Count the gap without inventing an execution result for an unexecuted check.
+ publishedVerdicts.push('uncertain');
+ log.warn(`${item.id}: not executed; required evidence not published: ${types.join(', ')}.`);
+ }
+
// 3. Write the report. `summary` is the overall conclusion (rendered at
// the top of the report page); `content` is the full markdown detail.
const conclusion =
@@ -884,29 +901,33 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
typeof summary.score === 'number' ? Math.max(0, Math.min(1, summary.score / 100)) : undefined;
// The authored counts describe the report the author wrote. Once a
// programmatic-test check is screened out they no longer match what was
- // published, so recount from the cases that actually landed β€” a stats block
- // that disagrees with the visible check list is worse than no stats.
- const recount = cases.length !== allCases.length;
- const verdicts = cases.map(({ case: c }) => toVerdict(c.result ?? c.status ?? c.verdict));
- const counted = (verdict: Verdict) => verdicts.filter((v) => v === verdict).length;
+ // published, so recount the landed cases and unexecuted evidence gaps β€” a
+ // stats block that disagrees with the visible check list is worse than no stats.
+ const recount = cases.length !== allCases.length || missingEvidence.length > 0;
+ const counted = (verdict: Verdict) => publishedVerdicts.filter((v) => v === verdict).length;
+ const derivedVerdict = deriveReportVerdict(publishedVerdicts.map((verdict) => ({ verdict })));
+ const reportVerdict =
+ summary.verdict && cases.length === allCases.length
+ ? toVerdict(summary.verdict)
+ : derivedVerdict;
await client.verify.upsertReport.mutate({
content,
failedChecks: recount ? counted('failed') : summary.failed,
overallConfidence: score,
passedChecks: recount ? counted('passed') : summary.passed,
summary: conclusion,
- totalChecks: recount ? cases.length : (summary.total ?? cases.length),
+ totalChecks: recount ? publishedVerdicts.length : (summary.total ?? cases.length),
uncertainChecks: recount
? counted('uncertain') || undefined
: (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,
- // An explicit summary.verdict wins; otherwise the headline is derived
- // from the ingested cases (deriveReportVerdict) so no report ships
- // verdict-less and lists as a permanent "?". After a screen the authored
- // verdict may have been about a check that is no longer here, so rederive.
+ // Missing evidence cannot be overridden by an authored "passed" summary.
+ // Keep a real failure rather than hiding it behind an evidence warning.
verdict:
- summary.verdict && !recount
- ? toVerdict(summary.verdict)
- : deriveReportVerdict(cases.map(({ case: c }) => c)),
+ missingEvidence.length > 0
+ ? reportVerdict === 'failed' || derivedVerdict === 'failed'
+ ? 'failed'
+ : 'uncertain'
+ : reportVerdict,
verifyRunId: runId,
});
@@ -945,6 +966,24 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
? [...seenCheckItemIds].filter((id) => !plan.some((item) => item.id === id))
: [];
+ const partial = failedEvidence.length > 0 || missingEvidence.length > 0;
+ if (partial) {
+ process.exitCode = 1;
+ log.warn(
+ 'Report saved, but evidence publication is incomplete. Keep the local artifacts; retry only the missing evidence, not the whole ingest. Supplementing evidence does not change recorded verdicts.',
+ );
+ if (missingEvidence.some(({ checkItemId }) => !seenCheckItemIds.has(checkItemId))) {
+ log.warn(
+ 'Unexecuted checks have no result to attach evidence to. Execute them and publish a new round on the same acceptance; do not re-ingest this unchanged report.',
+ );
+ }
+ if (failedEvidence.some((failure) => failure.reason === 'storage_quota')) {
+ log.warn(
+ 'Acceptance evidence uses your personal file storage quota. Free space or upgrade your storage plan, then retry the failed artifacts.',
+ );
+ }
+ }
+
if (options.json !== undefined) {
outputJson(
{
@@ -953,15 +992,19 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
cases: cases.length,
droppedProgrammaticChecks: droppedLabels,
evidence: evidenceCount,
+ failedEvidence,
inlined,
+ missingEvidence,
origin,
planItems: plan?.length ?? 0,
proposalPosted,
+ publicationStatus: partial ? 'partial' : 'complete',
pullRequest,
roundIndex,
roundUrl,
scenario,
subject: subject!.ref,
+ unexecuted: unexecuted.map((item) => item.id),
unplanned,
verifyRunId: runId,
},
@@ -971,12 +1014,17 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
}
console.log(
- `${pc.green('βœ“')} Ingested ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s)` +
+ `${partial ? pc.yellow('⚠ Partially published') : pc.green('βœ“ Ingested')} ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(evidenceCount))} evidence artifact(s)` +
`${inlined > 0 ? `, ${pc.bold(String(inlined))} inline` : ''}` +
`${droppedLabels.length > 0 ? pc.yellow(` β€” ${droppedLabels.length} programmatic-test check(s) dropped`) : ''}`,
);
+ for (const failure of failedEvidence) {
+ console.log(`${pc.yellow('retry (POSIX shell)')}: ${failure.retryCommand}`);
+ console.log(
+ `${pc.dim('retryArgs (lh, shell disabled)')}: ${JSON.stringify(failure.retryArgs)}`,
+ );
+ }
if (plan?.length) {
- const unexecuted = plan.filter((item) => !seenCheckItemIds.has(item.id));
console.log(
`${pc.bold('plan')}: ${plan.length} item(s)` +
`${unexecuted.length > 0 ? pc.yellow(` β€” ${unexecuted.length} planned but not executed`) : ''}` +
@@ -992,7 +1040,7 @@ async function ingestReportAction(reportDir: string, options: IngestReportOption
? 'standalone'
: `${subject!.ref.subjectType}:${subject!.ref.subjectId}`;
console.log(`${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subjectLabel})`)}`);
- if (options.open) {
+ if (options.open || partial) {
// The acceptance page is the only link surfaced to users β€” the raw /verify
// page stays internal. `?r=<roundIndex>` is this round's fixed snapshot.
console.log(`${pc.bold('open acceptance')}: ${acceptanceUrl}`);
@@ -1076,7 +1124,9 @@ function withEvidenceUploadOptions(cmd: Command): Command {
.requiredOption('--check <checkResultId>', 'Target check result id')
.requiredOption('--type <type>', 'screenshot|gif|video|text|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)')
+ .option('--metadata <json>', 'Evidence metadata, preserved when retrying an attachment')
.option('--by <capturedBy>', 'agent-browser|cdp|cli|program|llm_judge', 'cli')
.option('--desc <text>', 'Human-readable caption')
.option('--json [fields]', 'Output JSON');