๐คฏ 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
โป๏ธ refactor(server): split the 1,630-line acceptance router into sub-domain modules (#21091)
Arvin Xue9db070c7510
diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.tsindex 76958d3f2e8..9dcc694b5ba 100644--- a/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.ts+++ b/apps/server/src/routers/lambda/__tests__/acceptance.purge.test.ts@@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto';import { type LobeChatDatabase } from '@lobechat/database';import { acceptances, verifyRuns, workspaceMembers, workspaces } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';-import { eq } from 'drizzle-orm';+import { eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { acceptanceRouter } from '../acceptance';@@ -160,6 +160,63 @@ describe('acceptanceRouter purge', () => {caller(ownerId).purgePreview({ ids: [personalId, randomUUID()] }),).rejects.toMatchObject({ code: 'NOT_FOUND' });});++ it('caps concurrent per-scope previews while still summing every scope', async () => {+ const extraWorkspaces = await serverDB+ .insert(workspaces)+ .values(+ Array.from({ length: 6 }, (_, i) => ({+ name: `ws-${i}`,+ primaryOwnerId: ownerId,+ slug: `ws-${randomUUID()}`,+ })),+ )+ .returning();+ try {+ const rows = await serverDB+ .insert(acceptances)+ .values(+ extraWorkspaces.map((ws) => ({+ subjectId: randomUUID(),+ subjectType: 'standalone' as const,+ userId: ownerId,+ visibility: 'private' as const,+ workspaceId: ws.id,+ })),+ )+ .returning();++ let inFlight = 0;+ let maxInFlight = 0;+ purgeMocks.previewAcceptancePurge.mockImplementation(async () => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((resolve) => setTimeout(resolve, 5));+ inFlight -= 1;+ return { bytes: 1, fileCount: 1, files: { images: 1, other: 0, videos: 0 }, rounds: 1 };+ });++ const res = await caller(ownerId).purgePreview({ ids: rows.map((row) => row.id) });++ expect(res).toEqual({+ bytes: 6,+ fileCount: 6,+ files: { images: 6, other: 0, videos: 0 },+ rounds: 6,+ });+ expect(purgeMocks.previewAcceptancePurge).toHaveBeenCalledTimes(6);+ expect(maxInFlight).toBeGreaterThan(1);+ expect(maxInFlight).toBeLessThanOrEqual(4);+ } finally {+ purgeMocks.previewAcceptancePurge.mockReset();+ await serverDB.delete(workspaces).where(+ inArray(+ workspaces.id,+ extraWorkspaces.map((ws) => ws.id),+ ),+ );+ }+ });});describe('remove', () => {diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsdeleted file mode 100644index cbbe2c3a391..00000000000--- a/apps/server/src/routers/lambda/acceptance.ts+++ /dev/null@@ -1,1630 +0,0 @@-import {- acceptanceCheckReviewActions,- acceptanceRejectIntents,- acceptanceSubjectTypes,- acceptanceVisibilities,- reviewAdjudications,- reviewProposalEdits,- verifyEvidenceChapterKinds,-} from '@lobechat/const/verify';-import type { AcceptanceAttachment } from '@lobechat/types';-import { verifyCheckDefinitionSchema } from '@lobechat/types';-import { TRPCError } from '@trpc/server';-import { eq, inArray } from 'drizzle-orm';-import { z } from 'zod';--import {- requireWorkspaceRoleWhenScoped,- wsCompatProcedure,-} from '@/business/server/trpc-middlewares/workspaceAuth';-import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';-import { AgentOperationModel } from '@/database/models/agentOperation';-import { ProjectModel } from '@/database/models/project';-import { ScmChangeRequestModel } from '@/database/models/scm';-import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';-import { VerifyRunModel } from '@/database/models/verifyRun';-import { WorkspaceMemberModel } from '@/database/models/workspaceMember';-import { users } from '@/database/schemas';-import type { AcceptanceItem } from '@/database/schemas/verify';-import { acceptances } from '@/database/schemas/verify';-import type { LobeChatDatabase } from '@/database/type';-import { isUuid } from '@/database/utils/uuid';-import { publicProcedure, router } from '@/libs/trpc/lambda';-import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { notifyAcceptance } from '@/server/services/acceptanceReview/events';-import { FileService } from '@/server/services/file';-import { parseChangeRequestUrl } from '@/server/services/scm/changeRequestUrl';-import {- AcceptanceService,- buildAcceptanceCheckUnion,- buildCheckReviewOverlay,- createEvidenceFileResolver,- isCurrentReviewPrediction,- mapWithConcurrency,- previewAcceptancePurge,- purgeAcceptance,- REVIEW_PREDICT_CONCURRENCY,- REVIEW_PREDICT_MODEL_CONFIG,- shouldSurfaceProposal,- VerifyReviewPredictorService,-} from '@/server/services/verify';-import {- addPullRequestLink,- listAcceptancePullRequests,- removePullRequestLink,- updateAcceptancePullRequests,-} from '@/server/services/verify/acceptancePullRequests';-import { after } from '@/server/utils/scheduleAfterResponse';--import { previewUrlSchema, recordPreviewUrl } from './_helpers/acceptancePreviewUrl';-import {- type AcceptanceRepairDispatch,- dispatchAcceptanceRepair,-} from './_helpers/acceptanceRepairDispatch';-import {- acceptanceStatusOverrideSchema,- applyAcceptanceStatus,- settleGoalSignOff,-} from './_helpers/acceptanceStatus';-import { canManageAcceptance, filterManageableAcceptances } from './_helpers/acceptanceWriteScope';-import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';-import * as goalGate from './_helpers/goalGateAcceptance';--/**- * A reviewer's circled region. On video evidence it also carries the frame- * (`time.start`) or span (`time.start`โ`time.end`) it is about, and optionally- * quotes the agent chapter it disputes.- */-const reviewAnnotationSchema = z.object({- comment: z.string().max(2000).optional(),- disputes: z- .object({- kind: z.enum(verifyEvidenceChapterKinds),- note: z.string().max(500).optional(),- t: z.number().min(0),- })- .optional(),- evidenceId: z.string(),- rect: z.object({- height: z.number().min(0).max(1),- width: z.number().min(0).max(1),- x: z.number().min(0).max(1),- y: z.number().min(0).max(1),- }),- time: z- .object({ end: z.number().min(0).optional(), start: z.number().min(0) })- .refine((time) => time.end === undefined || time.end > time.start, {- message: 'time.end must be after time.start',- })- .optional(),-});--const reviewAnnotationsSchema = z.array(reviewAnnotationSchema).max(20).optional();--const flowDefinitionSchema = z.object({- title: z.string().min(1).max(200),- entryNodeId: z.string().uuid(),- nodes: z- .array(- z.object({- id: z.string().uuid(),- criterionId: z.string().uuid().optional(),- subFlowId: z.string().uuid().optional(),- check: z- .object({- id: z.string().uuid(),- title: z.string().min(1).max(200),- description: z.string().optional(),- definition: verifyCheckDefinitionSchema,- })- .optional(),- overrides: z- .object({- required: z.boolean().optional(),- onFail: z.enum(['manual', 'auto_repair']).optional(),- fixtureData: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),- })- .optional(),- }),- )- .min(1)- .max(100),- edges: z- .array(- z.object({- id: z.string().uuid(),- sourceNodeId: z.string().uuid(),- targetNodeId: z.string().uuid(),- trigger: z.string().min(1).max(1000),- condition: z.string().max(2000).optional(),- required: z.boolean(),- }),- )- .max(300),-});--const subjectTypeSchema = z.enum(acceptanceSubjectTypes);--/** Reads addressed purely by acceptance id โ visibility is checked in the handler. */-const publicAcceptanceProcedure = publicProcedure.use(serverDatabase);--const acceptanceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {- const { ctx } = opts;- return opts.next({- ctx: {- acceptanceService: new AcceptanceService(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- ),- },- });-});--// Writes: workspace mode requires at least the member role (viewers are-// read-only); personal mode passes through unrestricted.-const acceptanceWriteProcedure = acceptanceProcedure.use(requireWorkspaceRoleWhenScoped('member'));--/**- * Resolve an acceptance for WRITING, with a service bound to the scope the row- * actually lives in.- *- * Every model write is scoped by `buildWorkspaceWhere`, and `acceptances`- * carries a `visibility` column โ so that predicate narrows PRIVATE rows to- * `userId = <bound user>`, and workspace acceptances default to private. A- * service bound to the caller therefore cannot resolve a teammate's row at all,- * and the write dies as `NOT_FOUND` after authorization already said yes.- *- * So the service is bound to the row's OWNER โ the one binding that resolves it- * โ while the acting user is carried separately, because decisions record- * `decidedBy` and an audit trail that credits a teammate's verdict to the- * author is worse than one nobody can sign.- */-export const resolveAcceptanceForWrite = async (- ctx: { serverDB: LobeChatDatabase; userId: string },- id: string,-): Promise<{ acceptance: AcceptanceItem; service: AcceptanceService }> => {- const acceptance = isUuid(id)- ? await ctx.serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, id) })- : undefined;-- // An unauthorized caller gets the same answer as a missing row: the existence- // of someone else's delivery is not ours to disclose.- if (!acceptance || !(await canManageAcceptance(ctx, acceptance))) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });- }-- return {- acceptance,- service: new AcceptanceService(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- { actorUserId: ctx.userId },- ),- };-};--const canReadAcceptance = async (- ctx: { serverDB: LobeChatDatabase; userId?: string | null },- acceptance: AcceptanceItem,-) => {- if (ctx.userId && ctx.userId === acceptance.userId) return true;- if (acceptance.visibility === 'public') return true;- if (!ctx.userId || !acceptance.workspaceId) return false;- // Membership in the acceptance's OWN workspace โ not the viewer's currently- // active one, which may be a different workspace entirely.- const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(- acceptance.workspaceId,- ctx.userId,- );- return Boolean(member);-};--/**- * The list panel's narrowing, shared by the flat and paged reads. `projectId:- * null` asks for acceptances filed under no project.- */-const acceptanceListFiltersSchema = z.object({- filter: z.enum(['active', 'all', 'completed']).optional(),- projectId: z.string().nullable().optional(),- scope: z.enum(['all', 'created', 'participated']).optional(),- source: z.enum(['all', 'goal', 'standalone', 'task', 'topic']).optional(),-});--/**- * Tag each list row with whether the caller may rename, refile, re-status or- * delete it. "Participated" rows are often someone else's, so the panel must- * know which menus to offer instead of letting the write fail as NOT_FOUND.- */-const withManageFlag = async <T extends Pick<AcceptanceItem, 'id' | 'userId' | 'workspaceId'>>(- ctx: { serverDB: LobeChatDatabase; userId: string },- rows: T[],-): Promise<Array<T & { canManage: boolean }>> => {- const manageable = new Set((await filterManageableAcceptances(ctx, rows)).map((row) => row.id));- return rows.map((row) => ({ ...row, canManage: manageable.has(row.id) }));-};--/** Max rows one multi-select sweep may touch โ the list itself is capped at 200. */-const ACCEPTANCE_BATCH_LIMIT = 200;-const PURGE_BATCH_CONCURRENCY = 4;-const PURGE_PREVIEW_LIMIT = 20;--export const acceptanceRouter = router({- regroupChecks: acceptanceWriteProcedure- .input(- z.object({- id: z.string().uuid(),- expectedVersion: z.number().int().nonnegative(),- groups: z- .array(- z.object({- title: z.string().trim().min(1).max(200),- checkItemIds: z.array(z.string().min(1)).min(1).max(1000),- }),- )- .max(100),- }),- )- .mutation(async ({ ctx, input }) => {- const { service } = await resolveAcceptanceForWrite(ctx, input.id);- return service.regroupChecks(input.id, input.groups, input.expectedVersion);- }),- publishFlow: acceptanceWriteProcedure- .input(- z.object({- id: z.string().uuid(),- definition: flowDefinitionSchema,- flowId: z.string().uuid().optional(),- expectedHash: z.string().optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);- return new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).publish(- input.id,- input.definition,- input.flowId,- input.expectedHash,- );- }),- deleteFlow: acceptanceWriteProcedure- .input(z.object({ id: z.string().uuid(), flowId: z.string().uuid() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).delete(- input.id,- input.flowId,- );- await service.recomputeStatus(input.id);- return result;- }),- startFlow: acceptanceWriteProcedure- .input(- z.object({- id: z.string().uuid(),- flowId: z.string().uuid(),- sourceRunId: z.string().uuid().optional(),- verifyRunId: z.string().uuid().optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).start(- input.id,- input.flowId,- input.verifyRunId,- input.sourceRunId,- );- await service.recomputeStatus(input.id);- return result;- }),- recordFlowStep: acceptanceWriteProcedure- .input(- z.object({- id: z.string().uuid(),- verifyRunId: z.string().uuid(),- checkItemId: z.string().min(1),- observation: z.string().min(1).max(20000),- verdict: z.enum(['passed', 'failed', 'uncertain', 'blocked']),- }),- )- .mutation(async ({ ctx, input }) => {- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);- return new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).record(input.id, input);- }),- completeFlow: acceptanceWriteProcedure- .input(z.object({ id: z.string().uuid(), verifyRunId: z.string().uuid() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).complete(- input.id,- input.verifyRunId,- );- await service.recomputeStatus(input.id);- return result;- }),- reviewFlowStep: acceptanceWriteProcedure- .input(- z.object({- id: z.string().uuid(),- attemptId: z.string().uuid(),- review: z.enum(['accepted', 'rejected']),- comment: z.string().max(4000),- annotations: reviewAnnotationsSchema,- fileIds: z.array(z.string()).max(10).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);- return new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).review(- input.id,- input.attemptId,- input.review,- input.comment,- ctx.userId,- { annotations: input.annotations, fileIds: input.fileIds },- );- }),-- /**- * The user accepts the delivery โ the terminal business event that closes- * the acceptance lifecycle. The verifier's verdict is a recommendation; this- * click is the event (a failed/uncertain round can still be accepted, which- * means the user knowingly takes it with its exceptions).- */- accept: acceptanceWriteProcedure- .input(goalGate.gateDecisionInput.extend({ comment: z.string().max(2000).optional() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- const accepted = await goalGate.withGoalGateAnswer(- ctx.serverDB,- service,- acceptance,- 'release',- { comment: input.comment, roundId: input.roundId },- () => service.accept(acceptance.id, input.comment),- );- // Signed where it lives โ the inbox stops asking for the same sign-off.- await settleGoalSignOff(ctx.serverDB, acceptance, 'signOff', input.comment);- return accepted;- }),-- /**- * Chain an existing verify run onto an acceptance as its next round.- * Idempotent when the run is already chained to the same acceptance (the- * ingest CLI re-runs against a remembered session).- */- attachRun: acceptanceWriteProcedure- .input(z.object({ acceptanceId: z.string(), verifyRunId: z.string() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.acceptanceId);-- // The attach rewrites the RUN's acceptance_id/round_index too โ and a- // workspace-visible run is not necessarily the caller's. Creator-scope it- // like every other verify write, or a member could chain another- // member's report onto their aggregate.- const run = await new VerifyRunModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- ).findById(input.verifyRunId);- if (!run) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification run not found' });- }- assertWorkspaceRowManageable(ctx, run.userId, 'verify run');-- try {- return await service.attachRun(run.id, acceptance.id);- } catch (error) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: error instanceof Error ? error.message : 'Failed to attach run',- });- }- }),-- /**- * Record that a pull request delivers this acceptance. The link lives on the- * acceptance, not on a round: the pull request usually opens after the- * rounds that verified it, and stacked pull requests share one acceptance.- *- * Stored on the acceptance rather than on the shared `scm_change_requests`- * row: that row is keyed globally and owned by whichever tenant the- * provider routes the PR to, so a pasted URL must not claim it. A hand- * link is display-only and never drives merge โ accepted.- */- linkPullRequest: acceptanceWriteProcedure- .input(- z.object({- id: z.string(),- title: z.string().trim().min(1).max(500).optional(),- url: z.string().max(2000),- }),- )- .mutation(async ({ ctx, input }) => {- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);- const parsed = parseChangeRequestUrl(input.url);- if (!parsed) {- throw new TRPCError({- code: 'BAD_REQUEST',- message:- 'Expected a GitHub pull request URL, e.g. https://github.com/owner/repo/pull/123',- });- }-- await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>- addPullRequestLink(links, parsed, input.title),- );- return parsed;- }),-- unlinkPullRequest: acceptanceWriteProcedure- .input(z.object({ id: z.string(), url: z.string().max(2000) }))- .mutation(async ({ ctx, input }) => {- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);- const parsed = parseChangeRequestUrl(input.url);- const pullRequests = parsed- ? await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>- removePullRequestLink(links, parsed),- )- : null;- if (!pullRequests) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Linked pull request not found' });- }-- return { success: true };- }),-- /** Get (or lazily create) the aggregate for a subject โ the ingest entry point. */- ensure: acceptanceWriteProcedure- .input(- z.object({- /**- * Set by report ingest when the topic came from the ambient- * `LOBEHUB_TOPIC_ID`: a Task's run topic then lands on the Task. An- * explicitly requested subject is always kept exact.- */- foldTaskRunTopic: z.boolean().optional(),- requirement: z.string().max(2000).optional(),- subjectId: z.string(),- subjectType: subjectTypeSchema,- title: z.string().trim().min(1).max(500).optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const defaults = { requirement: input.requirement, title: input.title };- try {- return input.foldTaskRunTopic- ? await ctx.acceptanceService.ensureForIngest(- input.subjectType,- input.subjectId,- defaults,- )- : await ctx.acceptanceService.ensureForSubject(- input.subjectType,- input.subjectId,- defaults,- );- } catch (error) {- throw new TRPCError({- code: 'NOT_FOUND',- message: error instanceof Error ? error.message : 'Acceptance subject not found',- });- }- }),-- /** The acceptance row for a subject, or null when none exists yet. */- getBySubject: acceptanceProcedure- .input(z.object({ subjectId: z.string(), subjectType: subjectTypeSchema }))- .query(async ({ ctx, input }) => {- const acceptance = await ctx.acceptanceService.acceptanceModel.findBySubject(- input.subjectType,- input.subjectId,- );- if (!acceptance) return null;-- // `delivered` alone is ambiguous for the subject's status surface: a- // converged delivery waiting for sign-off and a failed one waiting for a- // decision both land there. The latest round's verdict is what tells- // them apart, so ship it with the aggregate instead of forcing callers- // to load the whole bundle for one field.- const latest = await ctx.acceptanceService.latestRound(acceptance.id);- return {- ...acceptance,- latestRunStatus: latest?.status ?? null,- latestRunUserDecision: latest?.userDecision ?? null,- };- }),-- /**- * Persist a subject's standing acceptance checklist (the topic tray). Ensures- * the aggregate exists, then writes the list into its `config.checklist` โ so- * the criteria live with the verify aggregate, not in client storage.- */- saveChecklist: acceptanceWriteProcedure- .input(- z.object({- checklist: z.array(- z.object({- id: z.string(),- method: z.string().optional(),- name: z.string(),- }),- ),- subjectId: z.string(),- subjectType: subjectTypeSchema,- }),- )- .mutation(async ({ ctx, input }) => {- try {- const aggregate = await ctx.acceptanceService.ensureForSubject(- input.subjectType,- input.subjectId,- );- await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {- config: { ...aggregate.config, checklist: input.checklist },- });- return { checklist: input.checklist, id: aggregate.id };- } catch (error) {- throw new TRPCError({- code: 'NOT_FOUND',- message: error instanceof Error ? error.message : 'Acceptance subject not found',- });- }- }),-- /**- * Set (or update) a subject's acceptance goal โ the one-sentence outcome the- * conversation is delivering. Unlike `ensure`, this overwrites: the goal is a- * user-editable field, so a later edit must stick.- */- saveGoal: acceptanceWriteProcedure- .input(- z.object({- requirement: z.string().max(2000),- subjectId: z.string(),- subjectType: subjectTypeSchema,- }),- )- .mutation(async ({ ctx, input }) => {- try {- const aggregate = await ctx.acceptanceService.ensureForSubject(- input.subjectType,- input.subjectId,- );- await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {- requirement: input.requirement,- });- return { id: aggregate.id, requirement: input.requirement };- } catch (error) {- throw new TRPCError({- code: 'NOT_FOUND',- message: error instanceof Error ? error.message : 'Acceptance subject not found',- });- }- }),-- /**- * One-shot payload for the acceptance decision workspace: the aggregate, its- * subject header, the round ledger (each round's run + report), and the- * cross-round check union โ every check ever planned, with its final verdict,- * final evidence (file-URL enriched) and round provenance.- *- * Public like the verify report viewer: the acceptance URL is meant to be- * linked from PRs/reports, so a `public` aggregate is readable by anyone- * holding the id. `private` stays gated to the owner and (for workspace- * scope) workspace members. A denied read is a NOT_FOUND, never a- * FORBIDDEN โ existence must not leak through the error code.- */- getBundle: publicAcceptanceProcedure- .input(z.object({ id: z.string() }))- .query(async ({ ctx, input }) => {- // Public entry fed by shared links: a chat autolinker can glue trailing- // CJK punctuation onto the URL, so a malformed uuid must read as- // NOT_FOUND instead of aborting in Postgres (22P02 โ 500).- const acceptance = isUuid(input.id)- ? await ctx.serverDB.query.acceptances.findFirst({- where: eq(acceptances.id, input.id),- })- : undefined;- if (!acceptance) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });- }-- const isOwner = Boolean(ctx.userId) && ctx.userId === acceptance.userId;- if (!isOwner && !(await canReadAcceptance(ctx, acceptance))) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });- }-- // The one rule the write path enforces โ same helper, so the page can- // never advertise an action the mutation would refuse.- const canReview = await canManageAcceptance(ctx, acceptance);-- // Sub-reads (rounds / results / evidence) are ownership-scoped models, so- // read them AS the aggregate's owner โ same pattern as the evidence file- // resolver. The visibility gate above is the actual access decision.- const ownerService = new AcceptanceService(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- );-- const [subject, { evidence, reports, results, runs }, authorRows, changeRequests] =- await Promise.all([- ownerService.resolveSubject(acceptance),- ownerService.loadRounds(acceptance.id),- // Who delivered this, the way a pull request names its author. A- // shared link lands on someone else's record, and a record with no- // name on it reads as nobody's.- ctx.serverDB- .select({- avatar: users.avatar,- fullName: users.fullName,- id: users.id,- username: users.username,- })- .from(users)- .where(eq(users.id, acceptance.userId)),- // Provider-verified PRs that deliver it. Owned by the acceptance, not- // by a round, so one opened after the last round still shows.- ScmChangeRequestModel.listByAcceptance(ctx.serverDB, acceptance.id),- ]);- const author = authorRows[0] ?? null;-- const flowData = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).list(- acceptance.id,- );- const flowResultIds = new Set(- flowData.flatMap((flow) =>- flow.versions.flatMap((version) =>- version.runs.flatMap((run) => run.attempts.map((attempt) => attempt.checkResultId)),- ),- ),- );- const resultsByRun = new Map<string, typeof results>();- for (const result of results) {- const key = result.verifyRunId!;- const bucket = resultsByRun.get(key) ?? [];- bucket.push(result);- resultsByRun.set(key, bucket);- }-- const checks = buildAcceptanceCheckUnion(- runs.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),- acceptance.metadata?.checkGrouping?.groups,- );-- // Enrich the evidence backing every executed timeline step โ the final- // round's artifacts render inline on the row; earlier steps' artifacts- // render inside the check's iteration-history timeline.- const resolveFileMeta = createEvidenceFileResolver(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- );- const timelineResultIds = new Set(- checks.flatMap((check) => check.timeline.map((entry) => entry.resultId)),- );- const enriched = await Promise.all(- evidence- .filter(- (e) => timelineResultIds.has(e.checkResultId) || flowResultIds.has(e.checkResultId),- )- .map(async (e) => ({ ...e, ...(await resolveFileMeta(e.fileId ?? null)) })),- );- const evidenceByResult = new Map<string, typeof enriched>();- for (const e of enriched) {- const bucket = evidenceByResult.get(e.checkResultId) ?? [];- bucket.push(e);- evidenceByResult.set(e.checkResultId, bucket);- }-- // Resolve the files backing user feedback (uploaded/pasted screenshots)- // to URLs with the same owner-scoped resolver the evidence uses โ one- // batch for every attachment id across check rejects and group feedback.- const attachmentIds = new Set<string>(- flowData.flatMap((flow) =>- flow.versions.flatMap((version) =>- version.runs.flatMap((run) =>- run.attempts.flatMap((attempt) => attempt.reviewDetail?.fileIds ?? []),- ),- ),- ),- );- for (const result of results)- for (const id of result.userDecisionDetail?.fileIds ?? []) attachmentIds.add(id);- for (const run of runs)- for (const entry of run.decisionDetail?.groupFeedback ?? [])- for (const id of entry.fileIds ?? []) attachmentIds.add(id);- const attachmentById = new Map<string, AcceptanceAttachment>();- await Promise.all(- [...attachmentIds].map(async (id) => {- const meta = await resolveFileMeta(id);- attachmentById.set(id, { id, name: meta.fileName ?? undefined, url: meta.fileUrl });- }),- );- const toAttachments = (fileIds?: string[]): AcceptanceAttachment[] | undefined => {- if (!fileIds?.length) return undefined;- const resolved = fileIds- .map((id) => attachmentById.get(id))- .filter((a): a is AcceptanceAttachment => Boolean(a));- return resolved.length > 0 ? resolved : undefined;- };-- const reportsByRun = new Map(reports.map((r) => [r.verifyRunId!, r]));- // What each round actually spent. Owner-only: cost is the author's- // operating detail, not something a shared link should expose.- // `isOwner` already implies a signed-in viewer; the explicit id check is- // what narrows it for the model, which is owner-scoped by construction.- const usageByOperation =- isOwner && ctx.userId- ? await new AgentOperationModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined)- .findUsageByOperations(- runs.flatMap((run) => (run.operationId ? [run.operationId] : [])),- )- .catch(() => new Map<string, { cost: number; tokens: number }>())- : new Map<string, { cost: number; tokens: number }>();- const rounds = runs.map((run) => {- // `origin` points at the author's private topic/agent โ never hand it- // to a visitor holding nothing but the shared link.- let publicRun = run;- if (!isOwner && run.metadata?.origin) {- const { origin: _origin, ...publicMetadata } = run.metadata;- publicRun = { ...run, metadata: publicMetadata };- }- // Enrich group feedback with resolved attachment URLs for the client.- const groupFeedback = publicRun.decisionDetail?.groupFeedback;- if (groupFeedback?.some((entry) => entry.fileIds?.length)) {- publicRun = {- ...publicRun,- decisionDetail: {- ...publicRun.decisionDetail,- groupFeedback: groupFeedback.map((entry) => {- const attachments = toAttachments(entry.fileIds);- return attachments ? { ...entry, attachments } : entry;- }),- },- };- }- return {- report: reportsByRun.get(run.id) ?? null,- run: publicRun,- usage: (run.operationId ? usageByOperation.get(run.operationId) : undefined) ?? null,- };- });- const latestReport = [...rounds].reverse().find((r) => r.report)?.report ?? null;-- // The authoring conversation (agent + topic), resolved for the header โ- // owner-only, same redaction rule as `run.metadata.origin`.- const origin = isOwner ? await ownerService.resolveOrigin(runs) : null;-- const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;- const resultsById = new Map(results.map((result) => [result.id, result]));-- // Automated proposals are the reviewer's working state, not published- // content โ a shared acceptance URL (the whole point of `public`- // visibility) must not show visitors "an AI thinks this is broken".- // Scoped to whoever may REVIEW, not to the creator: the predict button is- // gated the same way, and a reviewer who can spend the model budget but- // never receives a `predictionStatus` polls until it times out, then- // reports the work as still running after it finished.- const predictions = canReview- ? await new VerifyReviewPredictionModel(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- ).listByRuns(runs.map((run) => run.id))- : [];- // Keyed by the concrete check RESULT, never by the union row's id. The- // union exposes `sourceCriterionId ?? checkItemId` as `check.id` so a- // renamed check folds across rounds โ but a prediction is stored against- // the result it judged. Keying on the logical id silently misses every- // plan that uses a distinct snapshot id: generation reports success and- // no card ever renders.- const predictionByResult = new Map<string, (typeof predictions)[number]>();- // Goal reviews may use the owner's configured model. Their persisted ids- // identify the actual automatic decision without admitting unrelated rows.- const automaticPredictionIds = new Set(- runs.flatMap((run) => run.metadata?.goalReview?.predictionIds ?? []),- );- // Newest-first from the model, so the first write per check item wins and- // later (older) rows are ignored.- for (const prediction of predictions) {- // Rows from an earlier pin (another model / prompt version) stay in- // the table for the comparison set but are not this page's reviewer.- if (- !isCurrentReviewPrediction(- prediction,- REVIEW_PREDICT_MODEL_CONFIG,- automaticPredictionIds,- )- )- continue;- if (!predictionByResult.has(prediction.checkResultId)) {- predictionByResult.set(prediction.checkResultId, prediction);- }- }-- return {- author,- pullRequests: listAcceptancePullRequests(changeRequests, acceptance.metadata?.pullRequests),- flows: flowData.map((flow) => ({- ...flow,- versions: flow.versions.map((version) => ({- ...version,- runs: version.runs.map((run) => ({- ...run,- attempts: run.attempts.map((attempt) => ({- ...attempt,- reviewAttachments: toAttachments(attempt.reviewDetail?.fileIds),- evidence: evidenceByResult.get(attempt.checkResultId) ?? [],- })),- })),- })),- })),- acceptance,- canReview,- isOwner,- checks: checks.map((check) => {- // Projected from the result rows' user_decision(+detail) โ the- // events carry no user ids, so nothing needs redacting here.- const { reviews, userReview } = buildCheckReviewOverlay(- check,- resultsById,- currentRoundIndex,- );- // The standing verdict mirrors the latest review โ resolve its- // attachments too so the row's feedback card can render them.- const resolvedReviews = reviews.map((review) => {- const attachments = toAttachments(review.fileIds);- return attachments ? { ...review, attachments } : review;- });- const latestAttachments = toAttachments(reviews.at(-1)?.fileIds);- const prediction = check.result ? predictionByResult.get(check.result.id) : undefined;- // A STALE review is last round's rejection carried forward as history;- // THIS round's result is undecided. Treating it as a current verdict- // hid the proposal on exactly the repair round where the reviewer has- // to judge again.- const settled = Boolean(userReview && !userReview.stale);- return {- ...check,- evidence: check.result ? (evidenceByResult.get(check.result.id) ?? []) : [],- prediction:- prediction && shouldSurfaceProposal(prediction, settled) ? prediction : null,- // The card above is gated to actionable rejects, but the FACT that- // the predictor finished with this check must stay visible: an- // `accept`, a skip and an error all render no card, and without- // this the predict button's poll cannot tell "still running" from- // "reviewed, nothing to say" โ it spins to timeout on a clean bill.- predictionStatus: prediction?.status ?? null,- reviews: resolvedReviews,- timeline: check.timeline.map((entry) => ({- ...entry,- evidence: evidenceByResult.get(entry.resultId) ?? [],- })),- userReview:- userReview && latestAttachments- ? { ...userReview, attachments: latestAttachments }- : userReview,- };- }),- latestReport,- origin,- rounds,- subject,- };- }),-- /**- * Recent acceptances (with subject headers), newest first โ list panel + CLI.- *- * `limit` is capped rather than open: the read resolves each row's subject- * title one by one, so an unbounded window would fan out. The merge picker- * asks for the wide end because a target it cannot list is a target the user- * cannot merge into.- */- list: acceptanceProcedure- .input(- acceptanceListFiltersSchema- .extend({- limit: z.number().int().min(1).max(200).optional(),- q: z.string().max(200).optional(),- })- .optional(),- )- .query(async ({ ctx, input }) =>- withManageFlag(ctx, await ctx.acceptanceService.listWithSubjects(input)),- ),-- /**- * One keyset page of the same feed โ what the list panel scrolls.- *- * Speaks the same filter vocabulary as `list`, applied in the query, so a- * page of "in progress" is a full page of in-progress rows. There is no- * paged search on purpose: a title search must span the whole owned set,- * which `list` already does โ the panel asks that one while a query is live.- */- listPage: acceptanceProcedure- .input(- acceptanceListFiltersSchema- .extend({- cursor: z.string().optional(),- limit: z.number().int().min(1).max(100).optional(),- })- .optional(),- )- .query(async ({ ctx, input }) => {- const page = await ctx.acceptanceService.listPageWithSubjects({ ...input });- return { ...page, items: await withManageFlag(ctx, page.items) };- }),-- /**- * Fold one acceptance into another: the source's verification rounds (and- * with them its checks, verdicts and evidence) re-chain onto the target, and- * the source entry is deleted.- *- * Both sides are creator-scoped like every other verify write โ a merge- * rewrites BOTH aggregates, so a workspace member must not be able to fold- * another member's acceptance into (or out of) their own.- */- merge: acceptanceWriteProcedure- .input(z.object({ sourceId: z.string(), targetId: z.string() }))- .mutation(async ({ ctx, input }) => {- // A merge rewrites BOTH aggregates, so both have to authorize; the source- // owns the rows that move, so its scope is the one the write runs in.- const { acceptance: source, service } = await resolveAcceptanceForWrite(ctx, input.sourceId);- const { acceptance: target } = await resolveAcceptanceForWrite(ctx, input.targetId);- await goalGate.assertNotHoldingRelease(ctx.serverDB, source);- await goalGate.assertNotHoldingRelease(ctx.serverDB, target);-- try {- return await service.merge(source.id, target.id);- } catch (error) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: error instanceof Error ? error.message : 'Failed to merge acceptance',- });- }- }),-- /**- * Acceptance status for a known set of subjects, in one read.- *- * `list` is recency-capped and spans every subject type, so a list surface- * that derived per-row state from it would silently mis-read any subject- * pushed past the cap. This answers about exactly the subjects asked for.- */- listStatusesBySubjects: acceptanceProcedure- .input(- z.object({- subjectIds: z.array(z.string()).max(200),- subjectType: subjectTypeSchema,- }),- )- .query(async ({ ctx, input }) =>- ctx.acceptanceService.acceptanceModel.listStatusesBySubjects(- input.subjectType,- input.subjectIds,- ),- ),-- /**- * Feedback addressed to a check GROUP (business category) rather than any- * single check โ for concerns that don't invalidate an individual check- * (which may well be accepted) but still need to reach the next round.- * Append-only, stamped with the current round for the same staleness rule- * as check-level rejects.- */- addGroupFeedback: acceptanceWriteProcedure- .input(- z.object({- category: z.string().max(200),- comment: z.string().trim().min(1).max(2000),- fileIds: z.array(z.string()).max(10).optional(),- id: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- // The feedback is addressed to the CURRENT round and lives on its run's- // decision detail โ the same home as the round's terminal accept/reject- // note, so staleness falls out of the round chain and a deleted round- // takes its feedback along.- const { runs } = await service.loadRounds(acceptance.id);- const currentRun = runs.at(-1);- if (!currentRun) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'No verification round to address feedback to',- });- }-- const entry = {- category: input.category,- comment: input.comment,- createdAt: new Date().toISOString(),- ...(input.fileIds?.length ? { fileIds: input.fileIds } : {}),- };- await new VerifyRunModel(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- ).appendGroupFeedback(currentRun.id, entry);- return { entry: { ...entry, roundIndex: currentRun.roundIndex }, success: true };- }),-- /**- * The user's verdict on individual union checks โ `accept` settles a check- * for good ("ๅทฒ้ชๆถ,ไธ็จๅ็ฎก"); `reject` records feedback the next verify- * round reads as its re-tasking input. A group-level "accept all" is the- * same call with many ids. Independent of the aggregate-level accept/reject:- * reviewing checks never moves the acceptance lifecycle.- */- reviewChecks: acceptanceWriteProcedure- .input(- z- .object({- action: z.enum(acceptanceCheckReviewActions),- annotations: reviewAnnotationsSchema,- checkItemIds: z.array(z.string()).min(1).max(200),- comment: z.string().max(2000).optional(),- fileIds: z.array(z.string()).max(10).optional(),- id: z.string(),- /**- * Which of the three jobs a reject is doing. Optional so older- * clients keep working โ and left genuinely absent rather than- * defaulted, because guessing `unmet` here would recreate exactly the- * conflated label the split exists to remove.- */- rejectIntent: z.enum(acceptanceRejectIntents).optional(),- /** Set when the reviewer was responding to a model proposal. */- proposal: z- .object({- adjudication: z.enum(reviewAdjudications),- edit: z.enum(reviewProposalEdits).optional(),- predictionId: z.string(),- })- .optional(),- })- // A reject IS its feedback โ without a note (global, on an annotated- // region, or a screenshot attachment) the next round has nothing to act on.- .refine(- (value) =>- value.action !== 'reject' ||- Boolean(value.comment?.trim()) ||- Boolean(value.annotations?.some((annotation) => annotation.comment?.trim())) ||- Boolean(value.fileIds?.length),- { message: 'Rejecting a check requires a comment' },- ),- )- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- try {- const result = await service.reviewChecks(acceptance.id, {- action: input.action,- annotations: input.annotations,- checkItemIds: input.checkItemIds,- comment: input.comment?.trim() || undefined,- fileIds: input.fileIds,- proposal: input.proposal,- rejectIntent: input.rejectIntent,- });-- return result;- } catch (error) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: error instanceof Error ? error.message : 'Failed to review checks',- });- }- }),-- /**- * Answer a model proposal without ruling on the check itself.- *- * `not-an-issue` and `misidentified` are answers to the MODEL, not to the- * delivery โ the check stays pending and the reviewer still has to judge it.- * That is why this writes to the prediction row rather than going through- * `reviewChecks`: routing a dismissal through the review path would stamp a- * `user_decision` the reviewer never made.- *- * The `confirmed` case does not come here โ it rides along with the reject in- * `reviewChecks`, where the edit diff is available.- */- adjudicateProposal: acceptanceWriteProcedure- .input(- z.object({- adjudication: z.enum(['not-an-issue', 'misidentified'] as const),- id: z.string(),- predictionId: z.string(),- }),- )- .mutation(async ({ ctx, input }) => {- // Authorization only โ the prediction rows are read through their own- // owner-scoped model just below.- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);-- const model = new VerifyReviewPredictionModel(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- );- const prediction = await model.findById(input.predictionId);- if (!prediction) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Proposal not found' });- }-- await model.adjudicate(prediction.id, { adjudication: input.adjudication });- return { success: true };- }),-- /**- * Generate automated review proposals for the checks still awaiting a- * verdict in this acceptance.- *- * An explicit mutation rather than a side effect of `getBundle`: reading a- * report must not spend model budget, and the reviewer needs to be able to- * ask for proposals again after a new round lands.- */- predictReviews: acceptanceWriteProcedure- .input(z.object({ id: z.string() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- const { results, runs } = await service.loadRounds(acceptance.id);- const resultsByRun = new Map<string, typeof results>();- for (const result of results) {- const bucket = resultsByRun.get(result.verifyRunId!) ?? [];- bucket.push(result);- resultsByRun.set(result.verifyRunId!, bucket);- }- const checks = buildAcceptanceCheckUnion(- runs.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),- );-- // Pinned, never the verifier's own model: the predictor reads screenshots,- // and a text-only verifier model silently judges frames it cannot see.- const modelConfig = REVIEW_PREDICT_MODEL_CONFIG;-- const predictor = new VerifyReviewPredictorService(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- );-- // Only checks the reviewer has not already ruled on. Re-judging a settled- // check spends budget to argue with a decision that is already made.- const pending = checks.filter((check) => check.result && !check.result.userDecision);-- // Forget the previous batch's unanswered rows BEFORE responding: the- // client waits for every queued check to carry a recorded attempt, and- // with the old rows still in place that condition holds on the first- // poll โ before a single new judgement has landed.- await predictor.resetPending(- pending.map((check) => check.result!.id),- modelConfig,- );-- // Dispatched AFTER the response, with a ceiling on how many model calls- // are open at once.- //- // Awaiting the fan-out inline could not survive real data: each check is- // a 10-25s multimodal generation, so a thirty-check acceptance ran well- // past any gateway timeout and the reviewer lost every proposal the run- // had already paid for. The ceiling is the other half โ an unbounded- // `Promise.all` opened one generation per check simultaneously, which is- // how a single click turns into a provider rate-limit burst.- //- // The client polls the bundle for the cards to appear; a failed- // individual prediction is recorded as an `errored` row inside `predict`- // rather than thrown, so one bad check cannot abort its neighbours.- after(async () => {- try {- await mapWithConcurrency(pending, REVIEW_PREDICT_CONCURRENCY, (check) =>- predictor.predict({- checkResultId: check.result!.id,- instructionDocumentId: check.planItem?.documentId,- modelConfig,- requirement: acceptance.requirement,- surface: check.surface,- }),- );- } catch (error) {- console.error('[acceptance] review prediction batch failed', error);- }- });-- return { queued: pending.length };- }),-- /**- * Flip who can read the acceptance beyond its creator. Creation defaults are- * scope-dependent (personal โ public, workspace โ private); this is the- * deliberate override.- */- setVisibility: acceptanceWriteProcedure- .input(z.object({ id: z.string(), visibility: z.enum(acceptanceVisibilities) }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- const updated = await service.acceptanceModel.update(acceptance.id, {- visibility: input.visibility,- });- // Cascade to every chained round: each round's report page is its own- // shareable URL, so it must follow the umbrella (clobbering per-round- // overrides on purpose โ the aggregate flip is the deliberate act).- await new VerifyRunModel(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- ).setVisibilityByAcceptance(acceptance.id, input.visibility);- return updated;- }),-- /**- * The user sent the delivery back for a repair round (the in-app ๆๅ้่ท- * dispatch). Stamps the aggregate `repairing` so every surface reflects the- * send-back immediately; the next round's ingest recomputes the status from- * real run state, so a stale stamp cannot stick.- */- markRepairing: acceptanceWriteProcedure- .input(z.object({ id: z.string() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- if (acceptance.status !== 'delivered' && acceptance.status !== 'errored') {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Only a settled acceptance can be sent back (status: ${acceptance.status})`,- });- }- await service.acceptanceModel.updateStatus(acceptance.id, 'repairing');- notifyAcceptance(acceptance.id, 'session', ctx.userId);- }),-- /**- * The user rejects the delivery. An optional comment is a re-tasking input: it is- * recorded on the current round's decision and seeds the next repair/verify- * round. When the rounds name an authoring conversation, the delivery is sent- * straight back to that agent and the acceptance moves to `repairing`; the- * outcome rides on `repairDispatch` so every surface (UI, CLI, external- * callers) reports the same thing. Without one the caller hands the repair- * prompt over itself.- */- reject: acceptanceWriteProcedure- .input(- goalGate.gateDecisionInput.extend({- comment: z.string().trim().max(2000).optional(),- /**- * Send the delivery back to the agent that authored it (default). Pass- * `false` to only record the decision โ the caller hands the repair- * prompt over itself.- */- dispatch: z.boolean().optional(),- }),- )- .mutation(- async ({- ctx,- input,- }): Promise<AcceptanceItem & { repairDispatch: AcceptanceRepairDispatch }> => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- const comment = input.comment || undefined;- const rejected = await goalGate.withGoalGateAnswer(- ctx.serverDB,- service,- acceptance,- 'revise',- { comment, roundId: input.roundId },- () => service.reject(acceptance.id, comment),- );- await settleGoalSignOff(- ctx.serverDB,- acceptance,- 'requestChanges',- input.comment || undefined,- );- // A gate's revision is carried out by the goal: its main Agent rewrites the plan.- if (input.dispatch === false || acceptance.subjectType === 'goal_gate') {- return { ...rejected, repairDispatch: { dispatched: false, reason: 'skipped' } };- }-- const repairDispatch = await dispatchAcceptanceRepair(- ctx,- service,- acceptance,- input.comment || undefined,- );- if (!repairDispatch.dispatched) return { ...rejected, repairDispatch };-- const current = await service.acceptanceModel.findById(acceptance.id);- return { ...(current ?? rejected), repairDispatch };- },- ),-- /**- * Rename the acceptance in the caller's list โ a display-title override kept- * on the aggregate's metadata. The subject's own title (the source topic /- * task / document) is left untouched, so renaming the sidebar entry never- * mutates the origin conversation.- */- rename: acceptanceWriteProcedure- .input(z.object({ id: z.string(), title: z.string().trim().min(1).max(200) }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- return service.acceptanceModel.patchMetadata(acceptance.id, { title: input.title });- }),-- /**- * File the acceptance under a project (or take it out of one) from the list.- * Only the grouping pointer moves: the delivery, its rounds and its subject- * are untouched, so this is reversible and never rewrites history.- *- * The bar is READABLE, not manageable: a delivery may be filed under any- * project the caller can see โ the same set the list already groups by โ so- * a workspace member is not blocked from filing under a teammate's project.- */- setPreviewUrl: acceptanceWriteProcedure- .input(z.object({ id: z.string(), url: previewUrlSchema }))- .mutation(async ({ ctx, input }) => {- const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);- const run = await recordPreviewUrl(ctx.serverDB, acceptance.id, input.url);- if (run) notifyAcceptance(acceptance.id, 'session', ctx.userId);- if (!run)- throw new TRPCError({- code: 'PRECONDITION_FAILED',- message: 'The acceptance has no round to attach a preview to yet',- });- return { previewUrl: input.url, roundIndex: run.roundIndex };- }),-- setProject: acceptanceWriteProcedure- .input(z.object({ id: z.string(), projectId: z.string().nullable() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- if (input.projectId) {- const project = await new ProjectModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- ).findById(input.projectId);- if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });- }-- await service.acceptanceModel.update(acceptance.id, {- projectId: input.projectId,- });- return { success: true };- }),-- /**- * The multi-select twin of `setProject`: file a whole selection under one- * project (or take it out of any) in one action.- *- * The target project is validated ONCE, up front โ a missing project fails- * the sweep wholesale, because every row was headed to the same place. Rows- * keep the batch contract โ one the caller cannot write lands in `failedIds`- * instead of voiding the rest โ but unlike the status sweep there is no- * per-row recomputation, so the whole move is three bounded queries (resolve,- * authorize, bulk update) rather than a round trip per row.- */- setProjectBatch: acceptanceWriteProcedure- .input(- z.object({- ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),- projectId: z.string().nullable(),- }),- )- .mutation(async ({ ctx, input }) => {- if (input.projectId) {- const project = await new ProjectModel(- ctx.serverDB,- ctx.userId,- ctx.workspaceId ?? undefined,- ).findById(input.projectId);- if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });- }-- const ids = [...new Set(input.ids)];- const resolvableIds = ids.filter((id) => isUuid(id));- const rows =- resolvableIds.length > 0- ? await ctx.serverDB.query.acceptances.findMany({- columns: { id: true, userId: true, workspaceId: true },- where: inArray(acceptances.id, resolvableIds),- })- : [];- const manageable = await filterManageableAcceptances(ctx, rows);-- let updatedIds: string[] = [];- if (manageable.length > 0) {- updatedIds = (- await ctx.serverDB- .update(acceptances)- .set({ projectId: input.projectId })- .where(- inArray(- acceptances.id,- manageable.map((row) => row.id),- ),- )- .returning({ id: acceptances.id })- ).map((row) => row.id);- }-- const updatedSet = new Set(updatedIds);- return { failedIds: ids.filter((id) => !updatedSet.has(id)), updated: updatedIds.length };- }),-- /**- * Manually move the acceptance's user-facing lifecycle state from the list โ- * an owner override (mark accepted / closed / rejected, or reopen for another look).- */- updateStatus: acceptanceWriteProcedure- .input(z.object({ id: z.string(), status: acceptanceStatusOverrideSchema }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);-- try {- await applyAcceptanceStatus(ctx.serverDB, service, acceptance, input.status);- } catch (error) {- if (error instanceof TRPCError) throw error;- throw new TRPCError({- code: 'BAD_REQUEST',- message: error instanceof Error ? error.message : 'Failed to update status',- });- }- return { success: true };- }),-- /**- * The multi-select twin of `updateStatus`: sweep a backlog of deliveries into- * accepted / closed in one action.- *- * A row that cannot take the transition (mid-verification, so undecidable;- * or someone else's row in a workspace) is COLLECTED, not thrown: one- * ineligible row must not void the other forty the user just swept, and the- * caller reports what actually landed. Sequential on purpose โ each accept- * recomputes the aggregate and stamps its round, and a sweep is a background- * chore, not a latency-critical path.- */- updateStatusBatch: acceptanceWriteProcedure- .input(- z.object({- ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),- status: acceptanceStatusOverrideSchema,- }),- )- .mutation(async ({ ctx, input }) => {- const failedIds: string[] = [];- let updated = 0;-- for (const id of new Set(input.ids)) {- try {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);- await applyAcceptanceStatus(ctx.serverDB, service, acceptance, input.status);- updated += 1;- } catch (error) {- console.error('[acceptance] batch status update failed for %s', id, error);- failedIds.push(id);- }- }-- return { failedIds, updated };- }),-- purgePreview: acceptanceProcedure- .input(z.object({ ids: z.array(z.string()).min(1).max(PURGE_PREVIEW_LIMIT) }))- .query(async ({ ctx, input }) => {- const ids = [...new Set(input.ids)];- const rows = ids.every(isUuid)- ? await ctx.serverDB.query.acceptances.findMany({ where: inArray(acceptances.id, ids) })- : [];- const readable = await Promise.all(rows.map((row) => canReadAcceptance(ctx, row)));- if (rows.length !== ids.length || readable.includes(false)) {- throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });- }-- const scopes = new Map<string, { ids: string[]; userId: string; workspaceId?: string }>();- for (const row of rows) {- const workspaceId = row.workspaceId ?? undefined;- const key = workspaceId ?? `user:${row.userId}`;- const scope = scopes.get(key) ?? { ids: [], userId: row.userId, workspaceId };- scope.ids.push(row.id);- scopes.set(key, scope);- }- const previews = await Promise.all(- [...scopes.values()].map((scope) =>- previewAcceptancePurge(ctx.serverDB, scope.userId, scope.workspaceId, scope.ids),- ),- );- return previews.reduce(- (total, preview) => ({- bytes: total.bytes + preview.bytes,- fileCount: total.fileCount + preview.fileCount,- files: {- images: total.files.images + preview.files.images,- other: total.files.other + preview.files.other,- videos: total.files.videos + preview.files.videos,- },- rounds: total.rounds + preview.rounds,- }),- { bytes: 0, fileCount: 0, files: { images: 0, other: 0, videos: 0 }, rounds: 0 },- );- }),-- /**- * Delete the acceptance aggregate. By default its chained verify runs detach- * (acceptance_id โ null via the FK's `set null`) so the individual round- * reports stay reachable; `purge` also removes the rounds and the evidence- * files only they referenced.- */- remove: acceptanceWriteProcedure- .input(z.object({ id: z.string(), purge: z.boolean().optional() }))- .mutation(async ({ ctx, input }) => {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- await goalGate.assertNotHoldingRelease(ctx.serverDB, acceptance);-- if (input.purge) {- await purgeAcceptance(- ctx.serverDB,- new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),- acceptance.userId,- acceptance.workspaceId ?? undefined,- acceptance.id,- );- } else {- await service.acceptanceModel.delete(acceptance.id);- }- return { success: true };- }),-- /**- * The multi-select twin of `remove`. Like the batch status sweep, a row the- * caller may not delete is collected rather than thrown, so the rest of the- * selection still goes.- */- removeBatch: acceptanceWriteProcedure- .input(- z.object({- ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),- purge: z.boolean().optional(),- }),- )- .mutation(async ({ ctx, input }) => {- const failedIds: string[] = [];- let deleted = 0;- const fileService = new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);-- await mapWithConcurrency([...new Set(input.ids)], PURGE_BATCH_CONCURRENCY, async (id) => {- try {- const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);- await goalGate.assertNotHoldingRelease(ctx.serverDB, acceptance);- if (input.purge) {- await purgeAcceptance(- ctx.serverDB,- fileService,- acceptance.userId,- acceptance.workspaceId ?? undefined,- acceptance.id,- );- } else {- await service.acceptanceModel.delete(acceptance.id);- }- deleted += 1;- } catch (error) {- console.error('[acceptance] batch delete failed for %s', id, error);- failedIds.push(id);- }- });-- return { deleted, failedIds };- }),-});diff --git a/apps/server/src/routers/lambda/acceptance/bundle.ts b/apps/server/src/routers/lambda/acceptance/bundle.tsnew file mode 100644index 00000000000..ea89358500b--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/bundle.ts@@ -0,0 +1,345 @@+import type { AcceptanceAttachment } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';+import pMap from 'p-map';+import { z } from 'zod';++import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { ScmChangeRequestModel } from '@/database/models/scm';+import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';+import { users } from '@/database/schemas';+import { acceptances } from '@/database/schemas/verify';+import { isUuid } from '@/database/utils/uuid';+import { router } from '@/libs/trpc/lambda';+import {+ AcceptanceService,+ buildAcceptanceCheckUnion,+ buildCheckReviewOverlay,+ createEvidenceFileResolver,+ isCurrentReviewPrediction,+ REVIEW_PREDICT_MODEL_CONFIG,+ shouldSurfaceProposal,+} from '@/server/services/verify';+import { listAcceptancePullRequests } from '@/server/services/verify/acceptancePullRequests';++import { canManageAcceptance } from '../_helpers/acceptanceWriteScope';+import { canReadAcceptance, publicAcceptanceProcedure } from './procedures';++/** Cap on concurrent evidence/attachment file lookups while building one bundle. */+const FILE_META_RESOLVE_CONCURRENCY = 5;++export const bundleRouter = router({+ /**+ * One-shot payload for the acceptance decision workspace: the aggregate, its+ * subject header, the round ledger (each round's run + report), and the+ * cross-round check union โ every check ever planned, with its final verdict,+ * final evidence (file-URL enriched) and round provenance.+ *+ * Public like the verify report viewer: the acceptance URL is meant to be+ * linked from PRs/reports, so a `public` aggregate is readable by anyone+ * holding the id. `private` stays gated to the owner and (for workspace+ * scope) workspace members. A denied read is a NOT_FOUND, never a+ * FORBIDDEN โ existence must not leak through the error code.+ */+ getBundle: publicAcceptanceProcedure+ .input(z.object({ id: z.string() }))+ .query(async ({ ctx, input }) => {+ // Public entry fed by shared links: a chat autolinker can glue trailing+ // CJK punctuation onto the URL, so a malformed uuid must read as+ // NOT_FOUND instead of aborting in Postgres (22P02 โ 500).+ const acceptance = isUuid(input.id)+ ? await ctx.serverDB.query.acceptances.findFirst({+ where: eq(acceptances.id, input.id),+ })+ : undefined;+ if (!acceptance) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });+ }++ const isOwner = Boolean(ctx.userId) && ctx.userId === acceptance.userId;+ if (!isOwner && !(await canReadAcceptance(ctx, acceptance))) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });+ }++ // The one rule the write path enforces โ same helper, so the page can+ // never advertise an action the mutation would refuse.+ const canReview = await canManageAcceptance(ctx, acceptance);++ // Sub-reads (rounds / results / evidence) are ownership-scoped models, so+ // read them AS the aggregate's owner โ same pattern as the evidence file+ // resolver. The visibility gate above is the actual access decision.+ const ownerService = new AcceptanceService(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ );++ const [subject, { evidence, reports, results, runs }, authorRows, changeRequests] =+ await Promise.all([+ ownerService.resolveSubject(acceptance),+ ownerService.loadRounds(acceptance.id),+ // Who delivered this, the way a pull request names its author. A+ // shared link lands on someone else's record, and a record with no+ // name on it reads as nobody's.+ ctx.serverDB+ .select({+ avatar: users.avatar,+ fullName: users.fullName,+ id: users.id,+ username: users.username,+ })+ .from(users)+ .where(eq(users.id, acceptance.userId)),+ // Provider-verified PRs that deliver it. Owned by the acceptance, not+ // by a round, so one opened after the last round still shows.+ ScmChangeRequestModel.listByAcceptance(ctx.serverDB, acceptance.id),+ ]);+ const author = authorRows[0] ?? null;++ const flowData = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).list(+ acceptance.id,+ );+ const flowResultIds = new Set(+ flowData.flatMap((flow) =>+ flow.versions.flatMap((version) =>+ version.runs.flatMap((run) => run.attempts.map((attempt) => attempt.checkResultId)),+ ),+ ),+ );+ const resultsByRun = new Map<string, typeof results>();+ for (const result of results) {+ const key = result.verifyRunId!;+ const bucket = resultsByRun.get(key) ?? [];+ bucket.push(result);+ resultsByRun.set(key, bucket);+ }++ const checks = buildAcceptanceCheckUnion(+ runs.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),+ acceptance.metadata?.checkGrouping?.groups,+ );++ // Enrich the evidence backing every executed timeline step โ the final+ // round's artifacts render inline on the row; earlier steps' artifacts+ // render inside the check's iteration-history timeline.+ const resolveFileMeta = createEvidenceFileResolver(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ );+ const timelineResultIds = new Set(+ checks.flatMap((check) => check.timeline.map((entry) => entry.resultId)),+ );+ const enriched = await pMap(+ evidence.filter(+ (e) => timelineResultIds.has(e.checkResultId) || flowResultIds.has(e.checkResultId),+ ),+ async (e) => ({ ...e, ...(await resolveFileMeta(e.fileId ?? null)) }),+ { concurrency: FILE_META_RESOLVE_CONCURRENCY },+ );+ const evidenceByResult = new Map<string, typeof enriched>();+ for (const e of enriched) {+ const bucket = evidenceByResult.get(e.checkResultId) ?? [];+ bucket.push(e);+ evidenceByResult.set(e.checkResultId, bucket);+ }++ // Resolve the files backing user feedback (uploaded/pasted screenshots)+ // to URLs with the same owner-scoped resolver the evidence uses โ one+ // batch for every attachment id across check rejects and group feedback.+ const attachmentIds = new Set<string>(+ flowData.flatMap((flow) =>+ flow.versions.flatMap((version) =>+ version.runs.flatMap((run) =>+ run.attempts.flatMap((attempt) => attempt.reviewDetail?.fileIds ?? []),+ ),+ ),+ ),+ );+ for (const result of results)+ for (const id of result.userDecisionDetail?.fileIds ?? []) attachmentIds.add(id);+ for (const run of runs)+ for (const entry of run.decisionDetail?.groupFeedback ?? [])+ for (const id of entry.fileIds ?? []) attachmentIds.add(id);+ const attachmentById = new Map<string, AcceptanceAttachment>();+ await pMap(+ attachmentIds,+ async (id) => {+ const meta = await resolveFileMeta(id);+ attachmentById.set(id, { id, name: meta.fileName ?? undefined, url: meta.fileUrl });+ },+ { concurrency: FILE_META_RESOLVE_CONCURRENCY },+ );+ const toAttachments = (fileIds?: string[]): AcceptanceAttachment[] | undefined => {+ if (!fileIds?.length) return undefined;+ const resolved = fileIds+ .map((id) => attachmentById.get(id))+ .filter((a): a is AcceptanceAttachment => Boolean(a));+ return resolved.length > 0 ? resolved : undefined;+ };++ const reportsByRun = new Map(reports.map((r) => [r.verifyRunId!, r]));+ // What each round actually spent. Owner-only: cost is the author's+ // operating detail, not something a shared link should expose.+ // `isOwner` already implies a signed-in viewer; the explicit id check is+ // what narrows it for the model, which is owner-scoped by construction.+ const usageByOperation =+ isOwner && ctx.userId+ ? await new AgentOperationModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined)+ .findUsageByOperations(+ runs.flatMap((run) => (run.operationId ? [run.operationId] : [])),+ )+ .catch(() => new Map<string, { cost: number; tokens: number }>())+ : new Map<string, { cost: number; tokens: number }>();+ const rounds = runs.map((run) => {+ // `origin` points at the author's private topic/agent โ never hand it+ // to a visitor holding nothing but the shared link.+ let publicRun = run;+ if (!isOwner && run.metadata?.origin) {+ const { origin: _origin, ...publicMetadata } = run.metadata;+ publicRun = { ...run, metadata: publicMetadata };+ }+ // Enrich group feedback with resolved attachment URLs for the client.+ const groupFeedback = publicRun.decisionDetail?.groupFeedback;+ if (groupFeedback?.some((entry) => entry.fileIds?.length)) {+ publicRun = {+ ...publicRun,+ decisionDetail: {+ ...publicRun.decisionDetail,+ groupFeedback: groupFeedback.map((entry) => {+ const attachments = toAttachments(entry.fileIds);+ return attachments ? { ...entry, attachments } : entry;+ }),+ },+ };+ }+ return {+ report: reportsByRun.get(run.id) ?? null,+ run: publicRun,+ usage: (run.operationId ? usageByOperation.get(run.operationId) : undefined) ?? null,+ };+ });+ const latestReport = [...rounds].reverse().find((r) => r.report)?.report ?? null;++ // The authoring conversation (agent + topic), resolved for the header โ+ // owner-only, same redaction rule as `run.metadata.origin`.+ const origin = isOwner ? await ownerService.resolveOrigin(runs) : null;++ const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;+ const resultsById = new Map(results.map((result) => [result.id, result]));++ // Automated proposals are the reviewer's working state, not published+ // content โ a shared acceptance URL (the whole point of `public`+ // visibility) must not show visitors "an AI thinks this is broken".+ // Scoped to whoever may REVIEW, not to the creator: the predict button is+ // gated the same way, and a reviewer who can spend the model budget but+ // never receives a `predictionStatus` polls until it times out, then+ // reports the work as still running after it finished.+ const predictions = canReview+ ? await new VerifyReviewPredictionModel(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ ).listByRuns(runs.map((run) => run.id))+ : [];+ // Keyed by the concrete check RESULT, never by the union row's id. The+ // union exposes `sourceCriterionId ?? checkItemId` as `check.id` so a+ // renamed check folds across rounds โ but a prediction is stored against+ // the result it judged. Keying on the logical id silently misses every+ // plan that uses a distinct snapshot id: generation reports success and+ // no card ever renders.+ const predictionByResult = new Map<string, (typeof predictions)[number]>();+ // Goal reviews may use the owner's configured model. Their persisted ids+ // identify the actual automatic decision without admitting unrelated rows.+ const automaticPredictionIds = new Set(+ runs.flatMap((run) => run.metadata?.goalReview?.predictionIds ?? []),+ );+ // Newest-first from the model, so the first write per check item wins and+ // later (older) rows are ignored.+ for (const prediction of predictions) {+ // Rows from an earlier pin (another model / prompt version) stay in+ // the table for the comparison set but are not this page's reviewer.+ if (+ !isCurrentReviewPrediction(+ prediction,+ REVIEW_PREDICT_MODEL_CONFIG,+ automaticPredictionIds,+ )+ )+ continue;+ if (!predictionByResult.has(prediction.checkResultId)) {+ predictionByResult.set(prediction.checkResultId, prediction);+ }+ }++ return {+ author,+ pullRequests: listAcceptancePullRequests(changeRequests, acceptance.metadata?.pullRequests),+ flows: flowData.map((flow) => ({+ ...flow,+ versions: flow.versions.map((version) => ({+ ...version,+ runs: version.runs.map((run) => ({+ ...run,+ attempts: run.attempts.map((attempt) => ({+ ...attempt,+ reviewAttachments: toAttachments(attempt.reviewDetail?.fileIds),+ evidence: evidenceByResult.get(attempt.checkResultId) ?? [],+ })),+ })),+ })),+ })),+ acceptance,+ canReview,+ isOwner,+ checks: checks.map((check) => {+ // Projected from the result rows' user_decision(+detail) โ the+ // events carry no user ids, so nothing needs redacting here.+ const { reviews, userReview } = buildCheckReviewOverlay(+ check,+ resultsById,+ currentRoundIndex,+ );+ // The standing verdict mirrors the latest review โ resolve its+ // attachments too so the row's feedback card can render them.+ const resolvedReviews = reviews.map((review) => {+ const attachments = toAttachments(review.fileIds);+ return attachments ? { ...review, attachments } : review;+ });+ const latestAttachments = toAttachments(reviews.at(-1)?.fileIds);+ const prediction = check.result ? predictionByResult.get(check.result.id) : undefined;+ // A STALE review is last round's rejection carried forward as history;+ // THIS round's result is undecided. Treating it as a current verdict+ // hid the proposal on exactly the repair round where the reviewer has+ // to judge again.+ const settled = Boolean(userReview && !userReview.stale);+ return {+ ...check,+ evidence: check.result ? (evidenceByResult.get(check.result.id) ?? []) : [],+ prediction:+ prediction && shouldSurfaceProposal(prediction, settled) ? prediction : null,+ // The card above is gated to actionable rejects, but the FACT that+ // the predictor finished with this check must stay visible: an+ // `accept`, a skip and an error all render no card, and without+ // this the predict button's poll cannot tell "still running" from+ // "reviewed, nothing to say" โ it spins to timeout on a clean bill.+ predictionStatus: prediction?.status ?? null,+ reviews: resolvedReviews,+ timeline: check.timeline.map((entry) => ({+ ...entry,+ evidence: evidenceByResult.get(entry.resultId) ?? [],+ })),+ userReview:+ userReview && latestAttachments+ ? { ...userReview, attachments: latestAttachments }+ : userReview,+ };+ }),+ latestReport,+ origin,+ rounds,+ subject,+ };+ }),+});diff --git a/apps/server/src/routers/lambda/acceptance/deliveryLinks.ts b/apps/server/src/routers/lambda/acceptance/deliveryLinks.tsnew file mode 100644index 00000000000..1ee04ddf436--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/deliveryLinks.ts@@ -0,0 +1,124 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { VerifyRunModel } from '@/database/models/verifyRun';+import { router } from '@/libs/trpc/lambda';+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';+import { parseChangeRequestUrl } from '@/server/services/scm/changeRequestUrl';+import {+ addPullRequestLink,+ removePullRequestLink,+ updateAcceptancePullRequests,+} from '@/server/services/verify/acceptancePullRequests';++import { previewUrlSchema, recordPreviewUrl } from '../_helpers/acceptancePreviewUrl';+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';+import { acceptanceWriteProcedure, resolveAcceptanceForWrite } from './procedures';++export const deliveryLinksRouter = router({+ /**+ * Chain an existing verify run onto an acceptance as its next round.+ * Idempotent when the run is already chained to the same acceptance (the+ * ingest CLI re-runs against a remembered session).+ */+ attachRun: acceptanceWriteProcedure+ .input(z.object({ acceptanceId: z.string(), verifyRunId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.acceptanceId);++ // The attach rewrites the RUN's acceptance_id/round_index too โ and a+ // workspace-visible run is not necessarily the caller's. Creator-scope it+ // like every other verify write, or a member could chain another+ // member's report onto their aggregate.+ const run = await new VerifyRunModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).findById(input.verifyRunId);+ if (!run) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification run not found' });+ }+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');++ try {+ return await service.attachRun(run.id, acceptance.id);+ } catch (error) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: error instanceof Error ? error.message : 'Failed to attach run',+ });+ }+ }),+ /**+ * Record that a pull request delivers this acceptance. The link lives on the+ * acceptance, not on a round: the pull request usually opens after the+ * rounds that verified it, and stacked pull requests share one acceptance.+ *+ * Stored on the acceptance rather than on the shared `scm_change_requests`+ * row: that row is keyed globally and owned by whichever tenant the+ * provider routes the PR to, so a pasted URL must not claim it. A hand+ * link is display-only and never drives merge โ accepted.+ */+ linkPullRequest: acceptanceWriteProcedure+ .input(+ z.object({+ id: z.string(),+ title: z.string().trim().min(1).max(500).optional(),+ url: z.string().max(2000),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ const parsed = parseChangeRequestUrl(input.url);+ if (!parsed) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message:+ 'Expected a GitHub pull request URL, e.g. https://github.com/owner/repo/pull/123',+ });+ }++ await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>+ addPullRequestLink(links, parsed, input.title),+ );+ return parsed;+ }),+ unlinkPullRequest: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), url: z.string().max(2000) }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ const parsed = parseChangeRequestUrl(input.url);+ const pullRequests = parsed+ ? await updateAcceptancePullRequests(ctx.serverDB, acceptance.id, (links) =>+ removePullRequestLink(links, parsed),+ )+ : null;+ if (!pullRequests) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Linked pull request not found' });+ }++ return { success: true };+ }),+ /**+ * File the acceptance under a project (or take it out of one) from the list.+ * Only the grouping pointer moves: the delivery, its rounds and its subject+ * are untouched, so this is reversible and never rewrites history.+ *+ * The bar is READABLE, not manageable: a delivery may be filed under any+ * project the caller can see โ the same set the list already groups by โ so+ * a workspace member is not blocked from filing under a teammate's project.+ */+ setPreviewUrl: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), url: previewUrlSchema }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ const run = await recordPreviewUrl(ctx.serverDB, acceptance.id, input.url);+ if (run) notifyAcceptance(acceptance.id, 'session', ctx.userId);+ if (!run)+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'The acceptance has no round to attach a preview to yet',+ });+ return { previewUrl: input.url, roundIndex: run.roundIndex };+ }),+});diff --git a/apps/server/src/routers/lambda/acceptance/flow.ts b/apps/server/src/routers/lambda/acceptance/flow.tsnew file mode 100644index 00000000000..28a20bf6b7f--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/flow.ts@@ -0,0 +1,149 @@+import { verifyCheckDefinitionSchema } from '@lobechat/types';+import { z } from 'zod';++import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';+import { router } from '@/libs/trpc/lambda';++import { acceptanceWriteProcedure, resolveAcceptanceForWrite } from './procedures';+import { reviewAnnotationsSchema } from './schemas';++const flowDefinitionSchema = z.object({+ title: z.string().min(1).max(200),+ entryNodeId: z.string().uuid(),+ nodes: z+ .array(+ z.object({+ id: z.string().uuid(),+ criterionId: z.string().uuid().optional(),+ subFlowId: z.string().uuid().optional(),+ check: z+ .object({+ id: z.string().uuid(),+ title: z.string().min(1).max(200),+ description: z.string().optional(),+ definition: verifyCheckDefinitionSchema,+ })+ .optional(),+ overrides: z+ .object({+ required: z.boolean().optional(),+ onFail: z.enum(['manual', 'auto_repair']).optional(),+ fixtureData: z.record(z.string(), z.record(z.string(), z.unknown())).optional(),+ })+ .optional(),+ }),+ )+ .min(1)+ .max(100),+ edges: z+ .array(+ z.object({+ id: z.string().uuid(),+ sourceNodeId: z.string().uuid(),+ targetNodeId: z.string().uuid(),+ trigger: z.string().min(1).max(1000),+ condition: z.string().max(2000).optional(),+ required: z.boolean(),+ }),+ )+ .max(300),+});++export const flowRouter = router({+ publishFlow: acceptanceWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ definition: flowDefinitionSchema,+ flowId: z.string().uuid().optional(),+ expectedHash: z.string().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ return new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).publish(+ input.id,+ input.definition,+ input.flowId,+ input.expectedHash,+ );+ }),+ deleteFlow: acceptanceWriteProcedure+ .input(z.object({ id: z.string().uuid(), flowId: z.string().uuid() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);+ const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).delete(+ input.id,+ input.flowId,+ );+ await service.recomputeStatus(input.id);+ return result;+ }),+ startFlow: acceptanceWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ flowId: z.string().uuid(),+ sourceRunId: z.string().uuid().optional(),+ verifyRunId: z.string().uuid().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);+ const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).start(+ input.id,+ input.flowId,+ input.verifyRunId,+ input.sourceRunId,+ );+ await service.recomputeStatus(input.id);+ return result;+ }),+ recordFlowStep: acceptanceWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ verifyRunId: z.string().uuid(),+ checkItemId: z.string().min(1),+ observation: z.string().min(1).max(20000),+ verdict: z.enum(['passed', 'failed', 'uncertain', 'blocked']),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ return new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).record(input.id, input);+ }),+ completeFlow: acceptanceWriteProcedure+ .input(z.object({ id: z.string().uuid(), verifyRunId: z.string().uuid() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);+ const result = await new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).complete(+ input.id,+ input.verifyRunId,+ );+ await service.recomputeStatus(input.id);+ return result;+ }),+ reviewFlowStep: acceptanceWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ attemptId: z.string().uuid(),+ review: z.enum(['accepted', 'rejected']),+ comment: z.string().max(4000),+ annotations: reviewAnnotationsSchema,+ fileIds: z.array(z.string()).max(10).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);+ return new AcceptanceFlowModel(ctx.serverDB, acceptance.userId).review(+ input.id,+ input.attemptId,+ input.review,+ input.comment,+ ctx.userId,+ { annotations: input.annotations, fileIds: input.fileIds },+ );+ }),+});diff --git a/apps/server/src/routers/lambda/acceptance/index.procedures.test.ts b/apps/server/src/routers/lambda/acceptance/index.procedures.test.tsnew file mode 100644index 00000000000..dece3198859--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/index.procedures.test.ts@@ -0,0 +1,65 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { acceptanceRouter } from '.';++/**+ * Pins the router's public surface: every procedure path, its kind, and its+ * middleware chain length (which encodes the procedure builder and its input+ * parsers). Splitting the router across files must keep all three.+ */+describe('acceptanceRouter procedures', () => {+ const procedures = (acceptanceRouter as any)._def.procedures as Record<string, any>;++ it('exposes exactly the expected procedure paths', () => {+ expect(Object.keys(procedures).sort()).toEqual(expected().map(([name]) => name));+ });++ it.each(expected())('%s is a %s with %i middlewares', (name, type, middlewares) => {+ expect(procedures[name]._def.type).toBe(type);+ expect(procedures[name]._def.middlewares).toHaveLength(middlewares);+ });+});++function expected(): Array<+ [name: string, type: 'mutation' | 'query' | 'subscription', middlewares: number]+> {+ return [+ ['accept', 'mutation', 13],+ ['addGroupFeedback', 'mutation', 13],+ ['adjudicateProposal', 'mutation', 13],+ ['attachRun', 'mutation', 13],+ ['completeFlow', 'mutation', 13],+ ['deleteFlow', 'mutation', 13],+ ['ensure', 'mutation', 13],+ ['getBundle', 'query', 7],+ ['getBySubject', 'query', 12],+ ['linkPullRequest', 'mutation', 13],+ ['list', 'query', 12],+ ['listPage', 'query', 12],+ ['listStatusesBySubjects', 'query', 12],+ ['markRepairing', 'mutation', 13],+ ['merge', 'mutation', 13],+ ['predictReviews', 'mutation', 13],+ ['publishFlow', 'mutation', 13],+ ['purgePreview', 'query', 12],+ ['recordFlowStep', 'mutation', 13],+ ['regroupChecks', 'mutation', 13],+ ['reject', 'mutation', 13],+ ['remove', 'mutation', 13],+ ['removeBatch', 'mutation', 13],+ ['rename', 'mutation', 13],+ ['reviewChecks', 'mutation', 13],+ ['reviewFlowStep', 'mutation', 13],+ ['saveChecklist', 'mutation', 13],+ ['saveGoal', 'mutation', 13],+ ['setPreviewUrl', 'mutation', 13],+ ['setProject', 'mutation', 13],+ ['setProjectBatch', 'mutation', 13],+ ['setVisibility', 'mutation', 13],+ ['startFlow', 'mutation', 13],+ ['unlinkPullRequest', 'mutation', 13],+ ['updateStatus', 'mutation', 13],+ ['updateStatusBatch', 'mutation', 13],+ ];+}diff --git a/apps/server/src/routers/lambda/acceptance/index.ts b/apps/server/src/routers/lambda/acceptance/index.tsnew file mode 100644index 00000000000..34096419220--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/index.ts@@ -0,0 +1,19 @@+import { mergeRouters } from '@/libs/trpc/lambda';++import { bundleRouter } from './bundle';+import { deliveryLinksRouter } from './deliveryLinks';+import { flowRouter } from './flow';+import { listManagementRouter } from './listManagement';+import { reviewRouter } from './review';+import { subjectRouter } from './subject';++export { resolveAcceptanceForWrite } from './procedures';++export const acceptanceRouter = mergeRouters(+ reviewRouter,+ flowRouter,+ deliveryLinksRouter,+ subjectRouter,+ bundleRouter,+ listManagementRouter,+);diff --git a/apps/server/src/routers/lambda/acceptance/listManagement.ts b/apps/server/src/routers/lambda/acceptance/listManagement.tsnew file mode 100644index 00000000000..d6369bd71f4--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/listManagement.ts@@ -0,0 +1,410 @@+import { acceptanceVisibilities } from '@lobechat/const/verify';+import { TRPCError } from '@trpc/server';+import { inArray } from 'drizzle-orm';+import pMap from 'p-map';+import { z } from 'zod';++import { ProjectModel } from '@/database/models/project';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type { AcceptanceItem } from '@/database/schemas/verify';+import { acceptances } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';+import { isUuid } from '@/database/utils/uuid';+import { router } from '@/libs/trpc/lambda';+import { FileService } from '@/server/services/file';+import {+ mapWithConcurrency,+ previewAcceptancePurge,+ purgeAcceptance,+} from '@/server/services/verify';++import {+ acceptanceStatusOverrideSchema,+ applyAcceptanceStatus,+} from '../_helpers/acceptanceStatus';+import { filterManageableAcceptances } from '../_helpers/acceptanceWriteScope';+import * as goalGate from '../_helpers/goalGateAcceptance';+import {+ acceptanceProcedure,+ acceptanceWriteProcedure,+ canReadAcceptance,+ resolveAcceptanceForWrite,+} from './procedures';++/**+ * The list panel's narrowing, shared by the flat and paged reads. `projectId:+ * null` asks for acceptances filed under no project.+ */+const acceptanceListFiltersSchema = z.object({+ filter: z.enum(['active', 'all', 'completed']).optional(),+ projectId: z.string().nullable().optional(),+ scope: z.enum(['all', 'created', 'participated']).optional(),+ source: z.enum(['all', 'goal', 'standalone', 'task', 'topic']).optional(),+});++/**+ * Tag each list row with whether the caller may rename, refile, re-status or+ * delete it. "Participated" rows are often someone else's, so the panel must+ * know which menus to offer instead of letting the write fail as NOT_FOUND.+ */+const withManageFlag = async <T extends Pick<AcceptanceItem, 'id' | 'userId' | 'workspaceId'>>(+ ctx: { serverDB: LobeChatDatabase; userId: string },+ rows: T[],+): Promise<Array<T & { canManage: boolean }>> => {+ const manageable = new Set((await filterManageableAcceptances(ctx, rows)).map((row) => row.id));+ return rows.map((row) => ({ ...row, canManage: manageable.has(row.id) }));+};++/** Max rows one multi-select sweep may touch โ the list itself is capped at 200. */+const ACCEPTANCE_BATCH_LIMIT = 200;++const PURGE_BATCH_CONCURRENCY = 4;++const PURGE_PREVIEW_LIMIT = 20;++export const listManagementRouter = router({+ /**+ * Recent acceptances (with subject headers), newest first โ list panel + CLI.+ *+ * `limit` is capped rather than open: the read resolves each row's subject+ * title one by one, so an unbounded window would fan out. The merge picker+ * asks for the wide end because a target it cannot list is a target the user+ * cannot merge into.+ */+ list: acceptanceProcedure+ .input(+ acceptanceListFiltersSchema+ .extend({+ limit: z.number().int().min(1).max(200).optional(),+ q: z.string().max(200).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) =>+ withManageFlag(ctx, await ctx.acceptanceService.listWithSubjects(input)),+ ),+ /**+ * One keyset page of the same feed โ what the list panel scrolls.+ *+ * Speaks the same filter vocabulary as `list`, applied in the query, so a+ * page of "in progress" is a full page of in-progress rows. There is no+ * paged search on purpose: a title search must span the whole owned set,+ * which `list` already does โ the panel asks that one while a query is live.+ */+ listPage: acceptanceProcedure+ .input(+ acceptanceListFiltersSchema+ .extend({+ cursor: z.string().optional(),+ limit: z.number().int().min(1).max(100).optional(),+ })+ .optional(),+ )+ .query(async ({ ctx, input }) => {+ const page = await ctx.acceptanceService.listPageWithSubjects({ ...input });+ return { ...page, items: await withManageFlag(ctx, page.items) };+ }),+ /**+ * Fold one acceptance into another: the source's verification rounds (and+ * with them its checks, verdicts and evidence) re-chain onto the target, and+ * the source entry is deleted.+ *+ * Both sides are creator-scoped like every other verify write โ a merge+ * rewrites BOTH aggregates, so a workspace member must not be able to fold+ * another member's acceptance into (or out of) their own.+ */+ merge: acceptanceWriteProcedure+ .input(z.object({ sourceId: z.string(), targetId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ // A merge rewrites BOTH aggregates, so both have to authorize; the source+ // owns the rows that move, so its scope is the one the write runs in.+ const { acceptance: source, service } = await resolveAcceptanceForWrite(ctx, input.sourceId);+ const { acceptance: target } = await resolveAcceptanceForWrite(ctx, input.targetId);+ await goalGate.assertNotHoldingRelease(ctx.serverDB, source);+ await goalGate.assertNotHoldingRelease(ctx.serverDB, target);++ try {+ return await service.merge(source.id, target.id);+ } catch (error) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: error instanceof Error ? error.message : 'Failed to merge acceptance',+ });+ }+ }),+ /**+ * Flip who can read the acceptance beyond its creator. Creation defaults are+ * scope-dependent (personal โ public, workspace โ private); this is the+ * deliberate override.+ */+ setVisibility: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), visibility: z.enum(acceptanceVisibilities) }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ const updated = await service.acceptanceModel.update(acceptance.id, {+ visibility: input.visibility,+ });+ // Cascade to every chained round: each round's report page is its own+ // shareable URL, so it must follow the umbrella (clobbering per-round+ // overrides on purpose โ the aggregate flip is the deliberate act).+ await new VerifyRunModel(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ ).setVisibilityByAcceptance(acceptance.id, input.visibility);+ return updated;+ }),+ /**+ * Rename the acceptance in the caller's list โ a display-title override kept+ * on the aggregate's metadata. The subject's own title (the source topic /+ * task / document) is left untouched, so renaming the sidebar entry never+ * mutates the origin conversation.+ */+ rename: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), title: z.string().trim().min(1).max(200) }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ return service.acceptanceModel.patchMetadata(acceptance.id, { title: input.title });+ }),+ setProject: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), projectId: z.string().nullable() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ if (input.projectId) {+ const project = await new ProjectModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).findById(input.projectId);+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });+ }++ await service.acceptanceModel.update(acceptance.id, {+ projectId: input.projectId,+ });+ return { success: true };+ }),+ /**+ * The multi-select twin of `setProject`: file a whole selection under one+ * project (or take it out of any) in one action.+ *+ * The target project is validated ONCE, up front โ a missing project fails+ * the sweep wholesale, because every row was headed to the same place. Rows+ * keep the batch contract โ one the caller cannot write lands in `failedIds`+ * instead of voiding the rest โ but unlike the status sweep there is no+ * per-row recomputation, so the whole move is three bounded queries (resolve,+ * authorize, bulk update) rather than a round trip per row.+ */+ setProjectBatch: acceptanceWriteProcedure+ .input(+ z.object({+ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),+ projectId: z.string().nullable(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ if (input.projectId) {+ const project = await new ProjectModel(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).findById(input.projectId);+ if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });+ }++ const ids = [...new Set(input.ids)];+ const resolvableIds = ids.filter((id) => isUuid(id));+ const rows =+ resolvableIds.length > 0+ ? await ctx.serverDB.query.acceptances.findMany({+ columns: { id: true, userId: true, workspaceId: true },+ where: inArray(acceptances.id, resolvableIds),+ })+ : [];+ const manageable = await filterManageableAcceptances(ctx, rows);++ let updatedIds: string[] = [];+ if (manageable.length > 0) {+ updatedIds = (+ await ctx.serverDB+ .update(acceptances)+ .set({ projectId: input.projectId })+ .where(+ inArray(+ acceptances.id,+ manageable.map((row) => row.id),+ ),+ )+ .returning({ id: acceptances.id })+ ).map((row) => row.id);+ }++ const updatedSet = new Set(updatedIds);+ return { failedIds: ids.filter((id) => !updatedSet.has(id)), updated: updatedIds.length };+ }),+ /**+ * Manually move the acceptance's user-facing lifecycle state from the list โ+ * an owner override (mark accepted / closed / rejected, or reopen for another look).+ */+ updateStatus: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), status: acceptanceStatusOverrideSchema }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ try {+ await applyAcceptanceStatus(ctx.serverDB, service, acceptance, input.status);+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: error instanceof Error ? error.message : 'Failed to update status',+ });+ }+ return { success: true };+ }),+ /**+ * The multi-select twin of `updateStatus`: sweep a backlog of deliveries into+ * accepted / closed in one action.+ *+ * A row that cannot take the transition (mid-verification, so undecidable;+ * or someone else's row in a workspace) is COLLECTED, not thrown: one+ * ineligible row must not void the other forty the user just swept, and the+ * caller reports what actually landed. Sequential on purpose โ each accept+ * recomputes the aggregate and stamps its round, and a sweep is a background+ * chore, not a latency-critical path.+ */+ updateStatusBatch: acceptanceWriteProcedure+ .input(+ z.object({+ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),+ status: acceptanceStatusOverrideSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const failedIds: string[] = [];+ let updated = 0;++ for (const id of new Set(input.ids)) {+ try {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);+ await applyAcceptanceStatus(ctx.serverDB, service, acceptance, input.status);+ updated += 1;+ } catch (error) {+ console.error('[acceptance] batch status update failed for %s', id, error);+ failedIds.push(id);+ }+ }++ return { failedIds, updated };+ }),+ purgePreview: acceptanceProcedure+ .input(z.object({ ids: z.array(z.string()).min(1).max(PURGE_PREVIEW_LIMIT) }))+ .query(async ({ ctx, input }) => {+ const ids = [...new Set(input.ids)];+ const rows = ids.every(isUuid)+ ? await ctx.serverDB.query.acceptances.findMany({ where: inArray(acceptances.id, ids) })+ : [];+ const readable = await pMap(rows, (row) => canReadAcceptance(ctx, row), {+ concurrency: PURGE_BATCH_CONCURRENCY,+ });+ if (rows.length !== ids.length || readable.includes(false)) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });+ }++ const scopes = new Map<string, { ids: string[]; userId: string; workspaceId?: string }>();+ for (const row of rows) {+ const workspaceId = row.workspaceId ?? undefined;+ const key = workspaceId ?? `user:${row.userId}`;+ const scope = scopes.get(key) ?? { ids: [], userId: row.userId, workspaceId };+ scope.ids.push(row.id);+ scopes.set(key, scope);+ }+ const previews = await pMap(+ scopes.values(),+ (scope) => previewAcceptancePurge(ctx.serverDB, scope.userId, scope.workspaceId, scope.ids),+ { concurrency: PURGE_BATCH_CONCURRENCY },+ );+ return previews.reduce(+ (total, preview) => ({+ bytes: total.bytes + preview.bytes,+ fileCount: total.fileCount + preview.fileCount,+ files: {+ images: total.files.images + preview.files.images,+ other: total.files.other + preview.files.other,+ videos: total.files.videos + preview.files.videos,+ },+ rounds: total.rounds + preview.rounds,+ }),+ { bytes: 0, fileCount: 0, files: { images: 0, other: 0, videos: 0 }, rounds: 0 },+ );+ }),+ /**+ * Delete the acceptance aggregate. By default its chained verify runs detach+ * (acceptance_id โ null via the FK's `set null`) so the individual round+ * reports stay reachable; `purge` also removes the rounds and the evidence+ * files only they referenced.+ */+ remove: acceptanceWriteProcedure+ .input(z.object({ id: z.string(), purge: z.boolean().optional() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);+ await goalGate.assertNotHoldingRelease(ctx.serverDB, acceptance);++ if (input.purge) {+ await purgeAcceptance(+ ctx.serverDB,+ new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ acceptance.id,+ );+ } else {+ await service.acceptanceModel.delete(acceptance.id);+ }+ return { success: true };+ }),+ /**+ * The multi-select twin of `remove`. Like the batch status sweep, a row the+ * caller may not delete is collected rather than thrown, so the rest of the+ * selection still goes.+ */+ removeBatch: acceptanceWriteProcedure+ .input(+ z.object({+ ids: z.array(z.string()).min(1).max(ACCEPTANCE_BATCH_LIMIT),+ purge: z.boolean().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const failedIds: string[] = [];+ let deleted = 0;+ const fileService = new FileService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);++ await mapWithConcurrency([...new Set(input.ids)], PURGE_BATCH_CONCURRENCY, async (id) => {+ try {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);+ await goalGate.assertNotHoldingRelease(ctx.serverDB, acceptance);+ if (input.purge) {+ await purgeAcceptance(+ ctx.serverDB,+ fileService,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ acceptance.id,+ );+ } else {+ await service.acceptanceModel.delete(acceptance.id);+ }+ deleted += 1;+ } catch (error) {+ console.error('[acceptance] batch delete failed for %s', id, error);+ failedIds.push(id);+ }+ });++ return { deleted, failedIds };+ }),+});diff --git a/apps/server/src/routers/lambda/acceptance/procedures.ts b/apps/server/src/routers/lambda/acceptance/procedures.tsnew file mode 100644index 00000000000..052058a90f1--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/procedures.ts@@ -0,0 +1,95 @@+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';++import {+ requireWorkspaceRoleWhenScoped,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';+import type { AcceptanceItem } from '@/database/schemas/verify';+import { acceptances } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';+import { isUuid } from '@/database/utils/uuid';+import { publicProcedure } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { AcceptanceService } from '@/server/services/verify';++import { canManageAcceptance } from '../_helpers/acceptanceWriteScope';++/** Reads addressed purely by acceptance id โ visibility is checked in the handler. */+export const publicAcceptanceProcedure = publicProcedure.use(serverDatabase);++export const acceptanceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ acceptanceService: new AcceptanceService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ },+ });+});++// Writes: workspace mode requires at least the member role (viewers are+// read-only); personal mode passes through unrestricted.+export const acceptanceWriteProcedure = acceptanceProcedure.use(+ requireWorkspaceRoleWhenScoped('member'),+);++/**+ * Resolve an acceptance for WRITING, with a service bound to the scope the row+ * actually lives in.+ *+ * Every model write is scoped by `buildWorkspaceWhere`, and `acceptances`+ * carries a `visibility` column โ so that predicate narrows PRIVATE rows to+ * `userId = <bound user>`, and workspace acceptances default to private. A+ * service bound to the caller therefore cannot resolve a teammate's row at all,+ * and the write dies as `NOT_FOUND` after authorization already said yes.+ *+ * So the service is bound to the row's OWNER โ the one binding that resolves it+ * โ while the acting user is carried separately, because decisions record+ * `decidedBy` and an audit trail that credits a teammate's verdict to the+ * author is worse than one nobody can sign.+ */+export const resolveAcceptanceForWrite = async (+ ctx: { serverDB: LobeChatDatabase; userId: string },+ id: string,+): Promise<{ acceptance: AcceptanceItem; service: AcceptanceService }> => {+ const acceptance = isUuid(id)+ ? await ctx.serverDB.query.acceptances.findFirst({ where: eq(acceptances.id, id) })+ : undefined;++ // An unauthorized caller gets the same answer as a missing row: the existence+ // of someone else's delivery is not ours to disclose.+ if (!acceptance || !(await canManageAcceptance(ctx, acceptance))) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });+ }++ return {+ acceptance,+ service: new AcceptanceService(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ { actorUserId: ctx.userId },+ ),+ };+};++export const canReadAcceptance = async (+ ctx: { serverDB: LobeChatDatabase; userId?: string | null },+ acceptance: AcceptanceItem,+) => {+ if (ctx.userId && ctx.userId === acceptance.userId) return true;+ if (acceptance.visibility === 'public') return true;+ if (!ctx.userId || !acceptance.workspaceId) return false;+ // Membership in the acceptance's OWN workspace โ not the viewer's currently+ // active one, which may be a different workspace entirely.+ const member = await new WorkspaceMemberModel(ctx.serverDB, ctx.userId).getMember(+ acceptance.workspaceId,+ ctx.userId,+ );+ return Boolean(member);+};diff --git a/apps/server/src/routers/lambda/acceptance/review.ts b/apps/server/src/routers/lambda/acceptance/review.tsnew file mode 100644index 00000000000..f37f7bfa5c6--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/review.ts@@ -0,0 +1,383 @@+import {+ acceptanceCheckReviewActions,+ acceptanceRejectIntents,+ reviewAdjudications,+ reviewProposalEdits,+} from '@lobechat/const/verify';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type { AcceptanceItem } from '@/database/schemas/verify';+import { router } from '@/libs/trpc/lambda';+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';+import {+ buildAcceptanceCheckUnion,+ mapWithConcurrency,+ REVIEW_PREDICT_CONCURRENCY,+ REVIEW_PREDICT_MODEL_CONFIG,+ VerifyReviewPredictorService,+} from '@/server/services/verify';+import { after } from '@/server/utils/scheduleAfterResponse';++import {+ type AcceptanceRepairDispatch,+ dispatchAcceptanceRepair,+} from '../_helpers/acceptanceRepairDispatch';+import { settleGoalSignOff } from '../_helpers/acceptanceStatus';+import * as goalGate from '../_helpers/goalGateAcceptance';+import { acceptanceWriteProcedure, resolveAcceptanceForWrite } from './procedures';+import { reviewAnnotationsSchema } from './schemas';++export const reviewRouter = router({+ regroupChecks: acceptanceWriteProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ expectedVersion: z.number().int().nonnegative(),+ groups: z+ .array(+ z.object({+ title: z.string().trim().min(1).max(200),+ checkItemIds: z.array(z.string().min(1)).min(1).max(1000),+ }),+ )+ .max(100),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { service } = await resolveAcceptanceForWrite(ctx, input.id);+ return service.regroupChecks(input.id, input.groups, input.expectedVersion);+ }),+ /**+ * The user accepts the delivery โ the terminal business event that closes+ * the acceptance lifecycle. The verifier's verdict is a recommendation; this+ * click is the event (a failed/uncertain round can still be accepted, which+ * means the user knowingly takes it with its exceptions).+ */+ accept: acceptanceWriteProcedure+ .input(goalGate.gateDecisionInput.extend({ comment: z.string().max(2000).optional() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ const accepted = await goalGate.withGoalGateAnswer(+ ctx.serverDB,+ service,+ acceptance,+ 'release',+ { comment: input.comment, roundId: input.roundId },+ () => service.accept(acceptance.id, input.comment),+ );+ // Signed where it lives โ the inbox stops asking for the same sign-off.+ await settleGoalSignOff(ctx.serverDB, acceptance, 'signOff', input.comment);+ return accepted;+ }),+ /**+ * Feedback addressed to a check GROUP (business category) rather than any+ * single check โ for concerns that don't invalidate an individual check+ * (which may well be accepted) but still need to reach the next round.+ * Append-only, stamped with the current round for the same staleness rule+ * as check-level rejects.+ */+ addGroupFeedback: acceptanceWriteProcedure+ .input(+ z.object({+ category: z.string().max(200),+ comment: z.string().trim().min(1).max(2000),+ fileIds: z.array(z.string()).max(10).optional(),+ id: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ // The feedback is addressed to the CURRENT round and lives on its run's+ // decision detail โ the same home as the round's terminal accept/reject+ // note, so staleness falls out of the round chain and a deleted round+ // takes its feedback along.+ const { runs } = await service.loadRounds(acceptance.id);+ const currentRun = runs.at(-1);+ if (!currentRun) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'No verification round to address feedback to',+ });+ }++ const entry = {+ category: input.category,+ comment: input.comment,+ createdAt: new Date().toISOString(),+ ...(input.fileIds?.length ? { fileIds: input.fileIds } : {}),+ };+ await new VerifyRunModel(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ ).appendGroupFeedback(currentRun.id, entry);+ return { entry: { ...entry, roundIndex: currentRun.roundIndex }, success: true };+ }),+ /**+ * The user's verdict on individual union checks โ `accept` settles a check+ * for good ("ๅทฒ้ชๆถ,ไธ็จๅ็ฎก"); `reject` records feedback the next verify+ * round reads as its re-tasking input. A group-level "accept all" is the+ * same call with many ids. Independent of the aggregate-level accept/reject:+ * reviewing checks never moves the acceptance lifecycle.+ */+ reviewChecks: acceptanceWriteProcedure+ .input(+ z+ .object({+ action: z.enum(acceptanceCheckReviewActions),+ annotations: reviewAnnotationsSchema,+ checkItemIds: z.array(z.string()).min(1).max(200),+ comment: z.string().max(2000).optional(),+ fileIds: z.array(z.string()).max(10).optional(),+ id: z.string(),+ /**+ * Which of the three jobs a reject is doing. Optional so older+ * clients keep working โ and left genuinely absent rather than+ * defaulted, because guessing `unmet` here would recreate exactly the+ * conflated label the split exists to remove.+ */+ rejectIntent: z.enum(acceptanceRejectIntents).optional(),+ /** Set when the reviewer was responding to a model proposal. */+ proposal: z+ .object({+ adjudication: z.enum(reviewAdjudications),+ edit: z.enum(reviewProposalEdits).optional(),+ predictionId: z.string(),+ })+ .optional(),+ })+ // A reject IS its feedback โ without a note (global, on an annotated+ // region, or a screenshot attachment) the next round has nothing to act on.+ .refine(+ (value) =>+ value.action !== 'reject' ||+ Boolean(value.comment?.trim()) ||+ Boolean(value.annotations?.some((annotation) => annotation.comment?.trim())) ||+ Boolean(value.fileIds?.length),+ { message: 'Rejecting a check requires a comment' },+ ),+ )+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ try {+ const result = await service.reviewChecks(acceptance.id, {+ action: input.action,+ annotations: input.annotations,+ checkItemIds: input.checkItemIds,+ comment: input.comment?.trim() || undefined,+ fileIds: input.fileIds,+ proposal: input.proposal,+ rejectIntent: input.rejectIntent,+ });++ return result;+ } catch (error) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: error instanceof Error ? error.message : 'Failed to review checks',+ });+ }+ }),+ /**+ * Answer a model proposal without ruling on the check itself.+ *+ * `not-an-issue` and `misidentified` are answers to the MODEL, not to the+ * delivery โ the check stays pending and the reviewer still has to judge it.+ * That is why this writes to the prediction row rather than going through+ * `reviewChecks`: routing a dismissal through the review path would stamp a+ * `user_decision` the reviewer never made.+ *+ * The `confirmed` case does not come here โ it rides along with the reject in+ * `reviewChecks`, where the edit diff is available.+ */+ adjudicateProposal: acceptanceWriteProcedure+ .input(+ z.object({+ adjudication: z.enum(['not-an-issue', 'misidentified'] as const),+ id: z.string(),+ predictionId: z.string(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ // Authorization only โ the prediction rows are read through their own+ // owner-scoped model just below.+ const { acceptance } = await resolveAcceptanceForWrite(ctx, input.id);++ const model = new VerifyReviewPredictionModel(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ );+ const prediction = await model.findById(input.predictionId);+ if (!prediction) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Proposal not found' });+ }++ await model.adjudicate(prediction.id, { adjudication: input.adjudication });+ return { success: true };+ }),+ /**+ * Generate automated review proposals for the checks still awaiting a+ * verdict in this acceptance.+ *+ * An explicit mutation rather than a side effect of `getBundle`: reading a+ * report must not spend model budget, and the reviewer needs to be able to+ * ask for proposals again after a new round lands.+ */+ predictReviews: acceptanceWriteProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ const { results, runs } = await service.loadRounds(acceptance.id);+ const resultsByRun = new Map<string, typeof results>();+ for (const result of results) {+ const bucket = resultsByRun.get(result.verifyRunId!) ?? [];+ bucket.push(result);+ resultsByRun.set(result.verifyRunId!, bucket);+ }+ const checks = buildAcceptanceCheckUnion(+ runs.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),+ );++ // Pinned, never the verifier's own model: the predictor reads screenshots,+ // and a text-only verifier model silently judges frames it cannot see.+ const modelConfig = REVIEW_PREDICT_MODEL_CONFIG;++ const predictor = new VerifyReviewPredictorService(+ ctx.serverDB,+ acceptance.userId,+ acceptance.workspaceId ?? undefined,+ );++ // Only checks the reviewer has not already ruled on. Re-judging a settled+ // check spends budget to argue with a decision that is already made.+ const pending = checks.filter((check) => check.result && !check.result.userDecision);++ // Forget the previous batch's unanswered rows BEFORE responding: the+ // client waits for every queued check to carry a recorded attempt, and+ // with the old rows still in place that condition holds on the first+ // poll โ before a single new judgement has landed.+ await predictor.resetPending(+ pending.map((check) => check.result!.id),+ modelConfig,+ );++ // Dispatched AFTER the response, with a ceiling on how many model calls+ // are open at once.+ //+ // Awaiting the fan-out inline could not survive real data: each check is+ // a 10-25s multimodal generation, so a thirty-check acceptance ran well+ // past any gateway timeout and the reviewer lost every proposal the run+ // had already paid for. The ceiling is the other half โ an unbounded+ // `Promise.all` opened one generation per check simultaneously, which is+ // how a single click turns into a provider rate-limit burst.+ //+ // The client polls the bundle for the cards to appear; a failed+ // individual prediction is recorded as an `errored` row inside `predict`+ // rather than thrown, so one bad check cannot abort its neighbours.+ after(async () => {+ try {+ await mapWithConcurrency(pending, REVIEW_PREDICT_CONCURRENCY, (check) =>+ predictor.predict({+ checkResultId: check.result!.id,+ instructionDocumentId: check.planItem?.documentId,+ modelConfig,+ requirement: acceptance.requirement,+ surface: check.surface,+ }),+ );+ } catch (error) {+ console.error('[acceptance] review prediction batch failed', error);+ }+ });++ return { queued: pending.length };+ }),+ /**+ * The user sent the delivery back for a repair round (the in-app ๆๅ้่ท+ * dispatch). Stamps the aggregate `repairing` so every surface reflects the+ * send-back immediately; the next round's ingest recomputes the status from+ * real run state, so a stale stamp cannot stick.+ */+ markRepairing: acceptanceWriteProcedure+ .input(z.object({ id: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ if (acceptance.status !== 'delivered' && acceptance.status !== 'errored') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Only a settled acceptance can be sent back (status: ${acceptance.status})`,+ });+ }+ await service.acceptanceModel.updateStatus(acceptance.id, 'repairing');+ notifyAcceptance(acceptance.id, 'session', ctx.userId);+ }),+ /**+ * The user rejects the delivery. An optional comment is a re-tasking input: it is+ * recorded on the current round's decision and seeds the next repair/verify+ * round. When the rounds name an authoring conversation, the delivery is sent+ * straight back to that agent and the acceptance moves to `repairing`; the+ * outcome rides on `repairDispatch` so every surface (UI, CLI, external+ * callers) reports the same thing. Without one the caller hands the repair+ * prompt over itself.+ */+ reject: acceptanceWriteProcedure+ .input(+ goalGate.gateDecisionInput.extend({+ comment: z.string().trim().max(2000).optional(),+ /**+ * Send the delivery back to the agent that authored it (default). Pass+ * `false` to only record the decision โ the caller hands the repair+ * prompt over itself.+ */+ dispatch: z.boolean().optional(),+ }),+ )+ .mutation(+ async ({+ ctx,+ input,+ }): Promise<AcceptanceItem & { repairDispatch: AcceptanceRepairDispatch }> => {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);++ const comment = input.comment || undefined;+ const rejected = await goalGate.withGoalGateAnswer(+ ctx.serverDB,+ service,+ acceptance,+ 'revise',+ { comment, roundId: input.roundId },+ () => service.reject(acceptance.id, comment),+ );+ await settleGoalSignOff(+ ctx.serverDB,+ acceptance,+ 'requestChanges',+ input.comment || undefined,+ );+ // A gate's revision is carried out by the goal: its main Agent rewrites the plan.+ if (input.dispatch === false || acceptance.subjectType === 'goal_gate') {+ return { ...rejected, repairDispatch: { dispatched: false, reason: 'skipped' } };+ }++ const repairDispatch = await dispatchAcceptanceRepair(+ ctx,+ service,+ acceptance,+ input.comment || undefined,+ );+ if (!repairDispatch.dispatched) return { ...rejected, repairDispatch };++ const current = await service.acceptanceModel.findById(acceptance.id);+ return { ...(current ?? rejected), repairDispatch };+ },+ ),+});diff --git a/apps/server/src/routers/lambda/acceptance/schemas.ts b/apps/server/src/routers/lambda/acceptance/schemas.tsnew file mode 100644index 00000000000..4ac14b4dcd2--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/schemas.ts@@ -0,0 +1,33 @@+import { verifyEvidenceChapterKinds } from '@lobechat/const/verify';+import { z } from 'zod';++/**+ * A reviewer's circled region. On video evidence it also carries the frame+ * (`time.start`) or span (`time.start`โ`time.end`) it is about, and optionally+ * quotes the agent chapter it disputes.+ */+const reviewAnnotationSchema = z.object({+ comment: z.string().max(2000).optional(),+ disputes: z+ .object({+ kind: z.enum(verifyEvidenceChapterKinds),+ note: z.string().max(500).optional(),+ t: z.number().min(0),+ })+ .optional(),+ evidenceId: z.string(),+ rect: z.object({+ height: z.number().min(0).max(1),+ width: z.number().min(0).max(1),+ x: z.number().min(0).max(1),+ y: z.number().min(0).max(1),+ }),+ time: z+ .object({ end: z.number().min(0).optional(), start: z.number().min(0) })+ .refine((time) => time.end === undefined || time.end > time.start, {+ message: 'time.end must be after time.start',+ })+ .optional(),+});++export const reviewAnnotationsSchema = z.array(reviewAnnotationSchema).max(20).optional();diff --git a/apps/server/src/routers/lambda/acceptance/subject.ts b/apps/server/src/routers/lambda/acceptance/subject.tsnew file mode 100644index 00000000000..2ed57f9cb31--- /dev/null+++ b/apps/server/src/routers/lambda/acceptance/subject.ts@@ -0,0 +1,157 @@+import { acceptanceSubjectTypes } from '@lobechat/const/verify';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { router } from '@/libs/trpc/lambda';++import { acceptanceProcedure, acceptanceWriteProcedure } from './procedures';++const subjectTypeSchema = z.enum(acceptanceSubjectTypes);++export const subjectRouter = router({+ /** Get (or lazily create) the aggregate for a subject โ the ingest entry point. */+ ensure: acceptanceWriteProcedure+ .input(+ z.object({+ /**+ * Set by report ingest when the topic came from the ambient+ * `LOBEHUB_TOPIC_ID`: a Task's run topic then lands on the Task. An+ * explicitly requested subject is always kept exact.+ */+ foldTaskRunTopic: z.boolean().optional(),+ requirement: z.string().max(2000).optional(),+ subjectId: z.string(),+ subjectType: subjectTypeSchema,+ title: z.string().trim().min(1).max(500).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const defaults = { requirement: input.requirement, title: input.title };+ try {+ return input.foldTaskRunTopic+ ? await ctx.acceptanceService.ensureForIngest(+ input.subjectType,+ input.subjectId,+ defaults,+ )+ : await ctx.acceptanceService.ensureForSubject(+ input.subjectType,+ input.subjectId,+ defaults,+ );+ } catch (error) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: error instanceof Error ? error.message : 'Acceptance subject not found',+ });+ }+ }),+ /** The acceptance row for a subject, or null when none exists yet. */+ getBySubject: acceptanceProcedure+ .input(z.object({ subjectId: z.string(), subjectType: subjectTypeSchema }))+ .query(async ({ ctx, input }) => {+ const acceptance = await ctx.acceptanceService.acceptanceModel.findBySubject(+ input.subjectType,+ input.subjectId,+ );+ if (!acceptance) return null;++ // `delivered` alone is ambiguous for the subject's status surface: a+ // converged delivery waiting for sign-off and a failed one waiting for a+ // decision both land there. The latest round's verdict is what tells+ // them apart, so ship it with the aggregate instead of forcing callers+ // to load the whole bundle for one field.+ const latest = await ctx.acceptanceService.latestRound(acceptance.id);+ return {+ ...acceptance,+ latestRunStatus: latest?.status ?? null,+ latestRunUserDecision: latest?.userDecision ?? null,+ };+ }),+ /**+ * Persist a subject's standing acceptance checklist (the topic tray). Ensures+ * the aggregate exists, then writes the list into its `config.checklist` โ so+ * the criteria live with the verify aggregate, not in client storage.+ */+ saveChecklist: acceptanceWriteProcedure+ .input(+ z.object({+ checklist: z.array(+ z.object({+ id: z.string(),+ method: z.string().optional(),+ name: z.string(),+ }),+ ),+ subjectId: z.string(),+ subjectType: subjectTypeSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const aggregate = await ctx.acceptanceService.ensureForSubject(+ input.subjectType,+ input.subjectId,+ );+ await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {+ config: { ...aggregate.config, checklist: input.checklist },+ });+ return { checklist: input.checklist, id: aggregate.id };+ } catch (error) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: error instanceof Error ? error.message : 'Acceptance subject not found',+ });+ }+ }),+ /**+ * Set (or update) a subject's acceptance goal โ the one-sentence outcome the+ * conversation is delivering. Unlike `ensure`, this overwrites: the goal is a+ * user-editable field, so a later edit must stick.+ */+ saveGoal: acceptanceWriteProcedure+ .input(+ z.object({+ requirement: z.string().max(2000),+ subjectId: z.string(),+ subjectType: subjectTypeSchema,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const aggregate = await ctx.acceptanceService.ensureForSubject(+ input.subjectType,+ input.subjectId,+ );+ await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {+ requirement: input.requirement,+ });+ return { id: aggregate.id, requirement: input.requirement };+ } catch (error) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: error instanceof Error ? error.message : 'Acceptance subject not found',+ });+ }+ }),+ /**+ * Acceptance status for a known set of subjects, in one read.+ *+ * `list` is recency-capped and spans every subject type, so a list surface+ * that derived per-row state from it would silently mis-read any subject+ * pushed past the cap. This answers about exactly the subjects asked for.+ */+ listStatusesBySubjects: acceptanceProcedure+ .input(+ z.object({+ subjectIds: z.array(z.string()).max(200),+ subjectType: subjectTypeSchema,+ }),+ )+ .query(async ({ ctx, input }) =>+ ctx.acceptanceService.acceptanceModel.listStatusesBySubjects(+ input.subjectType,+ input.subjectIds,+ ),+ ),+});