π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(verify): reuse one report per case on re-ingest instead of a new run (#16702)
Arvin Xufc6ebd4efb87
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.mdindex c3086d7208f..90b1a05d09b 100644--- a/.agents/skills/agent-testing/SKILL.md+++ b/.agents/skills/agent-testing/SKILL.md@@ -516,6 +516,25 @@ inline screenshot/text evidence). On production that resolves to`https://app.lobehub.com/verify/<verifyRunId>`. **Include that full productionlink in the final chat reply** alongside the local report dir.+### Re-verifying the same case updates the report in place (don't spawn a new one)++When you iterate on one change β fix β re-verify β fix again β **keep reusing the+same report dir (`$DIR`)**. `ingest-report` records the session it created in a+`.verify-run.json` sidecar inside `$DIR`, so re-ingesting the **same dir**+**updates that session in place** (same `/verify/<id>` URL) instead of creating a+new list entry every round. The update is a full replace: cases are overwritten+by their stable `id`, each case's evidence is re-attached (old screenshots+cleared, not stacked), and cases the new report dropped are pruned.++So the rule for an iterative case: `report-init.sh` **once**, then re-run+`ingest-report "$DIR"` after each fix β the report accretes value at one stable+URL rather than flooding the list with near-duplicate runs. Only scaffold a fresh+`$DIR` when you start verifying a genuinely different case.++Escape hatches: `--new` forces a fresh session even if the dir already made one;+`--run <verifyRunId>` targets an existing session explicitly (e.g. to update from+a different machine/checkout where the sidecar is absent).+Notes:- `result.json` cases use `{ id?, name, result, observation?, evidence? }`;diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.tsindex dfc5c22da2f..9f8067bf794 100644--- a/apps/cli/src/commands/verify.ts+++ b/apps/cli/src/commands/verify.ts@@ -66,6 +66,34 @@ function evidencePaths(evidence: unknown): string[] {.filter((p): p is string => typeof p === 'string' && p.length > 0);}+/**+ * The report dir remembers which verification session it created, so+ * re-verifying the same case updates one evolving `/verify/<id>` in place+ * instead of spawning a fresh list entry every round. Kept in a sidecar (not+ * result.json, which the harness regenerates each round) so it survives a+ * rewrite of the report body.+ */+const RUN_SIDECAR = '.verify-run.json';++function readSidecarRunId(dir: string): string | undefined {+ const p = path.join(dir, RUN_SIDECAR);+ if (!existsSync(p)) return undefined;+ try {+ const parsed = JSON.parse(readFileSync(p, 'utf8'));+ return typeof parsed?.verifyRunId === 'string' ? parsed.verifyRunId : undefined;+ } catch {+ return undefined;+ }+}++function writeSidecarRunId(dir: string, verifyRunId: string): void {+ try {+ writeFileSync(path.join(dir, RUN_SIDECAR), `${JSON.stringify({ verifyRunId }, null, 2)}\n`);+ } catch {+ // Best-effort: a read-only dir just means the next run creates a new session.+ }+}+// ββ Command Registration βββββββββββββββββββββββββββββββββββexport function registerVerifyCommand(program: Command) {@@ -922,6 +950,8 @@ export function registerVerifyCommand(program: Command) {.option('--operation <id>', 'Link the session to an existing Agent Run').option('--title <title>', 'Override the session title').option('--goal <goal>', 'The goal/task being verified')+ .option('--run <verifyRunId>', 'Update an existing session in place instead of creating one')+ .option('--new', 'Force a fresh session even if this report dir already created one').option('--open', 'Print the in-app URL to open the report').option('--json [fields]', 'Output JSON').action(@@ -930,8 +960,10 @@ export function registerVerifyCommand(program: Command) {options: {goal?: string;json?: boolean | string;+ new?: boolean;open?: boolean;operation?: string;+ run?: string;source?: string;title?: string;},@@ -976,21 +1008,61 @@ export function registerVerifyCommand(program: Command) {const scenario = result.scenario === 'coding' ? 'coding' : ('coding' as const);const client = await getTrpcClient();+ const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);+ const title = options.title ?? result.title;++ // Resolve the target session. Reuse the one this report dir already+ // created (recorded in the sidecar) so re-verifying the same case+ // updates one evolving report in place rather than adding a list entry+ // per round. `--run` targets a session explicitly; `--new` forces a+ // fresh one; `--operation` links a fresh session to an Agent Run.+ const rememberedRunId = options.new ? undefined : (options.run ?? readSidecarRunId(dir));+ let runId!: string;+ let reused = false;+ if (rememberedRunId) {+ const existing = await client.verify.getRun.query({ verifyRunId: rememberedRunId });+ if (existing) {+ reused = true;+ runId = existing.id;+ // 1a. Refresh the scope header / title / goal in place.+ await client.verify.updateRun.mutate({+ value: { context, goal, scenario, title },+ verifyRunId: runId,+ });+ } else if (options.run) {+ // An explicit --run that doesn't resolve is a user error, not a+ // silent fall-through to a stray new session.+ log.error(`Verification session not found: ${options.run}`);+ process.exit(1);+ } else {+ // The remembered session was deleted β drop the stale pointer and+ // create a fresh one below.+ log.warn(`Recorded session ${rememberedRunId} no longer exists β creating a new one`);+ }+ }- // 1. Create the verification session.- const run = await client.verify.createRun.mutate({- context,- goal: options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined),- operationId: options.operation,- scenario,- source: options.source as any,- title: options.title ?? result.title,- });+ // 1b. Create the verification session when not updating one in place.+ if (!reused) {+ const run = await client.verify.createRun.mutate({+ context,+ goal,+ operationId: options.operation,+ scenario,+ source: options.source as any,+ title,+ });+ runId = run.id;+ }- // 2. Ingest each case as a check result + its evidence.+ // 2. Ingest each case as a check result + its evidence. `checkItemId` is+ // the stable upsert key, so a re-ingest overwrites the matching case+ // rather than duplicating it. Track the ids we touch to prune dropped+ // cases afterwards, keeping a re-run a full replace.+ const seenCheckItemIds = new Set<string>();let uploaded = 0;for (const [index, c] of cases.entries()) {const checkItemId = String(c.id ?? c.checkItemId ?? `case-${index + 1}`);+ seenCheckItemIds.add(checkItemId);const verdict = toVerdict(c.result ?? c.status ?? c.verdict);const observation = c.keyObservation ?? c.observation ?? c.note;const checkResult = await client.verify.ingestResult.mutate({@@ -1000,13 +1072,28 @@ export function registerVerifyCommand(program: Command) {required: c.required ?? true,// The case's key observation is recorded as Toulmin evidence; a real// remediation hint (if the report provides one) goes to `suggestion`.- suggestion: typeof c.suggestion === 'string' ? c.suggestion : undefined,- toulmin: typeof observation === 'string' ? { evidence: observation } : undefined,+ // Absent β explicit `null`, not `undefined`: ingest-report is a full+ // replace, so a case that dropped its observation/suggestion this+ // round must CLEAR the prior value on a reused run (undefined would be+ // skipped by the conflict UPDATE and leave stale text on the row).+ suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,+ toulmin: typeof observation === 'string' ? { evidence: observation } : null,verdict,verifierType: 'agent',- verifyRunId: run.id,+ verifyRunId: runId,});+ // On an in-place update, clear the case's prior evidence before+ // re-attaching so screenshots are replaced, not stacked round on round.+ if (reused) {+ const prior = await client.verify.listEvidence.query({+ checkResultId: checkResult.id,+ });+ for (const ev of prior) {+ await client.verify.deleteEvidence.mutate({ id: ev.id });+ }+ }+for (const rel of evidencePaths(c.evidence)) {const abs = path.isAbsolute(rel) ? rel : path.join(dir, rel);if (!existsSync(abs)) {@@ -1057,23 +1144,45 @@ export function registerVerifyCommand(program: Command) {totalChecks: summary.total ?? cases.length,uncertainChecks: (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,verdict: summary.verdict ? toVerdict(summary.verdict) : undefined,- verifyRunId: run.id,+ verifyRunId: runId,});+ // 4. Prune cases the report no longer has (only when updating in place β+ // a fresh session has nothing to prune). Keeps a re-run a full+ // replace: dropped checks and their evidence disappear.+ let pruned = 0;+ if (reused) {+ const existingResults = await client.verify.listResultsByRun.query({+ verifyRunId: runId,+ });+ for (const r of existingResults) {+ if (!seenCheckItemIds.has(r.checkItemId)) {+ await client.verify.deleteResult.mutate({ id: r.id });+ pruned += 1;+ }+ }+ }++ // 5. Remember this session on the report dir so the next ingest of the+ // same dir updates it in place instead of creating a new one.+ writeSidecarRunId(dir, runId);+if (options.json !== undefined) {outputJson(- { cases: cases.length, evidence: uploaded, verifyRunId: run.id },+ { cases: cases.length, evidence: uploaded, pruned, reused, verifyRunId: runId },typeof options.json === 'string' ? options.json : undefined,);return;}+ const verb = reused ? 'Updated' : 'Ingested';console.log(- `${pc.green('β')} Ingested ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(uploaded))} evidence file(s)`,+ `${pc.green('β')} ${verb} ${pc.bold(String(cases.length))} case(s), ${pc.bold(String(uploaded))} evidence file(s)` ++ `${pruned > 0 ? `, pruned ${pc.bold(String(pruned))} stale case(s)` : ''}`,);- console.log(`${pc.bold('verifyRunId')}: ${run.id}`);+ console.log(`${pc.bold('verifyRunId')}: ${runId}${reused ? pc.dim(' (updated in place)') : ''}`);if (options.open) {- console.log(`${pc.bold('open')}: /verify/${run.id}`);+ console.log(`${pc.bold('open')}: /verify/${runId}`);}},);diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.tsindex d824b896f93..ced54b8a852 100644--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts@@ -5,6 +5,7 @@ import { FileService } from '@/server/services/file';const modelMocks = vi.hoisted(() => ({createEvidence: vi.fn(),+ deleteResult: vi.fn(),deleteRun: vi.fn(),findRunByOperation: vi.fn(),findRunById: vi.fn(),@@ -21,6 +22,7 @@ vi.mock('@/database/core/db-adaptor', () => ({vi.mock('@/database/models/verifyCheckResult', () => ({VerifyCheckResultModel: vi.fn(() => ({+ delete: modelMocks.deleteResult,findById: modelMocks.findResultById,upsertByCheckItem: modelMocks.upsertByCheckItem,})),@@ -146,6 +148,44 @@ describe('verifyRouter', () => {expect(modelMocks.updateRun).toHaveBeenCalledWith('run-1', { title: 'Renamed report' });expect(res).toEqual({ data: updatedRun, success: true });});++ it('refreshes the scope context in place on a re-ingest', async () => {+ const updatedRun = { id: 'run-1' };+ modelMocks.findRunById.mockResolvedValueOnce({ id: 'run-1' });+ modelMocks.updateRun.mockResolvedValueOnce(updatedRun);++ await createCaller().updateRun({+ value: { context: { branch: 'feat/x', commit: 'abc123' }, goal: 'ship x' },+ verifyRunId: 'run-1',+ });++ expect(modelMocks.updateRun).toHaveBeenCalledWith('run-1', {+ context: { branch: 'feat/x', commit: 'abc123' },+ goal: 'ship x',+ });+ });+ });++ describe('deleteResult', () => {+ it("rejects a result outside the caller's scope before deleting", async () => {+ modelMocks.findResultById.mockResolvedValueOnce(undefined);++ await expect(createCaller().deleteResult({ id: 'other-user-result' })).rejects.toThrow(+ 'Verification check result not found',+ );++ expect(modelMocks.findResultById).toHaveBeenCalledWith('other-user-result');+ expect(modelMocks.deleteResult).not.toHaveBeenCalled();+ });++ it('prunes a result the caller owns', async () => {+ modelMocks.findResultById.mockResolvedValueOnce({ id: 'result-1' });++ const res = await createCaller().deleteResult({ id: 'result-1' });++ expect(modelMocks.deleteResult).toHaveBeenCalledWith('result-1');+ expect(res).toEqual({ id: 'result-1', success: true });+ });});describe('submitCheckEvidence', () => {diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex 8c2f00b0c4c..3d5703560d9 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -87,9 +87,26 @@ const checkItemSchema = z.object({});const verifyRunIdInputSchema = z.object({ verifyRunId: z.string() });++// The scenario's context (coding scope), rendered as the report's scope header.+// Shared by createRun and updateRun so a re-ingest can refresh the scope in place.+const runContextSchema = z.object({+ branch: z.string().optional(),+ commit: z.string().optional(),+ entry: z.string().optional(),+ focus: z.string().optional(),+ surfaces: z.array(z.string()).optional(),+ testedAt: z.string().optional(),+});+const updateRunInputSchema = verifyRunIdInputSchema.extend({+ // Every field optional β a re-ingest may refresh only the context/goal while+ // keeping the original title, so nothing here is required.value: z.object({- title: z.string().trim().min(1).max(200),+ context: runContextSchema.optional(),+ goal: z.string().optional(),+ scenario: z.enum(['coding']).optional(),+ title: z.string().trim().min(1).max(200).optional(),}),});@@ -437,16 +454,7 @@ export const verifyRouter = router({.input(z.object({// The active scenario's context, rendered as the report's scope header.- context: z- .object({- branch: z.string().optional(),- commit: z.string().optional(),- entry: z.string().optional(),- focus: z.string().optional(),- surfaces: z.array(z.string()).optional(),- testedAt: z.string().optional(),- })- .optional(),+ context: runContextSchema.optional(),goal: z.string().optional(),operationId: z.string().optional(),scenario: z.enum(['coding']).optional(),@@ -519,7 +527,12 @@ export const verifyRouter = router({updateRun: verifyProcedure.input(updateRunInputSchema).mutation(async ({ ctx, input }) => {const run = await resolveVerifyRun(ctx, input.verifyRunId);- const updated = await ctx.runModel.update(run.id, { title: input.value.title });+ const updated = await ctx.runModel.update(run.id, {+ context: input.value.context,+ goal: input.value.goal,+ scenario: input.value.scenario,+ title: input.value.title,+ });return { data: updated, success: true };}),@@ -532,8 +545,12 @@ export const verifyRouter = router({confidence: z.number().min(0).max(1).optional(),required: z.boolean().optional(),status: checkStatusSchema.optional(),- suggestion: z.string().optional(),- toulmin: toulminSchema.optional(),+ // `.nullish()` (not `.optional()`) so a re-ingest can pass an explicit+ // `null` to CLEAR a prior suggestion/observation β `undefined` would be+ // dropped from the conflict UPDATE and leave the stale value on the row,+ // breaking the full-replace guarantee. See the ingest-report caller.+ suggestion: z.string().nullish(),+ toulmin: toulminSchema.nullish(),verdict: verdictSchema,verifierType: verifierTypeSchema.optional(),verifyRunId: z.string(),@@ -558,6 +575,19 @@ export const verifyRouter = router({});}),+ // Prune one check result (ownership-scoped; its evidence cascades). The+ // re-ingest path calls this for cases a later report round dropped, so+ // updating a session in place stays a full replace and never accretes stale+ // checks. resolveCheckResult 404s a result that isn't the caller's.+ deleteResult: verifyProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const result = await resolveCheckResult(ctx, input.id);++ await ctx.resultModel.delete(result.id);+ return { id: result.id, success: true };+ }),+uploadEvidence: verifyProcedure.input(uploadEvidenceInputSchema).mutation(async ({ ctx, input }) => {diff --git a/packages/database/src/models/__tests__/verifyCheckResult.test.ts b/packages/database/src/models/__tests__/verifyCheckResult.test.tsindex d3b66ef5e1e..160b96775fd 100644--- a/packages/database/src/models/__tests__/verifyCheckResult.test.ts+++ b/packages/database/src/models/__tests__/verifyCheckResult.test.ts@@ -8,11 +8,13 @@ import {llmGenerationTracing,users,verifyCheckResults,+ verifyEvidence,verifyRuns,} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { AgentOperationModel } from '../agentOperation';import { VerifyCheckResultModel } from '../verifyCheckResult';+import { VerifyEvidenceModel } from '../verifyEvidence';import { VerifyRunModel } from '../verifyRun';const serverDB: LobeChatDatabase = await getTestDB();@@ -43,6 +45,7 @@ beforeEach(async () => {});afterEach(async () => {+ await serverDB.delete(verifyEvidence);await serverDB.delete(verifyCheckResults);await serverDB.delete(llmGenerationTracing);await serverDB.delete(verifyRuns);@@ -106,6 +109,32 @@ describe('VerifyCheckResultModel', () => {expect(row).toMatchObject({ status: 'failed', verdict: 'failed' });});+ it('delete removes a row by id and cascades its evidence, scoped to the user', async () => {+ const model = new VerifyCheckResultModel(serverDB, userId);+ const created = await model.create({+ checkItemId: 'a',+ checkItemIndex: 0,+ verifierType: 'llm',+ verifyRunId,+ });+ const evidenceModel = new VerifyEvidenceModel(serverDB, userId);+ const evidence = await evidenceModel.create({+ checkResultId: created.id,+ content: 'observed',+ type: 'text',+ });++ // a different user must not be able to delete the row+ await new VerifyCheckResultModel(serverDB, 'someone-else').delete(created.id);+ expect(await model.findById(created.id)).toBeDefined();++ await model.delete(created.id);++ expect(await model.findById(created.id)).toBeUndefined();+ // evidence cascades via the check_result_id FK+ expect(await evidenceModel.findById(evidence.id)).toBeUndefined();+ });+it('backfillTracingId fills NULL tracing ids for the named items only and is idempotent', async () => {const model = new VerifyCheckResultModel(serverDB, userId);const [tracing] = await serverDB@@ -173,6 +202,47 @@ describe('VerifyCheckResultModel', () => {expect(await model.listByRun(verifyRunId)).toHaveLength(1);});+ it('upsertByCheckItem clears an optional field on null but keeps it on undefined', async () => {+ const model = new VerifyCheckResultModel(serverDB, userId);++ const first = await model.upsertByCheckItem({+ checkItemId: 'c1',+ status: 'failed',+ suggestion: 'fix the padding',+ toulmin: { evidence: 'padding was 4px' },+ verdict: 'failed',+ verifierType: 'agent',+ verifyRunId,+ });+ expect(first.suggestion).toBe('fix the padding');++ // undefined β the conflict UPDATE skips the column, prior value survives+ await model.upsertByCheckItem({+ checkItemId: 'c1',+ status: 'passed',+ verdict: 'passed',+ verifierType: 'agent',+ verifyRunId,+ });+ let row = await model.findById(first.id);+ expect(row?.suggestion).toBe('fix the padding');+ expect(row?.toulmin).toEqual({ evidence: 'padding was 4px' });++ // explicit null β the column is set to NULL (the full-replace path)+ await model.upsertByCheckItem({+ checkItemId: 'c1',+ status: 'passed',+ suggestion: null,+ toulmin: null,+ verdict: 'passed',+ verifierType: 'agent',+ verifyRunId,+ });+ row = await model.findById(first.id);+ expect(row?.suggestion).toBeNull();+ expect(row?.toulmin).toBeNull();+ });+it('rejects upserting a colliding check item into another user run', async () => {const otherUserId = 'verify-result-other-user';const otherOperationId = 'verify-result-other-op';diff --git a/packages/database/src/models/verifyCheckResult.ts b/packages/database/src/models/verifyCheckResult.tsindex 860ab561f09..68802be849a 100644--- a/packages/database/src/models/verifyCheckResult.ts+++ b/packages/database/src/models/verifyCheckResult.ts@@ -127,6 +127,18 @@ export class VerifyCheckResultModel {.where(and(eq(verifyCheckResults.id, id), this.ownership()));};+ /**+ * Delete one result by id (ownership-scoped). Its evidence rows cascade via the+ * `verify_evidence.check_result_id` FK. Used by the re-ingest path to prune a+ * case that a later report round dropped, so a re-run stays a full replace+ * rather than accreting stale checks.+ */+ delete = async (id: string) => {+ return this.db+ .delete(verifyCheckResults)+ .where(and(eq(verifyCheckResults.id, id), this.ownership()));+ };+/*** Update a result by its stable `(verifyRunId, checkItemId)` key rather than* the row id β used by the executor / batch judge which produces verdicts keyeddiff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 3bbe15713b7..812dd44728b 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -205,7 +205,7 @@ export class VerifyRunModel {update = async (runId: string,- value: Partial<Pick<NewVerifyRun, 'title'>>,+ value: Partial<Pick<NewVerifyRun, 'context' | 'goal' | 'scenario' | 'title'>>,): Promise<VerifyRunItem | undefined> => {const [run] = await this.db.update(verifyRuns)