Skip to content

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

✨ feat(acceptance): expose offline report schema and validation (#20954)

Innei4ea8e69d1105
diff --git a/apps/cli/package.json b/apps/cli/package.json
index da0fe163194..d9fc970b3b0 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -64,7 +64,8 @@
"tsdown": "^0.21.10",
"typescript": "^6.0.3",
"url-join": "^5.0.0",
- "vitest": "5.0.0"
+ "vitest": "5.0.0",
+ "zod": "^4.4.3"
},
"engines": {
"node": ">=22.15"
diff --git a/apps/cli/src/commands/acceptance/run/index.schema.test.ts b/apps/cli/src/commands/acceptance/run/index.schema.test.ts
new file mode 100644
index 00000000000..25ec75fa09e
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/run/index.schema.test.ts
@@ -0,0 +1,98 @@
+import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTrpcClient } from '../../../api/client';
+import { attachAcceptanceRunCommands } from '.';
+
+vi.mock('../../../api/client', () => ({ getTrpcClient: vi.fn() }));
+
+describe('offline acceptance report commands', () => {
+ let dir: string;
+ let printed: string[];
+ let exitCode: typeof process.exitCode;
+
+ beforeEach(async () => {
+ vi.resetAllMocks();
+ exitCode = process.exitCode;
+ process.exitCode = undefined;
+ printed = [];
+ vi.spyOn(console, 'log').mockImplementation((line) => printed.push(String(line)));
+ vi.mocked(getTrpcClient).mockRejectedValue(new Error('No account configured'));
+ dir = await mkdtemp(path.join(tmpdir(), 'lh-offline-report-'));
+ });
+
+ afterEach(async () => {
+ process.exitCode = exitCode;
+ vi.restoreAllMocks();
+ await rm(dir, { force: true, recursive: true });
+ });
+
+ const run = async (...args: string[]) => {
+ const program = new Command().exitOverride();
+ attachAcceptanceRunCommands(program.command('acceptance'));
+ await program.parseAsync(['node', 'lh', 'acceptance', 'run', ...args]);
+ };
+
+ const result = () => JSON.parse(printed.at(-1)!);
+
+ it('generates and validates a CLI draft without account access or file mutations', async () => {
+ await run('schema', '--example', '--surface', 'cli');
+ const example = result();
+ expect(example.cases).toEqual([]);
+ expect(example.plan[0].surface).toBe('cli');
+ const report = JSON.stringify(example);
+ await writeFile(path.join(dir, 'result.json'), report);
+
+ await run('validate', dir);
+
+ expect(result()).toMatchObject({ valid: true, draft: true, planItems: 1, cases: 0 });
+ expect(getTrpcClient).not.toHaveBeenCalled();
+ expect(await readFile(path.join(dir, 'result.json'), 'utf8')).toBe(report);
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('emits parseable diagnostics and exits unsuccessfully for an invalid report', async () => {
+ await writeFile(path.join(dir, 'result.json'), '{"title":');
+
+ await run('validate', dir, '--json');
+
+ expect(result()).toMatchObject({ valid: false, errors: [expect.any(Object)] });
+ expect(process.exitCode).toBe(1);
+ expect(getTrpcClient).not.toHaveBeenCalled();
+ });
+
+ it('selects requested fields from schema output without logging prose', async () => {
+ await run('schema', '--json', 'type,required');
+
+ expect(Object.keys(result()).sort()).toEqual(['required', 'type']);
+ expect(result().type).toBe('object');
+ expect(printed).toHaveLength(1);
+ expect(getTrpcClient).not.toHaveBeenCalled();
+ });
+
+ it('accepts the generated draft through the existing account-aware ingest dry run', async () => {
+ await run('schema', '--example');
+ await writeFile(path.join(dir, 'result.json'), JSON.stringify(result()));
+ const mutate = vi.fn();
+ vi.mocked(getTrpcClient).mockResolvedValue({
+ acceptance: { ensure: { mutate } },
+ user: {
+ getUserState: {
+ query: vi
+ .fn()
+ .mockResolvedValue({ settings: { general: { responseLanguage: 'en-US' } } }),
+ },
+ },
+ verify: { createRun: { mutate } },
+ } as unknown as Awaited<ReturnType<typeof getTrpcClient>>);
+
+ await run('ingest', dir, '--dry-run', '--json');
+
+ expect(result()).toMatchObject({ dryRun: true, planItems: 1, cases: 0 });
+ expect(mutate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/run/index.ts b/apps/cli/src/commands/acceptance/run/index.ts
index 559d9a86f12..ed0d2c516ef 100644
--- a/apps/cli/src/commands/acceptance/run/index.ts
+++ b/apps/cli/src/commands/acceptance/run/index.ts
@@ -1,6 +1,9 @@
+import { verifySurfaces } from '@lobechat/const/verify';
import type { Command } from 'commander';
+import { Option } from 'commander';
import { createPublicLambdaClient } from '../../../api/client';
+import { outputJson } from '../../../utils/format';
import { installAction, type InstallOptions, withInstallOptions } from '../install';
import { DECISIONS } from '../utils';
import {
@@ -11,6 +14,11 @@ import {
} from './evidence';
import { ingestReportAction, withIngestReportOptions } from './ingest';
import { reportGetAction, reportUpsertAction, withReportUpsertOptions } from './report';
+import {
+ createAcceptanceReportTemplate,
+ getAcceptanceReportJsonSchema,
+ validateAcceptanceReport,
+} from './reportSchema';
import {
decisionAction,
resultIngestAction,
@@ -61,6 +69,45 @@ export function attachAcceptanceRunCommands(acceptance: Command): void {
.command('run')
.description('Acceptance rounds (immutable verification snapshots)');
+ run
+ .command('schema')
+ .description('Print the result.json authoring JSON Schema, without login or network access')
+ .option('--example', 'Print a draft result.json with no executed cases')
+ .addOption(
+ new Option('--surface <surface>', 'Surface for the example plan')
+ .choices(verifySurfaces)
+ .default('web'),
+ )
+ .option('--json [fields]', 'Output JSON (default); optionally select top-level fields')
+ .action(
+ (options: {
+ example?: boolean;
+ json?: boolean | string;
+ surface: (typeof verifySurfaces)[number];
+ }) => {
+ outputJson(
+ options.example
+ ? createAcceptanceReportTemplate(options.surface)
+ : getAcceptanceReportJsonSchema(),
+ options.json,
+ );
+ },
+ );
+
+ run
+ .command('validate <reportDir>')
+ .description('Check local result.json and evidence files offline; never publish')
+ .option('--json [fields]', 'Output JSON (default); optionally select top-level fields')
+ .addHelpText(
+ 'after',
+ '\nChecks the authoring schema, check IDs and local evidence. Account language, media inspection and remote plan membership remain unchecked. Invalid reports exit with code 1. Drafts are valid but unexecuted. Use ingest --dry-run for account checks.',
+ )
+ .action(async (reportDir: string, options: { json?: boolean | string }) => {
+ const result = await validateAcceptanceReport(reportDir);
+ outputJson(result, options.json);
+ if (!result.valid) process.exitCode = 1;
+ });
+
withIngestReportOptions(
run
.command('ingest <reportDir>')
diff --git a/apps/cli/src/commands/acceptance/run/reportSchema.test.ts b/apps/cli/src/commands/acceptance/run/reportSchema.test.ts
new file mode 100644
index 00000000000..4fcc9a21b82
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/run/reportSchema.test.ts
@@ -0,0 +1,413 @@
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { planFromResult } from '../utils';
+import {
+ acceptanceReportSchema,
+ createAcceptanceReportTemplate,
+ getAcceptanceReportJsonSchema,
+ validateAcceptanceReport,
+} from './reportSchema';
+
+describe('acceptance report authoring contract', () => {
+ let dir: string;
+ const setup = async (report: unknown) => {
+ dir = await mkdtemp(path.join(tmpdir(), 'acceptance-report-'));
+ await writeFile(path.join(dir, 'result.json'), JSON.stringify(report));
+ return dir;
+ };
+ afterEach(async () => {
+ if (dir) await rm(dir, { force: true, recursive: true });
+ });
+
+ it('exposes one Zod contract as JSON Schema and accepts its empty template draft', async () => {
+ const template = createAcceptanceReportTemplate('web');
+ expect(acceptanceReportSchema.safeParse(template).success).toBe(true);
+ expect(() => getAcceptanceReportJsonSchema()).not.toThrow();
+ expect(planFromResult(template)?.[0]).toMatchObject({
+ id: 'replace-with-check-id',
+ title: 'Describe the outcome to verify',
+ verifierType: 'agent',
+ });
+ const result = await validateAcceptanceReport(await setup(template));
+ expect(result).toMatchObject({ valid: true, draft: true, planItems: 1, cases: 0 });
+ });
+
+ it('rejects a claimed pass without its required evidence artifact', async () => {
+ const report = {
+ title: 'Checkout confirmation',
+ plan: [
+ {
+ id: 'confirmation',
+ title: 'Confirmation is visible',
+ method: 'Complete checkout',
+ expected: 'A confirmation is shown',
+ requiredEvidence: ['screenshot'],
+ },
+ ],
+ cases: [
+ {
+ id: 'confirmation',
+ surface: 'web',
+ status: 'passed',
+ observation: 'Confirmation appeared.',
+ evidence: [],
+ },
+ ],
+ };
+ const result = await validateAcceptanceReport(await setup(report));
+ expect(result.valid).toBe(false);
+ expect(result.errors[0].message).toContain('missing required evidence "screenshot"');
+ });
+
+ it('infers a file evidence type from its suffix like ingest does', async () => {
+ const reportDir = await setup({
+ title: 'Screenshot report',
+ plan: [
+ {
+ id: 'screen',
+ title: 'Screen is visible',
+ method: 'Open the page',
+ expected: 'The page is shown',
+ requiredEvidence: ['screenshot'],
+ },
+ ],
+ cases: [
+ {
+ id: 'screen',
+ surface: 'web',
+ status: 'pass',
+ observation: 'The page appeared.',
+ evidence: [{ description: 'Captured page', path: 'screen.png' }],
+ },
+ ],
+ });
+ await writeFile(path.join(reportDir, 'screen.png'), 'image fixture');
+ expect(await validateAcceptanceReport(reportDir)).toMatchObject({ valid: true, draft: false });
+ });
+
+ it('rejects a declared screenshot type when ingest will infer text from the filename', async () => {
+ const reportDir = await setup({
+ title: 'Mismatched evidence',
+ plan: [
+ {
+ id: 'proof',
+ title: 'Image evidence',
+ method: 'Capture the page',
+ expected: 'A screenshot is saved',
+ requiredEvidence: ['screenshot'],
+ },
+ ],
+ cases: [
+ {
+ id: 'proof',
+ surface: 'web',
+ status: 'pass',
+ observation: 'The page appeared.',
+ evidence: [
+ { type: 'screenshot', description: 'Incorrectly typed text file', path: 'proof.txt' },
+ ],
+ },
+ ],
+ });
+ await writeFile(path.join(reportDir, 'proof.txt'), 'not a screenshot');
+ const result = await validateAcceptanceReport(reportDir);
+ expect(
+ result.errors.some(
+ ({ path: issuePath, message }) =>
+ issuePath.endsWith('.type') &&
+ message.includes('Ingest infers the type from the file suffix'),
+ ),
+ ).toBe(true);
+ expect(
+ result.errors.some(({ message }) =>
+ message.includes('missing required evidence "screenshot"'),
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects duplicate plan ids and orphan case ids', async () => {
+ const result = await validateAcceptanceReport(
+ await setup({
+ title: 'Report',
+ plan: [
+ { id: 'same', title: 'One', method: 'Check', expected: 'Works', requiredEvidence: [] },
+ { id: 'same', title: 'Two', method: 'Check', expected: 'Works', requiredEvidence: [] },
+ ],
+ cases: [
+ {
+ id: 'orphan',
+ surface: 'cli',
+ status: 'failed',
+ observation: 'It failed.',
+ evidence: [],
+ },
+ ],
+ }),
+ );
+ expect(result.errors.map(({ message }) => message).join('\n')).toMatch(/Duplicate plan id/);
+ expect(result.errors.map(({ message }) => message).join('\n')).toMatch(/not present in plan/);
+ });
+
+ it('reports an orphaned pass without dereferencing a missing plan item', async () => {
+ const result = await validateAcceptanceReport(
+ await setup({
+ title: 'Report',
+ plan: [
+ {
+ id: 'planned',
+ title: 'Check',
+ method: 'Run check',
+ expected: 'Works',
+ requiredEvidence: ['text'],
+ },
+ ],
+ cases: [
+ { id: 'orphan', surface: 'cli', status: 'pass', observation: 'It passed.', evidence: [] },
+ ],
+ }),
+ );
+ expect(result.valid).toBe(false);
+ expect(result.errors.some(({ message }) => message.includes('not present in plan'))).toBe(true);
+ });
+
+ it('rejects malformed visualization metadata through the existing renderer validator', async () => {
+ const result = await validateAcceptanceReport(
+ await setup({
+ title: 'Report',
+ plan: [
+ {
+ id: 'data',
+ title: 'Data chart',
+ method: 'Inspect chart',
+ expected: 'Chart renders',
+ requiredEvidence: [],
+ },
+ ],
+ cases: [
+ {
+ id: 'data',
+ surface: 'web',
+ status: 'failed',
+ observation: 'Chart metadata is malformed.',
+ evidence: [],
+ datasets: [],
+ visualizations: [{ id: 'view', type: 'bar', dataset: 'missing', version: 1 }],
+ },
+ ],
+ }),
+ );
+ expect(result.valid).toBe(false);
+ expect(
+ result.errors.some(({ message }) =>
+ message.includes('invalid id, type, version, or dataset'),
+ ),
+ ).toBe(true);
+ });
+
+ it('preserves an honest blocked outcome and its extra metadata', async () => {
+ const result = await validateAcceptanceReport(
+ await setup({
+ title: 'Report',
+ plan: [
+ {
+ id: 'blocked-check',
+ title: 'Service responds',
+ method: 'Open the service',
+ expected: 'A response is returned',
+ requiredEvidence: ['text'],
+ },
+ ],
+ cases: [
+ {
+ id: 'blocked-check',
+ surface: 'cli',
+ status: 'blocked',
+ observation: 'The service was unavailable.',
+ evidence: [],
+ retryCount: 2,
+ },
+ ],
+ }),
+ );
+ expect(result).toMatchObject({ valid: true, draft: false, cases: 1 });
+ expect(result.errors).toEqual([]);
+ });
+
+ it('checks referenced file evidence and warns about unchecked remote and media facts', async () => {
+ const report = {
+ title: 'Report',
+ plan: [
+ {
+ id: 'shot',
+ title: 'Page is visible',
+ method: 'Open the page',
+ expected: 'Page loads',
+ requiredEvidence: ['screenshot'],
+ },
+ ],
+ cases: [
+ {
+ id: 'shot',
+ surface: 'web',
+ status: 'passed',
+ observation: 'Page loaded.',
+ evidence: [{ type: 'screenshot', description: 'Loaded page', path: 'missing.png' }],
+ },
+ ],
+ };
+ const result = await validateAcceptanceReport(await setup(report));
+ expect(result.errors.some(({ message }) => message.includes('does not exist'))).toBe(true);
+ expect(result.warnings[0].message).toContain('account language');
+ });
+
+ it('rejects directory evidence and accepts a contained filename beginning with two dots', async () => {
+ const reportDir = await setup({
+ title: 'Report',
+ plan: [
+ {
+ id: 'file',
+ title: 'File check',
+ method: 'Inspect file',
+ expected: 'File exists',
+ requiredEvidence: [],
+ },
+ ],
+ cases: [
+ {
+ id: 'file',
+ surface: 'cli',
+ status: 'failed',
+ observation: 'Directory path is not an artifact.',
+ evidence: [{ type: 'text', description: 'Directory', path: 'subdir' }],
+ },
+ ],
+ });
+ await mkdir(path.join(reportDir, 'subdir'));
+ let result = await validateAcceptanceReport(reportDir);
+ expect(result.errors.some(({ message }) => message.includes('not a regular file'))).toBe(true);
+
+ await writeFile(path.join(reportDir, '..prefix.txt'), 'evidence');
+ const reportWithPrefixFile = JSON.parse(
+ await readFile(path.join(reportDir, 'result.json'), 'utf8'),
+ );
+ reportWithPrefixFile.cases[0].evidence[0].path = '..prefix.txt';
+ await writeFile(path.join(reportDir, 'result.json'), JSON.stringify(reportWithPrefixFile));
+ result = await validateAcceptanceReport(reportDir);
+ expect(result.errors).toEqual([]);
+ });
+
+ it('marks partial plan coverage as a draft and names unexecuted checks', async () => {
+ const result = await validateAcceptanceReport(
+ await setup({
+ title: 'Partial report',
+ plan: [
+ {
+ id: 'done',
+ title: 'First check',
+ method: 'Run it',
+ expected: 'Works',
+ requiredEvidence: [],
+ },
+ {
+ id: 'later',
+ title: 'Second check',
+ method: 'Run it',
+ expected: 'Works',
+ requiredEvidence: [],
+ },
+ ],
+ cases: [
+ {
+ id: 'done',
+ surface: 'web',
+ status: 'fail',
+ observation: 'The check failed.',
+ evidence: [],
+ },
+ ],
+ }),
+ );
+ expect(result).toMatchObject({ valid: true, draft: true, planItems: 2, cases: 1 });
+ expect(result.warnings.some(({ message }) => message.includes('later'))).toBe(true);
+ });
+
+ it('rejects malformed video chapters through the shared evidence reader', async () => {
+ const reportDir = await setup({
+ title: 'Video report',
+ plan: [
+ {
+ id: 'video',
+ title: 'Playback',
+ method: 'Play video',
+ expected: 'Video plays',
+ requiredEvidence: [],
+ },
+ ],
+ cases: [
+ {
+ id: 'video',
+ surface: 'web',
+ status: 'fail',
+ observation: 'The video was captured.',
+ evidence: [
+ {
+ type: 'video',
+ description: 'Capture',
+ path: 'capture.mp4',
+ chapters: [{ t: -1, kind: 'step', label: '' }],
+ },
+ ],
+ },
+ ],
+ });
+ await writeFile(path.join(reportDir, 'capture.mp4'), 'fixture');
+ const result = await validateAcceptanceReport(reportDir);
+ expect(
+ result.errors.some(
+ ({ path: issuePath, message }) =>
+ issuePath.endsWith('.chapters') && message.includes('invalid'),
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects content-only evidence even when it satisfies a required text type', async () => {
+ const result = await validateAcceptanceReport(
+ await setup({
+ title: 'Report',
+ plan: [
+ {
+ id: 'text',
+ title: 'Text evidence',
+ method: 'Read output',
+ expected: 'Output is useful',
+ requiredEvidence: ['text'],
+ },
+ ],
+ cases: [
+ {
+ id: 'text',
+ surface: 'cli',
+ status: 'pass',
+ observation: 'Text was attached inline.',
+ evidence: [
+ { type: 'text', description: 'Inline text', content: 'This is ignored by ingest.' },
+ ],
+ },
+ ],
+ }),
+ );
+ expect(result.valid).toBe(false);
+ expect(result.errors.some(({ path: issuePath }) => issuePath.includes('evidence'))).toBe(true);
+ });
+
+ it('does not fabricate observations or cases in the generated template', () => {
+ const template = createAcceptanceReportTemplate('mobile');
+ expect(template.cases).toEqual([]);
+ expect(JSON.stringify(template)).not.toMatch(/observation|passed|failed|blocked/);
+ expect(template.plan[0].surface).toBe('mobile');
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/run/reportSchema.ts b/apps/cli/src/commands/acceptance/run/reportSchema.ts
new file mode 100644
index 00000000000..9203f0a5a10
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/run/reportSchema.ts
@@ -0,0 +1,279 @@
+import { constants } from 'node:fs';
+import { access, readFile, realpath, stat } from 'node:fs/promises';
+import path from 'node:path';
+
+import { verifyEvidenceTypes, verifyRunScenarios, verifySurfaces } from '@lobechat/const/verify';
+import { verifyCheckDefinitionSchema } from '@lobechat/types';
+import { isRecord } from '@lobechat/utils/object';
+import { z } from 'zod';
+
+import { evidenceTypeForFile, reportEvidence, visualizationMetadata } from '../utils';
+
+const evidenceDescriptorFields = {
+ description: z.string().min(1),
+};
+
+const evidenceSchema = z
+ .object({
+ ...evidenceDescriptorFields,
+ type: z.enum(verifyEvidenceTypes).optional(),
+ path: z.string().min(1),
+ content: z.never().optional(),
+ })
+ .passthrough();
+
+const requiredEvidenceSchema = z.union([
+ z.enum(verifyEvidenceTypes),
+ z.object({ type: z.enum(verifyEvidenceTypes), hint: z.string().optional() }).passthrough(),
+]);
+
+const planItemSchema = z
+ .object({
+ id: z.string().min(1),
+ title: z.string().min(1),
+ method: z.string().min(1),
+ expected: z.string().min(1),
+ surface: z.enum(verifySurfaces).optional(),
+ requiredEvidence: z.array(requiredEvidenceSchema),
+ definition: verifyCheckDefinitionSchema.optional(),
+ })
+ .passthrough();
+
+const caseSchema = z
+ .object({
+ id: z.string().min(1),
+ surface: z.enum(verifySurfaces),
+ status: z.enum(['pass', 'fail', 'blocked', 'passed', 'failed']),
+ observation: z.string().min(1),
+ evidence: z.array(evidenceSchema),
+ })
+ .passthrough();
+
+/** Canonical authoring shape. Local relations and file checks live in validateAcceptanceReport. */
+export const acceptanceReportSchema = z
+ .object({
+ title: z.string().trim().min(1),
+ scenario: z.enum(verifyRunScenarios).optional(),
+ surface: z.enum(verifySurfaces).optional(),
+ plan: z.array(planItemSchema),
+ cases: z.array(caseSchema),
+ })
+ .passthrough();
+
+export type AcceptanceReport = z.infer<typeof acceptanceReportSchema>;
+
+export function createAcceptanceReportTemplate(surface: (typeof verifySurfaces)[number]) {
+ return {
+ title: 'Acceptance report draft',
+ scenario: 'coding' as const,
+ surface,
+ plan: [
+ {
+ id: 'replace-with-check-id',
+ title: 'Describe the outcome to verify',
+ method: 'Describe how this check will be performed',
+ expected: 'Describe the expected behavior',
+ surface,
+ requiredEvidence: [],
+ },
+ ],
+ cases: [],
+ };
+}
+
+export function getAcceptanceReportJsonSchema(): Record<string, unknown> {
+ return z.toJSONSchema(acceptanceReportSchema) as Record<string, unknown>;
+}
+
+export interface AcceptanceReportValidation {
+ cases: number;
+ draft: boolean;
+ errors: { path: string; message: string }[];
+ planItems: number;
+ valid: boolean;
+ warnings: { path: string; message: string }[];
+}
+
+/** Validate a local result.json without credentials, network access, or writes. */
+export async function validateAcceptanceReport(
+ reportDir: string,
+): Promise<AcceptanceReportValidation> {
+ const errors: AcceptanceReportValidation['errors'] = [];
+ const warnings: AcceptanceReportValidation['warnings'] = [
+ {
+ path: '',
+ message: 'Media inspection, account language, and remote plan membership are unchecked.',
+ },
+ ];
+ let raw: unknown;
+ try {
+ raw = JSON.parse(await readFile(path.join(reportDir, 'result.json'), 'utf8'));
+ } catch (error) {
+ return {
+ valid: false,
+ draft: true,
+ errors: [
+ { path: 'result.json', message: error instanceof Error ? error.message : String(error) },
+ ],
+ warnings,
+ planItems: 0,
+ cases: 0,
+ };
+ }
+
+ const parsed = acceptanceReportSchema.safeParse(raw);
+ if (!parsed.success) {
+ for (const issue of parsed.error.issues) {
+ errors.push({
+ path: issue.path
+ .map((part) => (typeof part === 'number' ? `[${part}]` : part))
+ .join('.')
+ .replaceAll('.[', '['),
+ message: issue.message,
+ });
+ }
+ const rawObject = isRecord(raw) ? raw : undefined;
+ return {
+ valid: false,
+ draft: true,
+ errors,
+ warnings,
+ planItems: Array.isArray(rawObject?.plan) ? rawObject.plan.length : 0,
+ cases: Array.isArray(rawObject?.cases) ? rawObject.cases.length : 0,
+ };
+ }
+
+ const report = parsed.data;
+ const realReportDir = await realpath(reportDir);
+ const planIds = new Set<string>();
+ for (const [index, item] of report.plan.entries()) {
+ if (planIds.has(item.id)) {
+ errors.push({ path: `plan[${index}].id`, message: `Duplicate plan id "${item.id}".` });
+ }
+ planIds.add(item.id);
+ }
+ const caseIds = new Set<string>();
+ for (const [index, item] of report.cases.entries()) {
+ if (caseIds.has(item.id)) {
+ errors.push({ path: `cases[${index}].id`, message: `Duplicate case id "${item.id}".` });
+ }
+ caseIds.add(item.id);
+ if (!planIds.has(item.id)) {
+ errors.push({
+ path: `cases[${index}].id`,
+ message: `Case id "${item.id}" is not present in plan.`,
+ });
+ }
+
+ try {
+ visualizationMetadata(item);
+ } catch (error) {
+ errors.push({
+ path: `cases[${index}]`,
+ message: error instanceof Error ? error.message : String(error),
+ });
+ }
+
+ for (const [evidenceIndex, evidence] of item.evidence.entries()) {
+ const inferredType = evidenceTypeForFile(evidence.path);
+ if (evidence.type && evidence.type !== inferredType) {
+ errors.push({
+ path: `cases[${index}].evidence[${evidenceIndex}].type`,
+ message: `Evidence type "${evidence.type}" conflicts with filename inference ("${inferredType}"). Ingest infers the type from the file suffix.`,
+ });
+ }
+
+ const absoluteReportDir = path.resolve(reportDir);
+ const absoluteEvidencePath = path.resolve(absoluteReportDir, evidence.path);
+ const relativePath = path.relative(absoluteReportDir, absoluteEvidencePath);
+ const escapesReportDir =
+ relativePath === '..' ||
+ relativePath.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(relativePath);
+ if (path.isAbsolute(evidence.path) || escapesReportDir) {
+ errors.push({
+ path: `cases[${index}].evidence[${evidenceIndex}].path`,
+ message: 'Evidence path must stay within the report directory.',
+ });
+ } else {
+ try {
+ await access(absoluteEvidencePath, constants.R_OK);
+ const realEvidencePath = await realpath(absoluteEvidencePath);
+ const realRelativePath = path.relative(realReportDir, realEvidencePath);
+ const realPathEscapes =
+ realRelativePath === '..' ||
+ realRelativePath.startsWith(`..${path.sep}`) ||
+ path.isAbsolute(realRelativePath);
+ if (realPathEscapes) {
+ errors.push({
+ path: `cases[${index}].evidence[${evidenceIndex}].path`,
+ message: 'Evidence path resolves outside the report directory.',
+ });
+ } else if (!(await stat(realEvidencePath)).isFile()) {
+ errors.push({
+ path: `cases[${index}].evidence[${evidenceIndex}].path`,
+ message: `Referenced evidence path "${evidence.path}" is not a regular file.`,
+ });
+ }
+ } catch {
+ errors.push({
+ path: `cases[${index}].evidence[${evidenceIndex}].path`,
+ message: `Referenced evidence file "${evidence.path}" does not exist or cannot be read.`,
+ });
+ }
+ }
+ if ('chapters' in evidence && evidence.chapters !== undefined) {
+ const rawChapters = evidence.chapters;
+ const parsedChapters = reportEvidence([evidence])[0]?.chapters;
+ if (
+ !Array.isArray(rawChapters) ||
+ (Array.isArray(rawChapters) && (parsedChapters?.length ?? 0) !== rawChapters.length)
+ ) {
+ errors.push({
+ path: `cases[${index}].evidence[${evidenceIndex}].chapters`,
+ message: 'Video chapters contain invalid or unsupported entries.',
+ });
+ }
+ }
+ }
+
+ if (item.status === 'pass' || item.status === 'passed') {
+ const planItemIndex = report.plan.findIndex((plan) => plan.id === item.id);
+ const planItem = report.plan[planItemIndex];
+ if (planItem) {
+ for (const [requiredIndex, required] of planItem.requiredEvidence.entries()) {
+ const type = typeof required === 'string' ? required : required.type;
+ if (!item.evidence.some((evidence) => evidenceTypeForFile(evidence.path) === type)) {
+ errors.push({
+ path: `cases[${index}].evidence`,
+ message: `Claimed pass is missing required evidence "${type}" (plan[${planItemIndex}].requiredEvidence[${requiredIndex}]).`,
+ });
+ }
+ }
+ }
+ }
+ }
+
+ const coveredPlanIds = new Set(report.cases.map((item) => item.id));
+ const unexecutedIds = report.plan
+ .filter((item) => !coveredPlanIds.has(item.id))
+ .map((item) => item.id);
+ const draft = unexecutedIds.length > 0 || report.cases.length === 0;
+ if (draft) {
+ warnings.push({
+ path: 'cases',
+ message:
+ unexecutedIds.length > 0
+ ? `Partial or unexecuted plan coverage; no outcome is claimed for: ${unexecutedIds.join(', ')}.`
+ : 'Draft has no observed cases yet.',
+ });
+ }
+ return {
+ valid: errors.length === 0,
+ draft,
+ errors,
+ warnings,
+ planItems: report.plan.length,
+ cases: report.cases.length,
+ };
+}