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): terminal evidence on the platform (#21734)

Bryan48741d684e2f
diff --git a/apps/server/src/routers/lambda/acceptance/bundle.ts b/apps/server/src/routers/lambda/acceptance/bundle.ts
index 49f113ce217..46eb2cea15a 100644
--- a/apps/server/src/routers/lambda/acceptance/bundle.ts
+++ b/apps/server/src/routers/lambda/acceptance/bundle.ts
@@ -21,6 +21,7 @@ import {
buildCheckReviewOverlay,
createEvidenceFileResolver,
isCurrentReviewPrediction,
+ resolveEvidenceFiles,
REVIEW_PREDICT_MODEL_CONFIG,
shouldSurfaceProposal,
} from '@/server/services/verify';
@@ -156,7 +157,7 @@ export const bundleRouter = router({
evidence.filter(
(e) => timelineResultIds.has(e.checkResultId) || flowResultIds.has(e.checkResultId),
),
- async (e) => ({ ...e, ...(await resolveFileMeta(e.fileId ?? null)) }),
+ (e) => resolveEvidenceFiles(resolveFileMeta, e),
{ concurrency: FILE_META_RESOLVE_CONCURRENCY },
);
const evidenceByResult = new Map<string, typeof enriched>();
diff --git a/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts b/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts
index 4f9221eb2fd..596c291a176 100644
--- a/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts
+++ b/apps/server/src/routers/lambda/verify/fanOutConcurrency.test.ts
@@ -6,7 +6,7 @@ import type * as VerifyServiceModule from '@/server/services/verify';
import { verifyRouter } from '.';
const mocks = vi.hoisted(() => ({
- createEvidence: vi.fn(),
+ createManyEvidence: vi.fn(),
findCriteriaByIds: vi.fn(),
findDocumentById: vi.fn(),
findFileById: vi.fn(),
@@ -62,7 +62,7 @@ vi.mock('@/database/models/verifyCheckResult', () => ({
vi.mock('@/database/models/verifyEvidence', () => ({
VerifyEvidenceModel: vi.fn(function () {
- return { create: mocks.createEvidence };
+ return { createMany: mocks.createManyEvidence };
}),
}));
@@ -125,22 +125,28 @@ describe('verify router fan-outs', () => {
expect(state.peak).toBe(FAN_OUT_LIMIT);
});
- it('submitCheckEvidence writes evidence in order with bounded concurrency', async () => {
+ it('submitCheckEvidence resolves files in order with bounded concurrency and inserts once', async () => {
mocks.findRunById.mockResolvedValue({ id: 'run-1', plan: [] });
mocks.upsertByCheckItem.mockResolvedValue({ id: 'result-1' });
- const { state, tracked } = trackInFlight((row: { content: string }) => ({
- id: `evidence-${row.content}`,
+ const { state, tracked } = trackInFlight((id: string) => ({
+ fileType: 'image/png',
+ id,
+ name: `${id}.png`,
}));
- mocks.createEvidence.mockImplementation(tracked);
+ mocks.findFileById.mockImplementation(tracked);
+ mocks.createManyEvidence.mockImplementation(async (rows: { fileId: string }[]) =>
+ rows.map((row) => ({ id: `evidence-${row.fileId}` })),
+ );
const res = await createCaller().submitCheckEvidence({
checkItemId: 'item-1',
- evidence: ids.map((id) => ({ content: id, type: 'text' as const })),
+ evidence: ids.map((id) => ({ fileId: id, type: 'screenshot' as const })),
verifyRunId: 'run-1',
});
expect(res.evidence).toEqual(ids.map((id) => ({ id: `evidence-${id}` })));
expect(state.peak).toBe(FAN_OUT_LIMIT);
+ expect(mocks.createManyEvidence).toHaveBeenCalledTimes(1);
});
it('listReportSummaries loads reports in order with bounded concurrency', async () => {
diff --git a/apps/server/src/routers/lambda/verify/ingest.evidence.test.ts b/apps/server/src/routers/lambda/verify/ingest.evidence.test.ts
index ac53a9af613..352067868d7 100644
--- a/apps/server/src/routers/lambda/verify/ingest.evidence.test.ts
+++ b/apps/server/src/routers/lambda/verify/ingest.evidence.test.ts
@@ -6,6 +6,7 @@ import { verifyRouter } from '.';
const modelMocks = vi.hoisted(() => ({
createEvidence: vi.fn(),
+ createManyEvidence: vi.fn(),
findFileById: vi.fn(),
findResultById: vi.fn(),
findRunById: vi.fn(),
@@ -46,7 +47,7 @@ vi.mock('@/database/models/file', async (importOriginal) => {
vi.mock('@/database/models/verifyEvidence', () => ({
VerifyEvidenceModel: vi.fn(function () {
- return { create: modelMocks.createEvidence };
+ return { create: modelMocks.createEvidence, createMany: modelMocks.createManyEvidence };
}),
}));
@@ -79,7 +80,7 @@ describe('verifyRouter evidence writes', () => {
).rejects.toThrow('Verification run not found');
expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
- expect(modelMocks.createEvidence).not.toHaveBeenCalled();
+ expect(modelMocks.createManyEvidence).not.toHaveBeenCalled();
});
it('rejects an evidence item with both inline content and fileId', async () => {
@@ -95,7 +96,7 @@ describe('verifyRouter evidence writes', () => {
it('lazily upserts the check result and attaches evidence in one call', async () => {
modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });
modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verdict: 'passed' });
- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+ modelMocks.createManyEvidence.mockResolvedValueOnce([{ id: 'evidence-1' }]);
const res = await createCaller().submitCheckEvidence({
checkItemId: 'item-1',
@@ -107,13 +108,13 @@ describe('verifyRouter evidence writes', () => {
expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
expect.objectContaining({ checkItemId: 'item-1', verdict: 'passed', verifyRunId: 'run-1' }),
);
- expect(modelMocks.createEvidence).toHaveBeenCalledWith(
+ expect(modelMocks.createManyEvidence).toHaveBeenCalledWith([
expect.objectContaining({
checkResultId: 'result-1',
fileId: 'files-1',
type: 'screenshot',
}),
- );
+ ]);
expect(res).toEqual({
checkResult: { id: 'result-1', verdict: 'passed' },
evidence: [{ id: 'evidence-1' }],
@@ -130,7 +131,7 @@ describe('verifyRouter evidence writes', () => {
verifyRunId: 'run-1',
});
- expect(modelMocks.createEvidence).not.toHaveBeenCalled();
+ expect(modelMocks.createManyEvidence).not.toHaveBeenCalled();
expect(res.evidence).toEqual([]);
});
@@ -214,7 +215,7 @@ describe('verifyRouter evidence writes', () => {
id: 'result-2',
verifyRunId: 'round-2',
});
- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+ modelMocks.createManyEvidence.mockResolvedValueOnce([{ id: 'evidence-1' }]);
await createCaller().submitCheckEvidence({
checkItemId: 'item-1',
@@ -226,9 +227,9 @@ describe('verifyRouter evidence writes', () => {
expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
expect.objectContaining({ checkItemId: 'item-1', verifyRunId: 'round-2' }),
);
- expect(modelMocks.createEvidence).toHaveBeenCalledWith(
+ expect(modelMocks.createManyEvidence).toHaveBeenCalledWith([
expect.objectContaining({ checkResultId: 'result-2', type: 'gif' }),
- );
+ ]);
});
it('stores a GIF uploaded as video as a gif, not a video', async () => {
@@ -241,7 +242,7 @@ describe('verifyRouter evidence writes', () => {
name: 'rename.gif',
});
modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });
- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+ modelMocks.createManyEvidence.mockResolvedValueOnce([{ id: 'evidence-1' }]);
await createCaller().submitCheckEvidence({
checkItemId: 'item-1',
@@ -250,9 +251,9 @@ describe('verifyRouter evidence writes', () => {
});
expect(modelMocks.findFileById).toHaveBeenCalledWith('files-gif');
- expect(modelMocks.createEvidence).toHaveBeenCalledWith(
+ expect(modelMocks.createManyEvidence).toHaveBeenCalledWith([
expect.objectContaining({ fileId: 'files-gif', type: 'gif' }),
- );
+ ]);
});
it('keeps the chapters a plan-round video is submitted with', async () => {
@@ -265,9 +266,10 @@ describe('verifyRouter evidence writes', () => {
];
modelMocks.findRunByOperation.mockResolvedValueOnce({ id: 'run-1', plan: [] });
modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });
- modelMocks.createEvidence
- .mockResolvedValueOnce({ id: 'evidence-1' })
- .mockResolvedValueOnce({ id: 'evidence-2' });
+ modelMocks.createManyEvidence.mockResolvedValueOnce([
+ { id: 'evidence-1' },
+ { id: 'evidence-2' },
+ ]);
await createCaller().submitCheckEvidence({
checkItemId: 'item-1',
@@ -278,7 +280,11 @@ describe('verifyRouter evidence writes', () => {
operationId: 'op-1',
});
- expect(modelMocks.createEvidence.mock.calls.map(([row]) => row.metadata)).toEqual([
+ expect(
+ modelMocks.createManyEvidence.mock.calls[0][0].map(
+ (row: { metadata: unknown }) => row.metadata,
+ ),
+ ).toEqual([
{
chapters: [
{ kind: 'step', label: 'Reload with listDevices held', t: 1.2 },
@@ -307,10 +313,56 @@ describe('verifyRouter evidence writes', () => {
);
expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
- expect(modelMocks.createEvidence).not.toHaveBeenCalled();
+ expect(modelMocks.createManyEvidence).not.toHaveBeenCalled();
});
});
+ it('rejects an invalid terminal record before storing a verdict or evidence', async () => {
+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });
+
+ await expect(
+ createCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ evidence: [{ content: 'authored text', metadata: { terminal: {} }, type: 'terminal' }],
+ verdict: 'passed',
+ verifyRunId: 'run-1',
+ }),
+ ).rejects.toThrow('Invalid terminal evidence metadata');
+
+ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
+ expect(modelMocks.createManyEvidence).not.toHaveBeenCalled();
+ });
+
+ it('resolves a large submission with bounded concurrency and inserts it once', async () => {
+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });
+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });
+ let inFlight = 0;
+ let peak = 0;
+ modelMocks.findFileById.mockImplementation(async (id: string) => {
+ inFlight += 1;
+ peak = Math.max(peak, inFlight);
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ inFlight -= 1;
+ return { fileType: 'image/png', id, name: `${id}.png` };
+ });
+ const evidence = Array.from({ length: 12 }, (_, i) => ({
+ fileId: `files-${i}`,
+ type: 'screenshot' as const,
+ }));
+ modelMocks.createManyEvidence.mockResolvedValueOnce(evidence.map((_, i) => ({ id: `e-${i}` })));
+
+ await createCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ evidence,
+ verifyRunId: 'run-1',
+ });
+
+ expect(modelMocks.findFileById).toHaveBeenCalledTimes(12);
+ expect(peak).toBeLessThanOrEqual(5);
+ expect(modelMocks.createManyEvidence).toHaveBeenCalledTimes(1);
+ expect(modelMocks.createManyEvidence.mock.calls[0][0]).toHaveLength(12);
+ });
+
describe('uploadEvidence', () => {
it('rejects evidence with both inline content and fileId', async () => {
await expect(
@@ -368,4 +420,86 @@ describe('verifyRouter evidence writes', () => {
).rejects.toThrow('Provide exactly one of `content` or `fileId`.');
});
});
+
+ describe.each(['uploadEvidence', 'submitCheckEvidence'] as const)(
+ '%s inline evidence content limit',
+ (procedure) => {
+ const submit = (
+ content: string,
+ type: 'text' | 'markdown' | 'transcript' | 'dom_snapshot' | 'terminal' = 'text',
+ ) =>
+ procedure === 'uploadEvidence'
+ ? createCaller().uploadEvidence({ checkResultId: 'result-1', content, type })
+ : createCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ evidence: [{ content, type }],
+ verdict: 'passed',
+ verifyRunId: 'run-1',
+ });
+
+ it.each([
+ { label: 'CLI threshold', content: 'x'.repeat(5000) },
+ { label: 'server boundary', content: 'x'.repeat(6000) },
+ { label: 'Chinese boundary', content: '中'.repeat(6000) },
+ { label: 'UTF-16 boundary', content: '😀'.repeat(3000) },
+ ])('preserves $label content without truncation', async ({ content }) => {
+ if (procedure === 'uploadEvidence') {
+ modelMocks.findResultById.mockResolvedValueOnce({ id: 'result-1' });
+ modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+ } else {
+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1', plan: [] });
+ modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1' });
+ modelMocks.createManyEvidence.mockResolvedValueOnce([{ id: 'evidence-1' }]);
+ }
+
+ await submit(content);
+
+ const row =
+ procedure === 'uploadEvidence'
+ ? modelMocks.createEvidence.mock.calls[0][0]
+ : modelMocks.createManyEvidence.mock.calls[0][0][0];
+ expect(row.content).toBe(content);
+ });
+
+ it.each(['text', 'markdown', 'transcript', 'dom_snapshot', 'terminal'] as const)(
+ 'rejects oversized %s evidence before any lookup or write',
+ async (type) => {
+ await expect(submit('x'.repeat(6001), type)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('6000'),
+ });
+ expect(modelMocks.findResultById).not.toHaveBeenCalled();
+ expect(modelMocks.findRunById).not.toHaveBeenCalled();
+ expect(modelMocks.findFileById).not.toHaveBeenCalled();
+ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
+ expect(modelMocks.createEvidence).not.toHaveBeenCalled();
+ expect(modelMocks.createManyEvidence).not.toHaveBeenCalled();
+ },
+ );
+
+ it('counts surrogate pairs consistently with the CLI', async () => {
+ await expect(submit('😀'.repeat(3001))).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('6000'),
+ });
+ });
+ },
+ );
+
+ it('rejects a batch containing oversized evidence before persisting any result', async () => {
+ await expect(
+ createCaller().submitCheckEvidence({
+ checkItemId: 'item-1',
+ evidence: [
+ { content: 'valid', type: 'text' },
+ { content: 'x'.repeat(6001), type: 'text' },
+ ],
+ verdict: 'passed',
+ verifyRunId: 'run-1',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: expect.stringContaining('6000') });
+
+ expect(modelMocks.upsertByCheckItem).not.toHaveBeenCalled();
+ expect(modelMocks.createManyEvidence).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/routers/lambda/verify/ingest.ts b/apps/server/src/routers/lambda/verify/ingest.ts
index 4c39d89a907..0682b18fe91 100644
--- a/apps/server/src/routers/lambda/verify/ingest.ts
+++ b/apps/server/src/routers/lambda/verify/ingest.ts
@@ -1,19 +1,10 @@
-import { normalizeEvidenceMetadata } from '@lobechat/const/verify';
-import type {
- VerifyCheckItem,
- VerifyCheckResultMetadata,
- VerifyEvidenceCapturedBy,
- VerifyEvidenceType,
-} from '@lobechat/types';
+import type { VerifyCheckItem, VerifyCheckResultMetadata } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
-import pMap from 'p-map';
import { z } from 'zod';
-import type { FileModel } from '@/database/models/file';
-import type { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
import type { VerifyRunModel } from '@/database/models/verifyRun';
import { router } from '@/libs/trpc/lambda';
-import { evidenceTypeForStoredFile, resolveLiveRoundForItem } from '@/server/services/verify';
+import { prepareEvidenceRows, resolveLiveRoundForItem } from '@/server/services/verify';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
import {
@@ -45,6 +36,7 @@ const evidenceTypeSchema = z.enum([
'markdown',
'dom_snapshot',
'transcript',
+ 'terminal',
]);
const evidenceCapturedBySchema = z.enum(['agent-browser', 'cdp', 'cli', 'program', 'llm_judge']);
@@ -60,12 +52,22 @@ const toulminSchema = z.object({
const statusForVerdict = (verdict: 'passed' | 'failed' | 'uncertain') =>
verdict === 'passed' ? ('passed' as const) : ('failed' as const);
+// The CLI inlines fewer than 5000 UTF-16 code units. Leave 20% headroom at
+// the API boundary; larger evidence must go through file storage.
+const MAX_INLINE_EVIDENCE_CONTENT_LENGTH = 6000;
+const inlineEvidenceContentSchema = z
+ .string()
+ .min(1)
+ .refine((content) => content.length <= MAX_INLINE_EVIDENCE_CONTENT_LENGTH, {
+ message: `Inline evidence content must not exceed ${MAX_INLINE_EVIDENCE_CONTENT_LENGTH} UTF-16 code units. Upload larger evidence as a file and provide fileId instead.`,
+ });
+
const uploadEvidenceInputSchema = z
.object({
capturedBy: evidenceCapturedBySchema.optional(),
// Exactly one of `content` (inline text) or `fileId` (already-uploaded artifact).
checkResultId: z.string(),
- content: z.string().min(1).optional(),
+ content: inlineEvidenceContentSchema.optional(),
description: z.string().optional(),
fileId: z.string().min(1).optional(),
metadata: z.unknown().optional(),
@@ -87,46 +89,6 @@ const resolveRunByOperation = async (ctx: { runModel: VerifyRunModel }, operatio
return run;
};
-interface VerifyEvidenceRowInput {
- capturedBy?: VerifyEvidenceCapturedBy | null;
- content?: string | null;
- description?: string | null;
- fileId?: string | null;
- metadata?: unknown;
- type: VerifyEvidenceType;
-}
-
-/**
- * Store one evidence artifact on a check result — the single write path behind
- * `uploadEvidence` and `submitCheckEvidence`. A file-backed artifact is stored
- * under the medium of the file itself, not the caller's label, and its metadata
- * (a video's chapters, a comparison pair) is normalized for that medium.
- */
-const createVerifyEvidenceRow = async (
- ctx: { evidenceModel: VerifyEvidenceModel; fileModel: FileModel },
- checkResultId: string,
- input: VerifyEvidenceRowInput,
-) => {
- const type = input.fileId
- ? evidenceTypeForStoredFile(input.type, await ctx.fileModel.findById(input.fileId))
- : input.type;
-
- return ctx.evidenceModel.create({
- capturedAt: new Date(),
- capturedBy: input.capturedBy ?? null,
- checkResultId,
- content: input.content ?? null,
- description: input.description ?? null,
- fileId: input.fileId ?? null,
- metadata: normalizeEvidenceMetadata(input.metadata, type) ?? null,
- type,
- });
-};
-
-// A submitted result carries a runtime-sized evidence list; cap the per-entry
-// file lookup + insert.
-const EVIDENCE_WRITE_CONCURRENCY = 5;
-
export const ingestRouter = router({
ingestResult: verifyWriteProcedure
.input(
@@ -208,7 +170,8 @@ export const ingestRouter = router({
assertOperationInScope(ctx, run?.operationId);
}
- return createVerifyEvidenceRow(ctx, result.id, input);
+ const [row] = await prepareEvidenceRows(ctx.fileModel, [input]);
+ return ctx.evidenceModel.create({ ...row, checkResultId: result.id });
}),
/**
* Builder self-evidence contract: submit a check item's verdict AND its
@@ -230,10 +193,10 @@ export const ingestRouter = router({
z
.object({
capturedBy: evidenceCapturedBySchema.optional(),
- content: z.string().min(1).optional(),
+ content: inlineEvidenceContentSchema.optional(),
description: z.string().optional(),
fileId: z.string().min(1).optional(),
- metadata: z.unknown().optional(), // as on uploadEvidence: a video's chapters
+ metadata: z.unknown().optional(),
type: evidenceTypeSchema,
})
.refine((e) => Boolean(e.content) !== Boolean(e.fileId), {
@@ -293,6 +256,9 @@ export const ingestRouter = router({
.join('; ')}`,
});
+ // Validate every record before writing a verdict or any evidence.
+ const evidenceRows = await prepareEvidenceRows(ctx.fileModel, input.evidence ?? []);
+
const checkResult = await ctx.resultModel.upsertByCheckItem({
checkItemId: input.checkItemId,
checkItemIndex: input.checkItemIndex ?? planItem?.index,
@@ -308,11 +274,12 @@ export const ingestRouter = router({
verifyRunId: run.id,
});
- const evidence = input.evidence?.length
- ? await pMap(input.evidence, (e) => createVerifyEvidenceRow(ctx, checkResult.id, e), {
- concurrency: EVIDENCE_WRITE_CONCURRENCY,
- })
- : [];
+ const evidence =
+ evidenceRows.length === 0
+ ? []
+ : await ctx.evidenceModel.createMany(
+ evidenceRows.map((row) => ({ ...row, checkResultId: checkResult.id })),
+ );
return { checkResult, evidence };
}),
diff --git a/apps/server/src/routers/lambda/verify/operationScope.test.ts b/apps/server/src/routers/lambda/verify/operationScope.test.ts
index b28bd252d48..8c52946e0f3 100644
--- a/apps/server/src/routers/lambda/verify/operationScope.test.ts
+++ b/apps/server/src/routers/lambda/verify/operationScope.test.ts
@@ -6,6 +6,7 @@ import { verifyRouter } from '.';
const modelMocks = vi.hoisted(() => ({
createEvidence: vi.fn(),
+ createManyEvidence: vi.fn(),
findFileById: vi.fn(),
findResultById: vi.fn(),
findRunById: vi.fn(),
@@ -47,7 +48,7 @@ vi.mock('@/database/models/file', async (importOriginal) => {
vi.mock('@/database/models/verifyEvidence', () => ({
VerifyEvidenceModel: vi.fn(function () {
- return { create: modelMocks.createEvidence };
+ return { create: modelMocks.createEvidence, createMany: modelMocks.createManyEvidence };
}),
}));
@@ -78,7 +79,7 @@ describe("verifyRouter with a run's operation token", () => {
it('files evidence into its own round by operation id', async () => {
modelMocks.findRunByOperation.mockResolvedValueOnce(ownRun);
modelMocks.upsertByCheckItem.mockResolvedValueOnce({ id: 'result-1', verifyRunId: 'run-own' });
- modelMocks.createEvidence.mockResolvedValueOnce({ id: 'evidence-1' });
+ modelMocks.createManyEvidence.mockResolvedValueOnce([{ id: 'evidence-1' }]);
await createOperationCaller().submitCheckEvidence({
checkItemId: 'item-1',
@@ -89,9 +90,9 @@ describe("verifyRouter with a run's operation token", () => {
expect(modelMocks.upsertByCheckItem).toHaveBeenCalledWith(
expect.objectContaining({ checkItemId: 'item-1', verifyRunId: 'run-own' }),
);
- expect(modelMocks.createEvidence).toHaveBeenCalledWith(
+ expect(modelMocks.createManyEvidence).toHaveBeenCalledWith([
expect.objectContaining({ checkResultId: 'result-1', fileId: 'files-1' }),
- );
+ ]);
});
it("refuses another operation's round, by operation id or by run id", async () => {
diff --git a/apps/server/src/routers/lambda/verifyRunReport.ts b/apps/server/src/routers/lambda/verifyRunReport.ts
index b0f77fe7694..fa68814f3a4 100644
--- a/apps/server/src/routers/lambda/verifyRunReport.ts
+++ b/apps/server/src/routers/lambda/verifyRunReport.ts
@@ -13,7 +13,7 @@ import {
import { isUuid } from '@/database/utils/uuid';
import { publicProcedure } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { createEvidenceFileResolver } from '@/server/services/verify';
+import { createEvidenceFileResolver, resolveEvidenceFiles } from '@/server/services/verify';
const publicVerifyReportProcedure = publicProcedure.use(serverDatabase);
@@ -106,11 +106,9 @@ export const verifyRunReportProcedures = {
.orderBy(asc(verifyEvidence.createdAt));
return {
...r,
- evidence: await pMap(
- evidence,
- async (e) => ({ ...e, ...(await resolveFileMeta(e.fileId)) }),
- { concurrency: EVIDENCE_LOAD_CONCURRENCY },
- ),
+ evidence: await pMap(evidence, (e) => resolveEvidenceFiles(resolveFileMeta, e), {
+ concurrency: EVIDENCE_LOAD_CONCURRENCY,
+ }),
};
},
{ concurrency: EVIDENCE_LOAD_CONCURRENCY },
diff --git a/apps/server/src/services/verify/__tests__/acceptancePurge.test.ts b/apps/server/src/services/verify/__tests__/acceptancePurge.test.ts
index 9b02337850d..40fd8bbd686 100644
--- a/apps/server/src/services/verify/__tests__/acceptancePurge.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptancePurge.test.ts
@@ -54,14 +54,15 @@ describe('acceptancePurge', () => {
.insert(verifyCheckResults)
.values({ checkItemId: 'c1', userId, verifierType: 'agent', verifyRunId: run.id })
.returning();
- await serverDB.insert(verifyEvidence).values(
- fileIds.map((fileId) => ({
- checkResultId: result.id,
- fileId,
- type: 'screenshot' as const,
- userId,
- })),
- );
+ if (fileIds.length > 0)
+ await serverDB.insert(verifyEvidence).values(
+ fileIds.map((fileId) => ({
+ checkResultId: result.id,
+ fileId,
+ type: 'screenshot' as const,
+ userId,
+ })),
+ );
return run.id;
};
@@ -250,6 +251,56 @@ describe('acceptancePurge', () => {
expect(otherEvidence.map((row) => row.fileId)).toEqual([fileIds[2]]);
});
+ it('purges a terminal evidence’s artifact files unless another round still cites them', async () => {
+ const stdout = await seedFile({ fileHash: null, url: 'stdout.txt' });
+ const cast = await seedFile({ fileHash: null, url: 'session.cast' });
+ const shared = await seedFile({ fileHash: null, url: 'shared-stderr.txt' });
+ const terminal = (artifacts: Record<string, string>) => ({
+ terminal: {
+ artifacts: Object.fromEntries(
+ Object.entries(artifacts).map(([key, fileId]) => [key, { fileId }]),
+ ),
+ },
+ });
+ const resultOf = async (runId: string) =>
+ (await serverDB.query.verifyCheckResults.findFirst({
+ where: eq(verifyCheckResults.verifyRunId, runId),
+ }))!.id;
+
+ await serverDB.insert(verifyEvidence).values({
+ checkResultId: await resultOf(runIds[0]),
+ content: '$ ls',
+ metadata: terminal({ cast, stderr: shared, stdout }),
+ type: 'terminal',
+ userId,
+ });
+ const otherRunId = await seedRound(await seedAcceptance(), 1, []);
+ await serverDB.insert(verifyEvidence).values({
+ checkResultId: await resultOf(otherRunId),
+ content: '$ ls',
+ metadata: terminal({ stderr: shared }),
+ type: 'terminal',
+ userId,
+ });
+
+ await expect(
+ previewAcceptancePurge(serverDB, userId, undefined, [acceptanceId]),
+ ).resolves.toMatchObject({ fileCount: 5 });
+ await expect(
+ purgeAcceptance(serverDB, fileService, userId, undefined, acceptanceId),
+ ).resolves.toEqual({ deletedFiles: 5, deletedRuns: 2 });
+
+ expect(fileService.deleteFiles).toHaveBeenCalledWith(
+ expect.arrayContaining(['stdout.txt', 'session.cast']),
+ );
+ await expect(
+ serverDB.query.files.findMany({ where: inArray(files.id, [stdout, cast]) }),
+ ).resolves.toHaveLength(0);
+ await expect(
+ serverDB.query.files.findFirst({ where: eq(files.id, shared) }),
+ ).resolves.toBeDefined();
+ });
+
it('deletes rows but leaves storage alone when REMOVE_GLOBAL_FILE is off', async () => {
envMock.serverDBEnv.REMOVE_GLOBAL_FILE = false;
diff --git a/apps/server/src/services/verify/__tests__/executor.test.ts b/apps/server/src/services/verify/__tests__/executor.test.ts
index 9abc6bbd863..3a17ae3bb58 100644
--- a/apps/server/src/services/verify/__tests__/executor.test.ts
+++ b/apps/server/src/services/verify/__tests__/executor.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { terminalRecord } from '@lobechat/utils/verify/terminalEvidence.fixture';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { VerifyExecutorService } from '../executor';
@@ -520,4 +521,59 @@ describe('VerifyExecutorService', () => {
type: 'image_url',
});
});
+
+ it('gates an execution requirement on provenance and points the repair at a real capture', async () => {
+ const plan = [
+ {
+ id: 'cli',
+ index: 0,
+ required: true,
+ title: 'CLI lists agents',
+ verifierConfig: { requiredEvidence: [{ provenance: 'execution', type: 'terminal' }] },
+ verifierType: 'llm',
+ },
+ ];
+ mocks.runEnsureForOperation.mockResolvedValue({
+ id: 'run-1',
+ plan,
+ planConfirmedAt: new Date(),
+ });
+ // An authored example has the right medium but no execution behind it.
+ mocks.evidenceListByRun.mockResolvedValue([
+ {
+ checkItemId: 'cli',
+ content: '$ lh agent list',
+ metadata: {
+ terminal: terminalRecord({
+ capture: { ...terminalRecord().capture, mode: 'import' },
+ source: { kind: 'authored' },
+ }),
+ },
+ type: 'terminal',
+ },
+ ]);
+ mocks.resultListByRun.mockReset().mockResolvedValue([]);
+
+ await new VerifyExecutorService({} as never, 'user-1').execute({
+ deliverable: 'done',
+ goal: 'ship',
+ modelConfig: { model: 'model', provider: 'provider' },
+ operationId: 'op-1',
+ });
+
+ expect(mocks.aiGenerateObject).not.toHaveBeenCalled();
+ expect(mocks.resultUpdateByCheckItem).toHaveBeenCalledWith(
+ 'run-1',
+ 'cli',
+ expect.objectContaining({
+ suggestion: expect.stringContaining(
+ 'Run the command for real and publish it as terminal evidence (captured or imported, not authored).',
+ ),
+ toulmin: {
+ limitation: 'Required evidence not provided: terminal from a real command execution.',
+ },
+ verdict: 'uncertain',
+ }),
+ );
+ });
});
diff --git a/apps/server/src/services/verify/__tests__/terminalEvidence.test.ts b/apps/server/src/services/verify/__tests__/terminalEvidence.test.ts
new file mode 100644
index 00000000000..6197da79a0b
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/terminalEvidence.test.ts
@@ -0,0 +1,110 @@
+import { terminalRecord } from '@lobechat/utils/verify/terminalEvidence.fixture';
+import { describe, expect, it, vi } from 'vitest';
+
+import { resolveEvidenceFiles } from '../evidenceFiles';
+import { resolveEvidenceMetadata } from '../terminalEvidence';
+
+const HASH = 'a'.repeat(64);
+const file = { fileHash: HASH, size: 3 };
+
+describe('resolveEvidenceMetadata', () => {
+ it('stores a valid terminal record whose artifacts are the caller’s own matching files', async () => {
+ const findFile = vi.fn().mockResolvedValue(file);
+ const metadata = (await resolveEvidenceMetadata(findFile, 'terminal', {
+ terminal: terminalRecord(),
+ })) as { terminal: { execution: { command: string } } };
+ expect(findFile).toHaveBeenCalledWith('file_1');
+ expect(metadata.terminal.execution.command).toBe('ls -la');
+ });
+
+ it('refuses terminal evidence without a valid record', async () => {
+ await expect(resolveEvidenceMetadata(vi.fn(), 'terminal', undefined)).rejects.toThrow(
+ /Invalid terminal evidence metadata/,
+ );
+ await expect(
+ resolveEvidenceMetadata(vi.fn(), 'terminal', {
+ terminal: { ...terminalRecord(), version: 9 },
+ }),
+ ).rejects.toThrow(/terminal.version/);
+ });
+
+ it('refuses artifacts that are missing, foreign, or not the hashed file', async () => {
+ const noFileId = terminalRecord({
+ artifacts: { stdout: { path: 'stdout.txt', sha256: HASH, size: 3 } },
+ });
+ await expect(
+ resolveEvidenceMetadata(vi.fn(), 'terminal', { terminal: noFileId }),
+ ).rejects.toThrow(/no fileId/);
+ await expect(
+ resolveEvidenceMetadata(vi.fn().mockResolvedValue(undefined), 'terminal', {
+ terminal: terminalRecord(),
+ }),
+ ).rejects.toThrow(/does not exist or is not yours/);
+ await expect(
+ resolveEvidenceMetadata(
+ vi.fn().mockResolvedValue({ fileHash: 'b'.repeat(64), size: 3 }),
+ 'terminal',
+ {
+ terminal: terminalRecord(),
+ },
+ ),
+ ).rejects.toThrow(/does not match/);
+ await expect(
+ resolveEvidenceMetadata(vi.fn().mockResolvedValue({ fileHash: HASH, size: 4 }), 'terminal', {
+ terminal: terminalRecord(),
+ }),
+ ).rejects.toThrow(/does not match/);
+ });
+
+ it('drops a terminal record smuggled onto another medium', async () => {
+ expect(
+ await resolveEvidenceMetadata(vi.fn(), 'text', {
+ comparison: { id: 'x' },
+ terminal: terminalRecord(),
+ }),
+ ).toEqual({ comparison: { id: 'x' } });
+ expect(
+ await resolveEvidenceMetadata(vi.fn(), 'text', { terminal: terminalRecord() }),
+ ).toBeNull();
+ });
+});
+
+describe('resolveEvidenceFiles', () => {
+ const resolveFileMeta = vi.fn(async (fileId: string | null) => ({
+ fileHeight: null,
+ fileName: fileId,
+ fileUrl: fileId ? `https://s3.test/${fileId}?sig` : null,
+ fileWidth: null,
+ }));
+
+ it('signs every artifact a terminal record references', async () => {
+ const resolved = await resolveEvidenceFiles(resolveFileMeta, {
+ fileId: null,
+ metadata: { terminal: terminalRecord() },
+ type: 'terminal',
+ });
+ expect(resolved.terminalArtifacts).toEqual({
+ stdout: { fileUrl: 'https://s3.test/file_1?sig', sha256: HASH, size: 3 },
+ });
+ });
+
+ it('leaves other evidence and broken records without artifacts', async () => {
+ expect(
+ (
+ await resolveEvidenceFiles(resolveFileMeta, {
+ fileId: 'f',
+ metadata: { terminal: terminalRecord() },
+ type: 'text',
+ })
+ ).terminalArtifacts,
+ ).toBeUndefined();
+ expect(
+ (
+ await resolveEvidenceFiles(resolveFileMeta, {
+ metadata: { terminal: {} },
+ type: 'terminal',
+ })
+ ).terminalArtifacts,
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/verify/acceptancePurge.ts b/apps/server/src/services/verify/acceptancePurge.ts
index b5b2a719187..40bb5880f29 100644
--- a/apps/server/src/services/verify/acceptancePurge.ts
+++ b/apps/server/src/services/verify/acceptancePurge.ts
@@ -1,6 +1,7 @@
+import { verifyEvidenceFileIds } from '@lobechat/const/verify';
import { FileSource } from '@lobechat/types';
-import { and, eq, inArray, isNotNull, notExists, notInArray } from 'drizzle-orm';
-import { alias } from 'drizzle-orm/pg-core';
+import type { SQL } from 'drizzle-orm';
+import { and, eq, inArray, notInArray, or, sql } from 'drizzle-orm';
import { serverDBEnv } from '@/config/db';
import { AcceptanceModel } from '@/database/models/acceptance';
@@ -38,35 +39,63 @@ const listRunIds = async (
return rows.map((row) => row.id);
};
-const listExclusiveEvidenceFileIds = async (db: LobeChatDatabase, runIds: string[]) => {
- if (runIds.length === 0) return [];
- const otherEvidence = alias(verifyEvidence, 'other_evidence');
- const otherResults = alias(verifyCheckResults, 'other_results');
- const rows = await db
- .selectDistinct({ fileId: verifyEvidence.fileId })
+/** Evidence rows of the given rounds (inside) or of every other round (outside). */
+const evidenceRows = (
+ db: LobeChatDatabase,
+ runIds: string[],
+ where: 'inside' | 'outside',
+ extra?: SQL,
+) =>
+ db
+ .select({
+ fileId: verifyEvidence.fileId,
+ metadata: verifyEvidence.metadata,
+ type: verifyEvidence.type,
+ })
.from(verifyEvidence)
.innerJoin(verifyCheckResults, eq(verifyCheckResults.id, verifyEvidence.checkResultId))
- .innerJoin(files, eq(files.id, verifyEvidence.fileId))
.where(
and(
- inArray(verifyCheckResults.verifyRunId, runIds),
- isNotNull(verifyEvidence.fileId),
- eq(files.source, FileSource.Acceptance),
- notExists(
- db
- .select({ id: otherEvidence.id })
- .from(otherEvidence)
- .innerJoin(otherResults, eq(otherResults.id, otherEvidence.checkResultId))
- .where(
- and(
- eq(otherEvidence.fileId, verifyEvidence.fileId),
- notInArray(otherResults.verifyRunId, runIds),
- ),
- ),
- ),
+ where === 'inside'
+ ? inArray(verifyCheckResults.verifyRunId, runIds)
+ : notInArray(verifyCheckResults.verifyRunId, runIds),
+ extra,
),
);
- return rows.map((row) => row.fileId!);
+
+/**
+ * Acceptance files that only these rounds' evidence references — a row's own
+ * payload file and, for terminal evidence, the stdout / stderr / recording files
+ * its record names. A file another round still cites survives the purge.
+ */
+const listExclusiveEvidenceFileIds = async (db: LobeChatDatabase, runIds: string[]) => {
+ if (runIds.length === 0) return [];
+ const candidates = [
+ ...new Set((await evidenceRows(db, runIds, 'inside')).flatMap(verifyEvidenceFileIds)),
+ ];
+ if (candidates.length === 0) return [];
+
+ const acceptanceFiles = await db
+ .select({ id: files.id })
+ .from(files)
+ .where(and(inArray(files.id, candidates), eq(files.source, FileSource.Acceptance)));
+ if (acceptanceFiles.length === 0) return [];
+ const ids = acceptanceFiles.map((file) => file.id);
+
+ const citedElsewhere = await evidenceRows(
+ db,
+ runIds,
+ 'outside',
+ or(
+ inArray(verifyEvidence.fileId, ids),
+ and(
+ eq(verifyEvidence.type, 'terminal'),
+ sql`jsonb_path_exists(${verifyEvidence.metadata}, '$.terminal.artifacts.*.fileId ? (@ == $ids[*])', jsonb_build_object('ids', ${JSON.stringify(ids)}::jsonb))`,
+ ),
+ ),
+ );
+ const retained = new Set(citedElsewhere.flatMap(verifyEvidenceFileIds));
+ return ids.filter((id) => !retained.has(id));
};
const listRetainedHashes = async (
diff --git a/apps/server/src/services/verify/evidenceCoverage.ts b/apps/server/src/services/verify/evidenceCoverage.ts
index 6f855d36237..2196f74bd1a 100644
--- a/apps/server/src/services/verify/evidenceCoverage.ts
+++ b/apps/server/src/services/verify/evidenceCoverage.ts
@@ -1,10 +1,31 @@
import { readRequiredEvidence as readSpecs } from '@lobechat/const/verify';
-import type { RequiredEvidenceSpec } from '@lobechat/types';
+import type { RequiredEvidenceSpec, VerifyEvidenceType } from '@lobechat/types';
+import { type CoverageEvidence, coverageGaps } from '@lobechat/utils/verify/evidenceCoverage';
-// The coverage rule lives in `@lobechat/const/verify` so the CLI reports the
-// same gaps the verifier's structural gate enforces.
-export { coverageGaps, runEvidenceGaps } from '@lobechat/const/verify';
+export { coverageGaps, executionGapTypes } from '@lobechat/utils/verify/evidenceCoverage';
+/**
+ * Read the (optional) evidence requirement a criterion declares on its config.
+ * Evidence-driven criteria list the artifact types they need under
+ * `verifierConfig.requiredEvidence`; everything else returns undefined.
+ */
export const readRequiredEvidence = (
config: Record<string, unknown> | undefined | null,
): RequiredEvidenceSpec[] | undefined => readSpecs<RequiredEvidenceSpec>(config);
+
+/** The requirements the run itself must evidence — see {@link runEvidenceGaps}. */
+export const runEvidenceSpecs = (config: Record<string, unknown> | undefined | null) =>
+ readRequiredEvidence(config)?.filter((spec) => !spec.scope || spec.scope === 'run_evidence');
+
+/**
+ * Run-evidence types a criterion still misses. `deliverable` / `task_artifacts`
+ * requirements are resolved by the verifier from the operation's documents and
+ * files, so only `run_evidence` must exist as verify_evidence rows. This is the
+ * one coverage rule shared by the builder handoff and the structural gate:
+ * when they disagree, a builder that already evidenced a criterion is treated
+ * as missing evidence and gets its final report pasted into every check.
+ */
+export const runEvidenceGaps = (
+ config: Record<string, unknown> | undefined | null,
+ evidence: CoverageEvidence[],
+): VerifyEvidenceType[] => coverageGaps(runEvidenceSpecs(config), evidence);
diff --git a/apps/server/src/services/verify/evidenceFiles.ts b/apps/server/src/services/verify/evidenceFiles.ts
index 6f224a1fbe2..85a29cc1a15 100644
--- a/apps/server/src/services/verify/evidenceFiles.ts
+++ b/apps/server/src/services/verify/evidenceFiles.ts
@@ -1,3 +1,9 @@
+import {
+ readTerminalEvidenceMetadata,
+ TERMINAL_ARTIFACT_KEYS,
+ type TerminalArtifactKey,
+} from '@lobechat/utils/verify/terminalEvidence';
+
import { FileModel } from '@/database/models/file';
import type { LobeChatDatabase } from '@/database/type';
import { FileService } from '@/server/services/file';
@@ -79,3 +85,51 @@ export const createEvidenceFileResolver = (
}
};
};
+
+/** A terminal evidence artifact as the page loads it: a signed URL in place of the file id. */
+export interface TerminalArtifactLink {
+ fileUrl: string | null;
+ sha256: string;
+ size: number;
+}
+
+/**
+ * Display metadata for an evidence row: its own file, plus — for a `terminal`
+ * evidence — signed URLs for the stdout / stderr / output / recording files
+ * its record references. Unknown or invalid records resolve to no artifacts,
+ * and the page falls back to the row's text payload.
+ */
+export const resolveEvidenceFiles = async <
+ T extends { fileId?: string | null; metadata?: unknown; type: string },
+>(
+ resolveFileMeta: (fileId: string | null) => Promise<EvidenceFileMeta>,
+ evidence: T,
+): Promise<
+ T &
+ EvidenceFileMeta & {
+ terminalArtifacts?: Partial<Record<TerminalArtifactKey, TerminalArtifactLink>>;
+ }
+> => {
+ const meta = await resolveFileMeta(evidence.fileId ?? null);
+ if (evidence.type !== 'terminal') return { ...evidence, ...meta };
+
+ const terminal = readTerminalEvidenceMetadata(evidence.metadata);
+ if (!terminal) return { ...evidence, ...meta };
+
+ const entries = await Promise.all(
+ TERMINAL_ARTIFACT_KEYS.map(async (key) => {
+ const artifact = terminal.artifacts[key];
+ if (!artifact?.fileId) return null;
+ const file = await resolveFileMeta(artifact.fileId);
+ return [
+ key,
+ { fileUrl: file.fileUrl, sha256: artifact.sha256, size: artifact.size },
+ ] as const;
+ }),
+ );
+ return {
+ ...evidence,
+ ...meta,
+ terminalArtifacts: Object.fromEntries(entries.filter((entry) => entry !== null)),
+ };
+};
diff --git a/apps/server/src/services/verify/evidenceIntake.ts b/apps/server/src/services/verify/evidenceIntake.ts
new file mode 100644
index 00000000000..a9d4b5e6d01
--- /dev/null
+++ b/apps/server/src/services/verify/evidenceIntake.ts
@@ -0,0 +1,62 @@
+import type { VerifyEvidenceCapturedBy, VerifyEvidenceType } from '@lobechat/types';
+import pMap from 'p-map';
+
+import type { FileModel } from '@/database/models/file';
+
+import { evidenceTypeForStoredFile } from './evidenceMedium';
+import { resolveEvidenceMetadata } from './terminalEvidence';
+
+/** One evidence entry as a caller submits it — before its medium and metadata are trusted. */
+export interface IncomingEvidence {
+ capturedBy?: VerifyEvidenceCapturedBy;
+ content?: string;
+ description?: string;
+ fileId?: string;
+ metadata?: unknown;
+ type: VerifyEvidenceType;
+}
+
+/** Entries of one submission resolved at a time (a file lookup and a record check each). */
+const RESOLVE_CONCURRENCY = 5;
+
+/** Store a file-backed artifact under the medium of the file itself, not the caller's label. */
+const storedEvidenceType = async (
+ fileModel: Pick<FileModel, 'findById'>,
+ type: VerifyEvidenceType,
+ fileId?: string | null,
+): Promise<VerifyEvidenceType> =>
+ fileId ? evidenceTypeForStoredFile(type, await fileModel.findById(fileId)) : type;
+
+/**
+ * Turn submitted evidence into rows ready to insert, missing only the check
+ * result they back. Every entry is resolved before the caller writes anything:
+ * a rejected terminal record must fail the whole submission, not leave a
+ * verdict behind without the evidence that was meant to back it. File lookups
+ * are owner-scoped through `fileModel`, so a record can only bind the caller's
+ * own artifacts.
+ */
+export const prepareEvidenceRows = (
+ fileModel: Pick<FileModel, 'findById'>,
+ entries: IncomingEvidence[],
+) =>
+ pMap(
+ entries,
+ async (entry) => {
+ const type = await storedEvidenceType(fileModel, entry.type, entry.fileId);
+ const metadata = await resolveEvidenceMetadata(
+ (fileId) => fileModel.findById(fileId),
+ type,
+ entry.metadata,
+ );
+ return {
+ capturedAt: new Date(),
+ capturedBy: entry.capturedBy ?? null,
+ content: entry.content ?? null,
+ description: entry.description ?? null,
+ fileId: entry.fileId ?? null,
+ metadata: metadata ?? null,
+ type,
+ };
+ },
+ { concurrency: RESOLVE_CONCURRENCY },
+ );
diff --git a/apps/server/src/services/verify/evidencePlanner.ts b/apps/server/src/services/verify/evidencePlanner.ts
index f8b3e612efc..25f8c5a7ab4 100644
--- a/apps/server/src/services/verify/evidencePlanner.ts
+++ b/apps/server/src/services/verify/evidencePlanner.ts
@@ -1,3 +1,4 @@
+import { verifyTextEvidenceTypes } from '@lobechat/const/verify';
import type { JudgeEvidence } from '@lobechat/prompts';
import type { RequiredEvidenceSpec, VerifyCheckItem } from '@lobechat/types';
@@ -11,7 +12,7 @@ export interface EvidencePlan {
}
const imageEvidenceTypes = new Set(['gif', 'screenshot']);
-const textEvidenceTypes = new Set(['dom_snapshot', 'markdown', 'text', 'transcript']);
+const textEvidenceTypes = verifyTextEvidenceTypes;
/**
* Select the least-powerful verifier that can inspect every required artifact.
diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.ts
index 695f9548e18..ef757084990 100644
--- a/apps/server/src/services/verify/executor.ts
+++ b/apps/server/src/services/verify/executor.ts
@@ -30,7 +30,7 @@ import { AiGenerationService } from '@/server/services/aiGeneration';
import { FileService } from '@/server/services/file';
import { settledCarriedItemIds } from './carryForward';
-import { runEvidenceGaps } from './evidenceCoverage';
+import { executionGapTypes, runEvidenceGaps, runEvidenceSpecs } from './evidenceCoverage';
import { planEvidenceVerification } from './evidencePlanner';
import { GIF_FRAME_SHEET_NOTE, isGifFrameSheet, resolveModelReadableFrameUrl } from './modelFrames';
import { planItemToPendingResult } from './resultSnapshot';
@@ -243,6 +243,7 @@ export class VerifyExecutorService {
description: row.description,
documentId: row.documentId,
fileId: row.fileId,
+ metadata: row.metadata,
type: row.type,
});
byItem.set(row.checkItemId, list);
@@ -297,16 +298,29 @@ export class VerifyExecutorService {
if (gaps.length === 0) continue;
gapIds.add(item.id);
- const missing = gaps.join(', ');
+ const executionGaps = executionGapTypes(runEvidenceSpecs(item.verifierConfig), gaps);
+ const fileGaps = gaps.filter((type) => !executionGaps.includes(type));
+ const missing = [
+ ...fileGaps,
+ ...executionGaps.map((type) => `${type} from a real command execution`),
+ ].join(', ');
+ // The repair that acts on this suggestion runs as a new operation with a
+ // round of its own, so the command targets the caller's operation, not
+ // this run: naming this (settled) run sent every repair's evidence one
+ // round behind the round its gate checks.
+ const suggestions = [
+ fileGaps.length > 0 &&
+ `Capture and upload the missing evidence (${fileGaps.join(', ')}) to your current run via \`lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item ${item.id} --type ${fileGaps.length === 1 ? fileGaps[0] : `<${fileGaps.join('|')}>`} --file <path>${fileGaps.includes('video') ? ' --chapters <file>' : ''}\`.`,
+ // Format alone never covers an execution requirement: an authored
+ // example or a bare log carries no execution provenance.
+ executionGaps.length > 0 &&
+ 'Run the command for real and publish it as terminal evidence (captured or imported, not authored).',
+ ].filter(Boolean);
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
confidence: 0,
status: 'failed',
- // The repair that acts on this suggestion runs as a new operation with a
- // round of its own, so the command targets the caller's operation, not
- // this run: naming this (settled) run sent every repair's evidence one
- // round behind the round its gate checks.
- suggestion: `Capture and upload the missing evidence (${missing}) to your current run via \`lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item ${item.id} --type ${gaps.length === 1 ? gaps[0] : `<${gaps.join('|')}>`} --file <path>${gaps.includes('video') ? ' --chapters <file>' : ''}\`.`,
+ suggestion: suggestions.join(' '),
toulmin: { limitation: `Required evidence not provided: ${missing}.` },
verdict: 'uncertain',
});
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index 054a9880ea5..cd7001e8a73 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -24,7 +24,13 @@ export {
export { createVerifierAgentRunner } from './agentVerifier';
export { mapWithConcurrency } from './concurrency';
export { coverageGaps, readRequiredEvidence } from './evidenceCoverage';
-export { createEvidenceFileResolver, type EvidenceFileMeta } from './evidenceFiles';
+export {
+ createEvidenceFileResolver,
+ type EvidenceFileMeta,
+ resolveEvidenceFiles,
+ type TerminalArtifactLink,
+} from './evidenceFiles';
+export { prepareEvidenceRows } from './evidenceIntake';
export { evidenceTypeForStoredFile } from './evidenceMedium';
export {
type ExecuteVerifyParams,
@@ -60,4 +66,5 @@ export { driveTaskFromVerify, finalizeVerifyRun } from './settle';
export { VERIFY_ABANDONED_MS, VERIFY_ROLLUP_GRACE_MS } from './staleness';
export { VerifyStatusService } from './statusService';
export { sweepStuckVerifyRuns, type VerifySweepOutcome } from './sweep';
+export { resolveEvidenceMetadata } from './terminalEvidence';
export { settleVerifierCheckFromTerminal } from './verifierTerminal';
diff --git a/apps/server/src/services/verify/reviewEvidence.ts b/apps/server/src/services/verify/reviewEvidence.ts
index 6dc5ea61536..88e6a038307 100644
--- a/apps/server/src/services/verify/reviewEvidence.ts
+++ b/apps/server/src/services/verify/reviewEvidence.ts
@@ -1,3 +1,5 @@
+import { verifyTextEvidenceTypes } from '@lobechat/const/verify';
+
/**
* Nonvisual evidence assembly for the review predictor.
*
@@ -7,7 +9,7 @@
*/
/** Evidence types whose payload is text the model can read inline. */
-export const TEXT_EVIDENCE_TYPES = new Set(['text', 'markdown', 'dom_snapshot', 'transcript']);
+export const TEXT_EVIDENCE_TYPES = verifyTextEvidenceTypes;
/**
* Characters of nonvisual evidence one review prompt may carry.
diff --git a/apps/server/src/services/verify/reviewInspection.ts b/apps/server/src/services/verify/reviewInspection.ts
index 73ff92593b0..81133310a51 100644
--- a/apps/server/src/services/verify/reviewInspection.ts
+++ b/apps/server/src/services/verify/reviewInspection.ts
@@ -1,3 +1,5 @@
+import { verifyTextEvidenceTypes } from '@lobechat/const/verify';
+
/**
* What the review predictor could NOT look at.
*
@@ -14,7 +16,7 @@
/** Media a still frame can carry a judgement about — mirrors the predictor. */
const IMAGE_TYPES = new Set(['gif', 'screenshot']);
-const TEXT_TYPES = new Set(['dom_snapshot', 'markdown', 'text', 'transcript']);
+const TEXT_TYPES = verifyTextEvidenceTypes;
export interface WithheldEvidenceInput {
/** Visual rows actually attached to the request, after the frame cap. */
diff --git a/apps/server/src/services/verify/terminalEvidence.ts b/apps/server/src/services/verify/terminalEvidence.ts
new file mode 100644
index 00000000000..26793c1665b
--- /dev/null
+++ b/apps/server/src/services/verify/terminalEvidence.ts
@@ -0,0 +1,63 @@
+import { normalizeEvidenceMetadata } from '@lobechat/const/verify';
+import type { VerifyEvidenceType } from '@lobechat/types';
+import {
+ parseTerminalEvidenceMetadata,
+ TERMINAL_ARTIFACT_KEYS,
+} from '@lobechat/utils/verify/terminalEvidence';
+import { TRPCError } from '@trpc/server';
+
+interface ArtifactFile {
+ fileHash?: string | null;
+ size: number;
+}
+
+/**
+ * The metadata an evidence row is stored with. A `terminal` evidence must carry
+ * a valid execution record whose artifacts are files this caller can read, each
+ * matching the size and SHA-256 its bundle declared — so a record cannot point
+ * at someone else's file, or at a different file than the one that was hashed.
+ * Matching hashes prove the file did not change in transit; they say nothing
+ * about whether the command ran, which stays the record's declared provenance.
+ */
+export const resolveEvidenceMetadata = async (
+ findFile: (fileId: string) => Promise<ArtifactFile | null | undefined>,
+ type: VerifyEvidenceType,
+ metadata: unknown,
+): Promise<unknown> => {
+ const normalized = normalizeEvidenceMetadata(metadata, type);
+ if (type !== 'terminal') return normalized;
+
+ const bag =
+ normalized && typeof normalized === 'object' && !Array.isArray(normalized)
+ ? (normalized as Record<string, unknown>)
+ : {};
+ const parsed = parseTerminalEvidenceMetadata(bag.terminal);
+ if (!parsed.ok)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Invalid terminal evidence metadata: ${parsed.error}. Publish terminal evidence from a captured or imported command execution bundle, not an authored example.`,
+ });
+
+ for (const key of TERMINAL_ARTIFACT_KEYS) {
+ const artifact = parsed.metadata.artifacts[key];
+ if (!artifact) continue;
+ if (!artifact.fileId)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Terminal artifact "${key}" has no fileId — upload the file before attaching the evidence.`,
+ });
+ const file = await findFile(artifact.fileId);
+ if (!file)
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Terminal artifact "${key}" references file ${artifact.fileId}, which does not exist or is not yours.`,
+ });
+ if (file.size !== artifact.size || (file.fileHash && file.fileHash !== artifact.sha256))
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Terminal artifact "${key}" does not match file ${artifact.fileId} (size or SHA-256 differs).`,
+ });
+ }
+
+ return { ...bag, terminal: parsed.metadata };
+};
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 8426a871b8f..ab1044d9512 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -830,6 +830,7 @@
"report.evidence.medium.gif": "GIF",
"report.evidence.medium.markdown": "Markdown",
"report.evidence.medium.screenshot": "Screenshot",
+ "report.evidence.medium.terminal": "Terminal",
"report.evidence.medium.text": "Text",
"report.evidence.medium.transcript": "Transcript",
"report.evidence.medium.video": "Video",
@@ -868,6 +869,7 @@
"report.plan.method": "Method",
"report.plan.notExecutedHint": "This check was planned but never ran, so nothing was verified.",
"report.plan.requiredEvidence": "Required evidence",
+ "report.plan.requiredEvidenceExecution": "from a real run",
"report.scope.branch": "Branch",
"report.scope.commit": "Commit",
"report.scope.date": "Date",
@@ -893,6 +895,78 @@
"report.surface.desktop": "Desktop",
"report.surface.mobile": "Mobile",
"report.surface.web": "Web",
+ "report.terminal.authoredNotice": "Example output, not an execution. A person or an Agent wrote it, so it does not show that the command ran.",
+ "report.terminal.commandUnknown": "(command not recorded)",
+ "report.terminal.copy": "Copy output",
+ "report.terminal.copyCommand": "Copy command",
+ "report.terminal.download": "Download",
+ "report.terminal.downloadRecording": "Download recording",
+ "report.terminal.env.hide": "Hide",
+ "report.terminal.env.show_one": "Show {{count}} entry",
+ "report.terminal.env.show_other": "Show {{count}} entries",
+ "report.terminal.error.hide": "Hide details",
+ "report.terminal.error.show": "Show details",
+ "report.terminal.fact.capture": "Capture",
+ "report.terminal.fact.cwd": "Directory",
+ "report.terminal.fact.environment": "Environment",
+ "report.terminal.fact.result": "Result",
+ "report.terminal.fact.source": "Source",
+ "report.terminal.fact.time": "Time",
+ "report.terminal.fact.unknown": "Unknown",
+ "report.terminal.invalidRecord": "This terminal record couldn't be read, so only its stored text is shown.",
+ "report.terminal.mode.import": "Import · from existing output",
+ "report.terminal.mode.pipe": "Pipe · stdout and stderr kept apart",
+ "report.terminal.mode.pty": "PTY · one terminal stream",
+ "report.terminal.outcome.captureFailed": "capture failed",
+ "report.terminal.outcome.exit": "exit {{code}}",
+ "report.terminal.outcome.interrupted": "interrupted",
+ "report.terminal.outcome.signaled": "killed by {{signal}}",
+ "report.terminal.outcome.signaledUnknown": "killed by a signal",
+ "report.terminal.outcome.spawnFailed": "failed to start",
+ "report.terminal.outcome.timedOut": "timed out",
+ "report.terminal.outcome.unknown": "exit status unknown",
+ "report.terminal.output.empty": "No output",
+ "report.terminal.output.fromRecording": "Text read from the recording. Open Replay to see the screen as it ran.",
+ "report.terminal.output.lines_one": "{{count}} line",
+ "report.terminal.output.lines_other": "{{count}} lines",
+ "report.terminal.output.loadFailed": "Couldn't load this output. Try the Transcript view or download the file.",
+ "report.terminal.output.tooLarge": "Too large to preview here. Download it to read the full output.",
+ "report.terminal.output.unavailable": "The output files aren't available.",
+ "report.terminal.player.failed": "Couldn't load the recording. The text output is still available.",
+ "report.terminal.player.idleCompressed": "Pauses longer than {{seconds}}s are shortened. Recorded length: {{duration}}.",
+ "report.terminal.player.markers": "Markers",
+ "report.terminal.player.pause": "Pause",
+ "report.terminal.player.play": "Play",
+ "report.terminal.player.restart": "Restart",
+ "report.terminal.player.seek": "Seek",
+ "report.terminal.player.speed": "Speed",
+ "report.terminal.player.tooLarge": "The recording is larger than {{size}} and can't be replayed here. The text output is still available.",
+ "report.terminal.player.unplayable": "This recording can't be replayed. The text output is still available.",
+ "report.terminal.processing.missing": "Not recorded",
+ "report.terminal.processing.notes": "Notes",
+ "report.terminal.processing.redacted": "Redacted",
+ "report.terminal.processing.truncated": "Truncated",
+ "report.terminal.processing.truncatedItem": "{{stream}}: kept {{kept}}, dropped {{dropped}}",
+ "report.terminal.search.capped": "Showing the first {{count}} matching lines",
+ "report.terminal.search.count_one": "{{count}} match",
+ "report.terminal.search.count_other": "{{count}} matches",
+ "report.terminal.search.none": "No matches",
+ "report.terminal.search.placeholder": "Search output",
+ "report.terminal.source.authored": "Example",
+ "report.terminal.source.authoredHint": "Written by a person or an Agent. It can explain, but it does not show that the command ran.",
+ "report.terminal.source.captured": "Captured",
+ "report.terminal.source.capturedHint": "Declared as recorded by the capturer while the command ran.",
+ "report.terminal.source.imported": "Imported",
+ "report.terminal.source.importedHint": "Declared as taken from an existing log or recording. Nothing was re-run.",
+ "report.terminal.timing.recorded": "timing recorded",
+ "report.terminal.title": "Terminal command",
+ "report.terminal.view.output": "Output",
+ "report.terminal.view.replay": "Replay",
+ "report.terminal.view.stderr": "stderr",
+ "report.terminal.view.stdout": "stdout",
+ "report.terminal.view.streamEmpty": "{{stream}} is empty",
+ "report.terminal.view.transcript": "Transcript",
+ "report.terminal.view.transcriptHint": "The stored plain-text record, readable without the player",
"report.titleFallback": "Verification report",
"report.unavailable.description": "Reports now live on their acceptance. This one is not part of an acceptance, or it was never shared with you.",
"report.unavailable.title": "This report is no longer available",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index f3257ce082f..508755be3a1 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -830,6 +830,7 @@
"report.evidence.medium.gif": "GIF",
"report.evidence.medium.markdown": "Markdown",
"report.evidence.medium.screenshot": "截图",
+ "report.evidence.medium.terminal": "终端",
"report.evidence.medium.text": "文本",
"report.evidence.medium.transcript": "会话记录",
"report.evidence.medium.video": "视频",
@@ -868,6 +869,7 @@
"report.plan.method": "验法",
"report.plan.notExecutedHint": "这项检查计划中有,但本轮没有执行,因此未被验证。",
"report.plan.requiredEvidence": "须产出",
+ "report.plan.requiredEvidenceExecution": "须真实执行",
"report.scope.branch": "分支",
"report.scope.commit": "提交",
"report.scope.date": "日期",
@@ -893,6 +895,78 @@
"report.surface.desktop": "桌面端",
"report.surface.mobile": "移动端",
"report.surface.web": "网页端",
+ "report.terminal.authoredNotice": "这是示例输出,不是执行记录。它由人或 Agent 编写,不能证明命令真的运行过。",
+ "report.terminal.commandUnknown": "(未记录命令)",
+ "report.terminal.copy": "复制输出",
+ "report.terminal.copyCommand": "复制命令",
+ "report.terminal.download": "下载",
+ "report.terminal.downloadRecording": "下载录制文件",
+ "report.terminal.env.hide": "收起",
+ "report.terminal.env.show_one": "展开 {{count}} 项",
+ "report.terminal.env.show_other": "展开 {{count}} 项",
+ "report.terminal.error.hide": "收起详情",
+ "report.terminal.error.show": "查看详情",
+ "report.terminal.fact.capture": "采集方式",
+ "report.terminal.fact.cwd": "工作目录",
+ "report.terminal.fact.environment": "环境",
+ "report.terminal.fact.result": "结果",
+ "report.terminal.fact.source": "来源",
+ "report.terminal.fact.time": "时间",
+ "report.terminal.fact.unknown": "未知",
+ "report.terminal.invalidRecord": "无法读取这条终端记录,下面只显示保存的文本。",
+ "report.terminal.mode.import": "导入 · 来自已有输出",
+ "report.terminal.mode.pipe": "管道 · stdout 与 stderr 分开记录",
+ "report.terminal.mode.pty": "PTY · 单一终端流",
+ "report.terminal.outcome.captureFailed": "采集失败",
+ "report.terminal.outcome.exit": "退出码 {{code}}",
+ "report.terminal.outcome.interrupted": "已中断",
+ "report.terminal.outcome.signaled": "被 {{signal}} 终止",
+ "report.terminal.outcome.signaledUnknown": "被信号终止",
+ "report.terminal.outcome.spawnFailed": "启动失败",
+ "report.terminal.outcome.timedOut": "已超时",
+ "report.terminal.outcome.unknown": "退出状态未知",
+ "report.terminal.output.empty": "没有输出",
+ "report.terminal.output.fromRecording": "这段文本取自录制文件。打开「回放」可以查看运行时的屏幕。",
+ "report.terminal.output.lines_one": "{{count}} 行",
+ "report.terminal.output.lines_other": "{{count}} 行",
+ "report.terminal.output.loadFailed": "无法加载这段输出。可以切换到「文本记录」或下载文件查看。",
+ "report.terminal.output.tooLarge": "内容过大,无法在此预览。下载后可查看完整输出。",
+ "report.terminal.output.unavailable": "输出文件不可用。",
+ "report.terminal.player.failed": "无法加载录制文件,文本输出仍可查看。",
+ "report.terminal.player.idleCompressed": "超过 {{seconds}} 秒的停顿已缩短。实际录制时长:{{duration}}。",
+ "report.terminal.player.markers": "标记",
+ "report.terminal.player.pause": "暂停",
+ "report.terminal.player.play": "播放",
+ "report.terminal.player.restart": "从头播放",
+ "report.terminal.player.seek": "播放进度",
+ "report.terminal.player.speed": "播放速度",
+ "report.terminal.player.tooLarge": "录制文件超过 {{size}},无法在此回放,文本输出仍可查看。",
+ "report.terminal.player.unplayable": "这个录制文件无法回放,文本输出仍可查看。",
+ "report.terminal.processing.missing": "未记录",
+ "report.terminal.processing.notes": "处理说明",
+ "report.terminal.processing.redacted": "已脱敏",
+ "report.terminal.processing.truncated": "已截断",
+ "report.terminal.processing.truncatedItem": "{{stream}}:保留 {{kept}},丢弃 {{dropped}}",
+ "report.terminal.search.capped": "仅显示前 {{count}} 个匹配行",
+ "report.terminal.search.count_one": "{{count}} 处匹配",
+ "report.terminal.search.count_other": "{{count}} 处匹配",
+ "report.terminal.search.none": "没有匹配结果",
+ "report.terminal.search.placeholder": "搜索输出",
+ "report.terminal.source.authored": "示例",
+ "report.terminal.source.authoredHint": "由人或 Agent 编写,可用于说明,但不能证明命令运行过。",
+ "report.terminal.source.captured": "实时采集",
+ "report.terminal.source.capturedHint": "声明为命令运行时由采集工具记录。",
+ "report.terminal.source.imported": "导入",
+ "report.terminal.source.importedHint": "声明为取自已有日志或录制,未重新运行。",
+ "report.terminal.timing.recorded": "含时间记录",
+ "report.terminal.title": "终端命令",
+ "report.terminal.view.output": "输出",
+ "report.terminal.view.replay": "回放",
+ "report.terminal.view.stderr": "stderr",
+ "report.terminal.view.stdout": "stdout",
+ "report.terminal.view.streamEmpty": "{{stream}} 为空",
+ "report.terminal.view.transcript": "文本记录",
+ "report.terminal.view.transcriptHint": "保存的纯文本记录,无需播放器即可阅读",
"report.titleFallback": "验证报告",
"report.unavailable.description": "报告现在随其验收一起查看。这份报告不属于任何验收,或未分享给你。",
"report.unavailable.title": "该报告已不再提供",
diff --git a/packages/const/src/verify.test.ts b/packages/const/src/verify.test.ts
index 946be5707ab..5dffa4c66bc 100644
--- a/packages/const/src/verify.test.ts
+++ b/packages/const/src/verify.test.ts
@@ -54,6 +54,7 @@ import {
normalizeEvidenceMetadata,
normalizeVerifySurface,
readEvidenceChapters,
+ verifyEvidenceFileIds,
} from './verify';
/**
@@ -217,6 +218,29 @@ describe('readEvidenceChapters', () => {
});
});
+describe('verifyEvidenceFileIds', () => {
+ it('lists a terminal evidence payload and every artifact file', () => {
+ expect(
+ verifyEvidenceFileIds({
+ fileId: 'payload',
+ metadata: {
+ terminal: {
+ artifacts: { cast: { fileId: 'cast' }, output: null, stdout: { fileId: 'out' } },
+ },
+ },
+ type: 'terminal',
+ }),
+ ).toEqual(['payload', 'cast', 'out']);
+ });
+
+ it('ignores artifact records on other media and tolerates missing metadata', () => {
+ const metadata = { terminal: { artifacts: { stdout: { fileId: 'out' } } } };
+ expect(verifyEvidenceFileIds({ fileId: 'f', metadata, type: 'text' })).toEqual(['f']);
+ expect(verifyEvidenceFileIds({ type: 'terminal' })).toEqual([]);
+ expect(verifyEvidenceFileIds({ metadata: { terminal: {} }, type: 'terminal' })).toEqual([]);
+ });
+});
+
describe('normalizeEvidenceMetadata', () => {
const chapters = [
{ kind: 'step', label: 'Open', t: 0 },
@@ -237,6 +261,15 @@ describe('normalizeEvidenceMetadata', () => {
expect(normalizeEvidenceMetadata({ chapters }, 'screenshot')).toBeNull();
});
+ it('keeps a terminal record only on terminal evidence', () => {
+ const terminal = { version: 1 };
+ expect(normalizeEvidenceMetadata({ terminal }, 'terminal')).toEqual({ terminal });
+ expect(normalizeEvidenceMetadata({ comparison: { id: 'a' }, terminal }, 'text')).toEqual({
+ comparison: { id: 'a' },
+ });
+ expect(normalizeEvidenceMetadata({ chapters, terminal }, 'screenshot')).toBeNull();
+ });
+
it('passes metadata without chapters through untouched', () => {
const metadata = { comparison: { id: 'a' } };
expect(normalizeEvidenceMetadata(metadata, 'video')).toBe(metadata);
diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.ts
index 802e6ce5a6f..15ef722d996 100644
--- a/packages/const/src/verify.ts
+++ b/packages/const/src/verify.ts
@@ -376,6 +376,9 @@ export const verifyEvidenceTypes = [
'markdown',
'dom_snapshot',
'transcript',
+ // One command execution: a readable text payload plus structured execution
+ // facts, provenance and stdout / stderr / recording artifacts in metadata.
+ 'terminal',
] as const;
export type VerifyEvidenceType = (typeof verifyEvidenceTypes)[number];
@@ -450,6 +453,42 @@ export const runEvidenceGaps = (
readRequiredEvidence(config)?.filter((spec) => !spec.scope || spec.scope === 'run_evidence'),
evidence,
);
+/**
+ * Evidence whose payload is text a reader or model can take in directly. A
+ * `terminal` evidence belongs here because its payload is the text fallback of
+ * the execution, written for exactly the readers that have no player.
+ */
+export const verifyTextEvidenceTypes: ReadonlySet<string> = new Set([
+ 'dom_snapshot',
+ 'markdown',
+ 'terminal',
+ 'text',
+ 'transcript',
+]);
+
+/**
+ * Every stored file an evidence row references: its own payload file, plus —
+ * for a `terminal` evidence — the stdout / stderr / output / recording files its
+ * record names. Anything that follows evidence to its files (library hiding,
+ * permanent purge) must use this, or those artifacts outlive their evidence.
+ * Reads ids leniently; the record itself was validated when it was stored.
+ */
+export const verifyEvidenceFileIds = (evidence: {
+ fileId?: string | null;
+ metadata?: unknown;
+ type: string;
+}): string[] => {
+ const ids = evidence.fileId ? [evidence.fileId] : [];
+ if (evidence.type !== 'terminal') return ids;
+ const artifacts = (evidence.metadata as { terminal?: { artifacts?: unknown } } | null | undefined)
+ ?.terminal?.artifacts;
+ if (!artifacts || typeof artifacts !== 'object') return ids;
+ for (const artifact of Object.values(artifacts as Record<string, unknown>)) {
+ const fileId = (artifact as { fileId?: unknown } | null)?.fileId;
+ if (typeof fileId === 'string' && fileId.length > 0) ids.push(fileId);
+ }
+ return [...new Set(ids)];
+};
/** Who / what captured an evidence artifact (provenance). */
export const verifyEvidenceCapturedBy = [
@@ -527,6 +566,12 @@ export const readEvidenceChapters = (value: unknown): VerifyEvidenceChapter[] |
*/
export const normalizeEvidenceMetadata = (metadata: unknown, type: string): unknown => {
if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return metadata;
+ // Only a `terminal` row may carry an execution record — on any other medium
+ // it would claim provenance no reader checks.
+ if (type !== 'terminal' && 'terminal' in metadata) {
+ const { terminal: _terminal, ...rest } = metadata as Record<string, unknown>;
+ return normalizeEvidenceMetadata(Object.keys(rest).length > 0 ? rest : null, type);
+ }
if (!('chapters' in metadata)) return metadata;
const { chapters: _chapters, ...rest } = metadata as Record<string, unknown>;
const chapters = type === 'video' ? readEvidenceChapters(metadata) : undefined;
diff --git a/packages/database/src/models/__tests__/verifyEvidence.test.ts b/packages/database/src/models/__tests__/verifyEvidence.test.ts
index 141de8baa5c..2bc3483d34b 100644
--- a/packages/database/src/models/__tests__/verifyEvidence.test.ts
+++ b/packages/database/src/models/__tests__/verifyEvidence.test.ts
@@ -178,6 +178,44 @@ describe('VerifyEvidenceModel', () => {
expect(rows.every((f) => f.source === 'acceptance')).toBe(true);
});
+ it('stamps the stdout / stderr / recording files a terminal evidence references', async () => {
+ const model = new VerifyEvidenceModel(serverDB, userId);
+ const [stdout] = await serverDB
+ .insert(files)
+ .values({
+ fileType: 'text/plain',
+ name: 'stdout.txt',
+ size: 3,
+ url: 's3://ev/stdout',
+ userId,
+ })
+ .returning();
+ const [cast] = await serverDB
+ .insert(files)
+ .values({
+ fileType: 'application/octet-stream',
+ name: 'session.cast',
+ size: 9,
+ url: 's3://ev/cast',
+ userId,
+ })
+ .returning();
+
+ await model.create({
+ checkResultId,
+ content: '$ ls',
+ metadata: {
+ terminal: { artifacts: { cast: { fileId: cast.id }, stdout: { fileId: stdout.id } } },
+ },
+ type: 'terminal',
+ });
+
+ const rows = await serverDB.query.files.findMany({
+ where: (f, { inArray }) => inArray(f.id, [stdout.id, cast.id]),
+ });
+ expect(rows.map((f) => f.source)).toEqual(['acceptance', 'acceptance']);
+ });
+
it('keeps an existing file source instead of overwriting it', async () => {
const model = new VerifyEvidenceModel(serverDB, userId);
const [generated] = await serverDB
diff --git a/packages/database/src/models/verifyEvidence.ts b/packages/database/src/models/verifyEvidence.ts
index 5e7b07e0ca0..918f15746eb 100644
--- a/packages/database/src/models/verifyEvidence.ts
+++ b/packages/database/src/models/verifyEvidence.ts
@@ -1,3 +1,4 @@
+import { verifyEvidenceFileIds } from '@lobechat/const/verify';
import type { VerifyEvidence } from '@lobechat/types';
import { FileSource } from '@lobechat/types';
import { and, asc, eq, inArray, isNull } from 'drizzle-orm';
@@ -45,7 +46,8 @@ export class VerifyEvidenceModel {
* (attached as evidence) from losing its original attribution.
*/
private markFilesAsEvidence = async (rows: CreateVerifyEvidence[]) => {
- const fileIds = [...new Set(rows.map((r) => r.fileId).filter((id): id is string => !!id))];
+ // A terminal evidence's stdout / stderr / recording files are evidence too.
+ const fileIds = [...new Set(rows.flatMap(verifyEvidenceFileIds))];
if (fileIds.length === 0) return;
await this.db
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 5a8fbf15a35..813dc442a3b 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -1,3 +1,5 @@
+import { verifyEvidenceMessages } from './verify/evidence';
+
export default {
'acceptance.comments.evidenceUnavailable': 'This evidence is no longer available.',
'acceptance.comments.video.hintPaused': 'Drag to circle an area · frame {{frame}}',
@@ -860,68 +862,12 @@ export default {
'report.error.description':
'The report could not be loaded. Check your connection and try again.',
'report.error.title': 'Unable to load report',
- 'report.evidence.category.audio': 'Audio',
- 'report.evidence.category.file': 'File',
- 'report.evidence.category.image': 'Image',
- 'report.evidence.category.video': 'Video',
- 'report.evidence.count': '{{count}} evidence item(s)',
- 'report.evidence.inlineFallback': 'Inline evidence {{index}}',
- 'report.evidence.collapse': 'Collapse',
- 'report.evidence.comparison.after': 'After',
- 'report.evidence.comparison.before': 'Before',
- 'report.evidence.expand': 'Expand',
- 'report.evidence.openDetail': 'Open {{name}}',
- 'report.evidence.view': 'View evidence ({{count}})',
- 'report.filter.all': 'All',
- 'report.filter.failed': 'Failed',
- 'report.filter.notExecuted': 'Not run',
- 'report.filter.passed': 'Passed',
- 'report.filter.uncertain': 'Uncertain',
- 'report.filterEmpty': 'No checks match this filter.',
- 'report.visualization.after': 'After',
- 'report.visualization.before': 'Before',
- 'report.visualization.targetMet': 'Target met · {{value}}',
- 'report.visualization.targetMissed': 'Target missed · {{value}}',
- 'report.visualization.title': 'Data visualization',
- 'report.visualization.unnamed': 'Unnamed metric',
- 'report.interaction.active': 'Active',
- 'report.interaction.operator.H': 'H',
- 'report.interaction.operator.K': 'K',
- 'report.interaction.operator.M': 'M',
- 'report.interaction.operator.P': 'P',
- 'report.interaction.operator.R_ms': 'R',
- 'report.interaction.operator.T_chars': 'T',
- 'report.interaction.title': 'Interaction cost',
- 'report.interaction.total': 'Total',
- 'report.interaction.wait': 'Wait',
- 'report.missing.description': 'Open a verification report with a valid run ID.',
- 'report.missing.title': 'Missing report ID',
- 'report.notFound.description':
- 'This report may have been deleted, or the link is not available to you.',
- 'report.notFound.title': 'Report not found',
- 'report.overview.failed': 'Failed',
- 'report.overview.nextFailed':
- 'Review failed checks first, then add missing evidence or adjust the implementation.',
- 'report.overview.nextPassed': 'All checks passed. Review the evidence if needed, then deliver.',
- 'report.overview.nextTitle': 'Next steps',
- 'report.overview.nextUncertain':
- 'Uncertain checks need clearer evidence before treating this report as complete.',
- 'report.overview.passed': 'Passed',
- 'report.overview.title': 'Check overview',
- 'report.overview.total': 'All',
- 'report.overview.uncertain': 'Uncertain',
- 'report.evidence.medium.audio': 'Audio',
- 'report.evidence.medium.dom_snapshot': 'DOM snapshot',
- 'report.evidence.medium.gif': 'GIF',
- 'report.evidence.medium.markdown': 'Markdown',
- 'report.evidence.medium.screenshot': 'Screenshot',
- 'report.evidence.medium.text': 'Text',
- 'report.evidence.medium.transcript': 'Transcript',
- 'report.evidence.medium.video': 'Video',
+ ...verifyEvidenceMessages,
'report.plan.expected': 'Expected',
'report.plan.method': 'Method',
'report.plan.notExecutedHint': 'This check was planned but never ran, so nothing was verified.',
'report.plan.requiredEvidence': 'Required evidence',
+ 'report.plan.requiredEvidenceExecution': 'from a real run',
'report.scope.branch': 'Branch',
'report.scope.commit': 'Commit',
'report.scope.date': 'Date',
diff --git a/packages/locales/src/default/verify/evidence.ts b/packages/locales/src/default/verify/evidence.ts
new file mode 100644
index 00000000000..0395a4a16e0
--- /dev/null
+++ b/packages/locales/src/default/verify/evidence.ts
@@ -0,0 +1,146 @@
+export const verifyEvidenceMessages = {
+ 'report.evidence.category.audio': 'Audio',
+ 'report.evidence.category.file': 'File',
+ 'report.evidence.category.image': 'Image',
+ 'report.evidence.category.video': 'Video',
+ 'report.evidence.count': '{{count}} evidence item(s)',
+ 'report.evidence.inlineFallback': 'Inline evidence {{index}}',
+ 'report.evidence.collapse': 'Collapse',
+ 'report.evidence.comparison.after': 'After',
+ 'report.evidence.comparison.before': 'Before',
+ 'report.evidence.expand': 'Expand',
+ 'report.evidence.openDetail': 'Open {{name}}',
+ 'report.evidence.view': 'View evidence ({{count}})',
+ 'report.filter.all': 'All',
+ 'report.filter.failed': 'Failed',
+ 'report.filter.notExecuted': 'Not run',
+ 'report.filter.passed': 'Passed',
+ 'report.filter.uncertain': 'Uncertain',
+ 'report.filterEmpty': 'No checks match this filter.',
+ 'report.visualization.after': 'After',
+ 'report.visualization.before': 'Before',
+ 'report.visualization.targetMet': 'Target met · {{value}}',
+ 'report.visualization.targetMissed': 'Target missed · {{value}}',
+ 'report.visualization.title': 'Data visualization',
+ 'report.visualization.unnamed': 'Unnamed metric',
+ 'report.interaction.active': 'Active',
+ 'report.interaction.operator.H': 'H',
+ 'report.interaction.operator.K': 'K',
+ 'report.interaction.operator.M': 'M',
+ 'report.interaction.operator.P': 'P',
+ 'report.interaction.operator.R_ms': 'R',
+ 'report.interaction.operator.T_chars': 'T',
+ 'report.interaction.title': 'Interaction cost',
+ 'report.interaction.total': 'Total',
+ 'report.interaction.wait': 'Wait',
+ 'report.missing.description': 'Open a verification report with a valid run ID.',
+ 'report.missing.title': 'Missing report ID',
+ 'report.notFound.description':
+ 'This report may have been deleted, or the link is not available to you.',
+ 'report.notFound.title': 'Report not found',
+ 'report.overview.failed': 'Failed',
+ 'report.overview.nextFailed':
+ 'Review failed checks first, then add missing evidence or adjust the implementation.',
+ 'report.overview.nextPassed': 'All checks passed. Review the evidence if needed, then deliver.',
+ 'report.overview.nextTitle': 'Next steps',
+ 'report.overview.nextUncertain':
+ 'Uncertain checks need clearer evidence before treating this report as complete.',
+ 'report.overview.passed': 'Passed',
+ 'report.overview.title': 'Check overview',
+ 'report.overview.total': 'All',
+ 'report.overview.uncertain': 'Uncertain',
+ 'report.evidence.medium.audio': 'Audio',
+ 'report.evidence.medium.dom_snapshot': 'DOM snapshot',
+ 'report.evidence.medium.gif': 'GIF',
+ 'report.evidence.medium.markdown': 'Markdown',
+ 'report.evidence.medium.screenshot': 'Screenshot',
+ 'report.evidence.medium.terminal': 'Terminal',
+ 'report.evidence.medium.text': 'Text',
+ 'report.evidence.medium.transcript': 'Transcript',
+ 'report.evidence.medium.video': 'Video',
+ 'report.terminal.authoredNotice':
+ 'Example output, not an execution. A person or an Agent wrote it, so it does not show that the command ran.',
+ 'report.terminal.commandUnknown': '(command not recorded)',
+ 'report.terminal.copy': 'Copy output',
+ 'report.terminal.copyCommand': 'Copy command',
+ 'report.terminal.download': 'Download',
+ 'report.terminal.downloadRecording': 'Download recording',
+ 'report.terminal.env.hide': 'Hide',
+ 'report.terminal.error.hide': 'Hide details',
+ 'report.terminal.error.show': 'Show details',
+ 'report.terminal.env.show_one': 'Show {{count}} entry',
+ 'report.terminal.env.show_other': 'Show {{count}} entries',
+ 'report.terminal.fact.capture': 'Capture',
+ 'report.terminal.fact.cwd': 'Directory',
+ 'report.terminal.fact.environment': 'Environment',
+ 'report.terminal.fact.result': 'Result',
+ 'report.terminal.fact.source': 'Source',
+ 'report.terminal.fact.time': 'Time',
+ 'report.terminal.fact.unknown': 'Unknown',
+ 'report.terminal.invalidRecord':
+ "This terminal record couldn't be read, so only its stored text is shown.",
+ 'report.terminal.mode.import': 'Import · from existing output',
+ 'report.terminal.mode.pipe': 'Pipe · stdout and stderr kept apart',
+ 'report.terminal.mode.pty': 'PTY · one terminal stream',
+ 'report.terminal.outcome.captureFailed': 'capture failed',
+ 'report.terminal.outcome.exit': 'exit {{code}}',
+ 'report.terminal.outcome.interrupted': 'interrupted',
+ 'report.terminal.outcome.signaled': 'killed by {{signal}}',
+ 'report.terminal.outcome.signaledUnknown': 'killed by a signal',
+ 'report.terminal.outcome.spawnFailed': 'failed to start',
+ 'report.terminal.outcome.timedOut': 'timed out',
+ 'report.terminal.outcome.unknown': 'exit status unknown',
+ 'report.terminal.output.empty': 'No output',
+ 'report.terminal.output.fromRecording':
+ 'Text read from the recording. Open Replay to see the screen as it ran.',
+ 'report.terminal.output.lines_one': '{{count}} line',
+ 'report.terminal.output.lines_other': '{{count}} lines',
+ 'report.terminal.output.loadFailed':
+ "Couldn't load this output. Try the Transcript view or download the file.",
+ 'report.terminal.output.tooLarge':
+ 'Too large to preview here. Download it to read the full output.',
+ 'report.terminal.output.unavailable': "The output files aren't available.",
+ 'report.terminal.player.failed':
+ "Couldn't load the recording. The text output is still available.",
+ 'report.terminal.player.idleCompressed':
+ 'Pauses longer than {{seconds}}s are shortened. Recorded length: {{duration}}.',
+ 'report.terminal.player.unplayable':
+ "This recording can't be replayed. The text output is still available.",
+ 'report.terminal.player.markers': 'Markers',
+ 'report.terminal.player.pause': 'Pause',
+ 'report.terminal.player.play': 'Play',
+ 'report.terminal.player.restart': 'Restart',
+ 'report.terminal.player.seek': 'Seek',
+ 'report.terminal.player.speed': 'Speed',
+ 'report.terminal.player.tooLarge':
+ "The recording is larger than {{size}} and can't be replayed here. The text output is still available.",
+ 'report.terminal.processing.missing': 'Not recorded',
+ 'report.terminal.processing.notes': 'Notes',
+ 'report.terminal.processing.redacted': 'Redacted',
+ 'report.terminal.processing.truncated': 'Truncated',
+ 'report.terminal.processing.truncatedItem': '{{stream}}: kept {{kept}}, dropped {{dropped}}',
+ 'report.terminal.search.capped': 'Showing the first {{count}} matching lines',
+ 'report.terminal.search.count_one': '{{count}} match',
+ 'report.terminal.search.count_other': '{{count}} matches',
+ 'report.terminal.search.none': 'No matches',
+ 'report.terminal.search.placeholder': 'Search output',
+ 'report.terminal.source.authored': 'Example',
+ 'report.terminal.source.authoredHint':
+ 'Written by a person or an Agent. It can explain, but it does not show that the command ran.',
+ 'report.terminal.source.captured': 'Captured',
+ 'report.terminal.source.capturedHint':
+ 'Declared as recorded by the capturer while the command ran.',
+ 'report.terminal.source.imported': 'Imported',
+ 'report.terminal.source.importedHint':
+ 'Declared as taken from an existing log or recording. Nothing was re-run.',
+ 'report.terminal.timing.recorded': 'timing recorded',
+ 'report.terminal.title': 'Terminal command',
+ 'report.terminal.view.output': 'Output',
+ 'report.terminal.view.replay': 'Replay',
+ 'report.terminal.view.stderr': 'stderr',
+ 'report.terminal.view.stdout': 'stdout',
+ 'report.terminal.view.streamEmpty': '{{stream}} is empty',
+ 'report.terminal.view.transcript': 'Transcript',
+ 'report.terminal.view.transcriptHint':
+ 'The stored plain-text record, readable without the player',
+};
diff --git a/packages/prompts/src/chains/verify.ts b/packages/prompts/src/chains/verify.ts
index 7fb738b6fa9..87b84fa3872 100644
--- a/packages/prompts/src/chains/verify.ts
+++ b/packages/prompts/src/chains/verify.ts
@@ -259,6 +259,8 @@ export interface JudgeEvidence {
* every file to their isolated run.
*/
fileId?: string | null;
+ /** The row's metadata bag — the coverage gate reads a terminal evidence's provenance from it. */
+ metadata?: unknown;
type: VerifyEvidenceType;
}
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index eaa6cb6ab70..9e07f6d9ebf 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -1,5 +1,8 @@
import type { VerifyCheckDefinition } from './acceptanceFlow';
import type { GoalReleaseGateDossier } from './goalRollout';
+import type { RequiredEvidenceSpec } from './verify/evidence';
+
+export * from './verify/evidence';
/**
* Verify (delivery checker) domain types — the shared vocabulary, frozen-item
* shape, Toulmin narrative, and rubric run-policy config. Kept here (not in the
@@ -442,14 +445,6 @@ export type VerifyRunScenario = 'coding' | 'writing' | 'research' | 'generic';
*/
export type VerifySurface = 'web' | 'desktop' | 'cli' | 'mobile' | 'bot';
-/**
- * The medium of a captured evidence artifact. `audio` covers a delivered or
- * captured sound (TTS output, a recorded voice reply, an alert tone) — it plays
- * inline on the acceptance page instead of publishing as an unplayable blob.
- */
-export type VerifyEvidenceType =
- 'screenshot' | 'gif' | 'video' | 'audio' | 'text' | 'markdown' | 'dom_snapshot' | 'transcript';
-
/** Who / what captured an evidence artifact (provenance). */
export type VerifyEvidenceCapturedBy =
'agent' | 'agent-browser' | 'cdp' | 'cli' | 'program' | 'llm_judge';
@@ -939,58 +934,6 @@ export interface ToulminVerdict {
// Evidence — first-class artifacts a verifier produces (screenshots, logs, …)
// ============================================
-/**
- * Declares that a criterion is evidence-driven: it cannot pass on the
- * deliverable text alone — the run must capture and upload an artifact of each
- * listed `type` (via `lh acceptance run result submit`). Stored under the plan item's
- * `verifierConfig.requiredEvidence`, so adding it needs no schema change. The
- * structural gate marks a required item `uncertain` when any listed type is
- * missing, independent of the LLM judge.
- */
-export interface RequiredEvidenceSpec {
- /** What the capturer should produce — guidance only, not validated. */
- hint?: string;
- /** Semantic medium the verifier must actually understand, not merely observe exists. */
- modality?: 'audio' | 'document' | 'image' | 'structured' | 'text' | 'video';
- /** Where the evidence is expected to come from. */
- scope?: 'deliverable' | 'run_evidence' | 'task_artifacts';
- /** The evidence medium that must be present for this criterion. */
- type: VerifyEvidenceType;
-}
-
-/**
- * One evidence artifact produced while judging a check. Carries existence +
- * provenance only — no verdict logic. Verifying an evidence is itself a new
- * check (related through `verify_check_results`), so this table stays flat.
- *
- * The payload lives in exactly one of three places: `content` for small inline
- * text, `documentId` for a LobeHub document, or `fileId` for a stored artifact.
- */
-export interface VerifyEvidence {
- capturedAt?: Date | null;
- /** Who produced this artifact. */
- capturedBy?: VerifyEvidenceCapturedBy | null;
- /** The check result this evidence backs. */
- checkResultId: string;
- /** Inline payload for small text evidence (dom snapshot / console log / transcript). */
- content?: string | null;
- createdAt: Date;
- /** Human-readable caption, e.g. "首页首屏完整渲染". */
- description?: string | null;
- /** LobeHub document evidence — FK to `documents`. */
- documentId?: string | null;
- /** Stored artifact — FK to `files`, which owns mime / size / hash / url. */
- fileId?: string | null;
- id: string;
- /** Generic extension bag; concrete capturer-specific shape is not fixed yet. */
- metadata?: unknown | null;
- type: VerifyEvidenceType;
-}
-
-// ============================================
-// Report — the LLM-generated delivery-verification narrative for a run
-// ============================================
-
/**
* A delivery-verification report. A generated artifact (not a computed one):
* `summary` / `content` are written by an LLM from the round's check results +
diff --git a/packages/types/src/verify/evidence.ts b/packages/types/src/verify/evidence.ts
new file mode 100644
index 00000000000..9a2ab58da83
--- /dev/null
+++ b/packages/types/src/verify/evidence.ts
@@ -0,0 +1,188 @@
+import type { VerifyEvidenceCapturedBy } from '../verify';
+
+/**
+ * The medium of a captured evidence artifact. `audio` covers a delivered or
+ * captured sound (TTS output, a recorded voice reply, an alert tone) — it plays
+ * inline on the acceptance page instead of publishing as an unplayable blob.
+ * `terminal` is one command execution: its payload is the readable text
+ * fallback, and {@link VerifyTerminalEvidenceMetadata} under `metadata.terminal`
+ * carries the execution facts, provenance and the stdout / stderr / recording
+ * artifacts.
+ */
+export type VerifyEvidenceType =
+ | 'screenshot'
+ | 'gif'
+ | 'video'
+ | 'audio'
+ | 'text'
+ | 'markdown'
+ | 'dom_snapshot'
+ | 'transcript'
+ | 'terminal';
+
+/**
+ * Where a terminal evidence's observation came from. A declaration, not an
+ * attestation: a `.cast` can be edited and a captured file can be changed
+ * before upload, so the label decides eligibility, never authenticity.
+ * - captured: recorded by the capturer while the command actually ran
+ * - imported: taken from an existing real log, recording or tool result
+ * - authored: written by a person or agent — an example, simulation or demo.
+ * It may explain; it never satisfies an execution requirement.
+ */
+export type VerifyTerminalSourceKind = 'captured' | 'imported' | 'authored';
+
+/**
+ * How the observation was obtained. `pipe` keeps stdout and stderr apart,
+ * `pty` records one merged terminal stream with real timing, `import` builds
+ * the evidence from output that already exists without running anything.
+ */
+export type VerifyTerminalCaptureMode = 'pipe' | 'pty' | 'import';
+
+/**
+ * How the execution ended — kept apart from the upload so a failed command
+ * never reads as a successful one because its evidence published fine.
+ * `unknown` is the honest answer for imported output that never recorded it.
+ */
+export type VerifyTerminalOutcome =
+ | 'exited'
+ | 'signaled'
+ | 'timed_out'
+ | 'interrupted'
+ | 'spawn_failed'
+ | 'capture_failed'
+ | 'unknown';
+
+/** One file of a terminal evidence, hashed so its upload can be matched to the bundle. */
+export interface VerifyTerminalArtifact {
+ /** Stored file once uploaded. Absent in a local bundle. */
+ fileId?: string;
+ /** Bundle-relative file name before upload. Never an absolute local path. */
+ path?: string;
+ /** Hex SHA-256 of the (redacted) bytes — integrity of transport, not proof of execution. */
+ sha256: string;
+ size: number;
+}
+
+export interface VerifyTerminalTruncation {
+ droppedBytes: number;
+ keptBytes: number;
+ stream: 'cast' | 'output' | 'stderr' | 'stdout';
+}
+
+/**
+ * The structured half of a `terminal` evidence, stored under
+ * `verify_evidence.metadata.terminal`. Unknown facts stay `null` and are named
+ * in `processing.missingFields` — an import never infers an exit code from
+ * output that "looks successful", and never invents recording timing.
+ */
+export interface VerifyTerminalEvidenceMetadata {
+ artifacts: {
+ /** asciicast v3 recording — present only for real recorded timing. */
+ cast?: VerifyTerminalArtifact | null;
+ /** Merged terminal output with control sequences stripped (pty / import). */
+ output?: VerifyTerminalArtifact | null;
+ stderr?: VerifyTerminalArtifact | null;
+ stdout?: VerifyTerminalArtifact | null;
+ };
+ capture: {
+ /** The tool that produced the bundle, e.g. `{ name: 'lh', version: '0.0.64' }`. */
+ capturer?: { name: string; version?: string | null } | null;
+ mode: VerifyTerminalCaptureMode;
+ /** `separate` keeps stdout / stderr apart; `merged` is one terminal stream. */
+ streamLayout: 'merged' | 'separate' | 'unknown';
+ /** Terminal size at start (pty / recorded imports). */
+ terminal?: { cols: number; rows: number; type?: string | null } | null;
+ /** `recorded` only when real event timing exists, i.e. there is a cast to replay. */
+ timing: 'recorded' | 'unavailable';
+ };
+ execution: {
+ /** The command as run (redacted). */
+ command: string | null;
+ cwd: string | null;
+ durationMs: number | null;
+ /** Allow-listed environment facts (versions, platform) — never the full env. */
+ environmentSummary: Record<string, string>;
+ /** Why the capture itself failed, when it did. */
+ error?: string | null;
+ exitCode: number | null;
+ finishedAt: string | null;
+ outcome: VerifyTerminalOutcome;
+ signal: string | null;
+ startedAt: string | null;
+ };
+ processing: {
+ /** Fields left unknown, as dotted paths (`execution.exitCode`). */
+ missingFields: string[];
+ /** Human-readable processing record (derived fields, format normalization). */
+ notes: string[];
+ /** Which redaction rules fired and how often — never the redacted values. */
+ redactions: { count: number; rule: string }[];
+ truncation: VerifyTerminalTruncation[];
+ };
+ source: {
+ kind: VerifyTerminalSourceKind;
+ /** Where an import came from, e.g. the tool name or log path label. */
+ originalRecordRef?: string | null;
+ originalTool?: string | null;
+ };
+ version: 1;
+}
+
+/**
+ * Declares that a criterion is evidence-driven: it cannot pass on the
+ * deliverable text alone — the run must capture and upload an artifact of each
+ * listed `type` (via `lh acceptance run result submit`). Stored under the plan item's
+ * `verifierConfig.requiredEvidence`, so adding it needs no schema change. The
+ * structural gate marks a required item `uncertain` when any listed type is
+ * missing, independent of the LLM judge.
+ */
+export interface RequiredEvidenceSpec {
+ /** What the capturer should produce — guidance only, not validated. */
+ hint?: string;
+ /** Semantic medium the verifier must actually understand, not merely observe exists. */
+ modality?: 'audio' | 'document' | 'image' | 'structured' | 'text' | 'video';
+ /**
+ * `execution`: the requirement asks for a real command run, so only a
+ * `terminal` evidence whose source is `captured` or `imported` counts —
+ * an authored example never does, whatever its format. Absent means the
+ * medium alone is checked.
+ */
+ provenance?: 'execution';
+ /** Where the evidence is expected to come from. */
+ scope?: 'deliverable' | 'run_evidence' | 'task_artifacts';
+ /** The evidence medium that must be present for this criterion. */
+ type: VerifyEvidenceType;
+}
+
+/**
+ * One evidence artifact produced while judging a check. Carries existence +
+ * provenance only — no verdict logic. Verifying an evidence is itself a new
+ * check (related through `verify_check_results`), so this table stays flat.
+ *
+ * The payload lives in exactly one of three places: `content` for small inline
+ * text, `documentId` for a LobeHub document, or `fileId` for a stored artifact.
+ */
+export interface VerifyEvidence {
+ capturedAt?: Date | null;
+ /** Who produced this artifact. */
+ capturedBy?: VerifyEvidenceCapturedBy | null;
+ /** The check result this evidence backs. */
+ checkResultId: string;
+ /** Inline payload for small text evidence (dom snapshot / console log / transcript). */
+ content?: string | null;
+ createdAt: Date;
+ /** Human-readable caption, e.g. "首页首屏完整渲染". */
+ description?: string | null;
+ /** LobeHub document evidence — FK to `documents`. */
+ documentId?: string | null;
+ /** Stored artifact — FK to `files`, which owns mime / size / hash / url. */
+ fileId?: string | null;
+ id: string;
+ /** Generic extension bag; concrete capturer-specific shape is not fixed yet. */
+ metadata?: unknown | null;
+ type: VerifyEvidenceType;
+}
+
+// ============================================
+// Report — the LLM-generated delivery-verification narrative for a run
+// ============================================
diff --git a/packages/utils/src/verify/asciicast.test.ts b/packages/utils/src/verify/asciicast.test.ts
new file mode 100644
index 00000000000..9afe7512349
--- /dev/null
+++ b/packages/utils/src/verify/asciicast.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+
+import { ASCIICAST_LIMITS, AsciicastError, encodeAsciicastV3, parseAsciicast } from './asciicast';
+
+const v3 = (...lines: unknown[]) => lines.map((line) => JSON.stringify(line)).join('\n');
+
+describe('parseAsciicast', () => {
+ it('reads v3 relative intervals as absolute times, with resize and exit events', () => {
+ const cast = parseAsciicast(
+ `${v3(
+ {
+ command: 'ls',
+ term: { cols: 80, rows: 24, type: 'xterm-256color' },
+ timestamp: 100,
+ version: 3,
+ },
+ [0.5, 'o', 'a'],
+ [0.25, 'r', '100x30'],
+ [1, 'x', '2'],
+ )}\n# trailing comment\n`,
+ );
+ expect(cast).toMatchObject({
+ cols: 80,
+ command: 'ls',
+ duration: 1.75,
+ exitStatus: 2,
+ rows: 24,
+ termType: 'xterm-256color',
+ timestamp: 100,
+ version: 3,
+ });
+ expect(cast.events.map((e) => e.t)).toEqual([0.5, 0.75, 1.75]);
+ });
+
+ it('reads v2 absolute times and its env TERM', () => {
+ const cast = parseAsciicast(
+ v3(
+ { env: { TERM: 'xterm' }, height: 5, version: 2, width: 40 },
+ [0.1, 'o', 'a'],
+ [0.4, 'o', 'b'],
+ ),
+ );
+ expect(cast).toMatchObject({
+ cols: 40,
+ exitStatus: null,
+ rows: 5,
+ termType: 'xterm',
+ version: 2,
+ });
+ expect(cast.events.map((e) => e.t)).toEqual([0.1, 0.4]);
+ });
+
+ it.each([
+ ['empty input', ''],
+ ['an unknown version', v3({ height: 5, version: 1, width: 5 })],
+ ['a missing size', v3({ version: 3 })],
+ ['an oversized terminal', v3({ term: { cols: 5000, rows: 5 }, version: 3 })],
+ ['a non-JSON event', `${v3({ term: { cols: 5, rows: 5 }, version: 3 })}\nnot json`],
+ ['an unknown event code', v3({ term: { cols: 5, rows: 5 }, version: 3 }, [0, 'z', 'x'])],
+ ['a negative time', v3({ term: { cols: 5, rows: 5 }, version: 3 }, [-1, 'o', 'x'])],
+ [
+ 'v2 time going backwards',
+ v3({ height: 5, version: 2, width: 5 }, [1, 'o', 'a'], [0.5, 'o', 'b']),
+ ],
+ ['a malformed resize', v3({ term: { cols: 5, rows: 5 }, version: 3 }, [0, 'r', 'wide'])],
+ ['an oversized resize', v3({ term: { cols: 5, rows: 5 }, version: 3 }, [0, 'r', '5000x5'])],
+ ])('refuses %s', (_, text) => {
+ expect(() => parseAsciicast(text)).toThrow(AsciicastError);
+ });
+
+ it('enforces event, size and duration limits', () => {
+ const header = { term: { cols: 5, rows: 5 }, version: 3 };
+ const limits = { ...ASCIICAST_LIMITS, maxDurationSeconds: 10, maxEventBytes: 4, maxEvents: 2 };
+ expect(() => parseAsciicast(v3(header, [0, 'o', 'too long']), limits)).toThrow(
+ /exceeds 4 bytes/,
+ );
+ expect(() =>
+ parseAsciicast(v3(header, [0, 'o', 'a'], [0, 'o', 'b'], [0, 'o', 'c']), limits),
+ ).toThrow(/more than 2 events/);
+ expect(() => parseAsciicast(v3(header, [11, 'o', 'a']), limits)).toThrow(/past 10 seconds/);
+ expect(() => parseAsciicast(v3(header), { ...limits, maxBytes: 10 })).toThrow(
+ /exceeds 10 bytes/,
+ );
+ });
+
+ it('names the offending line', () => {
+ try {
+ parseAsciicast(`${v3({ term: { cols: 5, rows: 5 }, version: 3 })}\n\n[0, 'o']`);
+ expect.unreachable();
+ } catch (error) {
+ expect((error as AsciicastError).line).toBe(3);
+ }
+ });
+});
+
+describe('encodeAsciicastV3', () => {
+ it('round-trips through the parser with relative intervals', () => {
+ const text = encodeAsciicastV3(
+ { cols: 10, command: 'echo', rows: 3, termType: 'xterm', timestamp: 7.9 },
+ [
+ { code: 'o', data: 'hi', t: 0.1 },
+ { code: 'r', data: '20x5', t: 0.3 },
+ { code: 'x', data: '0', t: 0.35 },
+ ],
+ );
+ expect(text.split('\n')[1]).toBe('[0.1,"o","hi"]');
+ const cast = parseAsciicast(text);
+ expect(cast).toMatchObject({ command: 'echo', exitStatus: 0, timestamp: 7, version: 3 });
+ expect(cast.events.map((e) => Math.round(e.t * 1e6) / 1e6)).toEqual([0.1, 0.3, 0.35]);
+ });
+});
diff --git a/packages/utils/src/verify/asciicast.ts b/packages/utils/src/verify/asciicast.ts
new file mode 100644
index 00000000000..50579850665
--- /dev/null
+++ b/packages/utils/src/verify/asciicast.ts
@@ -0,0 +1,244 @@
+/**
+ * asciicast reading and writing for terminal evidence.
+ *
+ * The capturer writes v3 (https://docs.asciinema.org/manual/asciicast/v3/):
+ * relative event intervals and an `x` exit event. The reader also accepts v2,
+ * the format asciinema 2.x recorded for years, so an existing real recording can
+ * be imported as-is. Both normalize to absolute event times.
+ *
+ * A recording is untrusted input — it can be hand-edited, truncated or hostile —
+ * so every limit below is enforced while reading, before anything renders it.
+ */
+
+export type AsciicastEventCode = 'i' | 'm' | 'o' | 'r' | 'x';
+
+export interface AsciicastEvent {
+ code: AsciicastEventCode;
+ data: string;
+ /** Seconds since the recording started. */
+ t: number;
+}
+
+export interface Asciicast {
+ cols: number;
+ command: string | null;
+ /** Seconds from start to the last event. */
+ duration: number;
+ events: AsciicastEvent[];
+ /** Exit status from a v3 `x` event, when the recording has one. */
+ exitStatus: number | null;
+ rows: number;
+ termType: string | null;
+ /** Unix seconds the recording started at, when recorded. */
+ timestamp: number | null;
+ version: 2 | 3;
+}
+
+export interface AsciicastLimits {
+ maxBytes: number;
+ maxCols: number;
+ maxDurationSeconds: number;
+ maxEventBytes: number;
+ maxEvents: number;
+ maxRows: number;
+}
+
+export const ASCIICAST_LIMITS: AsciicastLimits = {
+ maxBytes: 20 * 1024 * 1024,
+ maxCols: 1000,
+ maxDurationSeconds: 6 * 60 * 60,
+ maxEventBytes: 1024 * 1024,
+ maxEvents: 200_000,
+ maxRows: 500,
+};
+
+export class AsciicastError extends Error {
+ constructor(
+ message: string,
+ readonly line?: number,
+ ) {
+ super(line === undefined ? message : `line ${line}: ${message}`);
+ this.name = 'AsciicastError';
+ }
+}
+
+const EVENT_CODES = new Set<string>(['i', 'm', 'o', 'r', 'x']);
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const positiveInt = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;
+
+const stringOrNull = (value: unknown): string | null =>
+ typeof value === 'string' && value.length > 0 ? value : null;
+
+/** `"120x40"` → `{ cols: 120, rows: 40 }`; anything else is not a resize. */
+export const parseResize = (data: string): { cols: number; rows: number } | undefined => {
+ const match = /^(\d{1,5})x(\d{1,5})$/.exec(data);
+ if (!match) return undefined;
+ const cols = Number(match[1]);
+ const rows = Number(match[2]);
+ return cols > 0 && rows > 0 ? { cols, rows } : undefined;
+};
+
+const utf8Length = (value: string) => new TextEncoder().encode(value).length;
+
+/**
+ * Parse and validate a v2 or v3 recording. Throws {@link AsciicastError} naming
+ * the offending line — the caller decides whether that means "reject the
+ * import" or "fall back to the text view".
+ */
+export const parseAsciicast = (
+ text: string,
+ limits: AsciicastLimits = ASCIICAST_LIMITS,
+): Asciicast => {
+ if (text.length > limits.maxBytes || utf8Length(text) > limits.maxBytes)
+ throw new AsciicastError(`recording exceeds ${limits.maxBytes} bytes`);
+
+ const lines = text.split('\n');
+ let index = 0;
+ // v3 allows comment and blank lines anywhere; v2 tolerates trailing blanks.
+ const skip = () => {
+ while (index < lines.length && (/^\s*$/.test(lines[index]) || lines[index].startsWith('#')))
+ index += 1;
+ };
+
+ skip();
+ if (index >= lines.length) throw new AsciicastError('recording is empty');
+
+ let header: unknown;
+ try {
+ header = JSON.parse(lines[index]);
+ } catch {
+ throw new AsciicastError('header is not valid JSON', index + 1);
+ }
+ if (!isRecord(header)) throw new AsciicastError('header must be a JSON object', index + 1);
+
+ const version = header.version;
+ if (version !== 2 && version !== 3)
+ throw new AsciicastError(`unsupported asciicast version ${String(version)}`, index + 1);
+
+ const term = version === 3 ? (isRecord(header.term) ? header.term : undefined) : header;
+ const cols = positiveInt(version === 3 ? term?.cols : header.width);
+ const rows = positiveInt(version === 3 ? term?.rows : header.height);
+ if (!cols || !rows)
+ throw new AsciicastError('header must declare a positive terminal size', index + 1);
+ if (cols > limits.maxCols || rows > limits.maxRows)
+ throw new AsciicastError(
+ `terminal size ${cols}x${rows} exceeds ${limits.maxCols}x${limits.maxRows}`,
+ index + 1,
+ );
+
+ const termType =
+ version === 3
+ ? stringOrNull(term?.type)
+ : stringOrNull(isRecord(header.env) ? header.env.TERM : undefined);
+ const timestamp =
+ typeof header.timestamp === 'number' && Number.isFinite(header.timestamp)
+ ? header.timestamp
+ : null;
+
+ const events: AsciicastEvent[] = [];
+ let clock = 0;
+ let exitStatus: number | null = null;
+ index += 1;
+
+ for (; index < lines.length; index += 1) {
+ const line = lines[index];
+ if (/^\s*$/.test(line) || line.startsWith('#')) continue;
+ const lineNo = index + 1;
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(line);
+ } catch {
+ throw new AsciicastError('event is not valid JSON', lineNo);
+ }
+ if (!Array.isArray(raw) || raw.length < 3)
+ throw new AsciicastError('event must be [time, code, data]', lineNo);
+
+ const [time, code, data] = raw;
+ if (typeof time !== 'number' || !Number.isFinite(time) || time < 0)
+ throw new AsciicastError('event time must be a non-negative number', lineNo);
+ if (typeof code !== 'string' || !EVENT_CODES.has(code))
+ throw new AsciicastError(`unknown event code ${JSON.stringify(code)}`, lineNo);
+ if (typeof data !== 'string') throw new AsciicastError('event data must be a string', lineNo);
+ if (utf8Length(data) > limits.maxEventBytes)
+ throw new AsciicastError(`event exceeds ${limits.maxEventBytes} bytes`, lineNo);
+
+ if (version === 3) clock += time;
+ else {
+ if (time < clock) throw new AsciicastError('event times must not go backwards', lineNo);
+ clock = time;
+ }
+ if (clock > limits.maxDurationSeconds)
+ throw new AsciicastError(`recording runs past ${limits.maxDurationSeconds} seconds`, lineNo);
+
+ if (code === 'r') {
+ const size = parseResize(data);
+ if (!size) throw new AsciicastError('resize data must be COLSxROWS', lineNo);
+ if (size.cols > limits.maxCols || size.rows > limits.maxRows)
+ throw new AsciicastError(
+ `resize ${data} exceeds ${limits.maxCols}x${limits.maxRows}`,
+ lineNo,
+ );
+ }
+ if (code === 'x') {
+ const status = Number(data);
+ exitStatus = Number.isInteger(status) ? status : null;
+ }
+
+ events.push({ code: code as AsciicastEventCode, data, t: clock });
+ if (events.length > limits.maxEvents)
+ throw new AsciicastError(`recording has more than ${limits.maxEvents} events`, lineNo);
+ }
+
+ return {
+ cols,
+ command: stringOrNull(header.command),
+ duration: clock,
+ events,
+ exitStatus,
+ rows,
+ termType,
+ timestamp,
+ version,
+ };
+};
+
+export interface AsciicastV3Header {
+ cols: number;
+ command?: string | null;
+ rows: number;
+ termType?: string | null;
+ /** Unix seconds. */
+ timestamp?: number | null;
+ title?: string | null;
+}
+
+/** Microsecond precision is what asciinema itself writes. */
+const interval = (seconds: number) => Math.round(Math.max(0, seconds) * 1e6) / 1e6;
+
+/** Serialize events with absolute times as an asciicast v3 document. */
+export const encodeAsciicastV3 = (header: AsciicastV3Header, events: AsciicastEvent[]): string => {
+ const head: Record<string, unknown> = {
+ term: {
+ cols: header.cols,
+ rows: header.rows,
+ ...(header.termType ? { type: header.termType } : {}),
+ },
+ version: 3,
+ };
+ if (typeof header.timestamp === 'number') head.timestamp = Math.floor(header.timestamp);
+ if (header.command) head.command = header.command;
+ if (header.title) head.title = header.title;
+
+ const out = [JSON.stringify(head)];
+ let previous = 0;
+ for (const event of events) {
+ out.push(JSON.stringify([interval(event.t - previous), event.code, event.data]));
+ previous = Math.max(previous, event.t);
+ }
+ return `${out.join('\n')}\n`;
+};
diff --git a/packages/utils/src/verify/evidenceCoverage.test.ts b/packages/utils/src/verify/evidenceCoverage.test.ts
new file mode 100644
index 00000000000..90132192181
--- /dev/null
+++ b/packages/utils/src/verify/evidenceCoverage.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+
+import { coverageGaps, executionGapTypes } from './evidenceCoverage';
+import { terminalRecord } from './terminalEvidence.fixture';
+
+const captured = { metadata: { terminal: terminalRecord() }, type: 'terminal' as const };
+const authored = {
+ metadata: {
+ terminal: terminalRecord({
+ capture: { ...terminalRecord().capture, mode: 'import' },
+ source: { kind: 'authored' },
+ }),
+ },
+ type: 'terminal' as const,
+};
+
+describe('coverageGaps', () => {
+ it('lets a terminal evidence stand in for text and transcript, but nothing stand in for terminal', () => {
+ expect(coverageGaps([{ type: 'text' }, { type: 'transcript' }], [captured])).toEqual([]);
+ expect(coverageGaps([{ type: 'terminal' }], [{ type: 'text' }])).toEqual(['terminal']);
+ });
+
+ it('matches an execution requirement only against real execution evidence', () => {
+ const required = [{ provenance: 'execution' as const, type: 'terminal' as const }];
+ expect(coverageGaps(required, [captured])).toEqual([]);
+ // An authored example, however it is packaged, never covers it.
+ expect(coverageGaps(required, [authored])).toEqual(['terminal']);
+ // Nor does a bare log: format compatibility is not execution.
+ expect(
+ coverageGaps([{ provenance: 'execution', type: 'text' }], [{ type: 'text' }, authored]),
+ ).toEqual(['text']);
+ expect(coverageGaps([{ provenance: 'execution', type: 'text' }], [captured])).toEqual([]);
+ });
+
+ it('keeps medium-only requirements satisfied by authored examples', () => {
+ expect(coverageGaps([{ type: 'terminal' }], [authored])).toEqual([]);
+ });
+
+ it('names which gaps are execution gaps', () => {
+ const required = [
+ { provenance: 'execution' as const, type: 'terminal' as const },
+ { type: 'screenshot' as const },
+ ];
+ expect(executionGapTypes(required, coverageGaps(required, [authored]))).toEqual(['terminal']);
+ });
+});
diff --git a/packages/utils/src/verify/evidenceCoverage.ts b/packages/utils/src/verify/evidenceCoverage.ts
new file mode 100644
index 00000000000..14b793ff018
--- /dev/null
+++ b/packages/utils/src/verify/evidenceCoverage.ts
@@ -0,0 +1,66 @@
+import type { RequiredEvidenceSpec, VerifyEvidenceType } from '@lobechat/types';
+
+import { isExecutionEvidence } from './terminalEvidence';
+
+/**
+ * Same-medium types that also satisfy a declared requirement. The gate checks
+ * that an artifact of the right medium exists; whether it proves the criterion
+ * is the judge's call. Without this, a recording uploaded as `video` against a
+ * `gif` requirement, or a CLI log uploaded as `text` against `transcript`,
+ * failed every repair round on a label while the judge never saw the artifact.
+ * 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. A `terminal` evidence carries a text
+ * payload, so it stands in for `text` and `transcript`; nothing stands in for
+ * `terminal`, whose point is the structured execution record. `dom_snapshot`
+ * and `audio` have no substitute.
+ */
+const SATISFIED_BY: Partial<Record<VerifyEvidenceType, VerifyEvidenceType[]>> = {
+ gif: ['video'],
+ markdown: ['text', 'transcript'],
+ screenshot: ['gif'],
+ text: ['markdown', 'transcript', 'terminal'],
+ transcript: ['text', 'markdown', 'terminal'],
+ video: ['gif'],
+};
+
+export interface CoverageEvidence {
+ metadata?: unknown;
+ type: VerifyEvidenceType;
+}
+
+/**
+ * Which required evidence types are still missing for a criterion — pure, so the
+ * structural gate is unit-testable without a database. Returns `[]` when the
+ * item declares no evidence requirement (nothing to gate on).
+ *
+ * A spec with `provenance: 'execution'` is matched only against evidence that
+ * can stand for a real command run ({@link isExecutionEvidence}): format
+ * compatibility says the attachment has the right shape, never that anything
+ * ran, so an authored example or a bare text log does not cover it.
+ */
+export const coverageGaps = (
+ required: RequiredEvidenceSpec[] | undefined,
+ evidence: CoverageEvidence[],
+): VerifyEvidenceType[] => {
+ if (!required?.length) return [];
+ const all = new Set(evidence.map((e) => e.type));
+ const executed = new Set(evidence.filter(isExecutionEvidence).map((e) => e.type));
+ const gaps = new Set<VerifyEvidenceType>();
+ for (const spec of required) {
+ const present = spec.provenance === 'execution' ? executed : all;
+ if (!present.has(spec.type) && !SATISFIED_BY[spec.type]?.some((alt) => present.has(alt)))
+ gaps.add(spec.type);
+ }
+ return [...gaps];
+};
+
+/** The gap types that are missing because no real execution backs them. */
+export const executionGapTypes = (
+ required: RequiredEvidenceSpec[] | undefined,
+ gaps: VerifyEvidenceType[],
+): VerifyEvidenceType[] =>
+ gaps.filter((type) =>
+ required?.some((spec) => spec.type === type && spec.provenance === 'execution'),
+ );
diff --git a/packages/utils/src/verify/terminalEvidence.fixture.ts b/packages/utils/src/verify/terminalEvidence.fixture.ts
new file mode 100644
index 00000000000..f5ea8c9fa40
--- /dev/null
+++ b/packages/utils/src/verify/terminalEvidence.fixture.ts
@@ -0,0 +1,33 @@
+import type { VerifyTerminalEvidenceMetadata } from '@lobechat/types';
+
+export const HASH = 'a'.repeat(64);
+
+/** A valid captured pipe record for tests; override any top-level section. */
+export const terminalRecord = (
+ overrides: Partial<VerifyTerminalEvidenceMetadata> = {},
+): VerifyTerminalEvidenceMetadata => ({
+ artifacts: { stdout: { fileId: 'file_1', sha256: HASH, size: 3 } },
+ capture: {
+ capturer: { name: 'lh', version: '1.0.0' },
+ mode: 'pipe',
+ streamLayout: 'separate',
+ terminal: null,
+ timing: 'unavailable',
+ },
+ execution: {
+ command: 'ls -la',
+ cwd: '~/repo',
+ durationMs: 12,
+ environmentSummary: { platform: 'darwin-arm64' },
+ error: null,
+ exitCode: 1,
+ finishedAt: '2026-10-13T00:00:00.012Z',
+ outcome: 'exited',
+ signal: null,
+ startedAt: '2026-10-13T00:00:00.000Z',
+ },
+ processing: { missingFields: [], notes: [], redactions: [], truncation: [] },
+ source: { kind: 'captured', originalRecordRef: null, originalTool: null },
+ version: 1,
+ ...overrides,
+});
diff --git a/packages/utils/src/verify/terminalEvidence.test.ts b/packages/utils/src/verify/terminalEvidence.test.ts
new file mode 100644
index 00000000000..64b68bb8e4c
--- /dev/null
+++ b/packages/utils/src/verify/terminalEvidence.test.ts
@@ -0,0 +1,187 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createTerminalSanitizer,
+ describeTerminalOutcome,
+ formatTerminalTranscript,
+ isExecutionEvidence,
+ parseTerminalEvidenceMetadata,
+ readTerminalEvidenceMetadata,
+ terminalTextFromStream,
+} from './terminalEvidence';
+import { HASH, terminalRecord } from './terminalEvidence.fixture';
+
+describe('parseTerminalEvidenceMetadata', () => {
+ it('accepts a complete record and normalizes optional fields', () => {
+ const parsed = parseTerminalEvidenceMetadata(terminalRecord());
+ expect(parsed.ok).toBe(true);
+ if (parsed.ok) expect(parsed.metadata.artifacts.cast).toBeNull();
+ });
+
+ it.each([
+ ['a wrong version', { version: 2 }],
+ ['an unknown source kind', { source: { kind: 'verified' } }],
+ [
+ 'recorded timing without a recording',
+ {
+ capture: { mode: 'pty', streamLayout: 'merged', timing: 'recorded' },
+ },
+ ],
+ [
+ 'a recording without recorded timing',
+ {
+ artifacts: { cast: { sha256: HASH, size: 1 } },
+ },
+ ],
+ [
+ 'a captured source in import mode',
+ { capture: { mode: 'import', streamLayout: 'merged', timing: 'unavailable' } },
+ ],
+ ['an import that claims a pipe capture', { source: { kind: 'imported' } }],
+ [
+ 'an absolute artifact path',
+ { artifacts: { stdout: { path: '/etc/passwd', sha256: HASH, size: 1 } } },
+ ],
+ [
+ 'an escaping artifact path',
+ { artifacts: { stdout: { path: '../x', sha256: HASH, size: 1 } } },
+ ],
+ ['a malformed hash', { artifacts: { stdout: { sha256: 'abc', size: 1 } } }],
+ [
+ 'a non-ISO start time',
+ { execution: { ...terminalRecord().execution, startedAt: 'yesterday' } },
+ ],
+ ])('refuses %s', (_, overrides) => {
+ const parsed = parseTerminalEvidenceMetadata({ ...terminalRecord(), ...overrides });
+ expect(parsed.ok).toBe(false);
+ });
+
+ it('names the offending field', () => {
+ const parsed = parseTerminalEvidenceMetadata({
+ ...terminalRecord(),
+ execution: { ...terminalRecord().execution, exitCode: 'zero' },
+ });
+ expect(parsed).toEqual({
+ error: 'terminal.execution.exitCode must be an integer or null',
+ ok: false,
+ });
+ });
+});
+
+describe('isExecutionEvidence', () => {
+ it('counts captured and imported terminal evidence only', () => {
+ const imported = terminalRecord({
+ capture: { ...terminalRecord().capture, mode: 'import' },
+ source: { kind: 'imported' },
+ });
+ const authored = terminalRecord({
+ capture: { ...terminalRecord().capture, mode: 'import' },
+ source: { kind: 'authored' },
+ });
+ expect(
+ isExecutionEvidence({ metadata: { terminal: terminalRecord() }, type: 'terminal' }),
+ ).toBe(true);
+ expect(isExecutionEvidence({ metadata: { terminal: imported }, type: 'terminal' })).toBe(true);
+ expect(isExecutionEvidence({ metadata: { terminal: authored }, type: 'terminal' })).toBe(false);
+ // A terminal record on a text row, or a broken record, is not provenance.
+ expect(isExecutionEvidence({ metadata: { terminal: terminalRecord() }, type: 'text' })).toBe(
+ false,
+ );
+ expect(isExecutionEvidence({ metadata: { terminal: { version: 1 } }, type: 'terminal' })).toBe(
+ false,
+ );
+ expect(isExecutionEvidence({ type: 'terminal' })).toBe(false);
+ });
+
+ it('reads the record only from metadata.terminal', () => {
+ expect(readTerminalEvidenceMetadata(terminalRecord())).toBeUndefined();
+ expect(readTerminalEvidenceMetadata({ terminal: terminalRecord() })?.execution.command).toBe(
+ 'ls -la',
+ );
+ });
+});
+
+describe('createTerminalSanitizer', () => {
+ it('drops hyperlinks, clipboard writes and other string sequences but keeps drawing', () => {
+ const clean = createTerminalSanitizer();
+ expect(
+ clean(
+ '\u001B[31mred\u001B[0m \u001B]8;;https://evil.example\u001B\\link\u001B]8;;\u001B\\ \u001B]52;c;Y2xpcA==\u0007done\u001BPq#0;2;0;0;0\u001B\\!',
+ ),
+ ).toBe('\u001B[31mred\u001B[0m link done!');
+ });
+
+ it('removes a sequence split across chunks', () => {
+ const clean = createTerminalSanitizer();
+ expect(clean('a\u001B]52;c;')).toBe('a');
+ expect(clean('Y2xp\u0007b')).toBe('b');
+ expect(clean('\u001B')).toBe('');
+ expect(clean(']0;title\u0007c')).toBe('c');
+ });
+
+ it('handles C1 introducers and keeps a lone escape before another', () => {
+ expect(createTerminalSanitizer()('x\u009D8;;u\u009Cy')).toBe('xy');
+ expect(createTerminalSanitizer()('\u001B\u001B[1mz')).toBe('\u001B\u001B[1mz');
+ });
+});
+
+describe('terminalTextFromStream', () => {
+ it('strips control sequences and keeps the last carriage-return write of a line', () => {
+ expect(
+ terminalTextFromStream(
+ '\u001B[1;32mok\u001B[0m\r\nprogress 10%\rprogress 90%\r\n\u001B]0;t\u0007end\r',
+ ),
+ ).toBe('ok\nprogress 90%\nend');
+ });
+});
+
+describe('formatTerminalTranscript', () => {
+ it('lists the facts, then each stream verbatim as plain text', () => {
+ const text = formatTerminalTranscript(
+ terminalRecord({
+ processing: {
+ missingFields: [],
+ notes: ['n'],
+ redactions: [{ count: 2, rule: 'env-secret' }],
+ truncation: [{ droppedBytes: 2048, keptBytes: 10, stream: 'stdout' }],
+ },
+ }),
+ { stderr: '', stdout: '\u001B[32mout\u001B[0m\n' },
+ );
+ expect(text).toBe(
+ [
+ '$ ls -la',
+ '# cwd: ~/repo',
+ '# source: captured · mode: pipe · no timing',
+ '# result: exit 1 · started 2026-10-13T00:00:00.000Z · 0.01s',
+ '# env: platform=darwin-arm64',
+ '# redacted: env-secret ×2',
+ '# truncated: stdout kept 10 B, dropped 2.0 KiB',
+ '# note: n',
+ '',
+ '--- stdout ---',
+ 'out',
+ '',
+ '--- stderr (empty) ---',
+ '',
+ ].join('\n'),
+ );
+ });
+
+ it('says what is unknown instead of guessing', () => {
+ expect(
+ describeTerminalOutcome({
+ ...terminalRecord().execution,
+ exitCode: null,
+ outcome: 'unknown',
+ }),
+ ).toBe('exit status unknown');
+ expect(
+ describeTerminalOutcome({
+ ...terminalRecord().execution,
+ outcome: 'timed_out',
+ signal: 'SIGTERM',
+ }),
+ ).toBe('timed out, killed by SIGTERM');
+ });
+});
diff --git a/packages/utils/src/verify/terminalEvidence.ts b/packages/utils/src/verify/terminalEvidence.ts
new file mode 100644
index 00000000000..b733e8c34dd
--- /dev/null
+++ b/packages/utils/src/verify/terminalEvidence.ts
@@ -0,0 +1,479 @@
+import type {
+ VerifyTerminalArtifact,
+ VerifyTerminalCaptureMode,
+ VerifyTerminalEvidenceMetadata,
+ VerifyTerminalOutcome,
+ VerifyTerminalSourceKind,
+ VerifyTerminalTruncation,
+} from '@lobechat/types';
+
+/**
+ * Terminal evidence: one command execution, shared by the CLI that captures it,
+ * the server that stores and gates it, and the page that shows it.
+ *
+ * The evidence row's payload is the readable text fallback
+ * ({@link formatTerminalTranscript}); `metadata.terminal` carries the
+ * execution facts and the artifact files. Every reader parses that metadata
+ * through {@link parseTerminalEvidenceMetadata}, so the three can never
+ * disagree on what a valid record is.
+ */
+
+export const TERMINAL_EVIDENCE_VERSION = 1;
+
+export const TERMINAL_ARTIFACT_KEYS = ['stdout', 'stderr', 'output', 'cast'] as const;
+export type TerminalArtifactKey = (typeof TERMINAL_ARTIFACT_KEYS)[number];
+
+const SOURCE_KINDS = new Set<VerifyTerminalSourceKind>(['authored', 'captured', 'imported']);
+const MODES = new Set<VerifyTerminalCaptureMode>(['import', 'pipe', 'pty']);
+const LAYOUTS = new Set<VerifyTerminalEvidenceMetadata['capture']['streamLayout']>([
+ 'merged',
+ 'separate',
+ 'unknown',
+]);
+const TIMINGS = new Set<VerifyTerminalEvidenceMetadata['capture']['timing']>([
+ 'recorded',
+ 'unavailable',
+]);
+const OUTCOMES = new Set<VerifyTerminalOutcome>([
+ 'capture_failed',
+ 'exited',
+ 'interrupted',
+ 'signaled',
+ 'spawn_failed',
+ 'timed_out',
+ 'unknown',
+]);
+const TRUNCATED_STREAMS = new Set<VerifyTerminalTruncation['stream']>([
+ 'cast',
+ 'output',
+ 'stderr',
+ 'stdout',
+]);
+
+/** Bounds on the record itself — it lives in a jsonb column and every page load reads it. */
+const MAX_TEXT = 8192;
+const MAX_LIST = 64;
+const MAX_ENV_ENTRIES = 32;
+
+type Result = { error: string; ok: false } | { metadata: VerifyTerminalEvidenceMetadata; ok: true };
+
+class InvalidMetadata extends Error {}
+
+const fail = (message: string): never => {
+ throw new InvalidMetadata(message);
+};
+
+const record = (value: unknown, path: string): Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : fail(`${path} must be an object`);
+
+const nullableString = (value: unknown, path: string): string | null => {
+ if (value === undefined || value === null) return null;
+ if (typeof value !== 'string') return fail(`${path} must be a string or null`);
+ if (value.length > MAX_TEXT) return fail(`${path} exceeds ${MAX_TEXT} characters`);
+ return value;
+};
+
+const nullableInt = (value: unknown, path: string): number | null => {
+ if (value === undefined || value === null) return null;
+ if (typeof value !== 'number' || !Number.isInteger(value))
+ return fail(`${path} must be an integer or null`);
+ return value;
+};
+
+const nullableIso = (value: unknown, path: string): string | null => {
+ const text = nullableString(value, path);
+ if (text !== null && Number.isNaN(Date.parse(text)))
+ return fail(`${path} must be an ISO 8601 timestamp`);
+ return text;
+};
+
+const oneOf = <T extends string>(value: unknown, allowed: ReadonlySet<T>, path: string): T =>
+ typeof value === 'string' && allowed.has(value as T)
+ ? (value as T)
+ : fail(`${path} must be one of ${[...allowed].join(', ')}`);
+
+const stringList = (value: unknown, path: string): string[] => {
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value) || value.length > MAX_LIST) return fail(`${path} must be a short list`);
+ return value.map(
+ (item, i) => nullableString(item, `${path}[${i}]`) ?? fail(`${path}[${i}] is empty`),
+ );
+};
+
+const artifact = (value: unknown, path: string): VerifyTerminalArtifact | null => {
+ if (value === undefined || value === null) return null;
+ const raw = record(value, path);
+ const sha256 = nullableString(raw.sha256, `${path}.sha256`);
+ if (!sha256 || !/^[\da-f]{64}$/.test(sha256)) fail(`${path}.sha256 must be a hex SHA-256`);
+ const size = nullableInt(raw.size, `${path}.size`);
+ if (size === null || size < 0) fail(`${path}.size must be a non-negative integer`);
+ const fileId = nullableString(raw.fileId, `${path}.fileId`);
+ const filePath = nullableString(raw.path, `${path}.path`);
+ // Only a bundle-relative name may travel: an absolute local path is not
+ // something any other machine can open, and it leaks the author's layout.
+ if (filePath && (/^(?:[/\\]|[a-z]:)/i.test(filePath) || filePath.split(/[/\\]/).includes('..')))
+ fail(`${path}.path must be relative to the bundle`);
+ return {
+ ...(fileId ? { fileId } : {}),
+ ...(filePath ? { path: filePath } : {}),
+ sha256: sha256!,
+ size: size!,
+ };
+};
+
+const truncation = (value: unknown, path: string): VerifyTerminalTruncation[] => {
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value) || value.length > MAX_LIST) return fail(`${path} must be a short list`);
+ return value.map((item, i) => {
+ const raw = record(item, `${path}[${i}]`);
+ const kept = nullableInt(raw.keptBytes, `${path}[${i}].keptBytes`);
+ const dropped = nullableInt(raw.droppedBytes, `${path}[${i}].droppedBytes`);
+ if (kept === null || dropped === null || kept < 0 || dropped < 0)
+ fail(`${path}[${i}] needs non-negative keptBytes and droppedBytes`);
+ return {
+ droppedBytes: dropped!,
+ keptBytes: kept!,
+ stream: oneOf(raw.stream, TRUNCATED_STREAMS, `${path}[${i}].stream`),
+ };
+ });
+};
+
+const terminalSize = (value: unknown, path: string) => {
+ if (value === undefined || value === null) return null;
+ const raw = record(value, path);
+ const cols = nullableInt(raw.cols, `${path}.cols`);
+ const rows = nullableInt(raw.rows, `${path}.rows`);
+ if (!cols || !rows || cols < 1 || rows < 1 || cols > 1000 || rows > 500)
+ fail(`${path} must have cols 1-1000 and rows 1-500`);
+ return { cols: cols!, rows: rows!, type: nullableString(raw.type, `${path}.type`) };
+};
+
+const environment = (value: unknown, path: string): Record<string, string> => {
+ if (value === undefined || value === null) return {};
+ const raw = record(value, path);
+ const entries = Object.entries(raw);
+ if (entries.length > MAX_ENV_ENTRIES) fail(`${path} has more than ${MAX_ENV_ENTRIES} entries`);
+ return Object.fromEntries(
+ entries.map(([key, v]) => [key, nullableString(v, `${path}.${key}`) ?? '']),
+ );
+};
+
+/**
+ * Validate a terminal evidence record. Strict on purpose: the server rejects
+ * an upload this refuses, so a malformed record surfaces at upload time with a
+ * path to the bad field, not as a blank card on the acceptance page.
+ */
+export const parseTerminalEvidenceMetadata = (value: unknown): Result => {
+ try {
+ const raw = record(value, 'terminal');
+ if (raw.version !== TERMINAL_EVIDENCE_VERSION)
+ fail(`terminal.version must be ${TERMINAL_EVIDENCE_VERSION}`);
+
+ const source = record(raw.source, 'terminal.source');
+ const execution = record(raw.execution, 'terminal.execution');
+ const capture = record(raw.capture, 'terminal.capture');
+ const processing = record(raw.processing ?? {}, 'terminal.processing');
+ const artifacts = record(raw.artifacts ?? {}, 'terminal.artifacts');
+
+ const parsedArtifacts = Object.fromEntries(
+ TERMINAL_ARTIFACT_KEYS.map((key) => [
+ key,
+ artifact(artifacts[key], `terminal.artifacts.${key}`),
+ ]),
+ ) as VerifyTerminalEvidenceMetadata['artifacts'];
+
+ const timing = oneOf(capture.timing, TIMINGS, 'terminal.capture.timing');
+ // Replay is offered only for real recorded timing, and real timing only
+ // exists as a recording. A claim of one without the other is refused.
+ if ((timing === 'recorded') !== Boolean(parsedArtifacts.cast))
+ fail('terminal.capture.timing is "recorded" exactly when artifacts.cast exists');
+
+ const capturer =
+ capture.capturer === undefined || capture.capturer === null
+ ? null
+ : (() => {
+ const c = record(capture.capturer, 'terminal.capture.capturer');
+ const name = nullableString(c.name, 'terminal.capture.capturer.name');
+ if (!name) fail('terminal.capture.capturer.name is required');
+ return {
+ name: name!,
+ version: nullableString(c.version, 'terminal.capture.capturer.version'),
+ };
+ })();
+
+ const durationMs = nullableInt(execution.durationMs, 'terminal.execution.durationMs');
+ if (durationMs !== null && durationMs < 0) fail('terminal.execution.durationMs must be >= 0');
+
+ const metadata: VerifyTerminalEvidenceMetadata = {
+ artifacts: parsedArtifacts,
+ capture: {
+ capturer,
+ mode: oneOf(capture.mode, MODES, 'terminal.capture.mode'),
+ streamLayout: oneOf(capture.streamLayout, LAYOUTS, 'terminal.capture.streamLayout'),
+ terminal: terminalSize(capture.terminal, 'terminal.capture.terminal'),
+ timing,
+ },
+ execution: {
+ command: nullableString(execution.command, 'terminal.execution.command'),
+ cwd: nullableString(execution.cwd, 'terminal.execution.cwd'),
+ durationMs,
+ environmentSummary: environment(
+ execution.environmentSummary,
+ 'terminal.execution.environmentSummary',
+ ),
+ error: nullableString(execution.error, 'terminal.execution.error'),
+ exitCode: nullableInt(execution.exitCode, 'terminal.execution.exitCode'),
+ finishedAt: nullableIso(execution.finishedAt, 'terminal.execution.finishedAt'),
+ outcome: oneOf(execution.outcome, OUTCOMES, 'terminal.execution.outcome'),
+ signal: nullableString(execution.signal, 'terminal.execution.signal'),
+ startedAt: nullableIso(execution.startedAt, 'terminal.execution.startedAt'),
+ },
+ processing: {
+ missingFields: stringList(processing.missingFields, 'terminal.processing.missingFields'),
+ notes: stringList(processing.notes, 'terminal.processing.notes'),
+ redactions: (() => {
+ const list = processing.redactions ?? [];
+ if (!Array.isArray(list) || list.length > MAX_LIST)
+ fail('terminal.processing.redactions must be a short list');
+ return (list as unknown[]).map((item, i) => {
+ const r = record(item, `terminal.processing.redactions[${i}]`);
+ const rule = nullableString(r.rule, `terminal.processing.redactions[${i}].rule`);
+ const count = nullableInt(r.count, `terminal.processing.redactions[${i}].count`);
+ if (!rule || count === null || count < 0)
+ fail(`terminal.processing.redactions[${i}] needs a rule and a count`);
+ return { count: count!, rule: rule! };
+ });
+ })(),
+ truncation: truncation(processing.truncation, 'terminal.processing.truncation'),
+ },
+ source: {
+ kind: oneOf(source.kind, SOURCE_KINDS, 'terminal.source.kind'),
+ originalRecordRef: nullableString(
+ source.originalRecordRef,
+ 'terminal.source.originalRecordRef',
+ ),
+ originalTool: nullableString(source.originalTool, 'terminal.source.originalTool'),
+ },
+ version: TERMINAL_EVIDENCE_VERSION,
+ };
+
+ // A captured run comes from the capturer itself; it cannot be "import" mode.
+ if (metadata.source.kind === 'captured' && metadata.capture.mode === 'import')
+ fail('terminal.source.kind "captured" needs capture.mode pipe or pty');
+ if (metadata.source.kind !== 'captured' && metadata.capture.mode !== 'import')
+ fail(`terminal.source.kind "${metadata.source.kind}" needs capture.mode import`);
+
+ return { metadata, ok: true };
+ } catch (error) {
+ if (error instanceof InvalidMetadata) return { error: error.message, ok: false };
+ throw error;
+ }
+};
+
+/** The terminal record of an evidence row's metadata bag, or undefined when absent / invalid. */
+export const readTerminalEvidenceMetadata = (
+ metadata: unknown,
+): VerifyTerminalEvidenceMetadata | undefined => {
+ if (typeof metadata !== 'object' || metadata === null || !('terminal' in metadata)) return;
+ const parsed = parseTerminalEvidenceMetadata((metadata as { terminal: unknown }).terminal);
+ return parsed.ok ? parsed.metadata : undefined;
+};
+
+/**
+ * Whether an evidence row can stand for a real command execution. Only a
+ * `terminal` evidence declaring a `captured` or `imported` source qualifies;
+ * legacy text has no provenance to check and an `authored` example never
+ * qualifies, however it is packaged. Eligibility is not authenticity — the
+ * judge still has to read the observation.
+ */
+export const isExecutionEvidence = (evidence: { metadata?: unknown; type: string }): boolean => {
+ if (evidence.type !== 'terminal') return false;
+ const terminal = readTerminalEvidenceMetadata(evidence.metadata);
+ return terminal?.source.kind === 'captured' || terminal?.source.kind === 'imported';
+};
+
+// ── Terminal stream hygiene ────────────────────────────────
+
+/**
+ * Strip the escape sequences that carry strings rather than drawing: OSC
+ * (hyperlinks, clipboard writes, notifications, titles), DCS, APC, PM and SOS,
+ * in their 7-bit and C1 forms. Recorded output is untrusted; none of these is
+ * needed to replay what the screen showed, and each is a way to make a viewer
+ * write the clipboard, open a link or talk to a handler.
+ *
+ * Stateful across chunks: a sequence split over two recorded events is still
+ * removed whole. Unterminated sequences are dropped until their terminator.
+ */
+export const createTerminalSanitizer = () => {
+ type State = 'escape' | 'normal' | 'string' | 'string-escape';
+ let state: State = 'normal';
+ // Whether the open string sequence is an OSC, which BEL also terminates.
+ let osc = false;
+
+ return (chunk: string): string => {
+ let out = '';
+ for (const ch of chunk) {
+ switch (state) {
+ case 'normal': {
+ if (ch === '\u001B') state = 'escape';
+ else if (
+ ch === '\u009D' ||
+ ch === '\u0090' ||
+ ch === '\u0098' ||
+ ch === '\u009E' ||
+ ch === '\u009F'
+ ) {
+ state = 'string';
+ osc = ch === '\u009D';
+ } else out += ch;
+ break;
+ }
+ case 'escape': {
+ if (ch === ']' || ch === 'P' || ch === 'X' || ch === '^' || ch === '_') {
+ state = 'string';
+ osc = ch === ']';
+ } else if (ch === '\u001B') {
+ // The first ESC introduced nothing; pass it through and keep waiting.
+ out += '\u001B';
+ } else {
+ out += `\u001B${ch}`;
+ state = 'normal';
+ }
+ break;
+ }
+ case 'string': {
+ if (ch === '\u001B') state = 'string-escape';
+ else if (ch === '\u009C' || (osc && ch === '\u0007')) state = 'normal';
+ break;
+ }
+ case 'string-escape': {
+ state = ch === '\\' ? 'normal' : ch === '\u001B' ? 'string-escape' : 'string';
+ break;
+ }
+ }
+ }
+ return out;
+ };
+};
+
+// CSI (with parameter and intermediate bytes), charset selection, and other
+// two-byte escapes. Ranges are spelled out: intermediates are U+0020–U+002F,
+// final bytes U+0040–U+007E.
+const CSI_OR_ESCAPE =
+ // eslint-disable-next-line no-control-regex
+ /\u001B\[[\d:;<=>?]*[\u0020-\u002F]*[\u0040-\u007E]|\u009B[\d:;<=>?]*[\u0020-\u002F]*[\u0040-\u007E]|\u001B[()*+][\dA-Z]|\u001B[\u0020-\u002F]*[\w:;<=>?@\\^`{|}~]/gi;
+// eslint-disable-next-line no-control-regex
+const OTHER_CONTROL = /[\u0000-\u0008\v\f\u000E-\u001A\u001C-\u001F\u007F]/g;
+
+/**
+ * Plain text of a terminal stream for reading, searching and AI review.
+ * Carriage-return overwrites keep only the last write of each line — what a
+ * progress bar left on screen — which approximates the screen, not replaces it.
+ */
+export const terminalTextFromStream = (stream: string): string => {
+ const text = createTerminalSanitizer()(stream)
+ .replaceAll(CSI_OR_ESCAPE, '')
+ .replaceAll('\u001B', '')
+ .replaceAll('\r\n', '\n');
+ return text
+ .split('\n')
+ .map((line) => {
+ const segments = line.split('\r');
+ // A trailing \r just returns the carriage; the line already written stays.
+ while (segments.length > 1 && segments.at(-1) === '') segments.pop();
+ return segments.at(-1)!.replaceAll(OTHER_CONTROL, '');
+ })
+ .join('\n');
+};
+
+// ── Text fallback ──────────────────────────────────────────
+
+const formatBytes = (bytes: number) =>
+ bytes < 1024
+ ? `${bytes} B`
+ : bytes < 1024 * 1024
+ ? `${(bytes / 1024).toFixed(1)} KiB`
+ : `${(bytes / 1024 / 1024).toFixed(1)} MiB`;
+
+/** One-line outcome, e.g. `exit 1`, `killed by SIGTERM (timeout)`, `exit status unknown`. */
+export const describeTerminalOutcome = (execution: VerifyTerminalEvidenceMetadata['execution']) => {
+ switch (execution.outcome) {
+ case 'exited': {
+ return `exit ${execution.exitCode ?? '?'}`;
+ }
+ case 'signaled': {
+ return `killed by ${execution.signal ?? 'a signal'}`;
+ }
+ case 'timed_out': {
+ return `timed out${execution.signal ? `, killed by ${execution.signal}` : ''}`;
+ }
+ case 'interrupted': {
+ return `interrupted${execution.signal ? ` (${execution.signal})` : ''}`;
+ }
+ case 'spawn_failed': {
+ return `failed to start${execution.error ? `: ${execution.error}` : ''}`;
+ }
+ case 'capture_failed': {
+ return `capture failed${execution.error ? `: ${execution.error}` : ''}`;
+ }
+ default: {
+ return execution.exitCode === null ? 'exit status unknown' : `exit ${execution.exitCode}`;
+ }
+ }
+};
+
+/**
+ * The evidence payload: everything a reader without a player — the judge, an
+ * export, an old client — needs to review the execution, as plain text.
+ * Header lines are facts from the record; the sections are the observation
+ * verbatim. No interpretation is added: the reasoning is its own evidence.
+ */
+export const formatTerminalTranscript = (
+ metadata: VerifyTerminalEvidenceMetadata,
+ streams: { output?: string | null; stderr?: string | null; stdout?: string | null },
+): string => {
+ const { capture, execution, processing, source } = metadata;
+ const lines: string[] = [
+ `$ ${execution.command ?? '(command not recorded)'}`,
+ `# cwd: ${execution.cwd ?? 'unknown'}`,
+ `# source: ${source.kind}${source.originalTool ? ` from ${source.originalTool}` : ''}${
+ source.originalRecordRef ? ` (${source.originalRecordRef})` : ''
+ } · mode: ${capture.mode} · ${capture.timing === 'recorded' ? 'recorded timing' : 'no timing'}`,
+ ];
+ const when = [
+ execution.startedAt && `started ${execution.startedAt}`,
+ execution.durationMs !== null && `${(execution.durationMs / 1000).toFixed(2)}s`,
+ ].filter(Boolean);
+ lines.push(
+ `# result: ${describeTerminalOutcome(execution)}${when.length ? ` · ${when.join(' · ')}` : ''}`,
+ );
+ const env = Object.entries(execution.environmentSummary);
+ if (env.length) lines.push(`# env: ${env.map(([k, v]) => `${k}=${v}`).join(' ')}`);
+ if (processing.redactions.length)
+ lines.push(
+ `# redacted: ${processing.redactions.map((r) => `${r.rule} ×${r.count}`).join(', ')}`,
+ );
+ for (const t of processing.truncation)
+ lines.push(
+ `# truncated: ${t.stream} kept ${formatBytes(t.keptBytes)}, dropped ${formatBytes(t.droppedBytes)}`,
+ );
+ if (processing.missingFields.length)
+ lines.push(`# unknown: ${processing.missingFields.join(', ')}`);
+ for (const note of processing.notes) lines.push(`# note: ${note}`);
+
+ const section = (name: string, raw: string | null | undefined) => {
+ if (raw === undefined || raw === null) return;
+ // Plain text for readers without a terminal; the artifacts keep the bytes.
+ const body = terminalTextFromStream(raw);
+ lines.push('', `--- ${name}${body.length === 0 ? ' (empty)' : ''} ---`);
+ if (body.length > 0) lines.push(body.endsWith('\n') ? body.slice(0, -1) : body);
+ };
+ if (capture.streamLayout === 'separate') {
+ section('stdout', streams.stdout ?? '');
+ section('stderr', streams.stderr ?? '');
+ } else section('output', streams.output ?? streams.stdout ?? '');
+
+ return `${lines.join('\n')}\n`;
+};
diff --git a/src/features/Acceptance/Report/ReportViewer.tsx b/src/features/Acceptance/Report/ReportViewer.tsx
index 2335a5a3d62..aa795f2b449 100644
--- a/src/features/Acceptance/Report/ReportViewer.tsx
+++ b/src/features/Acceptance/Report/ReportViewer.tsx
@@ -4,7 +4,6 @@ import type {
VerifyAgentPlanConfig,
VerifyCheckItem,
VerifyCodingScope,
- VerifyEvidenceType,
VerifyRunOrigin,
VerifySurface,
VerifyVerdict,
@@ -68,20 +67,28 @@ import {
} from '../utils';
import {
EvidenceComparisonCard,
- type EvidenceComparisonMeta,
isFilenameLike,
meaningfulEvidenceCaption,
- readEvidenceComparison,
} from './EvidenceComparisonCard';
import InteractionCostPanel, { readInteractionCost } from './InteractionCost';
import {
CollapsibleMarkdownEvidence,
DocumentViewer,
- filenameFromUrl,
markdownTextEvidenceTypes,
rendersAsMarkdown,
} from './MarkdownEvidence';
import { originTopicHref } from './originLink';
+import {
+ type EvidenceCategory,
+ evidenceCategory,
+ evidenceComparison,
+ evidenceDisplayName,
+ imageEvidenceTypes,
+ isInlineEvidence,
+ isInlineVisualEvidence,
+ isTerminalEvidence,
+} from './ReportViewer/model';
+import { TerminalEvidenceCard } from './TerminalEvidence';
import { readVisualizationManifest } from './visualization';
import { VisualizationRenderer } from './VisualizationRenderer';
@@ -718,35 +725,6 @@ const SURFACE_ICON: Record<VerifySurface, typeof Check> = {
web: Globe,
};
-const imageEvidenceTypes = new Set(['gif', 'screenshot']);
-/** Player media — a `<video>`/`<audio>` element, not an image box. */
-const playerEvidenceTypes = new Set(['audio', 'video']);
-/** Media that renders/plays inline in the check body, no click-to-open. */
-const isInlineVisualEvidence = (evidence: VerifyEvidenceWithUrl) =>
- Boolean(
- evidence.fileUrl &&
- (imageEvidenceTypes.has(evidence.type) || playerEvidenceTypes.has(evidence.type)),
- );
-
-/**
- * Evidence with a directly renderable payload in the check body, no
- * click-to-open. File-backed documents stay behind the file card on purpose —
- * an uploaded artifact is long by definition, and rendering it inline drowns
- * the check list.
- */
-const isInlineEvidence = (evidence: VerifyEvidenceWithUrl) =>
- Boolean(evidence.content) || isInlineVisualEvidence(evidence);
-
-/** Coarse attachment bucket for the type marker: image / video / audio / everything else. */
-type EvidenceCategory = 'audio' | 'file' | 'image' | 'video';
-const evidenceCategory = (type: VerifyEvidenceType): EvidenceCategory =>
- type === 'video'
- ? 'video'
- : type === 'audio'
- ? 'audio'
- : imageEvidenceTypes.has(type)
- ? 'image'
- : 'file';
const CATEGORY_ICON: Record<EvidenceCategory, typeof FileText> = {
audio: AudioLines,
file: FileText,
@@ -764,24 +742,6 @@ const liveStatusLabelKey = {
verifying: 'report.status.verifying',
} as const;
-const evidenceDisplayName = (
- evidence: VerifyEvidenceWithUrl,
- t: TFunction<'verify'>,
- index: number,
-) =>
- evidence.fileName ||
- (evidence.fileUrl ? filenameFromUrl(evidence.fileUrl) : '') ||
- evidence.description ||
- t('report.evidence.inlineFallback', { index });
-
-type EvidenceComparison = EvidenceComparisonMeta;
-
-const evidenceComparison = (evidence: VerifyEvidenceWithUrl): EvidenceComparison | null => {
- // Only inline media pairs — a text artifact can't sit in a visual diptych.
- if (!isInlineVisualEvidence(evidence)) return null;
- return readEvidenceComparison(evidence.metadata);
-};
-
/** One evidence artifact rendered by its type: zoomable image/gif, video, doc, text. */
const EvidenceItem = memo<{
evidence: VerifyEvidenceWithUrl;
@@ -795,9 +755,11 @@ const EvidenceItem = memo<{
// Inline media (image/gif/video) speaks for itself — the raw filename header
// is visual noise, so only keep a meaningful caption (description) for it.
const isMedia = isInlineVisualEvidence(e);
- const isDocument = Boolean(e.fileUrl) && !isMedia && e.type !== 'audio';
+ const isTerminal = isTerminalEvidence(e);
+ const isDocument = Boolean(e.fileUrl) && !isMedia && e.type !== 'audio' && !isTerminal;
const isInlineProse = Boolean(e.content) && markdownTextEvidenceTypes.has(e.type);
const hideLabel =
+ isTerminal ||
isDocument ||
isMedia ||
(markdownTextEvidenceTypes.has(e.type) && isFilenameLike(label)) ||
@@ -810,14 +772,17 @@ const EvidenceItem = memo<{
{label}
</Text>
)}
- {description && !flat && !isInlineProse && (
+ {description && !flat && !isInlineProse && !isTerminal && (
// Inline prose is excluded: its authored description becomes the fold
// row's title below, so a standalone line here would say it twice.
<Text fontSize={13} type={'secondary'}>
{description}
</Text>
)}
- {e.fileUrl && imageEvidenceTypes.has(e.type) ? (
+ {isTerminal ? (
+ // The card titles itself with the command and shows the description under it.
+ <TerminalEvidenceCard defaultExpanded={flat} evidence={e} />
+ ) : e.fileUrl && imageEvidenceTypes.has(e.type) ? (
<Flexbox align={flat ? undefined : 'flex-start'} style={{ maxWidth: '100%' }}>
<Image
preview
@@ -1080,6 +1045,9 @@ const CheckRow = memo<{ defaultOpen: boolean; row: CheckRowData }>(({ defaultOpe
<span className={styles.surfaceChip} key={spec.type} title={spec.hint}>
<Icon icon={CATEGORY_ICON[evidenceCategory(spec.type)]} size={12} />
{t(`report.evidence.medium.${spec.type}`)}
+ {/* Says why an authored example or a bare log leaves it uncovered. */}
+ {spec.provenance === 'execution' &&
+ ` · ${t('report.plan.requiredEvidenceExecution')}`}
</span>
))}
</span>
diff --git a/src/features/Acceptance/Report/ReportViewer/model.ts b/src/features/Acceptance/Report/ReportViewer/model.ts
new file mode 100644
index 00000000000..5a865cb0439
--- /dev/null
+++ b/src/features/Acceptance/Report/ReportViewer/model.ts
@@ -0,0 +1,62 @@
+import type { VerifyEvidenceType } from '@lobechat/types';
+import type { TFunction } from 'i18next';
+
+import type { VerifyEvidenceWithUrl } from '@/services/verify';
+
+import { type EvidenceComparisonMeta, readEvidenceComparison } from '../EvidenceComparisonCard';
+import { filenameFromUrl } from '../MarkdownEvidence';
+
+export const imageEvidenceTypes = new Set(['gif', 'screenshot']);
+/** Player media — a `<video>`/`<audio>` element, not an image box. */
+const playerEvidenceTypes = new Set(['audio', 'video']);
+/** Media that renders/plays inline in the check body, no click-to-open. */
+export const isInlineVisualEvidence = (evidence: VerifyEvidenceWithUrl) =>
+ Boolean(
+ evidence.fileUrl &&
+ (imageEvidenceTypes.has(evidence.type) || playerEvidenceTypes.has(evidence.type)),
+ );
+
+/**
+ * A command execution folds itself to one row and loads its output files on
+ * demand, so it sits in the check body whether its transcript is inline or a
+ * file — never behind the generic file card that would open it as a document.
+ */
+export const isTerminalEvidence = (evidence: VerifyEvidenceWithUrl) => evidence.type === 'terminal';
+
+/**
+ * Evidence with a directly renderable payload in the check body, no
+ * click-to-open. File-backed documents stay behind the file card on purpose —
+ * an uploaded artifact is long by definition, and rendering it inline drowns
+ * the check list.
+ */
+export const isInlineEvidence = (evidence: VerifyEvidenceWithUrl) =>
+ Boolean(evidence.content) || isInlineVisualEvidence(evidence) || isTerminalEvidence(evidence);
+
+/** Coarse attachment bucket for the type marker: image / video / audio / everything else. */
+export type EvidenceCategory = 'audio' | 'file' | 'image' | 'video';
+export const evidenceCategory = (type: VerifyEvidenceType): EvidenceCategory =>
+ type === 'video'
+ ? 'video'
+ : type === 'audio'
+ ? 'audio'
+ : imageEvidenceTypes.has(type)
+ ? 'image'
+ : 'file';
+export const evidenceDisplayName = (
+ evidence: VerifyEvidenceWithUrl,
+ t: TFunction<'verify'>,
+ index: number,
+) =>
+ evidence.fileName ||
+ (evidence.fileUrl ? filenameFromUrl(evidence.fileUrl) : '') ||
+ evidence.description ||
+ t('report.evidence.inlineFallback', { index });
+
+type EvidenceComparison = EvidenceComparisonMeta;
+
+export const evidenceComparison = (evidence: VerifyEvidenceWithUrl): EvidenceComparison | null => {
+ // Inline media pairs, and so do two runs of one command; a plain text
+ // artifact can't sit in a visual diptych.
+ if (!isInlineVisualEvidence(evidence) && !isTerminalEvidence(evidence)) return null;
+ return readEvidenceComparison(evidence.metadata);
+};
diff --git a/src/features/Acceptance/Report/TerminalEvidence/TerminalEvidenceCard.tsx b/src/features/Acceptance/Report/TerminalEvidence/TerminalEvidenceCard.tsx
new file mode 100644
index 00000000000..99b9b174145
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/TerminalEvidenceCard.tsx
@@ -0,0 +1,175 @@
+'use client';
+
+import { Alert, cx, Icon, Segmented, type SegmentedOption, Spin } from '@lobehub/ui';
+import { ChevronRight, SquareTerminal } from 'lucide-react';
+import { lazy, memo, Suspense, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ formatTerminalDuration,
+ resolveTerminalViews,
+ type TerminalEvidenceInput,
+ terminalFoldTitle,
+ type TerminalTextViewKey,
+} from './model';
+import { styles } from './styles';
+import { TerminalFacts, TerminalOutcomeBadge, TerminalSourceBadge } from './TerminalFacts';
+import { TerminalOutput } from './TerminalOutput';
+
+// xterm is only needed once a reader opens Replay — keep it out of the page bundle.
+const TerminalPlayer = lazy(() => import('./TerminalPlayer'));
+
+type BodyView = TerminalTextViewKey | 'replay';
+
+const downloadNameFor = (key: TerminalTextViewKey, fileName?: string | null) =>
+ key === 'transcript' && fileName ? fileName : `terminal-${key}.txt`;
+
+/**
+ * One command execution, folded to a single titled row like other text
+ * evidence. The row already answers the reader's first questions — which
+ * command, how it ended, and (when it is not a live capture) where the
+ * observation came from — so the list stays scannable.
+ *
+ * Expanded, the execution record comes before the output: command, directory,
+ * time, source, capture mode and every processing step that changed what the
+ * output shows. The body opens on static text — stdout / stderr apart for a
+ * pipe capture, one merged output for a pty — with Replay offered only when a
+ * real recording exists, and the stored transcript always one click away so
+ * the record is reviewable without the player.
+ */
+export const TerminalEvidenceCard = memo<{
+ /** Open on mount — a before/after pair is read side by side, not one fold at a time. */
+ defaultExpanded?: boolean;
+ evidence: TerminalEvidenceInput;
+}>(({ defaultExpanded = false, evidence }) => {
+ const { t } = useTranslation('verify');
+ const [expanded, setExpanded] = useState(defaultExpanded);
+ const plan = useMemo(
+ () => resolveTerminalViews(evidence),
+ // The row object is rebuilt on every bundle refresh; its parts are what matter.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [evidence.content, evidence.fileUrl, evidence.metadata, evidence.terminalArtifacts],
+ );
+ const [selected, setSelected] = useState<BodyView>(plan.defaultView);
+ const { terminal } = plan;
+
+ // A refreshed bundle can drop a view (e.g. an expired link); fall back rather than blank.
+ const available = new Set<BodyView>([
+ ...plan.views.map((view) => view.key),
+ ...(plan.replayUrl ? (['replay'] as const) : []),
+ ]);
+ const current: BodyView = available.has(selected) ? selected : plan.defaultView;
+ const textView = plan.views.find((view) => view.key === current);
+
+ const command = terminal?.execution.command?.trim();
+ const title = terminalFoldTitle(terminal, evidence) || t('report.terminal.title');
+ const description = evidence.description?.trim();
+ const showDescription = Boolean(description) && description !== title;
+ const duration =
+ terminal?.execution.durationMs === null || terminal?.execution.durationMs === undefined
+ ? undefined
+ : formatTerminalDuration(terminal.execution.durationMs);
+
+ const badges = terminal && (
+ <>
+ <TerminalOutcomeBadge execution={terminal.execution} />
+ {/* A live capture is the expected case; only the exceptions earn row space. */}
+ {terminal.source.kind !== 'captured' && <TerminalSourceBadge source={terminal.source} />}
+ </>
+ );
+
+ const options: SegmentedOption<BodyView>[] = [
+ ...plan.views
+ .filter((view) => view.key !== 'transcript')
+ .map((view) => {
+ const empty = view.source.kind === 'empty';
+ return {
+ disabled: empty && view.key !== current,
+ label: t(`report.terminal.view.${view.key}`),
+ title: empty ? t('report.terminal.view.streamEmpty', { stream: view.key }) : undefined,
+ value: view.key as BodyView,
+ };
+ }),
+ ...(plan.replayUrl
+ ? [{ label: t('report.terminal.view.replay'), value: 'replay' as BodyView }]
+ : []),
+ ...(plan.views.some((view) => view.key === 'transcript')
+ ? [
+ {
+ label: t('report.terminal.view.transcript'),
+ title: t('report.terminal.view.transcriptHint'),
+ value: 'transcript' as BodyView,
+ },
+ ]
+ : []),
+ ];
+
+ return (
+ <div>
+ <button
+ aria-expanded={expanded}
+ className={styles.foldHeader}
+ title={t(expanded ? 'report.evidence.collapse' : 'report.evidence.expand')}
+ type={'button'}
+ onClick={() => setExpanded(!expanded)}
+ >
+ <Icon
+ className={cx(styles.foldChevron, expanded && styles.foldChevronOpen)}
+ icon={ChevronRight}
+ size={14}
+ />
+ <span className={styles.foldIcon}>
+ <Icon icon={SquareTerminal} size={13} />
+ </span>
+ <span data-fold-title className={styles.foldTitle}>
+ {command ? `$ ${title}` : title}
+ </span>
+ <span className={styles.foldMeta}>
+ {badges}
+ {duration && <span>{duration}</span>}
+ </span>
+ </button>
+ {terminal && <div className={styles.foldMetaMobile}>{badges}</div>}
+ {showDescription && <div className={styles.description}>{description}</div>}
+ {expanded && (
+ <div className={styles.body}>
+ {terminal ? (
+ <TerminalFacts terminal={terminal} />
+ ) : (
+ <Alert showIcon title={t('report.terminal.invalidRecord')} type={'info'} />
+ )}
+ {options.length > 1 && (
+ <Segmented
+ options={options}
+ size={'small'}
+ style={{ alignSelf: 'flex-start', maxWidth: '100%' }}
+ value={current}
+ onChange={(value) => setSelected(value)}
+ />
+ )}
+ {current === 'replay' && plan.replayUrl ? (
+ <Suspense
+ fallback={
+ <div className={styles.outputState}>
+ <Spin size={'large'} />
+ </div>
+ }
+ >
+ <TerminalPlayer url={plan.replayUrl} />
+ </Suspense>
+ ) : textView ? (
+ <TerminalOutput
+ downloadName={downloadNameFor(textView.key, evidence.fileName)}
+ key={textView.key}
+ view={textView}
+ />
+ ) : (
+ <div className={styles.outputState}>{t('report.terminal.output.unavailable')}</div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+});
+
+TerminalEvidenceCard.displayName = 'TerminalEvidenceCard';
diff --git a/src/features/Acceptance/Report/TerminalEvidence/TerminalFacts.tsx b/src/features/Acceptance/Report/TerminalEvidence/TerminalFacts.tsx
new file mode 100644
index 00000000000..91b00a9ba0d
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/TerminalFacts.tsx
@@ -0,0 +1,243 @@
+'use client';
+
+import type { VerifyTerminalEvidenceMetadata } from '@lobechat/types';
+import { formatSize } from '@lobechat/utils/format';
+import { Alert, CopyButton, Tag } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatTerminalDuration, terminalOutcomeLabel, terminalOutcomeTone } from './model';
+import { styles } from './styles';
+
+const TONE_COLOR = { error: 'error', neutral: undefined, success: 'success', warning: 'warning' };
+
+/** How the execution ended — the first fact a reader looks for. */
+export const TerminalOutcomeBadge = memo<{
+ execution: VerifyTerminalEvidenceMetadata['execution'];
+}>(({ execution }) => {
+ const { t } = useTranslation('verify');
+ const label = terminalOutcomeLabel(execution);
+ return (
+ <Tag color={TONE_COLOR[terminalOutcomeTone(execution)]} size={'small'}>
+ {t(label.key as 'report.terminal.outcome.unknown', label.values)}
+ </Tag>
+ );
+});
+
+TerminalOutcomeBadge.displayName = 'TerminalOutcomeBadge';
+
+/**
+ * Where the observation came from. A declaration, never an attestation — the
+ * tooltip says what the label means, not that it was verified. `authored`
+ * reads as an example in warning tone so it cannot pass for a real run.
+ */
+export const TerminalSourceBadge = memo<{ source: VerifyTerminalEvidenceMetadata['source'] }>(
+ ({ source }) => {
+ const { t } = useTranslation('verify');
+ return (
+ <Tag
+ color={source.kind === 'authored' ? 'warning' : undefined}
+ size={'small'}
+ title={t(`report.terminal.source.${source.kind}Hint`)}
+ >
+ {t(`report.terminal.source.${source.kind}`)}
+ </Tag>
+ );
+ },
+);
+
+TerminalSourceBadge.displayName = 'TerminalSourceBadge';
+
+const EnvironmentSummary = memo<{ env: Record<string, string> }>(({ env }) => {
+ const { t } = useTranslation('verify');
+ const [open, setOpen] = useState(false);
+ const entries = Object.entries(env);
+ return (
+ <div className={styles.inlineList}>
+ {open &&
+ entries.map(([key, value]) => (
+ <span className={styles.mono} key={key}>
+ {key}={value}
+ </span>
+ ))}
+ <button
+ aria-expanded={open}
+ className={styles.linkButton}
+ type={'button'}
+ onClick={() => setOpen(!open)}
+ >
+ {open
+ ? t('report.terminal.env.hide')
+ : t('report.terminal.env.show', { count: entries.length })}
+ </button>
+ </div>
+ );
+});
+
+EnvironmentSummary.displayName = 'EnvironmentSummary';
+
+/**
+ * The result row: the outcome badge is the readable summary ("failed to
+ * start", "capture failed"); the capturer's raw error stays one click away
+ * instead of being dumped beside it.
+ */
+const ExecutionResult = memo<{ execution: VerifyTerminalEvidenceMetadata['execution'] }>(
+ ({ execution }) => {
+ const { t } = useTranslation('verify');
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ <div className={styles.inlineList}>
+ <TerminalOutcomeBadge execution={execution} />
+ {execution.error && (
+ <button
+ aria-expanded={open}
+ className={styles.linkButton}
+ type={'button'}
+ onClick={() => setOpen(!open)}
+ >
+ {t(open ? 'report.terminal.error.hide' : 'report.terminal.error.show')}
+ </button>
+ )}
+ </div>
+ {open && execution.error && <div className={styles.mono}>{execution.error}</div>}
+ </>
+ );
+ },
+);
+
+ExecutionResult.displayName = 'ExecutionResult';
+
+/**
+ * The execution record: the command (copyable, never runnable), where and when
+ * it ran, how it ended, how it was observed, and everything processing did to
+ * the output — redactions, truncation, unknown fields — so a reader judges the
+ * output knowing what is not in it.
+ */
+export const TerminalFacts = memo<{ terminal: VerifyTerminalEvidenceMetadata }>(({ terminal }) => {
+ const { t } = useTranslation('verify');
+ const { capture, execution, processing, source } = terminal;
+ // `parseTerminalEvidenceMetadata` already fills these; the defaults keep the
+ // card safe for any record that reaches it some other way.
+ const { environmentSummary: env = {} } = execution;
+ const { missingFields = [], notes = [], redactions = [], truncation = [] } = processing;
+ const capturer = capture.capturer
+ ? [capture.capturer.name, capture.capturer.version].filter(Boolean).join(' ')
+ : undefined;
+ const origin = [source.originalTool, source.originalRecordRef].filter(Boolean).join(' · ');
+ const started = execution.startedAt ? dayjs(execution.startedAt) : undefined;
+
+ return (
+ <>
+ {source.kind === 'authored' && (
+ <Alert showIcon title={t('report.terminal.authoredNotice')} type={'warning'} />
+ )}
+ <div className={styles.command}>
+ <pre className={styles.commandText}>
+ <span className={styles.commandPrompt}>$ </span>
+ {execution.command ?? t('report.terminal.commandUnknown')}
+ </pre>
+ {execution.command && (
+ <CopyButton
+ content={execution.command}
+ size={'small'}
+ title={t('report.terminal.copyCommand')}
+ />
+ )}
+ </div>
+ <dl className={styles.facts}>
+ <dt>{t('report.terminal.fact.result')}</dt>
+ <dd>
+ <ExecutionResult execution={execution} />
+ </dd>
+ <dt>{t('report.terminal.fact.cwd')}</dt>
+ <dd className={execution.cwd ? styles.mono : undefined}>
+ {execution.cwd ?? t('report.terminal.fact.unknown')}
+ </dd>
+ <dt>{t('report.terminal.fact.time')}</dt>
+ <dd>
+ {[
+ started?.isValid() ? started.format('YYYY-MM-DD HH:mm:ss') : undefined,
+ execution.durationMs === null
+ ? undefined
+ : formatTerminalDuration(execution.durationMs),
+ ]
+ .filter(Boolean)
+ .join(' · ') || t('report.terminal.fact.unknown')}
+ </dd>
+ <dt>{t('report.terminal.fact.source')}</dt>
+ <dd className={styles.inlineList}>
+ <TerminalSourceBadge source={source} />
+ {origin && <span>{origin}</span>}
+ </dd>
+ <dt>{t('report.terminal.fact.capture')}</dt>
+ <dd className={styles.inlineList}>
+ <span>{t(`report.terminal.mode.${capture.mode}`)}</span>
+ {capture.timing === 'recorded' && <span>{t('report.terminal.timing.recorded')}</span>}
+ {capture.terminal && (
+ <span className={styles.mono}>
+ {capture.terminal.cols}×{capture.terminal.rows}
+ {capture.terminal.type ? ` ${capture.terminal.type}` : ''}
+ </span>
+ )}
+ {capturer && <span>{capturer}</span>}
+ </dd>
+ {Object.keys(env).length > 0 && (
+ <>
+ <dt>{t('report.terminal.fact.environment')}</dt>
+ <dd>
+ <EnvironmentSummary env={env} />
+ </dd>
+ </>
+ )}
+ {redactions.length > 0 && (
+ <>
+ <dt>{t('report.terminal.processing.redacted')}</dt>
+ <dd className={styles.inlineList}>
+ {redactions.map((redaction) => (
+ <span key={redaction.rule}>
+ <span className={styles.mono}>{redaction.rule}</span> ×{redaction.count}
+ </span>
+ ))}
+ </dd>
+ </>
+ )}
+ {truncation.length > 0 && (
+ <>
+ <dt>{t('report.terminal.processing.truncated')}</dt>
+ <dd className={styles.inlineList}>
+ {truncation.map((item) => (
+ <span key={item.stream}>
+ {t('report.terminal.processing.truncatedItem', {
+ dropped: formatSize(item.droppedBytes),
+ kept: formatSize(item.keptBytes),
+ stream: item.stream,
+ })}
+ </span>
+ ))}
+ </dd>
+ </>
+ )}
+ {missingFields.length > 0 && (
+ <>
+ <dt>{t('report.terminal.processing.missing')}</dt>
+ <dd className={styles.mono}>{missingFields.join(', ')}</dd>
+ </>
+ )}
+ {notes.length > 0 && (
+ <>
+ <dt>{t('report.terminal.processing.notes')}</dt>
+ <dd>
+ {notes.map((note, index) => (
+ <div key={index}>{note}</div>
+ ))}
+ </dd>
+ </>
+ )}
+ </dl>
+ </>
+ );
+});
+
+TerminalFacts.displayName = 'TerminalFacts';
diff --git a/src/features/Acceptance/Report/TerminalEvidence/TerminalOutput.tsx b/src/features/Acceptance/Report/TerminalEvidence/TerminalOutput.tsx
new file mode 100644
index 00000000000..254f9b5d7b6
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/TerminalOutput.tsx
@@ -0,0 +1,214 @@
+'use client';
+
+import { downloadFile } from '@lobechat/utils/client/downloadFile';
+import { terminalTextFromStream } from '@lobechat/utils/verify/terminalEvidence';
+import { ActionIcon, CopyButton, Input, Spin } from '@lobehub/ui';
+import { Download, Search } from 'lucide-react';
+import { Fragment, memo, type ReactNode, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useTextFileLoader } from '@/features/FileViewer/hooks/useTextFileLoader';
+
+import { searchTerminalLines, splitTerminalLines, type TerminalTextView } from './model';
+import { styles } from './styles';
+import { castPlainText } from './timeline';
+import { useAsciicast } from './useAsciicast';
+
+const SEARCH_LINE_LIMIT = 2000;
+
+type LoadedText =
+ | { status: 'error' }
+ | { status: 'loading' }
+ | { status: 'ready'; text: string }
+ | { status: 'tooLarge' };
+
+/** Resolve a view's source to display text. Hooks run unconditionally; a null URL idles them. */
+const useViewText = (view: TerminalTextView): LoadedText => {
+ const { source } = view;
+ const file = useTextFileLoader(source.kind === 'url' ? source.url : null);
+ const cast = useAsciicast(source.kind === 'cast' ? source.url : null);
+ const castText = useMemo(() => (cast.cast ? castPlainText(cast.cast.events) : null), [cast.cast]);
+ const fileText = useMemo(
+ () =>
+ file.fileData === null
+ ? null
+ : view.plain
+ ? terminalTextFromStream(file.fileData)
+ : file.fileData,
+ [file.fileData, view.plain],
+ );
+
+ switch (source.kind) {
+ case 'empty': {
+ return { status: 'ready', text: '' };
+ }
+ case 'inline': {
+ return { status: 'ready', text: source.text };
+ }
+ case 'url': {
+ if (file.loading) return { status: 'loading' };
+ if (file.tooLarge) return { status: 'tooLarge' };
+ return fileText === null ? { status: 'error' } : { status: 'ready', text: fileText };
+ }
+ case 'cast': {
+ if (cast.loading) return { status: 'loading' };
+ if (cast.error?.kind === 'tooLarge') return { status: 'tooLarge' };
+ return castText === null ? { status: 'error' } : { status: 'ready', text: castText };
+ }
+ }
+};
+
+const downloadText = (text: string, fileName: string) => {
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }));
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = fileName;
+ link.click();
+ // Revoking in the same task can cancel the download in some browsers.
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+};
+
+/** Matched substrings wrapped in <mark>, the rest left as text. */
+const highlight = (text: string, ranges: [number, number][], className: string) => {
+ const parts: ReactNode[] = [];
+ let cursor = 0;
+ ranges.forEach(([start, end], index) => {
+ if (start > cursor) parts.push(text.slice(cursor, start));
+ parts.push(
+ <mark className={className} key={index}>
+ {text.slice(start, end)}
+ </mark>,
+ );
+ cursor = end;
+ });
+ if (cursor < text.length) parts.push(text.slice(cursor));
+ return parts;
+};
+
+/**
+ * One static text view of a terminal evidence: line-numbered, searchable,
+ * copyable, downloadable, and bounded in height so a long log scrolls inside
+ * the card instead of drowning the check list.
+ *
+ * Download hands over the stored file itself — the already-redacted upload —
+ * never a re-rendering of it: a stream file for a stream, the recording when
+ * the text was read out of one, the stored payload for the transcript.
+ */
+export const TerminalOutput = memo<{ downloadName: string; view: TerminalTextView }>(
+ ({ downloadName, view }) => {
+ const { t } = useTranslation('verify');
+ const loaded = useViewText(view);
+ const [query, setQuery] = useState('');
+ const text = loaded.status === 'ready' ? loaded.text : '';
+ const lines = useMemo(() => splitTerminalLines(text), [text]);
+ const search = useMemo(
+ () => searchTerminalLines(text, query.trim(), SEARCH_LINE_LIMIT),
+ [text, query],
+ );
+ const searching = query.trim().length > 0;
+ const { source } = view;
+ const fromRecording = source.kind === 'cast';
+
+ const onDownload = () => {
+ if (source.kind === 'url') void downloadFile(source.url, downloadName);
+ else if (source.kind === 'cast')
+ void downloadFile(source.url, downloadName.replace(/\.\w+$/, '') + '.cast');
+ else if (source.kind === 'inline') downloadText(source.text, downloadName);
+ };
+
+ const toolbar = (
+ <div className={styles.toolbar}>
+ <Input
+ allowClear
+ aria-label={t('report.terminal.search.placeholder')}
+ disabled={loaded.status !== 'ready' || text.length === 0}
+ placeholder={t('report.terminal.search.placeholder')}
+ prefix={<Search size={14} />}
+ size={'small'}
+ style={{ maxWidth: 280 }}
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ />
+ <span style={{ alignItems: 'center', display: 'flex', gap: 8 }}>
+ <span className={styles.hint}>
+ {searching
+ ? search.matchCount > 0
+ ? t('report.terminal.search.count', { count: search.matchCount })
+ : t('report.terminal.search.none')
+ : loaded.status === 'ready' && text.length > 0
+ ? t('report.terminal.output.lines', { count: lines.length })
+ : null}
+ </span>
+ {loaded.status === 'ready' && text.length > 0 && (
+ <CopyButton content={text} size={'small'} title={t('report.terminal.copy')} />
+ )}
+ {source.kind !== 'empty' && (
+ <ActionIcon
+ icon={Download}
+ size={'small'}
+ title={t(
+ fromRecording ? 'report.terminal.downloadRecording' : 'report.terminal.download',
+ )}
+ onClick={onDownload}
+ />
+ )}
+ </span>
+ </div>
+ );
+
+ let body: ReactNode;
+ if (loaded.status === 'loading')
+ body = (
+ <div className={styles.outputState}>
+ <Spin size={'large'} />
+ </div>
+ );
+ else if (loaded.status === 'tooLarge')
+ body = <div className={styles.outputState}>{t('report.terminal.output.tooLarge')}</div>;
+ else if (loaded.status === 'error')
+ body = <div className={styles.outputState}>{t('report.terminal.output.loadFailed')}</div>;
+ else if (text.length === 0)
+ body = <div className={styles.outputState}>{t('report.terminal.output.empty')}</div>;
+ else if (searching && search.matchCount === 0)
+ body = <div className={styles.outputState}>{t('report.terminal.search.none')}</div>;
+ else
+ body = (
+ <div className={styles.outputBox}>
+ <div className={styles.outputGrid}>
+ <pre aria-hidden className={styles.gutter}>
+ {searching
+ ? search.lines.map((match) => match.line).join('\n')
+ : lines.map((_, index) => index + 1).join('\n')}
+ </pre>
+ <pre className={styles.lines}>
+ {searching
+ ? search.lines.map((match, index) => (
+ <Fragment key={match.line}>
+ {index > 0 && '\n'}
+ {highlight(match.text, match.ranges, styles.match)}
+ </Fragment>
+ ))
+ : lines.join('\n')}
+ </pre>
+ </div>
+ </div>
+ );
+
+ return (
+ <>
+ {toolbar}
+ {body}
+ {searching && search.matchedLineCount > search.lines.length && (
+ <span className={styles.hint}>
+ {t('report.terminal.search.capped', { count: search.lines.length })}
+ </span>
+ )}
+ {fromRecording && loaded.status === 'ready' && (
+ <span className={styles.hint}>{t('report.terminal.output.fromRecording')}</span>
+ )}
+ </>
+ );
+ },
+);
+
+TerminalOutput.displayName = 'TerminalOutput';
diff --git a/src/features/Acceptance/Report/TerminalEvidence/TerminalPlayer.tsx b/src/features/Acceptance/Report/TerminalEvidence/TerminalPlayer.tsx
new file mode 100644
index 00000000000..9dbcc9abf55
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/TerminalPlayer.tsx
@@ -0,0 +1,293 @@
+'use client';
+
+import '@xterm/xterm/css/xterm.css';
+
+import { formatSize } from '@lobechat/utils/format';
+import { ASCIICAST_LIMITS } from '@lobechat/utils/verify/asciicast';
+import { createTerminalSanitizer } from '@lobechat/utils/verify/terminalEvidence';
+import { ActionIcon, cx, DropdownMenu, Flexbox, Icon, Slider, Spin, useTheme } from '@lobehub/ui';
+import { Terminal } from '@xterm/xterm';
+import { Check, Pause, Play, RotateCcw } from 'lucide-react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { buildXtermTheme } from '@/features/ChatTerminal/theme';
+
+import { terminalReplayError } from './model';
+import { styles } from './playerStyle';
+import { styles as sharedStyles } from './styles';
+import {
+ buildTimeline,
+ collectOps,
+ eventCountAt,
+ formatPlaybackClock,
+ MAX_IDLE_SECONDS,
+ PLAYBACK_RATES,
+ type PlaybackTimeline,
+ PRECISE_CLOCK_MAX_SECONDS,
+} from './timeline';
+import { useAsciicast } from './useAsciicast';
+
+/**
+ * Replays a recording into a terminal that can only be watched. Nothing it
+ * renders can reach out: stdin is disabled and no input handler is attached,
+ * links never open, no clipboard or web-links addon is loaded, and every
+ * output chunk passes one sanitizer per pass that strips OSC / DCS / APC / PM
+ * strings before xterm parses them.
+ */
+const Player = memo<{ duration: number; timeline: PlaybackTimeline }>(({ duration, timeline }) => {
+ const { t } = useTranslation('verify');
+ const theme = useTheme();
+ const hostRef = useRef<HTMLDivElement>(null);
+ const termRef = useRef<Terminal | null>(null);
+ const appliedRef = useRef(0);
+ // One sanitizer per playback pass; created with the terminal, replaced on every rewind.
+ const sanitizerRef = useRef<ReturnType<typeof createTerminalSanitizer> | null>(null);
+ const timeRef = useRef(0);
+ const [time, setTime] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const [rate, setRate] = useState<number>(1);
+
+ /** Bring the screen to playback time `t`: forward applies the gap, backward replays from zero. */
+ const renderTo = useCallback(
+ (target: number) => {
+ const term = termRef.current;
+ let sanitize = sanitizerRef.current;
+ if (!term || !sanitize) return;
+ const count = eventCountAt(timeline.events, target);
+ if (count < appliedRef.current) {
+ // RIS through the write queue, so it lands after anything still being
+ // parsed; the resize rides the same queue for the same reason.
+ term.write('\u001Bc', () => term.resize(timeline.cols, timeline.rows));
+ sanitize = createTerminalSanitizer();
+ sanitizerRef.current = sanitize;
+ appliedRef.current = 0;
+ }
+ for (const op of collectOps(timeline.events, appliedRef.current, count, sanitize)) {
+ if (op.type === 'write') term.write(op.data);
+ else term.write('', () => term.resize(op.cols, op.rows));
+ }
+ appliedRef.current = count;
+ },
+ [timeline],
+ );
+
+ useEffect(() => {
+ const host = hostRef.current;
+ if (!host) return;
+ let term: Terminal | null = null;
+ const mount = () => {
+ term = new Terminal({
+ allowProposedApi: false,
+ cols: timeline.cols,
+ cursorBlink: false,
+ disableStdin: true,
+ fontFamily: theme.fontFamilyCode,
+ fontSize: 12,
+ // OSC 8 links are already stripped; this makes sure none would ever open.
+ linkHandler: { activate: () => {} },
+ rows: timeline.rows,
+ scrollback: 5000,
+ theme: buildXtermTheme(theme),
+ });
+ term.open(host);
+ termRef.current = term;
+ appliedRef.current = 0;
+ sanitizerRef.current = createTerminalSanitizer();
+ timeRef.current = 0;
+ renderTo(0);
+ setTime(0);
+ // The reader opened Replay to watch it run; start right away.
+ setPlaying(true);
+ };
+ // Open the terminal only once its host is on screen. xterm pauses painting
+ // while it believes it is hidden and repaints on the next visibility change;
+ // opened mid-layout (two replays opened together push each other around) it
+ // could record "hidden", miss that change, and play a whole recording into
+ // a screen that stayed blank.
+ const visibility = new IntersectionObserver((entries) => {
+ if (term || !entries.some((entry) => entry.isIntersecting)) return;
+ visibility.disconnect();
+ mount();
+ });
+ visibility.observe(host);
+ return () => {
+ visibility.disconnect();
+ term?.dispose();
+ termRef.current = null;
+ };
+ // The theme is applied live below; recreating the terminal would lose the screen.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [renderTo, timeline]);
+
+ useEffect(() => {
+ if (termRef.current) termRef.current.options.theme = buildXtermTheme(theme);
+ }, [theme]);
+
+ useEffect(() => {
+ if (!playing) return;
+ let last = performance.now();
+ let frame = 0;
+ const tick = (now: number) => {
+ const next = Math.min(timeRef.current + ((now - last) / 1000) * rate, timeline.duration);
+ last = now;
+ timeRef.current = next;
+ renderTo(next);
+ setTime(next);
+ if (next >= timeline.duration) {
+ setPlaying(false);
+ return;
+ }
+ frame = requestAnimationFrame(tick);
+ };
+ frame = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(frame);
+ }, [playing, rate, renderTo, timeline]);
+
+ const seek = (target: number) => {
+ const next = Math.min(Math.max(0, target), timeline.duration);
+ timeRef.current = next;
+ renderTo(next);
+ setTime(next);
+ };
+
+ const togglePlay = () => {
+ if (!playing && timeRef.current >= timeline.duration) seek(0);
+ setPlaying(!playing);
+ };
+
+ const compressed = duration - timeline.duration > 0.05;
+ const precise = timeline.duration < PRECISE_CLOCK_MAX_SECONDS;
+
+ return (
+ <Flexbox gap={8}>
+ <div className={styles.screen}>
+ {/* Sized before the terminal exists, so visibility can be observed and the
+ card does not jump when it opens. */}
+ <div ref={hostRef} style={{ minHeight: timeline.rows * 14 }} />
+ </div>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <ActionIcon
+ icon={playing ? Pause : Play}
+ size={'small'}
+ title={t(playing ? 'report.terminal.player.pause' : 'report.terminal.player.play')}
+ onClick={togglePlay}
+ />
+ <ActionIcon
+ icon={RotateCcw}
+ size={'small'}
+ title={t('report.terminal.player.restart')}
+ onClick={() => {
+ seek(0);
+ setPlaying(true);
+ }}
+ />
+ <span className={styles.clock}>
+ {formatPlaybackClock(time, precise)} / {formatPlaybackClock(timeline.duration, precise)}
+ </span>
+ <Slider
+ aria-label={t('report.terminal.player.seek')}
+ max={Math.max(timeline.duration, 0.01)}
+ min={0}
+ step={0.01}
+ style={{ flex: 1, minWidth: 80 }}
+ value={time}
+ onChange={seek}
+ />
+ <DropdownMenu
+ items={PLAYBACK_RATES.map((value) => ({
+ extra: value === rate ? <Icon icon={Check} /> : undefined,
+ key: String(value),
+ label: `${value}×`,
+ onClick: () => setRate(value),
+ }))}
+ >
+ <button
+ className={cx(styles.rate, rate !== 1 && styles.rateActive)}
+ title={t('report.terminal.player.speed')}
+ type={'button'}
+ >
+ {rate}×
+ </button>
+ </DropdownMenu>
+ </Flexbox>
+ {timeline.markers.length > 0 && (
+ <Flexbox horizontal aria-label={t('report.terminal.player.markers')} gap={6} wrap={'wrap'}>
+ {timeline.markers.map((marker, index) => (
+ <button
+ className={styles.marker}
+ key={`${marker.at}-${index}`}
+ type={'button'}
+ onClick={() => seek(marker.at)}
+ >
+ <span className={styles.markerTime}>{formatPlaybackClock(marker.at, precise)}</span>
+ {marker.label}
+ </button>
+ ))}
+ </Flexbox>
+ )}
+ {compressed && (
+ <span className={sharedStyles.hint}>
+ {t('report.terminal.player.idleCompressed', {
+ duration: formatPlaybackClock(duration),
+ seconds: MAX_IDLE_SECONDS,
+ })}
+ </span>
+ )}
+ </Flexbox>
+ );
+});
+
+Player.displayName = 'TerminalReplayPlayer';
+
+/**
+ * The Replay view: load and validate the recording, then hand it to the
+ * player. Any failure is stated plainly and the text views stay one click
+ * away — a recording that cannot replay never hides the output.
+ */
+const TerminalPlayer = memo<{ url: string }>(({ url }) => {
+ const { t } = useTranslation('verify');
+ const { cast, error, loading } = useAsciicast(url);
+ const timeline = useMemo(() => (cast ? buildTimeline(cast) : null), [cast]);
+
+ if (loading)
+ return (
+ <div className={sharedStyles.outputState}>
+ <Spin size={'large'} />
+ </div>
+ );
+
+ if (error || !timeline || !cast) {
+ const failure = terminalReplayError(error);
+ return (
+ <div className={sharedStyles.outputState} role={'alert'}>
+ {t(failure.summaryKey, { size: formatSize(ASCIICAST_LIMITS.maxBytes, 0) })}
+ {failure.details && (
+ <details key={url} style={{ maxWidth: '100%' }}>
+ <summary className={sharedStyles.linkButton}>{t('report.terminal.error.show')}</summary>
+ <pre
+ className={sharedStyles.mono}
+ style={{
+ margin: 0,
+ overflowWrap: 'anywhere',
+ textAlign: 'start',
+ whiteSpace: 'pre-wrap',
+ }}
+ >
+ {failure.details}
+ </pre>
+ </details>
+ )}
+ </div>
+ );
+ }
+
+ if (timeline.events.length === 0)
+ return <div className={sharedStyles.outputState}>{t('report.terminal.output.empty')}</div>;
+
+ return <Player duration={cast.duration} timeline={timeline} />;
+});
+
+TerminalPlayer.displayName = 'TerminalPlayer';
+
+export default TerminalPlayer;
diff --git a/src/features/Acceptance/Report/TerminalEvidence/index.ts b/src/features/Acceptance/Report/TerminalEvidence/index.ts
new file mode 100644
index 00000000000..ba54765b9a4
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/index.ts
@@ -0,0 +1,2 @@
+export type { TerminalEvidenceInput } from './model';
+export { TerminalEvidenceCard } from './TerminalEvidenceCard';
diff --git a/src/features/Acceptance/Report/TerminalEvidence/model.test.ts b/src/features/Acceptance/Report/TerminalEvidence/model.test.ts
new file mode 100644
index 00000000000..c653ec7c6ad
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/model.test.ts
@@ -0,0 +1,298 @@
+import type { VerifyTerminalEvidenceMetadata } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatTerminalDuration,
+ readTerminalArtifactLinks,
+ resolveTerminalViews,
+ searchTerminalLines,
+ splitTerminalLines,
+ terminalFoldTitle,
+ terminalOutcomeLabel,
+ terminalOutcomeTone,
+ terminalReplayError,
+} from './model';
+
+const SHA = 'a'.repeat(64);
+const artifact = (size: number) => ({ fileId: `file-${size}`, sha256: SHA, size });
+
+const record = (
+ overrides: {
+ artifacts?: VerifyTerminalEvidenceMetadata['artifacts'];
+ capture?: Partial<VerifyTerminalEvidenceMetadata['capture']>;
+ execution?: Partial<VerifyTerminalEvidenceMetadata['execution']>;
+ source?: VerifyTerminalEvidenceMetadata['source'];
+ } = {},
+): VerifyTerminalEvidenceMetadata => ({
+ artifacts: overrides.artifacts ?? { stderr: artifact(0), stdout: artifact(12) },
+ capture: { mode: 'pipe', streamLayout: 'separate', timing: 'unavailable', ...overrides.capture },
+ execution: {
+ command: 'pnpm test',
+ cwd: '/repo',
+ durationMs: 1200,
+ environmentSummary: {},
+ exitCode: 0,
+ finishedAt: null,
+ outcome: 'exited',
+ signal: null,
+ startedAt: null,
+ ...overrides.execution,
+ },
+ processing: { missingFields: [], notes: [], redactions: [], truncation: [] },
+ source: overrides.source ?? { kind: 'captured' },
+ version: 1,
+});
+
+const link = (url: string | null, size = 12) => ({ fileUrl: url, sha256: SHA, size });
+
+describe('readTerminalArtifactLinks', () => {
+ it('keeps well-formed links and drops malformed ones', () => {
+ expect(
+ readTerminalArtifactLinks({
+ bogus: link('https://x/bogus'),
+ cast: { fileUrl: 'https://x/cast' },
+ stderr: link(''),
+ stdout: link('https://x/out'),
+ }),
+ ).toEqual({ stderr: link(null), stdout: link('https://x/out') });
+ expect(readTerminalArtifactLinks(null)).toEqual({});
+ expect(readTerminalArtifactLinks([link('x')])).toEqual({});
+ });
+});
+
+describe('terminalOutcomeTone', () => {
+ it('maps outcomes to tones without inventing success', () => {
+ expect(terminalOutcomeTone({ exitCode: 0, outcome: 'exited' })).toBe('success');
+ expect(terminalOutcomeTone({ exitCode: 2, outcome: 'exited' })).toBe('error');
+ expect(terminalOutcomeTone({ exitCode: null, outcome: 'exited' })).toBe('neutral');
+ expect(terminalOutcomeTone({ exitCode: null, outcome: 'unknown' })).toBe('neutral');
+ expect(terminalOutcomeTone({ exitCode: 0, outcome: 'unknown' })).toBe('success');
+ expect(terminalOutcomeTone({ exitCode: null, outcome: 'signaled' })).toBe('error');
+ expect(terminalOutcomeTone({ exitCode: null, outcome: 'timed_out' })).toBe('error');
+ expect(terminalOutcomeTone({ exitCode: null, outcome: 'spawn_failed' })).toBe('error');
+ expect(terminalOutcomeTone({ exitCode: null, outcome: 'interrupted' })).toBe('warning');
+ expect(terminalOutcomeTone({ exitCode: 0, outcome: 'capture_failed' })).toBe('warning');
+ });
+});
+
+describe('terminalOutcomeLabel', () => {
+ it('names the exit code, signal or unknown state', () => {
+ expect(terminalOutcomeLabel({ exitCode: 1, outcome: 'exited', signal: null })).toEqual({
+ key: 'report.terminal.outcome.exit',
+ values: { code: 1 },
+ });
+ expect(
+ terminalOutcomeLabel({ exitCode: null, outcome: 'signaled', signal: 'SIGKILL' }),
+ ).toEqual({ key: 'report.terminal.outcome.signaled', values: { signal: 'SIGKILL' } });
+ expect(terminalOutcomeLabel({ exitCode: null, outcome: 'signaled', signal: null }).key).toBe(
+ 'report.terminal.outcome.signaledUnknown',
+ );
+ expect(terminalOutcomeLabel({ exitCode: null, outcome: 'unknown', signal: null }).key).toBe(
+ 'report.terminal.outcome.unknown',
+ );
+ expect(
+ terminalOutcomeLabel({ exitCode: null, outcome: 'timed_out', signal: 'SIGTERM' }).key,
+ ).toBe('report.terminal.outcome.timedOut');
+ });
+});
+
+describe('formatTerminalDuration', () => {
+ it('stays precise for short runs', () => {
+ expect(formatTerminalDuration(850)).toBe('850 ms');
+ expect(formatTerminalDuration(1234)).toBe('1.23 s');
+ expect(formatTerminalDuration(12_345)).toBe('12.3 s');
+ expect(formatTerminalDuration(187_000)).toBe('3m 7s');
+ });
+});
+
+describe('resolveTerminalViews', () => {
+ const base = { content: '$ pnpm test\n--- stdout ---\nok\n', id: 'e1' };
+
+ it('falls back to the transcript alone without a readable record', () => {
+ const plan = resolveTerminalViews({ ...base, metadata: { terminal: { version: 2 } } });
+ expect(plan.terminal).toBeUndefined();
+ expect(plan.views.map((view) => view.key)).toEqual(['transcript']);
+ expect(plan.defaultView).toBe('transcript');
+ expect(plan.views[0]!.source).toEqual({ kind: 'inline', text: base.content });
+ });
+
+ it('uses the payload file when there is no inline content', () => {
+ const plan = resolveTerminalViews({ fileUrl: 'https://x/payload', id: 'e1' });
+ expect(plan.views[0]!.source).toEqual({ kind: 'url', url: 'https://x/payload' });
+ });
+
+ it('splits a pipe capture into stdout and stderr, an empty stream needing no fetch', () => {
+ const plan = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: record() },
+ terminalArtifacts: { stdout: link('https://x/stdout') },
+ });
+ expect(plan.views.map((view) => [view.key, view.source.kind])).toEqual([
+ ['stdout', 'url'],
+ ['stderr', 'empty'],
+ ['transcript', 'inline'],
+ ]);
+ expect(plan.defaultView).toBe('stdout');
+ expect(plan.replayUrl).toBeUndefined();
+ });
+
+ it('opens on stderr when stdout is empty', () => {
+ const plan = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: record({ artifacts: { stderr: artifact(30), stdout: null } }) },
+ terminalArtifacts: { stderr: link('https://x/stderr', 30) },
+ });
+ expect(plan.defaultView).toBe('stderr');
+ });
+
+ it('reads an unlisted stream as empty — the capturer writes no file for one', () => {
+ const plan = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: record({ artifacts: {} }) },
+ });
+ expect(plan.views.map((view) => [view.key, view.source.kind])).toEqual([
+ ['stdout', 'empty'],
+ ['stderr', 'empty'],
+ ['transcript', 'inline'],
+ ]);
+ });
+
+ it('drops both streams for the transcript when one with bytes did not resolve', () => {
+ const plan = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: record({ artifacts: { stderr: artifact(5), stdout: artifact(5) } }) },
+ terminalArtifacts: { stdout: link('https://x/stdout') },
+ });
+ expect(plan.views.map((view) => view.key)).toEqual(['transcript']);
+ });
+
+ it('shows merged output from its own file, else from the recording', () => {
+ const pty = record({
+ artifacts: { cast: artifact(900), output: artifact(40) },
+ capture: { mode: 'pty', streamLayout: 'merged', timing: 'recorded' },
+ });
+ const withOutput = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: pty },
+ terminalArtifacts: { cast: link('https://x/cast'), output: link('https://x/output') },
+ });
+ expect(withOutput.views[0]).toMatchObject({ key: 'output', source: { kind: 'url' } });
+ expect(withOutput.replayUrl).toBe('https://x/cast');
+
+ const castOnly = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: { ...pty, artifacts: { cast: artifact(900) } } },
+ terminalArtifacts: { cast: link('https://x/cast') },
+ });
+ expect(castOnly.views[0]).toEqual({
+ key: 'output',
+ plain: true,
+ source: { kind: 'cast', url: 'https://x/cast' },
+ });
+ });
+
+ it('never offers replay without recorded timing, nor for an unresolved recording', () => {
+ const imported = record({
+ artifacts: { output: artifact(10) },
+ capture: { mode: 'import', streamLayout: 'merged', timing: 'unavailable' },
+ source: { kind: 'imported' },
+ });
+ const plan = resolveTerminalViews({
+ ...base,
+ metadata: { terminal: imported },
+ terminalArtifacts: { cast: link('https://x/cast'), output: link('https://x/output') },
+ });
+ expect(plan.replayUrl).toBeUndefined();
+
+ const recorded = record({
+ artifacts: { cast: artifact(900) },
+ capture: { mode: 'pty', streamLayout: 'merged', timing: 'recorded' },
+ });
+ const unresolved = resolveTerminalViews({ ...base, metadata: { terminal: recorded } });
+ expect(unresolved.replayUrl).toBeUndefined();
+ // Output unknown (the recording did not resolve) — not claimed as empty.
+ expect(unresolved.views.map((view) => view.key)).toEqual(['transcript']);
+ });
+});
+
+describe('terminalFoldTitle', () => {
+ it('prefers the command, then the description, then the first transcript line', () => {
+ expect(terminalFoldTitle(record(), { description: 'Run tests' })).toBe('pnpm test');
+ expect(
+ terminalFoldTitle(record({ execution: { command: null } }), { description: ' Run tests ' }),
+ ).toBe('Run tests');
+ expect(terminalFoldTitle(undefined, { content: '\n$ ls -la\nfoo' })).toBe('ls -la');
+ expect(terminalFoldTitle(undefined, {})).toBe('');
+ });
+});
+
+describe('searchTerminalLines', () => {
+ const text = 'PASS a.test\nFAIL b.test\npass c — Pass again\n';
+
+ it('finds every case-insensitive match with its line number and ranges', () => {
+ const result = searchTerminalLines(text, 'pass');
+ expect(result.matchCount).toBe(3);
+ expect(result.matchedLineCount).toBe(2);
+ expect(result.lines).toEqual([
+ { line: 1, ranges: [[0, 4]], text: 'PASS a.test' },
+ {
+ line: 3,
+ ranges: [
+ [0, 4],
+ [9, 13],
+ ],
+ text: 'pass c — Pass again',
+ },
+ ]);
+ });
+
+ it('treats the query literally, not as a pattern', () => {
+ expect(searchTerminalLines('a.b\naxb', '.').matchCount).toBe(1);
+ expect(searchTerminalLines('[x] done', '[x]').matchCount).toBe(1);
+ });
+
+ it('caps listed lines but keeps the full counts', () => {
+ const result = searchTerminalLines('x\nx\nx', 'x', 2);
+ expect(result.lines).toHaveLength(2);
+ expect(result.matchedLineCount).toBe(3);
+ });
+
+ it('returns nothing for an empty query', () => {
+ expect(searchTerminalLines(text, '')).toEqual({
+ lines: [],
+ matchCount: 0,
+ matchedLineCount: 0,
+ });
+ });
+});
+
+describe('splitTerminalLines', () => {
+ it('does not count a trailing newline as a line', () => {
+ expect(splitTerminalLines('a\nb\n')).toEqual(['a', 'b']);
+ expect(splitTerminalLines('a\n\n')).toEqual(['a', '']);
+ expect(splitTerminalLines('')).toEqual(['']);
+ });
+});
+
+describe('terminalReplayError', () => {
+ it('keeps a parser failure out of the translated summary and retains it as optional details', () => {
+ const message = 'Line 2: event time must be a non-negative number';
+ expect(terminalReplayError({ kind: 'invalid', message })).toEqual({
+ details: message,
+ summaryKey: 'report.terminal.player.unplayable',
+ });
+ });
+
+ it('preserves the size-limit summary without parser details', () => {
+ expect(terminalReplayError({ kind: 'tooLarge' })).toEqual({
+ summaryKey: 'report.terminal.player.tooLarge',
+ });
+ });
+
+ it('uses the load failure summary when no valid recording is available', () => {
+ expect(terminalReplayError({ kind: 'failed' })).toEqual({
+ summaryKey: 'report.terminal.player.failed',
+ });
+ expect(terminalReplayError(null)).toEqual({ summaryKey: 'report.terminal.player.failed' });
+ });
+});
diff --git a/src/features/Acceptance/Report/TerminalEvidence/model.ts b/src/features/Acceptance/Report/TerminalEvidence/model.ts
new file mode 100644
index 00000000000..74117fe324b
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/model.ts
@@ -0,0 +1,332 @@
+import type { VerifyTerminalEvidenceMetadata } from '@lobechat/types';
+import { formatDuration } from '@lobechat/utils/timing';
+import {
+ readTerminalEvidenceMetadata,
+ TERMINAL_ARTIFACT_KEYS,
+ type TerminalArtifactKey,
+} from '@lobechat/utils/verify/terminalEvidence';
+
+import type { AsciicastLoadError } from './useAsciicast';
+
+interface TerminalReplayErrorPresentation {
+ details?: string;
+ summaryKey:
+ | 'report.terminal.player.failed'
+ | 'report.terminal.player.tooLarge'
+ | 'report.terminal.player.unplayable';
+}
+
+/** Parser diagnostics belong in the disclosure, never in the readable summary. */
+export const terminalReplayError = (
+ error: AsciicastLoadError | null,
+): TerminalReplayErrorPresentation => {
+ if (error?.kind === 'invalid')
+ return { details: error.message, summaryKey: 'report.terminal.player.unplayable' };
+ return {
+ summaryKey:
+ error?.kind === 'tooLarge'
+ ? 'report.terminal.player.tooLarge'
+ : 'report.terminal.player.failed',
+ };
+};
+
+/**
+ * Pure decisions behind the terminal evidence card: which files back which
+ * view, how an outcome reads, and how a search filters the output. Kept out of
+ * the components so every branch is unit-tested without rendering.
+ */
+
+/** One artifact as the bundle hands it to the page: a signed URL in place of the file id. */
+export interface TerminalArtifactLink {
+ fileUrl: string | null;
+ sha256: string;
+ size: number;
+}
+
+export type TerminalArtifactLinks = Partial<Record<TerminalArtifactKey, TerminalArtifactLink>>;
+
+/**
+ * What the card reads off an evidence row. Structural on purpose: the
+ * acceptance bundle and the report bundle type their rows differently, and the
+ * artifact links arrive untyped on the latter, so they are validated here.
+ */
+export interface TerminalEvidenceInput {
+ content?: string | null;
+ description?: string | null;
+ fileName?: string | null;
+ fileUrl?: string | null;
+ id: string;
+ metadata?: unknown;
+ terminalArtifacts?: unknown;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+/** The artifact links of a row, dropping anything malformed instead of trusting the wire. */
+export const readTerminalArtifactLinks = (value: unknown): TerminalArtifactLinks => {
+ if (!isRecord(value)) return {};
+ const links: TerminalArtifactLinks = {};
+ for (const key of TERMINAL_ARTIFACT_KEYS) {
+ const raw = value[key];
+ if (!isRecord(raw)) continue;
+ const { fileUrl, sha256, size } = raw;
+ if (typeof sha256 !== 'string' || typeof size !== 'number') continue;
+ links[key] = {
+ fileUrl: typeof fileUrl === 'string' && fileUrl.length > 0 ? fileUrl : null,
+ sha256,
+ size,
+ };
+ }
+ return links;
+};
+
+// ── Outcome ─────────────────────────────────────────────────
+
+export type TerminalOutcomeTone = 'error' | 'neutral' | 'success' | 'warning';
+
+/**
+ * Color for the outcome badge. Only a recorded exit 0 is success; anything the
+ * record does not know stays neutral rather than borrowing a tone it has not
+ * earned. An interrupted run or a failed capture says the observation is
+ * incomplete, not that the command failed — warning, not error.
+ */
+export const terminalOutcomeTone = (
+ execution: Pick<VerifyTerminalEvidenceMetadata['execution'], 'exitCode' | 'outcome'>,
+): TerminalOutcomeTone => {
+ switch (execution.outcome) {
+ case 'signaled':
+ case 'spawn_failed':
+ case 'timed_out': {
+ return 'error';
+ }
+ case 'capture_failed':
+ case 'interrupted': {
+ return 'warning';
+ }
+ default: {
+ if (execution.exitCode === null) return 'neutral';
+ return execution.exitCode === 0 ? 'success' : 'error';
+ }
+ }
+};
+
+/** i18n key + values for the outcome badge, e.g. `exit 1`, `killed by SIGTERM`. */
+export const terminalOutcomeLabel = (
+ execution: Pick<VerifyTerminalEvidenceMetadata['execution'], 'exitCode' | 'outcome' | 'signal'>,
+): { key: string; values?: Record<string, string | number> } => {
+ const signal = execution.signal ?? undefined;
+ switch (execution.outcome) {
+ case 'signaled': {
+ return signal
+ ? { key: 'report.terminal.outcome.signaled', values: { signal } }
+ : { key: 'report.terminal.outcome.signaledUnknown' };
+ }
+ case 'timed_out': {
+ return { key: 'report.terminal.outcome.timedOut' };
+ }
+ case 'interrupted': {
+ return { key: 'report.terminal.outcome.interrupted' };
+ }
+ case 'spawn_failed': {
+ return { key: 'report.terminal.outcome.spawnFailed' };
+ }
+ case 'capture_failed': {
+ return { key: 'report.terminal.outcome.captureFailed' };
+ }
+ default: {
+ return execution.exitCode === null
+ ? { key: 'report.terminal.outcome.unknown' }
+ : { key: 'report.terminal.outcome.exit', values: { code: execution.exitCode } };
+ }
+ }
+};
+
+/** `850 ms` · `1.24 s` · `12.3 s` · `3m 7s` — precise where a command's duration usually lives. */
+export const formatTerminalDuration = (ms: number): string => {
+ if (ms < 1000) return `${Math.round(ms)} ms`;
+ if (ms < 10_000) return `${(ms / 1000).toFixed(2)} s`;
+ if (ms < 60_000) return `${(ms / 1000).toFixed(1)} s`;
+ return formatDuration(ms);
+};
+
+// ── Views ───────────────────────────────────────────────────
+
+/**
+ * Where a view's text comes from.
+ * - url: an uploaded artifact file, decoded for display
+ * - cast: no plain-text artifact exists, so the text is read out of the recording
+ * - inline: the row's inline payload
+ * - empty: the record says the stream is empty, so there is nothing to fetch
+ */
+export type TerminalTextSource =
+ | { kind: 'cast'; url: string }
+ | { kind: 'empty' }
+ | { kind: 'inline'; text: string }
+ | { kind: 'url'; url: string };
+
+export type TerminalTextViewKey = 'output' | 'stderr' | 'stdout' | 'transcript';
+
+export interface TerminalTextView {
+ key: TerminalTextViewKey;
+ /** Strip escape sequences before display — terminal streams, never the transcript. */
+ plain: boolean;
+ source: TerminalTextSource;
+}
+
+export interface TerminalViewPlan {
+ /** The view the body opens on. */
+ defaultView: TerminalTextViewKey | 'replay';
+ /** The recording to replay — only when the record claims real timing AND the file resolved. */
+ replayUrl?: string;
+ terminal?: VerifyTerminalEvidenceMetadata;
+ /** Text views in display order; the transcript, when there is one, is always last. */
+ views: TerminalTextView[];
+}
+
+/**
+ * One stream's source. The capturer writes a file for every non-empty stream
+ * and none for an empty one, so a stream the record does not list — or lists
+ * with size 0 — is honestly empty. One it lists with bytes but whose URL did
+ * not resolve is unavailable: returning `undefined` makes the caller fall back
+ * to the transcript instead of claiming "no output".
+ */
+const streamSource = (
+ key: TerminalArtifactKey,
+ terminal: VerifyTerminalEvidenceMetadata,
+ links: TerminalArtifactLinks,
+): TerminalTextSource | undefined => {
+ const url = links[key]?.fileUrl;
+ if (url) return { kind: 'url', url };
+ const artifact = terminal.artifacts[key];
+ if (!artifact || artifact.size === 0) return { kind: 'empty' };
+ return undefined;
+};
+
+const transcriptSource = (input: TerminalEvidenceInput): TerminalTextSource | undefined => {
+ if (input.content) return { kind: 'inline', text: input.content };
+ if (input.fileUrl) return { kind: 'url', url: input.fileUrl };
+ return undefined;
+};
+
+/**
+ * Decide the card's body: stdout / stderr apart for a pipe capture, one merged
+ * output otherwise, the recording for replay when there is one, and the row's
+ * own transcript as the always-reachable text path. Without a readable record
+ * the transcript is the whole body.
+ */
+export const resolveTerminalViews = (input: TerminalEvidenceInput): TerminalViewPlan => {
+ const terminal = readTerminalEvidenceMetadata(input.metadata);
+ const transcript = transcriptSource(input);
+ const transcriptView: TerminalTextView[] = transcript
+ ? [{ key: 'transcript', plain: false, source: transcript }]
+ : [];
+
+ if (!terminal) return { defaultView: 'transcript', views: transcriptView };
+
+ const links = readTerminalArtifactLinks(input.terminalArtifacts);
+ const replayUrl =
+ terminal.capture.timing === 'recorded' ? (links.cast?.fileUrl ?? undefined) : undefined;
+
+ const streams: TerminalTextView[] = [];
+ if (terminal.capture.streamLayout === 'separate') {
+ const stdout = streamSource('stdout', terminal, links);
+ const stderr = streamSource('stderr', terminal, links);
+ // Both or neither: a lone stdout tab next to a stream we cannot load would
+ // read as "stderr was empty" when it was only unavailable.
+ if (stdout && stderr)
+ streams.push(
+ { key: 'stdout', plain: true, source: stdout },
+ { key: 'stderr', plain: true, source: stderr },
+ );
+ } else {
+ const output = links.output?.fileUrl
+ ? ({ kind: 'url', url: links.output.fileUrl } as const)
+ : links.cast?.fileUrl
+ ? ({ kind: 'cast', url: links.cast.fileUrl } as const)
+ : streamSource('output', terminal, links);
+ // An empty `output` with an unresolved recording is unknown, not empty.
+ const castPending = Boolean(terminal.artifacts.cast) && !links.cast?.fileUrl;
+ if (output && !(output.kind === 'empty' && castPending))
+ streams.push({ key: 'output', plain: true, source: output });
+ }
+
+ const views = [...streams, ...transcriptView];
+ // Open on the stream that has something to say: stderr when stdout is empty.
+ const firstWithText = streams.find((view) => view.source.kind !== 'empty');
+ const defaultView = firstWithText?.key ?? views[0]?.key ?? (replayUrl ? 'replay' : 'transcript');
+ return { defaultView, replayUrl, terminal, views };
+};
+
+/**
+ * The collapsed row's label: the command itself when recorded — it is the one
+ * fact a reader scans for — else the authored description, else the first
+ * line of the transcript.
+ */
+export const terminalFoldTitle = (
+ terminal: VerifyTerminalEvidenceMetadata | undefined,
+ input: Pick<TerminalEvidenceInput, 'content' | 'description' | 'fileName'>,
+): string => {
+ const command = terminal?.execution.command?.trim();
+ if (command) return command;
+ const label = input.description?.trim() || input.fileName?.trim();
+ if (label) return label;
+ const firstLine = input.content
+ ?.split('\n')
+ .map((line) => line.trim())
+ .find(Boolean);
+ return firstLine?.replace(/^\$\s+/, '') ?? '';
+};
+
+// ── Search ──────────────────────────────────────────────────
+
+export interface TerminalLineMatch {
+ /** 1-based line number in the full output. */
+ line: number;
+ /** [start, end) offsets of each match within the line. */
+ ranges: [number, number][];
+ text: string;
+}
+
+export interface TerminalSearchResult {
+ /** Matching lines, capped at `limit`; `matchCount` still counts them all. */
+ lines: TerminalLineMatch[];
+ matchCount: number;
+ matchedLineCount: number;
+}
+
+/**
+ * Case-insensitive plain-substring search, line by line. Plain text, not a
+ * regex: output is full of characters a reader types literally (`[`, `.`, `*`).
+ */
+export const searchTerminalLines = (
+ text: string,
+ query: string,
+ limit = 2000,
+): TerminalSearchResult => {
+ const needle = query.toLowerCase();
+ const result: TerminalSearchResult = { lines: [], matchCount: 0, matchedLineCount: 0 };
+ if (!needle) return result;
+
+ text.split('\n').forEach((line, index) => {
+ const haystack = line.toLowerCase();
+ const ranges: [number, number][] = [];
+ let from = haystack.indexOf(needle);
+ while (from !== -1) {
+ ranges.push([from, from + needle.length]);
+ from = haystack.indexOf(needle, from + needle.length);
+ }
+ if (ranges.length === 0) return;
+ result.matchCount += ranges.length;
+ result.matchedLineCount += 1;
+ if (result.lines.length < limit) result.lines.push({ line: index + 1, ranges, text: line });
+ });
+ return result;
+};
+
+/** Number of display lines; a trailing newline ends the last line rather than opening one. */
+export const splitTerminalLines = (text: string): string[] => {
+ const lines = text.split('\n');
+ if (lines.length > 1 && lines.at(-1) === '') lines.pop();
+ return lines;
+};
diff --git a/src/features/Acceptance/Report/TerminalEvidence/player.module.css b/src/features/Acceptance/Report/TerminalEvidence/player.module.css
new file mode 100644
index 00000000000..35fe9588c58
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/player.module.css
@@ -0,0 +1,3 @@
+.screen :global(.xterm) {
+ width: max-content;
+ }
diff --git a/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts b/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts
new file mode 100644
index 00000000000..6a0736839a4
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/playerStyle.ts
@@ -0,0 +1,72 @@
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import relational from './player.module.css';
+
+const definitions = stylex.create({
+ screen: {
+ overflow: 'auto',
+ maxHeight: '480px',
+ padding: '8px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorBgContainer,
+ },
+ clock: {
+ flex: 'none',
+ minWidth: '88px',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ color: cssVar.colorTextSecondary,
+ },
+ rate: {
+ cursor: 'pointer',
+ flex: 'none',
+ minWidth: '36px',
+ paddingBlock: '2px',
+ paddingInline: '6px',
+ borderWidth: '0',
+ borderStyle: 'none',
+ borderRadius: cssVar.borderRadiusSM,
+ fontSize: '12px',
+ color: cssVar.colorTextSecondary,
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ },
+ rateActive: {
+ color: cssVar.colorText,
+ backgroundColor: cssVar.colorFillSecondary,
+ },
+ marker: {
+ cursor: 'pointer',
+ display: 'inline-flex',
+ gap: '6px',
+ alignItems: 'center',
+ maxWidth: '100%',
+ paddingBlock: '2px',
+ paddingInline: '8px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusXS,
+ fontSize: '12px',
+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ },
+ markerTime: {
+ fontFamily: cssVar.fontFamilyCode,
+ color: cssVar.colorTextTertiary,
+ },
+});
+
+export const styles = {
+ screen: cx(stylex.props(definitions.screen).className ?? '', relational.screen),
+ clock: stylex.props(definitions.clock).className ?? '',
+ rate: stylex.props(definitions.rate).className ?? '',
+ rateActive: stylex.props(definitions.rateActive).className ?? '',
+ marker: stylex.props(definitions.marker).className ?? '',
+ markerTime: stylex.props(definitions.markerTime).className ?? '',
+};
diff --git a/src/features/Acceptance/Report/TerminalEvidence/relational.module.css b/src/features/Acceptance/Report/TerminalEvidence/relational.module.css
new file mode 100644
index 00000000000..82f13db7a3d
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/relational.module.css
@@ -0,0 +1,18 @@
+.foldHeader:hover [data-fold-title] {
+ color: var(--lobe-color-text);
+ }
+
+.facts dt {
+ color: var(--lobe-color-text-tertiary);
+ }
+
+.facts dd {
+ min-width: 0;
+ margin: 0;
+ color: var(--lobe-color-text-secondary);
+ overflow-wrap: anywhere;
+ }
+
+@media (width <= 767px) { .facts dd + dt {
+ margin-block-start: 6px;
+ } }
diff --git a/src/features/Acceptance/Report/TerminalEvidence/styles.ts b/src/features/Acceptance/Report/TerminalEvidence/styles.ts
new file mode 100644
index 00000000000..80bf0c4cef5
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/styles.ts
@@ -0,0 +1,263 @@
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+
+import relational from './relational.module.css';
+
+const definitions = stylex.create({
+ foldHeader: {
+ cursor: 'pointer',
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'center',
+ width: '100%',
+ minWidth: '0',
+ paddingBlock: '4px',
+ paddingInline: '0',
+ borderWidth: '0',
+ borderStyle: 'none',
+ textAlign: 'start',
+ backgroundColor: 'transparent',
+ borderRadius: { ':focus-visible': cssVar.borderRadiusSM },
+ outlineWidth: { ':focus-visible': '2px' },
+ outlineStyle: { ':focus-visible': 'solid' },
+ outlineColor: { ':focus-visible': cssVar.colorPrimaryBorder },
+ minHeight: { '@media (width <= 767px), (pointer: coarse)': '44px' },
+ },
+ foldChevron: {
+ flex: 'none',
+ color: cssVar.colorTextTertiary,
+ transitionProperty: {
+ 'default': 'transform',
+ '@media (prefers-reduced-motion: reduce)': 'none',
+ },
+ transitionDuration: '160ms',
+ transitionTimingFunction: 'ease',
+ },
+ foldChevronOpen: {
+ transform: 'rotate(90deg)',
+ },
+ foldIcon: {
+ display: 'flex',
+ flex: 'none',
+ color: cssVar.colorTextTertiary,
+ },
+ foldTitle: {
+ overflow: 'hidden',
+ flex: '1',
+ minWidth: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ lineHeight: 1.5,
+ color: cssVar.colorTextSecondary,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ transitionProperty: 'color',
+ transitionDuration: '120ms',
+ transitionTimingFunction: 'ease',
+ },
+ foldMeta: {
+ display: { 'default': 'flex', '@media (width <= 767px)': 'none' },
+ flex: 'none',
+ gap: '6px',
+ alignItems: 'center',
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ },
+ foldMetaMobile: {
+ display: { 'default': 'none', '@media (width <= 767px)': 'flex' },
+ flexWrap: 'wrap',
+ gap: '6px',
+ alignItems: 'center',
+ paddingInlineStart: '22px',
+ },
+ body: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ minWidth: '0',
+ paddingBlockStart: '4px',
+ paddingBlockEnd: '8px',
+ paddingInlineStart: { 'default': '22px', '@media (width <= 767px)': '0' },
+ paddingInlineEnd: '0',
+ },
+ description: {
+ paddingInlineStart: '22px',
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ },
+ command: {
+ display: 'flex',
+ gap: '8px',
+ alignItems: 'flex-start',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+ commandText: {
+ flex: '1',
+ minWidth: '0',
+ margin: '0',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ lineHeight: 1.6,
+ color: cssVar.colorText,
+ overflowWrap: 'anywhere',
+ whiteSpace: 'pre-wrap',
+ },
+ commandPrompt: {
+ userSelect: 'none',
+ color: cssVar.colorTextTertiary,
+ },
+ facts: {
+ display: 'grid',
+ gridTemplateColumns: {
+ 'default': 'max-content minmax(0, 1fr)',
+ '@media (width <= 767px)': 'minmax(0, 1fr)',
+ },
+ rowGap: { 'default': '6px', '@media (width <= 767px)': '2px' },
+ columnGap: { 'default': '16px', '@media (width <= 767px)': '2px' },
+ margin: '0',
+ fontSize: '12px',
+ lineHeight: 1.6,
+ },
+ mono: {
+ fontFamily: cssVar.fontFamilyCode,
+ },
+ inlineList: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ rowGap: '4px',
+ columnGap: '12px',
+ },
+ linkButton: {
+ cursor: 'pointer',
+ padding: '0',
+ borderWidth: '0',
+ borderStyle: 'none',
+ fontSize: '12px',
+ color: { 'default': cssVar.colorTextSecondary, ':hover': cssVar.colorText },
+ textDecorationLine: 'underline',
+ textDecorationColor: cssVar.colorBorder,
+ textUnderlineOffset: '2px',
+ backgroundColor: 'transparent',
+ },
+ toolbar: {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: '8px',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ },
+ outputBox: {
+ overflow: 'auto',
+ maxHeight: '360px',
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ backgroundColor: cssVar.colorFillQuaternary,
+ },
+ outputGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'max-content max-content',
+ minWidth: '100%',
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: '12px',
+ lineHeight: 1.6,
+ },
+ gutter: {
+ userSelect: 'none',
+ position: 'sticky',
+ zIndex: 1,
+ insetInlineStart: '0',
+ margin: '0',
+ paddingBlock: '8px',
+ paddingInlineStart: '12px',
+ paddingInlineEnd: '10px',
+ borderInlineEndWidth: '1px',
+ borderInlineEndStyle: 'solid',
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ fontStyle: 'inherit',
+ fontWeight: 'inherit',
+ lineHeight: 'inherit',
+ fontVariant: 'inherit',
+ fontStretch: 'inherit',
+ color: cssVar.colorTextQuaternary,
+ textAlign: 'end',
+ backgroundColor: cssVar.colorBgContainer,
+ },
+ lines: {
+ margin: '0',
+ paddingBlock: '8px',
+ paddingInline: '12px',
+ fontFamily: 'inherit',
+ fontSize: 'inherit',
+ fontStyle: 'inherit',
+ fontWeight: 'inherit',
+ lineHeight: 'inherit',
+ fontVariant: 'inherit',
+ fontStretch: 'inherit',
+ color: cssVar.colorText,
+ whiteSpace: 'pre',
+ },
+ match: {
+ borderRadius: '2px',
+ color: 'inherit',
+ backgroundColor: cssVar.colorWarningBg,
+ boxShadow: `0 0 0 1px ${cssVar.colorWarningBorder}`,
+ },
+ outputState: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '8px',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: '96px',
+ padding: '16px',
+ borderWidth: '1px',
+ borderStyle: 'dashed',
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ textAlign: 'center',
+ },
+ hint: {
+ fontSize: '12px',
+ color: cssVar.colorTextTertiary,
+ },
+});
+
+export const styles = {
+ foldHeader: cx(stylex.props(definitions.foldHeader).className ?? '', relational.foldHeader),
+ foldChevron: stylex.props(definitions.foldChevron).className ?? '',
+ foldChevronOpen: stylex.props(definitions.foldChevronOpen).className ?? '',
+ foldIcon: stylex.props(definitions.foldIcon).className ?? '',
+ foldTitle: stylex.props(definitions.foldTitle).className ?? '',
+ foldMeta: stylex.props(definitions.foldMeta).className ?? '',
+ foldMetaMobile: stylex.props(definitions.foldMetaMobile).className ?? '',
+ body: stylex.props(definitions.body).className ?? '',
+ description: stylex.props(definitions.description).className ?? '',
+ command: stylex.props(definitions.command).className ?? '',
+ commandText: stylex.props(definitions.commandText).className ?? '',
+ commandPrompt: stylex.props(definitions.commandPrompt).className ?? '',
+ facts: cx(stylex.props(definitions.facts).className ?? '', relational.facts),
+ mono: stylex.props(definitions.mono).className ?? '',
+ inlineList: stylex.props(definitions.inlineList).className ?? '',
+ linkButton: stylex.props(definitions.linkButton).className ?? '',
+ toolbar: stylex.props(definitions.toolbar).className ?? '',
+ outputBox: stylex.props(definitions.outputBox).className ?? '',
+ outputGrid: stylex.props(definitions.outputGrid).className ?? '',
+ gutter: stylex.props(definitions.gutter).className ?? '',
+ lines: stylex.props(definitions.lines).className ?? '',
+ match: stylex.props(definitions.match).className ?? '',
+ outputState: stylex.props(definitions.outputState).className ?? '',
+ hint: stylex.props(definitions.hint).className ?? '',
+};
diff --git a/src/features/Acceptance/Report/TerminalEvidence/timeline.test.ts b/src/features/Acceptance/Report/TerminalEvidence/timeline.test.ts
new file mode 100644
index 00000000000..398fe0346fb
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/timeline.test.ts
@@ -0,0 +1,131 @@
+import type { AsciicastEvent } from '@lobechat/utils/verify/asciicast';
+import { createTerminalSanitizer } from '@lobechat/utils/verify/terminalEvidence';
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildTimeline,
+ castPlainText,
+ clampTerminalSize,
+ collectOps,
+ eventCountAt,
+ formatPlaybackClock,
+} from './timeline';
+
+const ev = (t: number, code: AsciicastEvent['code'], data: string): AsciicastEvent => ({
+ code,
+ data,
+ t,
+});
+
+describe('buildTimeline', () => {
+ it('compresses idle gaps longer than the cap and keeps shorter ones', () => {
+ const timeline = buildTimeline({
+ cols: 80,
+ events: [ev(0.5, 'o', 'a'), ev(1, 'o', 'b'), ev(31, 'o', 'c'), ev(32.5, 'o', 'd')],
+ rows: 24,
+ });
+ expect(timeline.events.map((event) => event.at)).toEqual([0.5, 1, 3, 4.5]);
+ expect(timeline.duration).toBe(4.5);
+ });
+
+ it('extracts markers with their playback time, labelling unnamed ones', () => {
+ const timeline = buildTimeline({
+ cols: 80,
+ events: [ev(0, 'o', 'x'), ev(10, 'm', ' build done '), ev(11, 'm', '')],
+ rows: 24,
+ });
+ expect(timeline.markers).toEqual([
+ { at: 2, label: 'build done' },
+ { at: 3, label: '#2' },
+ ]);
+ });
+
+ it('clamps an oversized starting terminal', () => {
+ const timeline = buildTimeline({ cols: 1000, events: [], rows: 500 });
+ expect([timeline.cols, timeline.rows]).toEqual([500, 200]);
+ expect(timeline.duration).toBe(0);
+ });
+});
+
+describe('eventCountAt', () => {
+ const events = [{ at: 0 }, { at: 1 }, { at: 1 }, { at: 2.5 }];
+
+ it('counts every event at or before the playhead', () => {
+ expect(eventCountAt(events, -1)).toBe(0);
+ expect(eventCountAt(events, 0)).toBe(1);
+ expect(eventCountAt(events, 1)).toBe(3);
+ expect(eventCountAt(events, 2.4)).toBe(3);
+ expect(eventCountAt(events, 99)).toBe(4);
+ expect(eventCountAt([], 5)).toBe(0);
+ });
+});
+
+describe('collectOps', () => {
+ const identity = (chunk: string) => chunk;
+
+ it('merges consecutive output and orders resizes between writes', () => {
+ const events = [
+ ev(0, 'o', 'a'),
+ ev(0.1, 'o', 'b'),
+ ev(0.2, 'r', '100x30'),
+ ev(0.3, 'i', 'typed'),
+ ev(0.4, 'm', 'marker'),
+ ev(0.5, 'o', 'c'),
+ ev(0.6, 'x', '0'),
+ ];
+ expect(collectOps(events, 0, events.length, identity)).toEqual([
+ { data: 'ab', type: 'write' },
+ { cols: 100, rows: 30, type: 'resize' },
+ { data: 'c', type: 'write' },
+ ]);
+ expect(collectOps(events, 5, 7, identity)).toEqual([{ data: 'c', type: 'write' }]);
+ });
+
+ it('strips OSC strings split across events with one sanitizer per pass', () => {
+ const events = [
+ ev(0, 'o', 'before \u001B]8;;https://evil'),
+ ev(0.1, 'o', '.example\u0007link\u001B]8;;\u0007 after'),
+ ev(0.2, 'o', ' \u001B]52;c;aGVsbG8=\u0007done'),
+ ];
+ const ops = collectOps(events, 0, events.length, createTerminalSanitizer());
+ expect(ops).toEqual([{ data: 'before link after done', type: 'write' }]);
+ });
+
+ it('clamps hostile resizes and ignores malformed ones', () => {
+ const events = [ev(0, 'r', '5000x5000'), ev(0, 'r', 'big')];
+ expect(collectOps(events, 0, 2, identity)).toEqual([{ cols: 500, rows: 200, type: 'resize' }]);
+ });
+});
+
+describe('clampTerminalSize', () => {
+ it('keeps sizes within 1..max', () => {
+ expect(clampTerminalSize(0, -3)).toEqual({ cols: 1, rows: 1 });
+ expect(clampTerminalSize(120.7, 40.2)).toEqual({ cols: 120, rows: 40 });
+ });
+});
+
+describe('castPlainText', () => {
+ it('joins output events and strips escape sequences', () => {
+ expect(
+ castPlainText([
+ ev(0, 'o', '\u001B[32mok\u001B[0m\r\n'),
+ ev(0.1, 'i', 'ignored'),
+ ev(0.2, 'o', '50%\r100%\r\n'),
+ ]),
+ ).toBe('ok\n100%\n');
+ });
+});
+
+describe('formatPlaybackClock', () => {
+ it('formats minutes and hours', () => {
+ expect(formatPlaybackClock(0)).toBe('0:00');
+ expect(formatPlaybackClock(65.9)).toBe('1:05');
+ expect(formatPlaybackClock(3725)).toBe('1:02:05');
+ });
+
+ it('shows tenths for short recordings so they never read 0:00 / 0:00', () => {
+ expect(formatPlaybackClock(0.8005, true)).toBe('0:00.8');
+ expect(formatPlaybackClock(9.96, true)).toBe('0:09.9');
+ expect(formatPlaybackClock(0, true)).toBe('0:00.0');
+ });
+});
diff --git a/src/features/Acceptance/Report/TerminalEvidence/timeline.ts b/src/features/Acceptance/Report/TerminalEvidence/timeline.ts
new file mode 100644
index 00000000000..8add16fda0a
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/timeline.ts
@@ -0,0 +1,154 @@
+import type { Asciicast, AsciicastEvent } from '@lobechat/utils/verify/asciicast';
+import { parseResize } from '@lobechat/utils/verify/asciicast';
+import { terminalTextFromStream } from '@lobechat/utils/verify/terminalEvidence';
+
+/**
+ * Playback math for the read-only terminal player, kept pure so seeking,
+ * idle compression and markers are tested without a terminal.
+ *
+ * The player never streams events one by one: at any moment it knows the
+ * playhead, asks {@link eventCountAt} how many events belong on screen, and
+ * applies the ones it has not applied yet with {@link collectOps}. Seeking
+ * backwards resets the terminal and replays from the start — a terminal screen
+ * is the sum of everything written to it, so there is no cheaper way back.
+ */
+
+export const PLAYBACK_RATES = [0.5, 1, 2, 4] as const;
+
+/**
+ * Idle stretches longer than this play as this long. A recording that waited
+ * a minute on a network call is still honest about the order of events; the
+ * reader just doesn't sit through the wait. The real duration stays on the card.
+ */
+export const MAX_IDLE_SECONDS = 2;
+
+/** Terminal size bounds while replaying — a hostile resize must not allocate a huge buffer. */
+const MAX_COLS = 500;
+const MAX_ROWS = 200;
+
+export interface TimelineEvent extends AsciicastEvent {
+ /** Playback time after idle compression, in seconds. */
+ at: number;
+}
+
+export interface TimelineMarker {
+ at: number;
+ label: string;
+}
+
+export interface PlaybackTimeline {
+ cols: number;
+ duration: number;
+ events: TimelineEvent[];
+ markers: TimelineMarker[];
+ rows: number;
+}
+
+export const clampTerminalSize = (cols: number, rows: number) => ({
+ cols: Math.min(Math.max(1, Math.floor(cols)), MAX_COLS),
+ rows: Math.min(Math.max(1, Math.floor(rows)), MAX_ROWS),
+});
+
+/** Compress idle gaps and pull out the `m` markers a reader can jump to. */
+export const buildTimeline = (
+ cast: Pick<Asciicast, 'cols' | 'events' | 'rows'>,
+ maxIdle = MAX_IDLE_SECONDS,
+): PlaybackTimeline => {
+ let previous = 0;
+ let at = 0;
+ const events = cast.events.map((event) => {
+ at += Math.min(Math.max(0, event.t - previous), maxIdle);
+ previous = event.t;
+ return { ...event, at };
+ });
+ const markers = events
+ .filter((event) => event.code === 'm')
+ .map((event, index) => ({ at: event.at, label: event.data.trim() || `#${index + 1}` }));
+ return {
+ ...clampTerminalSize(cast.cols, cast.rows),
+ duration: events.at(-1)?.at ?? 0,
+ events,
+ markers,
+ };
+};
+
+/** How many events are on screen at playback time `t` (all with `at <= t`). Binary search. */
+export const eventCountAt = (events: Pick<TimelineEvent, 'at'>[], t: number): number => {
+ let low = 0;
+ let high = events.length;
+ while (low < high) {
+ const mid = (low + high) >> 1;
+ if (events[mid]!.at <= t) low = mid + 1;
+ else high = mid;
+ }
+ return low;
+};
+
+export type TerminalOp =
+ { cols: number; rows: number; type: 'resize' } | { data: string; type: 'write' };
+
+/**
+ * The terminal operations for events `[from, to)`: output writes, merged so
+ * xterm parses one string instead of thousands, and resizes in order between
+ * them. Every output chunk goes through `sanitize` — one sanitizer per pass,
+ * so an escape sequence split across events is still stripped whole. Input
+ * (`i`), markers and the exit event never touch the screen.
+ */
+export const collectOps = (
+ events: AsciicastEvent[],
+ from: number,
+ to: number,
+ sanitize: (chunk: string) => string,
+): TerminalOp[] => {
+ const ops: TerminalOp[] = [];
+ let pending = '';
+ const flush = () => {
+ if (pending) ops.push({ data: pending, type: 'write' });
+ pending = '';
+ };
+ for (let index = from; index < to; index++) {
+ const event = events[index]!;
+ if (event.code === 'o') pending += sanitize(event.data);
+ else if (event.code === 'r') {
+ const size = parseResize(event.data);
+ if (!size) continue;
+ flush();
+ ops.push({ ...clampTerminalSize(size.cols, size.rows), type: 'resize' });
+ }
+ }
+ flush();
+ return ops;
+};
+
+/** `m:ss` under an hour, `h:mm:ss` beyond. */
+export const formatPlaybackClock = (seconds: number, precise = false): string => {
+ // A recording shorter than a few seconds would read 0:00 / 0:00 at whole
+ // seconds — as if nothing were there to play. `precise` adds tenths.
+ if (precise) {
+ const tenths = Math.max(0, Math.floor(seconds * 10));
+ const m = Math.floor(tenths / 600);
+ const s = ((tenths % 600) / 10).toFixed(1).padStart(4, '0');
+ return `${m}:${s}`;
+ }
+ const total = Math.max(0, Math.floor(seconds));
+ const h = Math.floor(total / 3600);
+ const m = Math.floor((total % 3600) / 60);
+ const s = String(total % 60).padStart(2, '0');
+ return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}`;
+};
+
+/** Tenths are worth showing while whole seconds would hide the playback. */
+export const PRECISE_CLOCK_MAX_SECONDS = 10;
+
+/**
+ * The recording's output as plain text — the static view of a pty capture
+ * that has no separate output file. Approximates the final screen (carriage
+ * return overwrites keep the last write), it does not replace the replay.
+ */
+export const castPlainText = (events: AsciicastEvent[]): string =>
+ terminalTextFromStream(
+ events
+ .filter((event) => event.code === 'o')
+ .map((event) => event.data)
+ .join(''),
+ );
diff --git a/src/features/Acceptance/Report/TerminalEvidence/useAsciicast.ts b/src/features/Acceptance/Report/TerminalEvidence/useAsciicast.ts
new file mode 100644
index 00000000000..a8bb6e7ce73
--- /dev/null
+++ b/src/features/Acceptance/Report/TerminalEvidence/useAsciicast.ts
@@ -0,0 +1,86 @@
+import { readBlobWithLimit } from '@lobechat/utils/readBlobWithLimit';
+import {
+ type Asciicast,
+ ASCIICAST_LIMITS,
+ AsciicastError,
+ parseAsciicast,
+} from '@lobechat/utils/verify/asciicast';
+import { useEffect, useState } from 'react';
+
+export type AsciicastLoadError =
+ { kind: 'failed' } | { kind: 'invalid'; message: string } | { kind: 'tooLarge' };
+
+interface AsciicastState {
+ cast: Asciicast | null;
+ error: AsciicastLoadError | null;
+ loading: boolean;
+ url: string | null;
+}
+
+type LoadResult = { cast: Asciicast } | { error: AsciicastLoadError };
+
+/**
+ * The replay and the "output from recording" view read the same file; one
+ * in-flight / settled load per URL keeps switching between them from
+ * downloading it twice. Small on purpose — a parsed recording can be large.
+ */
+const cache = new Map<string, Promise<LoadResult>>();
+const CACHE_SIZE = 2;
+
+const load = (url: string): Promise<LoadResult> => {
+ const cached = cache.get(url);
+ if (cached) return cached;
+
+ const promise = (async (): Promise<LoadResult> => {
+ try {
+ const response = await fetch(url);
+ if (!response.ok) return { error: { kind: 'failed' } };
+ // Cancels the download past the limit, whether or not Content-Length says so.
+ const blob = await readBlobWithLimit(response, ASCIICAST_LIMITS.maxBytes);
+ const text = new TextDecoder('utf-8').decode(await blob.arrayBuffer());
+ return { cast: parseAsciicast(text) };
+ } catch (error) {
+ if (error instanceof RangeError) return { error: { kind: 'tooLarge' } };
+ if (error instanceof AsciicastError)
+ return { error: { kind: 'invalid', message: error.message } };
+ return { error: { kind: 'failed' } };
+ }
+ })();
+
+ cache.set(url, promise);
+ // A failed load is not cached: the next attempt (a retry, a reopened card) refetches.
+ void promise.then((result) => {
+ if ('error' in result && result.error.kind === 'failed') cache.delete(url);
+ });
+ while (cache.size > CACHE_SIZE) cache.delete(cache.keys().next().value!);
+ return promise;
+};
+
+/** Fetch, bound and validate an asciicast recording. `null` disables the request. */
+export const useAsciicast = (url: string | null): AsciicastState => {
+ const [state, setState] = useState<AsciicastState>({
+ cast: null,
+ error: null,
+ loading: !!url,
+ url,
+ });
+
+ useEffect(() => {
+ let active = true;
+ setState({ cast: null, error: null, loading: !!url, url });
+ if (!url) return;
+ void load(url).then((result) => {
+ if (!active) return;
+ setState(
+ 'cast' in result
+ ? { cast: result.cast, error: null, loading: false, url }
+ : { cast: null, error: result.error, loading: false, url },
+ );
+ });
+ return () => {
+ active = false;
+ };
+ }, [url]);
+
+ return state.url === url ? state : { cast: null, error: null, loading: !!url, url };
+};
diff --git a/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx b/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx
index 353377e394b..ee641f6b360 100644
--- a/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx
+++ b/src/features/Acceptance/Viewer/Checks/CheckHistory.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import AudioPlayer from '@/features/AudioPlayer';
import { useIsHydrated } from '@/hooks/useIsHydrated';
+import { TerminalEvidenceCard } from '../../Report/TerminalEvidence';
import { AnnotatedImage } from '../Evidence/Annotation';
import { AttachmentThumbs } from '../Evidence/attachments';
import { IMAGE_EVIDENCE, imageRatio } from '../Evidence/evidence';
@@ -267,6 +268,12 @@ export const IterationTimeline = memo<{
url={item.fileUrl}
/>
</div>
+ ) : item.type === 'terminal' ? (
+ // An earlier round's execution keeps its command card —
+ // folded to one line, the same record the live row shows.
+ <div key={item.id} style={{ width: '100%' }}>
+ <TerminalEvidenceCard evidence={item} />
+ </div>
) : item.content ? (
<div
className={evidenceStyles.evidenceText}
diff --git a/src/features/Acceptance/Viewer/Evidence/AcceptanceResources.tsx b/src/features/Acceptance/Viewer/Evidence/AcceptanceResources.tsx
index b9571cb6ed4..ad65f31a1be 100644
--- a/src/features/Acceptance/Viewer/Evidence/AcceptanceResources.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/AcceptanceResources.tsx
@@ -11,7 +11,7 @@ import {
useResponsive,
} from '@lobehub/ui';
import dayjs from 'dayjs';
-import { FileText, Film, Paperclip } from 'lucide-react';
+import { FileText, Film, Paperclip, SquareTerminal } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useIsHydrated } from '@/hooks/useIsHydrated';
@@ -166,9 +166,15 @@ const AcceptanceResources = () => {
) : (
<div className={styles.nonVisual}>
<Icon
- icon={evidence.type === 'video' ? Film : FileText}
size={16}
style={{ color: cssVar.colorTextTertiary }}
+ icon={
+ evidence.type === 'video'
+ ? Film
+ : evidence.type === 'terminal'
+ ? SquareTerminal
+ : FileText
+ }
/>
<Text ellipsis fontSize={13}>
{name}
diff --git a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx
index b61e5834054..40649d421db 100644
--- a/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx
+++ b/src/features/Acceptance/Viewer/Evidence/EvidenceList.tsx
@@ -18,6 +18,7 @@ import {
markdownTextEvidenceTypes,
rendersAsMarkdown,
} from '../../Report/MarkdownEvidence';
+import { TerminalEvidenceCard } from '../../Report/TerminalEvidence';
import type { AcceptanceEvidence } from '../Checks/types';
import { AnnotatedImage } from '../Evidence/Annotation';
import { ScreenshotTiles } from '../Evidence/ScreenshotTiles';
@@ -29,6 +30,7 @@ import { VideoEvidenceDiscussion } from './Video/VideoEvidenceDiscussion';
/** Flat media for a comparison side — the card frames it, so no own border/radius. */
const comparisonContent = (item: AcceptanceEvidence, action?: ReactNode, video?: ReactNode) => {
+ if (item.type === 'terminal') return <TerminalEvidenceCard defaultExpanded evidence={item} />;
if (item.type === 'video') return video;
if (item.type === 'audio')
return (
@@ -102,7 +104,8 @@ export const EvidenceList = memo<{
// artifact, matching the ingest CLI's warning semantics.
const groups = new Map<string, Partial<Record<'after' | 'before', AcceptanceEvidence>>>();
for (const item of sorted) {
- if (!isVisual(item)) continue;
+ // Two runs of one command pair like two captures of one view.
+ if (!isVisual(item) && item.type !== 'terminal') continue;
const comparison = readEvidenceComparison(item.metadata);
if (!comparison) continue;
const group = groups.get(comparison.id) ?? {};
@@ -320,6 +323,9 @@ export const EvidenceList = memo<{
</Flexbox>
);
}
+ // A command execution: the record first, then its output — whether the
+ // row carries its transcript inline or as a file.
+ if (item.type === 'terminal') return <TerminalEvidenceCard evidence={item} key={item.id} />;
if (item.content && markdownTextEvidenceTypes.has(item.type))
return (
// An authored alt/description becomes the fold row's title itself —
diff --git a/src/services/verify.ts b/src/services/verify.ts
index ab69c01b3b0..d5ca82c17d7 100644
--- a/src/services/verify.ts
+++ b/src/services/verify.ts
@@ -132,6 +132,13 @@ export interface VerifyStateResponse {
export type VerifyEvidenceWithUrl = VerifyEvidence & {
fileName: string | null;
fileUrl: string | null;
+ /** `terminal` evidence only: signed URLs for the stdout / stderr / output / recording files. */
+ terminalArtifacts?: Partial<
+ Record<
+ 'cast' | 'output' | 'stderr' | 'stdout',
+ { fileUrl: string | null; sha256: string; size: number }
+ >
+ >;
};
/** One check result plus the evidence artifacts attached to it. */