Skip to content

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

♻️ refactor(server): split the 1835-line acceptanceService into cohesive modules (#21143)

Arvin Xu3ae66edd40e4
diff --git a/apps/server/src/services/task/detail.ts b/apps/server/src/services/task/detail.ts
index c632a010553..12ee5747104 100644
--- a/apps/server/src/services/task/detail.ts
+++ b/apps/server/src/services/task/detail.ts
@@ -22,7 +22,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { extractFileIdsFromEditorData } from '../file/extractFileIdsFromEditorData';
import { resolveAttachmentMetadata } from '../file/resolveAttachments';
-import { resolveTaskAcceptance } from '../verify/taskAcceptance';
+import { resolveTaskAcceptance } from '../verify/taskAcceptanceResolution';
import { collapseActivityLog } from './collapseActivityLog';
import { projectTaskDetailState } from './detailProjection';
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 284fc9786c8..97ce7e73200 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -68,7 +68,7 @@ const { resolveTaskAcceptance } = vi.hoisted(() => ({
resolveTaskAcceptance: vi.fn(),
}));
-vi.mock('@/server/services/verify/taskAcceptance', () => ({ resolveTaskAcceptance }));
+vi.mock('@/server/services/verify/taskAcceptanceResolution', () => ({ resolveTaskAcceptance }));
// AiAgentService pulls in ~14 sub-dependencies in its constructor; mock it so
// the running-status branch in updateStatus doesn't drag them in.
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index e211760f5eb..ea380c8f5f2 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -18,7 +18,7 @@ import {
countUnchargedRuns,
resolveTaskAttemptBudget,
} from '@/server/services/goal/recoveryPolicy';
-import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';
+import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptanceResolution';
/** Cap on unresolved checks carried into the next round's prompt. */
const MAX_GOAL_FAILED_CHECKS = 8;
diff --git a/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts b/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts
new file mode 100644
index 00000000000..4ce354fd07e
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptanceListPage.test.ts
@@ -0,0 +1,141 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AcceptanceService } from '../acceptanceService';
+
+/**
+ * The paged list read: the filter becomes a status set in the query, and each
+ * row is decorated with its subject header, project and latest check count.
+ */
+const mocks = vi.hoisted(() => ({
+ projectFindByIds: vi.fn(),
+ queryPage: vi.fn(),
+ taskResolveMany: vi.fn(),
+}));
+
+vi.mock('@/database/models/acceptance', () => ({
+ AcceptanceModel: vi.fn(function () {
+ return { queryPage: mocks.queryPage };
+ }),
+}));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(function () {
+ return { resolveMany: mocks.taskResolveMany };
+ }),
+}));
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn(function () {
+ return { findOwnTopicsByIds: vi.fn().mockResolvedValue([]) };
+ }),
+}));
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: vi.fn(function () {
+ return { findByIds: vi.fn().mockResolvedValue([]) };
+ }),
+}));
+vi.mock('@/database/models/project', () => ({
+ ProjectModel: vi.fn(function () {
+ return { findByIds: mocks.projectFindByIds };
+ }),
+}));
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const rows = [
+ {
+ id: 'acc-1',
+ metadata: {},
+ projectId: 'project-1',
+ subjectId: 'task-1',
+ subjectType: 'task',
+ userId: 'user-1',
+ workspaceId: null,
+ },
+ {
+ id: 'acc-2',
+ metadata: { title: 'Kept title' },
+ projectId: null,
+ subjectId: 'task-2',
+ subjectType: 'task',
+ userId: 'user-1',
+ workspaceId: null,
+ },
+];
+
+const db = () => ({
+ query: {
+ verifyReports: {
+ findMany: vi.fn().mockResolvedValue([{ totalChecks: 4, verifyRunId: 'run-1b' }]),
+ },
+ verifyRuns: {
+ findMany: vi.fn().mockResolvedValue([
+ { acceptanceId: 'acc-1', id: 'run-1a', roundIndex: 1 },
+ { acceptanceId: 'acc-1', id: 'run-1b', roundIndex: 2 },
+ ]),
+ },
+ },
+});
+
+describe('AcceptanceService.listPageWithSubjects', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.queryPage.mockResolvedValue({ items: rows, nextCursor: 'cursor-2' });
+ mocks.taskResolveMany.mockResolvedValue([{ id: 'task-1', identifier: 'T-1', name: 'Task 1' }]);
+ mocks.projectFindByIds.mockResolvedValue([{ id: 'project-1', name: 'Project 1' }]);
+ });
+
+ it('queries the filter as a status set and decorates each row', async () => {
+ const service = new AcceptanceService(db() as any, 'user-1');
+
+ const page = await service.listPageWithSubjects({
+ cursor: 'cursor-1',
+ filter: 'completed',
+ limit: 30,
+ });
+
+ expect(mocks.queryPage).toHaveBeenCalledWith({
+ cursor: 'cursor-1',
+ limit: 30,
+ projectId: undefined,
+ scope: undefined,
+ source: undefined,
+ statuses: ['accepted', 'closed'],
+ });
+ expect(mocks.projectFindByIds).toHaveBeenCalledWith(['project-1']);
+ expect(page.nextCursor).toBe('cursor-2');
+ expect(
+ page.items.map(({ checkCount, id, project, subject }) => ({
+ checkCount,
+ id,
+ project,
+ subject,
+ })),
+ ).toEqual([
+ {
+ checkCount: 4,
+ id: 'acc-1',
+ project: { id: 'project-1', name: 'Project 1' },
+ subject: { id: 'task-1', title: 'Task 1', type: 'task' },
+ },
+ {
+ checkCount: null,
+ id: 'acc-2',
+ project: null,
+ subject: { id: 'task-2', title: 'Kept title', type: 'task' },
+ },
+ ]);
+ });
+
+ it('degrades subject titles and projects when their reads fail', async () => {
+ mocks.taskResolveMany.mockRejectedValue(new Error('db down'));
+ mocks.projectFindByIds.mockRejectedValue(new Error('db down'));
+ const service = new AcceptanceService(db() as any, 'user-1');
+
+ const page = await service.listPageWithSubjects({});
+
+ expect(mocks.queryPage).toHaveBeenCalledWith(expect.objectContaining({ statuses: undefined }));
+ expect(page.items.map(({ project, subject }) => ({ project, title: subject.title }))).toEqual([
+ { project: null, title: null },
+ { project: null, title: 'Kept title' },
+ ]);
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceOrigin.test.ts b/apps/server/src/services/verify/__tests__/acceptanceOrigin.test.ts
index 84430201a56..20dfe405c4c 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceOrigin.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceOrigin.test.ts
@@ -84,3 +84,25 @@ describe('AcceptanceService.resolveOrigin', () => {
expect(origin).toEqual({ agent: null, topic: { id: 'tpc_1', title: 'Harbor' } });
});
});
+
+describe('AcceptanceService.findRepairOrigin', () => {
+ it.each([
+ {
+ expected: { agentId: 'agt_2', topicId: 'tpc_2' },
+ runs: [{ origin: { topicId: 'tpc_1' } }, { origin: { agentId: 'agt_2', topicId: 'tpc_2' } }],
+ },
+ {
+ expected: { agentId: undefined, topicId: 'tpc_1' },
+ runs: [{ origin: { topicId: 'tpc_1' } }],
+ },
+ { expected: null, runs: [{ origin: { agentId: 'agt_1' } }] },
+ { expected: null, runs: [] },
+ ])('resolves the latest recorded origin to $expected', async ({ expected, runs }) => {
+ const service = new AcceptanceService({} as never, 'user', 'ws');
+ vi.spyOn((service as any).runModel, 'listByAcceptance').mockResolvedValue(
+ runs.map(({ origin }) => ({ metadata: { origin } })),
+ );
+
+ await expect(service.findRepairOrigin('acc-1')).resolves.toEqual(expected);
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceReviewChecks.test.ts b/apps/server/src/services/verify/__tests__/acceptanceReviewChecks.test.ts
new file mode 100644
index 00000000000..12a150ffefd
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptanceReviewChecks.test.ts
@@ -0,0 +1,205 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AcceptanceService } from '../acceptanceService';
+
+/**
+ * Per-check reviews stamp the verdict on each union row's FINAL result row,
+ * and a merged pull request accepts the delivery it was linked to.
+ */
+const mocks = vi.hoisted(() => ({
+ adjudicate: vi.fn(),
+ findById: vi.fn(),
+ listByAcceptance: vi.fn(),
+ resultUpdate: vi.fn(),
+ resultModelScopes: [] as unknown[],
+ setDecision: vi.fn(),
+ taskResolve: vi.fn(),
+ taskServiceUpdateStatus: vi.fn(),
+ trigger: vi.fn(),
+ updateStatus: vi.fn(),
+}));
+
+vi.mock('@/database/models/acceptance', () => ({
+ AcceptanceModel: vi.fn(function () {
+ return { findById: mocks.findById, updateStatus: mocks.updateStatus };
+ }),
+}));
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(function () {
+ return { listByAcceptance: mocks.listByAcceptance, setDecision: mocks.setDecision };
+ }),
+}));
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(function (db: unknown) {
+ mocks.resultModelScopes.push(db);
+ return { update: mocks.resultUpdate };
+ }),
+}));
+vi.mock('@/database/models/verifyReviewPrediction', () => ({
+ VerifyReviewPredictionModel: vi.fn(function () {
+ return { adjudicate: mocks.adjudicate };
+ }),
+}));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(function () {
+ return { resolve: mocks.taskResolve };
+ }),
+}));
+vi.mock('@/server/services/task', () => ({
+ TaskService: vi.fn(function () {
+ return { updateStatus: mocks.taskServiceUpdateStatus };
+ }),
+}));
+vi.mock('@/server/workflows/expertiseRejection', () => ({
+ ExpertiseRejectionWorkflow: { trigger: mocks.trigger },
+}));
+
+const tx = { tx: true };
+const db = { transaction: vi.fn(async (fn: (tx: unknown) => unknown) => fn(tx)) };
+
+const result = (id: string, checkItemId: string, verdict = 'failed') => ({
+ checkItemId,
+ id,
+ status: verdict,
+ verdict,
+ verifyRunId: id.startsWith('r1') ? 'run-1' : 'run-2',
+});
+
+const rounds = {
+ results: [result('r1-a', 'check-a', 'failed'), result('r2-a', 'check-a', 'passed')],
+ runs: [
+ { id: 'run-1', plan: [], roundIndex: 1 },
+ { id: 'run-2', plan: [{ id: 'check-b', required: true, title: 'B' }], roundIndex: 2 },
+ ],
+};
+
+const service = () => {
+ const instance = new AcceptanceService(db as any, 'owner-1', 'ws-1', {
+ actorUserId: 'actor-1',
+ });
+ vi.spyOn(instance, 'loadRounds').mockResolvedValue(rounds as any);
+ return instance;
+};
+
+describe('AcceptanceService.reviewChecks', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.resultModelScopes.length = 0;
+ mocks.findById.mockResolvedValue({ id: 'acc-1', status: 'delivered' });
+ });
+
+ it.each([
+ { action: 'accept', decision: 'accepted', rejectIntent: undefined },
+ { action: 'ignore', decision: 'overridden', rejectIntent: undefined },
+ { action: 'reject', decision: 'rejected', rejectIntent: 'unmet' },
+ ] as const)(
+ '$action stamps $decision on the final result row inside one transaction',
+ async ({ action, decision, rejectIntent }) => {
+ const output = await service().reviewChecks('acc-1', {
+ action,
+ checkItemIds: ['check-a'],
+ comment: 'note',
+ rejectIntent: 'unmet',
+ });
+
+ expect(output).toEqual({ resultIds: ['r2-a'] });
+ expect(db.transaction).toHaveBeenCalledOnce();
+ expect(mocks.resultModelScopes.at(-1)).toBe(tx);
+ expect(mocks.resultUpdate).toHaveBeenCalledWith('r2-a', {
+ isFalseNegative: expect.any(Boolean),
+ isFalsePositive: expect.any(Boolean),
+ userDecision: decision,
+ userDecisionDetail: {
+ comment: 'note',
+ decidedAt: expect.any(String),
+ decidedBy: 'actor-1',
+ roundIndex: 2,
+ ...(rejectIntent ? { rejectIntent } : {}),
+ },
+ });
+ },
+ );
+
+ it.each([
+ { error: 'Unknown check item(s): nope', ids: ['nope'] },
+ { error: 'Check(s) never executed β€” nothing to review: check-b', ids: ['check-b'] },
+ ])('rejects $ids before writing', async ({ error, ids }) => {
+ await expect(
+ service().reviewChecks('acc-1', { action: 'accept', checkItemIds: ids }),
+ ).rejects.toThrow(error);
+ expect(db.transaction).not.toHaveBeenCalled();
+ });
+
+ it('fails the whole decision when its proposal cannot be answered', async () => {
+ mocks.adjudicate.mockResolvedValue(undefined);
+
+ await expect(
+ service().reviewChecks('acc-1', {
+ action: 'reject',
+ checkItemIds: ['check-a'],
+ proposal: { adjudication: 'agree', predictionId: 'pred-1' } as any,
+ }),
+ ).rejects.toThrow('Proposal "pred-1" not found');
+ expect(mocks.adjudicate).toHaveBeenCalledWith('pred-1', {
+ adjudication: 'agree',
+ edit: undefined,
+ });
+ });
+});
+
+describe('AcceptanceService.acceptFromScmMerge', () => {
+ const changeRequest = { number: 7, repoFullName: 'org/repo' } as any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1' }, { id: 'run-2' }]);
+ mocks.taskResolve.mockResolvedValue({ id: 'task-1', status: 'running' });
+ });
+
+ it('returns null for a missing acceptance and an accepted one unchanged', async () => {
+ mocks.findById.mockResolvedValueOnce(undefined);
+ await expect(service().acceptFromScmMerge('acc-1', changeRequest)).resolves.toBeNull();
+
+ mocks.findById.mockResolvedValueOnce({ id: 'acc-1', status: 'accepted' });
+ await expect(service().acceptFromScmMerge('acc-1', changeRequest)).resolves.toEqual({
+ id: 'acc-1',
+ status: 'accepted',
+ });
+ expect(mocks.updateStatus).not.toHaveBeenCalled();
+ });
+
+ it('stamps the merge on the current round, accepts, and completes the task', async () => {
+ mocks.findById
+ .mockResolvedValueOnce({
+ id: 'acc-1',
+ status: 'delivered',
+ subjectId: 'task-1',
+ subjectType: 'task',
+ })
+ .mockResolvedValueOnce({ id: 'acc-1', status: 'accepted' });
+
+ await expect(service().acceptFromScmMerge('acc-1', changeRequest)).resolves.toEqual({
+ id: 'acc-1',
+ status: 'accepted',
+ });
+
+ expect(mocks.setDecision).toHaveBeenCalledWith('run-2', 'accept', {
+ changeRequest,
+ decidedAt: expect.any(String),
+ decidedBy: 'actor-1',
+ source: 'scm_merge',
+ });
+ expect(mocks.updateStatus).toHaveBeenCalledWith('acc-1', 'accepted');
+ expect(mocks.trigger).toHaveBeenCalledWith({
+ acceptanceId: 'acc-1',
+ userId: 'owner-1',
+ verifyRunId: 'run-2',
+ workspaceId: 'ws-1',
+ });
+ expect(mocks.taskServiceUpdateStatus).toHaveBeenCalledWith({
+ id: 'task-1',
+ status: 'completed',
+ });
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts b/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts
new file mode 100644
index 00000000000..ce5e116d7f9
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptanceSubjects.test.ts
@@ -0,0 +1,157 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AcceptanceService } from '../acceptanceService';
+
+/**
+ * Subject resolution: the header title a bundle shows, and the project an
+ * aggregate is filed under when it is first created for a subject.
+ */
+const mocks = vi.hoisted(() => ({
+ documentFindById: vi.fn(),
+ ensureForSubject: vi.fn(),
+ goalFindByNode: vi.fn(),
+ taskResolve: vi.fn(),
+ taskTopicFindByTopicId: vi.fn(),
+ topicFindOwnTopicById: vi.fn(),
+}));
+
+vi.mock('@/database/models/acceptance', () => ({
+ AcceptanceModel: vi.fn(function () {
+ return { ensureForSubject: mocks.ensureForSubject };
+ }),
+}));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(function () {
+ return { resolve: mocks.taskResolve };
+ }),
+}));
+vi.mock('@/database/models/taskTopic', () => ({
+ TaskTopicModel: vi.fn(function () {
+ return { findByTopicId: mocks.taskTopicFindByTopicId };
+ }),
+}));
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn(function () {
+ return { findOwnTopicById: mocks.topicFindOwnTopicById };
+ }),
+}));
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: vi.fn(function () {
+ return { findById: mocks.documentFindById };
+ }),
+}));
+vi.mock('@/database/models/goal', () => ({
+ GoalModel: vi.fn(function () {
+ return { findByNode: mocks.goalFindByNode };
+ }),
+}));
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const service = () => new AcceptanceService({} as any, 'user-1', 'ws-1');
+
+const acceptance = (subjectType: string, metadata: Record<string, unknown> = {}) =>
+ ({ id: 'acc-1', metadata, subjectId: 'subject-1', subjectType }) as any;
+
+describe('AcceptanceService subjects', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.ensureForSubject.mockResolvedValue({ id: 'acc-1' });
+ });
+
+ describe('resolveSubject', () => {
+ it.each([
+ {
+ expected: 'T-1',
+ setup: () => mocks.taskResolve.mockResolvedValue({ identifier: 'T-1', name: null }),
+ type: 'task',
+ },
+ {
+ expected: 'Topic title',
+ setup: () => mocks.topicFindOwnTopicById.mockResolvedValue({ title: 'Topic title' }),
+ type: 'topic',
+ },
+ {
+ expected: 'Doc title',
+ setup: () => mocks.documentFindById.mockResolvedValue({ title: 'Doc title' }),
+ type: 'document',
+ },
+ {
+ expected: 'Goal title',
+ setup: () => mocks.goalFindByNode.mockResolvedValue({ title: 'Goal title' }),
+ type: 'goal_gate',
+ },
+ { expected: null, setup: () => {}, type: 'standalone' },
+ {
+ expected: null,
+ setup: () => mocks.taskResolve.mockRejectedValue(new Error('db down')),
+ type: 'task',
+ },
+ ])('resolves a $type subject title to $expected', async ({ expected, setup, type }) => {
+ setup();
+
+ await expect(service().resolveSubject(acceptance(type))).resolves.toEqual({
+ id: 'subject-1',
+ title: expected,
+ type,
+ });
+ });
+
+ it('prefers a trimmed user rename over the subject lookup', async () => {
+ await expect(
+ service().resolveSubject(acceptance('task', { title: ' Renamed ' })),
+ ).resolves.toEqual({ id: 'subject-1', title: 'Renamed', type: 'task' });
+ expect(mocks.taskResolve).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('ensureForSubject', () => {
+ it("files a goal-gate subject under its goal's project", async () => {
+ mocks.goalFindByNode.mockResolvedValue({ projectId: 'project-goal', title: 'Goal' });
+
+ await service().ensureForSubject('goal_gate', 'node-1');
+
+ expect(mocks.goalFindByNode).toHaveBeenCalledWith('node-1');
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith('goal_gate', 'node-1', {
+ config: undefined,
+ projectId: 'project-goal',
+ requirement: undefined,
+ });
+ });
+
+ it("files a task run topic under its task's project", async () => {
+ mocks.topicFindOwnTopicById.mockResolvedValue({ title: 'Run topic' });
+ mocks.taskTopicFindByTopicId.mockResolvedValue({ taskId: 'task-1' });
+ mocks.taskResolve.mockResolvedValue({ projectId: 'project-task' });
+
+ await service().ensureForSubject('topic', 'topic-1', { requirement: 'req' });
+
+ expect(mocks.taskResolve).toHaveBeenCalledWith('task-1');
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith('topic', 'topic-1', {
+ config: undefined,
+ projectId: 'project-task',
+ requirement: 'req',
+ });
+ });
+
+ it('stores a standalone title as metadata without a project', async () => {
+ await service().ensureForSubject('standalone', 'standalone-1', { title: 'Report' });
+
+ expect(mocks.ensureForSubject).toHaveBeenCalledWith('standalone', 'standalone-1', {
+ config: undefined,
+ metadata: { title: 'Report' },
+ projectId: null,
+ requirement: undefined,
+ });
+ });
+
+ it('rejects a subject missing from the current workspace', async () => {
+ mocks.taskResolve.mockResolvedValue(undefined);
+
+ await expect(service().ensureForSubject('task', 'task-x')).rejects.toThrow(
+ 'task "task-x" not found in the current workspace',
+ );
+ expect(mocks.ensureForSubject).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
deleted file mode 100644
index cd906d91107..00000000000
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ /dev/null
@@ -1,1835 +0,0 @@
-import { isDraftVerifyRun, normalizeVerifySurface } from '@lobechat/const/verify';
-import type {
- AcceptanceAttachment,
- AcceptanceCheckGroup,
- AcceptanceCheckReviewAction,
- AcceptanceConfig,
- AcceptanceRejectIntent,
- AcceptanceReviewAnnotation,
- AcceptanceStatus,
- AcceptanceSubjectType,
- ReviewProposalOutcome,
- VerifyAgentPlanConfig,
- VerifyCheckDecisionDetail,
- VerifyCheckItem,
- VerifyCheckTally,
- VerifyRunDecisionDetail,
- VerifySurface,
-} from '@lobechat/types';
-import debug from 'debug';
-
-import {
- type AcceptanceListProject,
- type AcceptanceListScope,
- type AcceptanceListSource,
- AcceptanceModel,
-} from '@/database/models/acceptance';
-import { AgentModel } from '@/database/models/agent';
-import { DocumentModel } from '@/database/models/document';
-import { GoalModel } from '@/database/models/goal';
-import { ProjectModel } from '@/database/models/project';
-import { TaskModel } from '@/database/models/task';
-import { TaskTopicModel } from '@/database/models/taskTopic';
-import { TopicModel } from '@/database/models/topic';
-import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
-import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
-import { VerifyReportModel } from '@/database/models/verifyReport';
-import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';
-import { VerifyRunModel } from '@/database/models/verifyRun';
-import type {
- AcceptanceItem,
- VerifyCheckResultItem,
- VerifyRunItem,
-} from '@/database/schemas/verify';
-import type { LobeChatDatabase } from '@/database/type';
-import { notTrashed } from '@/database/utils/softDelete';
-import { notifyAcceptance } from '@/server/services/acceptanceReview/events';
-import { ExpertiseRejectionWorkflow } from '@/server/workflows/expertiseRejection';
-
-import { requireDecidableAcceptance } from './acceptanceDecision';
-import {
- type AcceptanceMergeSummary,
- findUnresolvedSupersedes,
- mergeAcceptanceRounds,
-} from './acceptanceMerge';
-import { computeFalseFlags } from './feedbackService';
-
-const log = debug('lobe-server:verify-acceptance');
-
-// ============================================
-// Union view β€” the cross-round check merge (P-14: the complete inventory of
-// acceptance checks, each with its final verdict + evidence; rounds demoted to
-// provenance). Deterministically computed at read time β€” never stored, so it
-// can't go stale.
-// ============================================
-
-type CheckState = 'passed' | 'failed' | 'uncertain' | 'not_executed';
-
-const resultState = (result: VerifyCheckResultItem): CheckState => {
- const v = result.verdict ?? result.status;
- if (v === 'passed' || v === 'failed' || v === 'uncertain') return v;
- return 'uncertain';
-};
-
-export interface AcceptanceCheckHistoryEntry {
- roundIndex: number;
- state: CheckState;
- verifyRunId: string;
-}
-
-/**
- * One executed step of a check's iteration timeline. Carries the title THAT
- * round used (a superseded item keeps its own wording) so the evolution reads
- * as written, newest rendered first by the viewer.
- */
-export interface AcceptanceTimelineEntry {
- /** The result row backing this step β€” the key its evidence attaches by. */
- resultId: string;
- roundIndex: number;
- state: CheckState;
- title: string;
- verifyRunId: string;
-}
-
-/** One row of the acceptance union: a check item merged across every round. */
-export interface AcceptanceCheckRow {
- /**
- * Set when the item was planned in rounds AFTER the one that produced its
- * final result (it was carried forward without a re-run): the round the
- * evidence actually comes from.
- */
- carriedFromRound?: number;
- /** Grouping key for the union view (harness-authored page section / domain). */
- category: string | null;
- /** Passed now, but failed in at least one earlier round β€” a repaired check. */
- fixed: boolean;
- /** Verdict trail across rounds, oldest first β€” only rounds that produced a result. */
- history: AcceptanceCheckHistoryEntry[];
- /** The `checkItemId` every round agrees on (the successor id after folding). */
- id: string;
- /** First round whose plan (or results) named this check (or one it supersedes). */
- introducedAtRound: number;
- /** The latest plan snapshot of this item (carries method/expected/requiredEvidence). */
- planItem?: VerifyCheckItem;
- required: boolean;
- /** The final (latest-round) result row, or undefined when the item never ran. */
- result?: VerifyCheckResultItem;
- /** Round the final result came from. */
- resultRound?: number;
- /** How many executed steps the timeline holds (re-runs + folded generations). */
- revisions: number;
- /**
- * Stable 1-based label across the whole union ("C3") β€” first-appearance
- * order over the round chain, so earlier rounds' numbering never shifts when
- * a new round lands. Feedback and annotations reference checks by it.
- * (Folding a superseded generation removes its row, so numbering after the
- * folded id shifts by one β€” the successor keeps its own slot.)
- */
- seq: number;
- /** Final cross-round state β€” what the decision is made on. */
- state: CheckState;
- /** Ids folded into this row via `supersedes` declarations. */
- supersededIds: string[];
- /** Per-item product surface (from the plan item's `verifierConfig.surface`). */
- surface: VerifySurface | null;
- /** The executed steps, oldest first β€” drives the iteration-history timeline. */
- timeline: AcceptanceTimelineEntry[];
- title: string;
- /** The wording evolved across the timeline (a real iteration, not a re-run). */
- titleChanged: boolean;
-}
-
-interface RoundInput {
- results: VerifyCheckResultItem[];
- run: VerifyRunItem;
-}
-
-const itemSurface = (item: VerifyCheckItem | undefined): VerifySurface | null => {
- const raw = (item?.verifierConfig as VerifyAgentPlanConfig | undefined)?.surface;
- return typeof raw === 'string' ? normalizeVerifySurface(raw) : null;
-};
-
-/** A run chained onto an acceptance, with anything the author should fix. */
-export type AttachedRun = VerifyRunItem & {
- /** `supersedes` ids naming no check of this acceptance; they fold nothing. */
- unresolvedSupersedes?: string[];
-};
-
-/**
- * Merge a whole round chain into the union check list.
- *
- * Alignment is two-layered, both harness-authored (no fuzzy matching):
- * - the stable `checkItemId` aligns re-runs of the same check across rounds;
- * - a plan item's `supersedes` folds the ids of checks it REPLACES into this
- * item's iteration timeline, so a semantically-dead older wording stops
- * showing up as its own row.
- */
-export const buildAcceptanceCheckUnion = (
- rounds: RoundInput[],
- groups: AcceptanceCheckGroup[] = [],
-): AcceptanceCheckRow[] => {
- const ordered = [...rounds].sort((a, b) => (a.run.roundIndex ?? 0) - (b.run.roundIndex ?? 0));
-
- const rows = new Map<string, AcceptanceCheckRow>();
- // Last round whose PLAN named each item β€” drives the carried-forward flag.
- const lastPlannedRound = new Map<string, number>();
- // A `supersedes` entry names the check the author knew: often the plan item id
- // they wrote, while the row is keyed by the criterion minted for it. Remember
- // every plan item id's row so the fold below resolves either spelling.
- const logicalIdByPlanItemId = new Map<string, string>();
-
- const ensureRow = (id: string, roundIndex: number): AcceptanceCheckRow => {
- const existing = rows.get(id);
- if (existing) return existing;
- const row: AcceptanceCheckRow = {
- category: null,
- fixed: false,
- history: [],
- id,
- introducedAtRound: roundIndex,
- required: true,
- revisions: 0,
- seq: 0,
- state: 'not_executed',
- supersededIds: [],
- surface: null,
- timeline: [],
- title: id,
- titleChanged: false,
- };
- rows.set(id, row);
- return row;
- };
-
- for (const { results, run } of ordered) {
- const roundIndex = run.roundIndex ?? 0;
- const plan = (run.plan ?? []) as VerifyCheckItem[];
- const planById = new Map(plan.map((item) => [item.id, item]));
- const logicalIdByCheckItemId = new Map(
- plan.map((item) => [
- item.id,
- item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id),
- ]),
- );
-
- for (const item of plan) {
- const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
- const row = ensureRow(logicalId, roundIndex);
- logicalIdByPlanItemId.set(item.id, logicalId);
- // The latest snapshot wins: repair rounds may refine method/expected.
- if (item.sourceFlowNode) {
- // A rerun is a fresh execution; historical evidence stays in the timeline.
- row.result = undefined;
- row.resultRound = undefined;
- }
- row.planItem = item;
- row.title = item.title;
- row.required = item.required;
- row.category = item.category ?? row.category;
- row.surface = itemSurface(item) ?? row.surface;
- lastPlannedRound.set(logicalId, roundIndex);
- }
-
- for (const result of results) {
- const logicalId = logicalIdByCheckItemId.get(result.checkItemId) ?? result.checkItemId;
- const row = ensureRow(logicalId, roundIndex);
- const state = resultState(result);
- // The title THIS round used β€” the current round's snapshot, not the final one.
- const roundTitle =
- planById.get(result.checkItemId)?.title ?? result.checkItemTitle ?? row.title;
- row.history.push({ roundIndex, state, verifyRunId: run.id });
- row.timeline.push({
- resultId: result.id,
- roundIndex,
- state,
- title: roundTitle,
- verifyRunId: run.id,
- });
- row.result = result;
- row.resultRound = roundIndex;
- if (!row.planItem && result.checkItemTitle) row.title = result.checkItemTitle;
- if (!row.planItem) row.required = result.required;
- }
- }
-
- // Fold superseded generations into their successor's timeline, in round
- // order so a chain (C replaced by B replaced by A) collapses fully into A.
- const foldOrder = [...rows.values()].sort((a, b) => a.introducedAtRound - b.introducedAtRound);
- for (const row of foldOrder) {
- const supersedes = (row.planItem?.supersedes ?? []).map((id) =>
- rows.has(id) ? id : (logicalIdByPlanItemId.get(id) ?? id),
- );
- for (const oldId of supersedes) {
- const old = rows.get(oldId);
- if (!old || old === row) continue;
- row.timeline = [...old.timeline, ...row.timeline].sort((a, b) => a.roundIndex - b.roundIndex);
- row.history = [...old.history, ...row.history].sort((a, b) => a.roundIndex - b.roundIndex);
- row.introducedAtRound = Math.min(row.introducedAtRound, old.introducedAtRound);
- row.supersededIds = [...row.supersededIds, ...old.supersededIds, old.id];
- // The successor's own state stands; a never-run successor inherits the
- // superseded item's final result so the row still shows evidence.
- if (!row.result && old.result) {
- row.result = old.result;
- row.resultRound = old.resultRound;
- }
- rows.delete(oldId);
- }
- }
-
- // Number the surviving rows by first appearance (Map insertion order) β€”
- // stable as rounds accrue, because a new round only appends new ids.
- let seq = 0;
- for (const row of rows.values()) row.seq = ++seq;
-
- for (const row of rows.values()) {
- row.state = row.result ? resultState(row.result) : 'not_executed';
- row.fixed = row.state === 'passed' && row.history.some((entry) => entry.state === 'failed');
- row.revisions = row.timeline.length;
- row.titleChanged = row.timeline.some((entry) => entry.title !== row.title);
- // Carried forward: a later round still planned the item but never re-ran it,
- // so the final evidence predates the current round.
- const planned = lastPlannedRound.get(row.id);
- if (row.resultRound !== undefined && planned !== undefined && planned > row.resultRound) {
- row.carriedFromRound = row.resultRound;
- }
- }
-
- // Organization belongs to the current acceptance, not its immutable execution
- // snapshots. Preserve IDs, numbering and result references when a check moves.
- const grouped = new Map<string, AcceptanceCheckRow>();
- for (const group of groups) {
- for (const id of group.checkItemIds) {
- const row = rows.get(id);
- if (row) grouped.set(id, { ...row, category: group.title });
- }
- }
- return [...grouped.values(), ...[...rows.values()].filter((row) => !grouped.has(row.id))];
-};
-
-/**
- * The union's own three-way split, counted β€” the number a summary can show
- * without opening the list.
- *
- * It counts UNION ROWS, not one round's result rows. A repair round re-runs the
- * check it was asked to fix and carries the rest forward, so the current round's
- * rows are a subset of the union: counting them would print "1 passed" beside a
- * list that expands to the repaired check plus everything it carried, and the
- * two readings of one acceptance would contradict each other.
- */
-export const tallyCheckUnion = (checks: AcceptanceCheckRow[]): VerifyCheckTally => {
- let failed = 0;
- let passed = 0;
- let unjudged = 0;
- for (const check of checks) {
- if (check.state === 'passed') passed++;
- else if (check.state === 'failed') failed++;
- // `uncertain` and `not_executed` are both "planned, never judged" β€” the same
- // split the acceptance's criteria list draws.
- else unjudged++;
- }
- return { failed, passed, total: checks.length, unjudged };
-};
-
-// ============================================
-// User review overlay β€” the per-check human verdict layered onto the union.
-// An accept or ignore is sticky across rounds; a reject binds to the round it
-// judged and demotes to iteration history once a newer round lands.
-// ============================================
-
-/** The standing user verdict on one union row, derived from its result rows. */
-export interface AcceptanceCheckUserReview {
- action: AcceptanceCheckReviewAction;
- annotations?: AcceptanceReviewAnnotation[];
- /** Attachments backing a reject, resolved to URLs by the bundle read. */
- attachments?: AcceptanceAttachment[];
- comment?: string;
- createdAt: string;
- roundIndex: number;
- /**
- * A reject made against a round older than the current one β€” the feedback
- * was (or is being) consumed by a newer round, so the check is back to
- * awaiting the user's confirmation instead of standing rejected.
- */
- stale: boolean;
-}
-
-/**
- * One user decision on one executed step of a check, projected out of the
- * result rows (`user_decision` + `user_decision_detail`) β€” no dedicated store:
- * each round's row keeps the decision the user made on THAT round's evidence.
- */
-export interface AcceptanceCheckReviewEvent {
- action: AcceptanceCheckReviewAction;
- annotations?: AcceptanceReviewAnnotation[];
- /** Attachments backing the reject, resolved to URLs by the bundle read. */
- attachments?: AcceptanceAttachment[];
- comment?: string;
- /** When the decision was made (ISO 8601; falls back to the row's timestamps). */
- createdAt: string;
- /** Who decided (user id). Absent on legacy rows, which only the owner could write. */
- decidedBy?: string;
- /** Uploaded/pasted screenshots backing the reject (FKs to files). */
- fileIds?: string[];
- /** The result row the decision is stamped on. */
- id: string;
- roundIndex: number;
-}
-
-export interface AcceptanceCheckReviewOverlay {
- /** The full review trail for this check, oldest first β€” the iteration history input. */
- reviews: AcceptanceCheckReviewEvent[];
- /** The newest review, with its staleness resolved against the current round. */
- userReview?: AcceptanceCheckUserReview;
-}
-
-/**
- * Project a union row's review trail + standing user verdict from its result
- * rows. Superseded generations' decisions ride along automatically β€” the union
- * already folded their results into this row's timeline.
- */
-export const buildCheckReviewOverlay = (
- check: Pick<AcceptanceCheckRow, 'timeline'> & Partial<Pick<AcceptanceCheckRow, 'planItem'>>,
- resultsById: Map<string, VerifyCheckResultItem>,
- currentRoundIndex: number,
-): AcceptanceCheckReviewOverlay => {
- const reviews: AcceptanceCheckReviewEvent[] = [];
- for (const entry of check.timeline) {
- const result = resultsById.get(entry.resultId);
- const decision = result?.userDecision;
- if (
- !result ||
- (decision !== 'accepted' && decision !== 'rejected' && decision !== 'overridden')
- )
- continue;
- const detail = result.userDecisionDetail ?? undefined;
- reviews.push({
- action: decision === 'accepted' ? 'accept' : decision === 'overridden' ? 'ignore' : 'reject',
- annotations: detail?.annotations,
- comment: detail?.comment,
- createdAt: detail?.decidedAt ?? (result.completedAt ?? result.createdAt)?.toISOString() ?? '',
- decidedBy: detail?.decidedBy,
- fileIds: detail?.fileIds,
- id: result.id,
- // A carried-forward check is judged at the CURRENT round even though its
- // evidence row belongs to an older one β€” the detail records that round.
- roundIndex: detail?.roundIndex ?? entry.roundIndex,
- });
- }
- // ISO strings order lexically; ties (legacy rows without decidedAt) keep round order.
- reviews.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.roundIndex - b.roundIndex);
-
- const latest = reviews.at(-1);
- if (!latest) return { reviews };
- return {
- reviews,
- userReview: {
- action: latest.action,
- annotations: latest.annotations,
- comment: latest.comment,
- createdAt: latest.createdAt,
- roundIndex: latest.roundIndex,
- stale:
- (Boolean(check.planItem?.sourceFlowNode) || latest.action === 'reject') &&
- latest.roundIndex < currentRoundIndex,
- },
- };
-};
-
-// ============================================
-// Status rollup β€” the aggregate's user-facing lifecycle state, derived from the
-// current (highest) round. `accepted` is terminal and user-owned: recompute
-// never overwrites it. `rejected` holds until a newer round re-opens the loop.
-// ============================================
-
-/** Derive the aggregate status from the current round's pipeline state. */
-const statusFromRound = (run: VerifyRunItem, hasReport: boolean): AcceptanceStatus => {
- switch (run.status) {
- case 'planned': {
- return 'planned';
- }
- case 'verifying': {
- return 'verifying';
- }
- case 'repairing': {
- return 'repairing';
- }
- case 'errored': {
- return 'errored';
- }
- // Both settled outcomes await the same human decision β€” the verdict is
- // advice, acceptance is the user's event (P-12).
- case 'passed':
- case 'failed':
- case 'delivered': {
- return 'delivered';
- }
- default: {
- // Ingested rounds carry no rollup status: a published report means the
- // round has settled and awaits the decision; otherwise it is still open.
- return hasReport ? 'delivered' : 'verifying';
- }
- }
-};
-
-export interface AcceptanceSubjectSummary {
- id: string;
- title: string | null;
- type: AcceptanceSubjectType;
-}
-
-/** The list filter as a status set β€” one definition for the flat and paged reads. */
-export type AcceptanceListFilter = 'active' | 'all' | 'completed';
-
-/** Every narrowing the list panel can apply, shared by the flat and paged reads. */
-export interface AcceptanceListOptions {
- filter?: AcceptanceListFilter;
- /** A project id, or `null` for acceptances filed under no project. */
- projectId?: AcceptanceListProject;
- scope?: AcceptanceListScope;
- source?: AcceptanceListSource;
-}
-
-const statusesForFilter = (filter: AcceptanceListFilter): AcceptanceStatus[] | undefined => {
- if (filter === 'active')
- return ['pending', 'planned', 'verifying', 'repairing', 'delivered', 'rejected', 'errored'];
- if (filter === 'completed') return ['accepted', 'closed'];
- return undefined;
-};
-
-export class AcceptanceService {
- private readonly db: LobeChatDatabase;
- private readonly userId: string;
- private readonly workspaceId?: string;
-
- readonly acceptanceModel: AcceptanceModel;
- private readonly runModel: VerifyRunModel;
- private readonly resultModel: VerifyCheckResultModel;
- private readonly evidenceModel: VerifyEvidenceModel;
- private readonly reportModel: VerifyReportModel;
-
- /**
- * Who is CREDITED for the writes this service performs.
- *
- * Normally the same person the service is scoped to. They diverge for an
- * elevated write β€” a workspace owner acting on a teammate's delivery β€” where
- * the scope has to be the row's owner for the ownership predicate to resolve
- * it at all, while `decidedBy` must still name the human who decided. An
- * audit trail that credits a teammate's verdict to the author is worse than
- * one nobody can sign.
- */
- private readonly actorUserId: string;
-
- constructor(
- db: LobeChatDatabase,
- userId: string,
- workspaceId?: string,
- options?: { actorUserId?: string },
- ) {
- this.db = db;
- this.userId = userId;
- this.actorUserId = options?.actorUserId ?? userId;
- this.workspaceId = workspaceId;
- this.acceptanceModel = new AcceptanceModel(db, userId, workspaceId);
- this.runModel = new VerifyRunModel(db, userId, workspaceId);
- this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
- this.evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
- this.reportModel = new VerifyReportModel(db, userId, workspaceId);
- }
-
- /**
- * Validate the subject exists in the caller's scope before creating an
- * aggregate for it β€” the table deliberately has no FK (polymorphic subject),
- * so this is where dangling aggregates are prevented.
- */
- private assertSubjectExists = async (
- subjectType: AcceptanceSubjectType,
- subjectId: string,
- ): Promise<void> => {
- // Standalone acceptances are the subject themselves. They deliberately do
- // not require a Task/Topic/Document row, which keeps external repositories
- // from having to manufacture a LobeHub task before publishing evidence.
- if (subjectType === 'standalone') return;
-
- const found = await this.findSubject(subjectType, subjectId);
- if (!found) {
- throw new Error(`${subjectType} "${subjectId}" not found in the current workspace`);
- }
- };
-
- private findSubject = async (
- subjectType: AcceptanceSubjectType,
- subjectId: string,
- ): Promise<{ title: string | null } | null> => {
- switch (subjectType) {
- case 'task': {
- const task = await new TaskModel(this.db, this.userId, this.workspaceId).resolve(subjectId);
- return task ? { title: task.name ?? task.identifier } : null;
- }
- case 'topic': {
- // Creator-facing lookup: an agent-share visitor topic must not be
- // treated as a valid acceptance subject for the creator.
- const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicById(
- subjectId,
- );
- return topic ? { title: topic.title ?? null } : null;
- }
- case 'document': {
- const doc = await new DocumentModel(this.db, this.userId, this.workspaceId).findById(
- subjectId,
- );
- return doc ? { title: doc.title ?? null } : null;
- }
- case 'goal_gate': {
- const goal = await this.goalOfGate(subjectId);
- return goal ? { title: goal.title } : null;
- }
- case 'standalone': {
- return null;
- }
- }
- };
-
- /** Get (or create) the aggregate for a subject, validating the subject first. */
- ensureForSubject = async (
- subjectType: AcceptanceSubjectType,
- subjectId: string,
- defaults?: { config?: AcceptanceConfig; requirement?: string; title?: string },
- ): Promise<AcceptanceItem> => {
- await this.assertSubjectExists(subjectType, subjectId);
- const projectId = await this.resolveSubjectProjectId(subjectType, subjectId);
- return this.acceptanceModel.ensureForSubject(subjectType, subjectId, {
- config: defaults?.config,
- projectId,
- requirement: defaults?.requirement,
- ...(subjectType === 'standalone' && defaults?.title
- ? { metadata: { title: defaults.title } }
- : {}),
- });
- };
-
- /**
- * The ingest entry point (`lh acceptance run ingest`). An agent authoring its
- * own report inside a Task run only knows its topic, so a topic subject that
- * is a Task's run topic is folded onto that Task β€” otherwise the delivery
- * lands on a topic aggregate no task surface reads, and the Task page shows
- * no acceptance at all. A topic that already owns an acceptance keeps it, so
- * its earlier rounds are not split across two aggregates; recurring
- * (automation) tasks stay on their per-tick topic.
- */
- ensureForIngest = async (
- subjectType: AcceptanceSubjectType,
- subjectId: string,
- defaults?: { requirement?: string; title?: string },
- ): Promise<AcceptanceItem> => {
- const taskId =
- subjectType === 'topic' ? await this.resolveRunTopicTaskId(subjectId) : undefined;
- if (taskId) return this.ensureForSubject('task', taskId, defaults);
- return this.ensureForSubject(subjectType, subjectId, defaults);
- };
-
- private resolveRunTopicTaskId = async (topicId: string): Promise<string | undefined> => {
- const taskTopic = await new TaskTopicModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findByTopicId(topicId);
- if (!taskTopic) return;
- if (await this.acceptanceModel.findBySubject('topic', topicId)) return;
- const task = await new TaskModel(this.db, this.userId, this.workspaceId).findById(
- taskTopic.taskId,
- );
- if (!task || task.automationMode) return;
- return task.id;
- };
-
- /** The Goal a release-gate subject (its review node) belongs to. */
- private goalOfGate = (nodeId: string) =>
- new GoalModel(this.db, this.userId, this.workspaceId).findByNode(nodeId);
-
- private resolveSubjectProjectId = async (
- subjectType: AcceptanceSubjectType,
- subjectId: string,
- ): Promise<string | null> => {
- if (subjectType === 'task') {
- return (
- (await new TaskModel(this.db, this.userId, this.workspaceId).resolve(subjectId))
- ?.projectId ?? null
- );
- }
- if (subjectType === 'goal_gate') return (await this.goalOfGate(subjectId))?.projectId ?? null;
- if (subjectType === 'topic') {
- const taskTopic = await new TaskTopicModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findByTopicId(subjectId);
- if (!taskTopic) return null;
- return (
- (await new TaskModel(this.db, this.userId, this.workspaceId).resolve(taskTopic.taskId))
- ?.projectId ?? null
- );
- }
- return null;
- };
-
- /**
- * Chain a run onto an acceptance as its next round, then re-derive the
- * aggregate status (a new round re-opens a rejected loop).
- */
- attachRun = async (runId: string, acceptanceId: string): Promise<AttachedRun> => {
- const acceptance = await this.acceptanceModel.findById(acceptanceId);
- if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
-
- return this.attachResolvedRun(runId, acceptance);
- };
-
- /** Attach a Task run using policy scope while preserving report visibility. */
- attachPolicyRun = async (runId: string, acceptanceId: string): Promise<AttachedRun> => {
- const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);
- if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
-
- return this.attachResolvedRun(runId, acceptance);
- };
-
- /**
- * An accepted check is settled and its verdict is sticky: a later result on
- * the same id inherits the tick, so the round publishes green and the
- * reviewer is never told there is anything new to look at. That is only safe
- * while nothing writes to a settled check, which is what this enforces β€”
- * refusing the whole round rather than letting the write through, because a
- * partially attached round is harder to reason about than a rejected one.
- *
- * The escape hatch is a new check id: a criterion the reviewer has not ruled
- * on gets its own row and shows up unreviewed, which is what "there is more
- * to look at here" should look like.
- */
- private assertPlanLeavesAcceptedChecksAlone = async (
- run: VerifyRunItem,
- acceptanceId: string,
- ): Promise<void> => {
- // Every identity by which an incoming item could come to rest on an
- // existing row. The union keys rows by `sourceCriterionId ?? id`, and a
- // `supersedes` declaration folds the named row into this one β€” so comparing
- // physical ids alone lets both routes write into a settled row unblocked.
- const candidates = new Map<string, string>();
- for (const item of run.plan ?? []) {
- const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
- if (logicalId) candidates.set(logicalId, item.id);
- if (item.id) candidates.set(item.id, item.id);
- for (const superseded of item.supersedes ?? []) {
- if (superseded) candidates.set(superseded, item.id);
- }
- }
- if (candidates.size === 0) return;
-
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- if (runs.length === 0) return;
-
- const results = await this.resultModel.listByRuns(runs.map((item) => item.id));
- const resultsById = new Map(results.map((result) => [result.id, result]));
- const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
- for (const result of results) {
- if (!result.verifyRunId) continue;
- const bucket = resultsByRun.get(result.verifyRunId) ?? [];
- bucket.push(result);
- resultsByRun.set(result.verifyRunId, bucket);
- }
-
- const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;
- const checks = buildAcceptanceCheckUnion(
- runs.map((item) => ({ results: resultsByRun.get(item.id) ?? [], run: item })),
- );
-
- // Read the standing verdict exactly the way the page renders it, so the
- // rule cannot diverge from the tick the reviewer actually sees.
- const settled = checks.filter((check) => {
- const { userReview } = buildCheckReviewOverlay(check, resultsById, currentRoundIndex);
- return userReview?.action === 'accept' && !userReview.stale;
- });
-
- // A superseded generation's id is folded into its successor's row, so match
- // on both β€” re-running `old-id` after `new-id supersedes: [old-id]` was
- // accepted is the same write to the same settled row.
- const blocked = new Set<string>();
- for (const check of settled) {
- blocked.add(check.id);
- for (const superseded of check.supersededIds ?? []) blocked.add(superseded);
- }
- // Rows are keyed by criterion, but an author names a check by the plan item
- // id they wrote β€” in `supersedes` as much as in a re-run. Block those too.
- for (const { plan } of runs) {
- for (const item of (plan ?? []) as VerifyCheckItem[]) {
- const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
- if (blocked.has(logicalId)) blocked.add(item.id);
- }
- }
-
- // Report the plan item the author has to change, not the internal identity
- // it collided through β€” those can differ, and only the former is editable.
- const offenders = [
- ...new Set(
- [...candidates]
- .filter(([identity]) => blocked.has(identity))
- .map(([, planItemId]) => planItemId),
- ),
- ];
- if (offenders.length === 0) return;
-
- throw new Error(
- `Already accepted, so ${offenders.length === 1 ? 'this check' : 'these checks'} cannot take another result: ` +
- `${offenders.join(', ')}. An accepted check is settled β€” publish new work under a new check id instead.`,
- );
- };
-
- private attachResolvedRun = async (
- runId: string,
- acceptance: AcceptanceItem,
- ): Promise<AttachedRun> => {
- const acceptanceId = acceptance.id;
-
- // Idempotent for the re-ingest path (the CLI sidecar remembers the run):
- // an already-chained round keeps its index instead of being re-appended.
- const existing = await this.runModel.findById(runId);
- if (!existing) throw new Error(`Verify run "${runId}" not found in the current workspace`);
- // A retried attach (the response of the first one was lost) still reports
- // the warnings the first one did.
- if (existing.acceptanceId === acceptanceId)
- return this.withUnresolvedSupersedes(existing, acceptanceId);
- if (existing.acceptanceId) {
- throw new Error('This verify run already belongs to another acceptance');
- }
- if (acceptance.status === 'accepted' || acceptance.status === 'closed') {
- throw new Error(
- `This acceptance has already been ${acceptance.status} β€” reopen it before attaching another round`,
- );
- }
-
- await this.assertPlanLeavesAcceptedChecksAlone(existing, acceptanceId);
-
- // A round that is still only planned has nothing to preserve: the incoming
- // run folds into it instead of pushing the ledger to yet another number.
- // Only the newest round counts β€” `listByAcceptance` is ascending, and an
- // older draft the chain has moved past is an abandoned ledger position.
- const latest = (await this.runModel.listByAcceptance(acceptanceId)).at(-1);
- // Resolved against the chain as it stood before this run joined it.
- const withWarnings = (attached: VerifyRunItem): Promise<AttachedRun> =>
- this.withUnresolvedSupersedes(attached, acceptanceId, existing);
- // A run that already executed cannot fold (`foldIntoRound` refuses any source
- // with results): its verdicts belong to its own round. It is appended after
- // the draft instead β€” the path a verification driven by the CLI takes, since
- // it writes its results before the Task drive binds the round.
- const draft =
- latest && isDraftVerifyRun(latest) && (await this.resultModel.listByRun(runId)).length === 0
- ? latest
- : undefined;
- if (draft) {
- const folded = await this.runModel.foldIntoRound(runId, draft.id);
- await this.recomputeStatus(acceptanceId);
- log(
- 'run %s folded into draft round %d of acceptance %s',
- runId,
- folded.roundIndex,
- acceptanceId,
- );
- return await withWarnings(folded);
- }
-
- // Rounds inherit the aggregate's visibility so a private acceptance's new
- // round never leaks through its own report URL.
- const run = await this.runModel.attachToAcceptance(runId, acceptanceId, acceptance.visibility);
- notifyAcceptance(acceptanceId, 'session');
- await this.recomputeStatus(acceptanceId);
- log('run %s attached to acceptance %s as round %d', runId, acceptanceId, run.roundIndex);
-
- // A new round landing is the first server-side proof that the reviewer is done with the
- // previous one: rejecting a check ends at a clipboard copy, so nothing else marks "I finished
- // reviewing".
- if (latest) this.distilSettledRound(acceptanceId, latest.id);
-
- return await withWarnings(run);
- };
-
- /**
- * Attach `unresolvedSupersedes` β€” `supersedes` ids of `source`'s plan that
- * name no check of the acceptance β€” to the run handed back to the caller.
- * The source run itself is excluded from the chain it is resolved against.
- */
- private withUnresolvedSupersedes = async (
- attached: VerifyRunItem,
- acceptanceId: string,
- source: VerifyRunItem = attached,
- ): Promise<AttachedRun> => {
- const plan = (source.plan ?? []) as VerifyCheckItem[];
- if (!plan.some((item) => item.supersedes?.length)) return attached;
-
- const priorRuns = (await this.runModel.listByAcceptance(acceptanceId)).filter(
- (run) => run.id !== source.id,
- );
- // Results of the earlier rounds and of the source run itself: an executed
- // run may supersede one of its own result-only checks.
- const priorResults = await this.resultModel.listByRuns([
- ...priorRuns.map((run) => run.id),
- source.id,
- ]);
- const unresolvedSupersedes = findUnresolvedSupersedes(
- plan,
- priorRuns,
- priorResults.map((result) => result.checkItemId),
- );
- return unresolvedSupersedes.length ? { ...attached, unresolvedSupersedes } : attached;
- };
-
- /**
- * Fold one acceptance into another β€” the source's checks (with their rounds,
- * verdicts and evidence) become part of the target's inventory, and the
- * source entry goes away.
- *
- * The two aggregates are the same delivery arriving twice: a second CLI
- * ingest that minted a new standalone acceptance, or a topic and the task it
- * was promoted into. Merging is what makes them one review surface again.
- */
- merge = async (sourceId: string, targetId: string): Promise<AcceptanceMergeSummary> => {
- if (sourceId === targetId) throw new Error('An acceptance cannot be merged into itself');
-
- const source = await this.acceptanceModel.findById(sourceId);
- if (!source) throw new Error(`Acceptance "${sourceId}" not found`);
- const target = await this.acceptanceModel.findById(targetId);
- if (!target) throw new Error(`Acceptance "${targetId}" not found`);
-
- // Same rule as attaching a single round: a settled aggregate must be
- // re-opened deliberately before more checks land in it, or an `accepted`
- // sign-off would silently start covering checks nobody signed off on.
- if (target.status === 'accepted' || target.status === 'closed') {
- throw new Error(
- `This acceptance has already been ${target.status} β€” reopen it before merging into it`,
- );
- }
-
- const summary = await mergeAcceptanceRounds({
- db: this.db,
- source,
- target,
- userId: this.userId,
- workspaceId: this.workspaceId,
- });
-
- // Past this point the merge is COMMITTED and the source no longer exists β€”
- // so a failure here must not be reported as a failed merge. The caller
- // would surface a retry that can only ever fail ("Acceptance not found"),
- // for a rollup that is derived and re-derived by every later round,
- // decision and sweep. Log it and return the merge that did happen.
- try {
- await this.recomputeStatus(targetId);
- } catch (error) {
- log('acceptance %s merged, but status recompute failed (non-fatal): %O', targetId, error);
- }
-
- return summary;
- };
-
- /**
- * Re-derive the aggregate's lifecycle state from its current round. The
- * user's `accepted` / `closed` are terminal; `rejected` is sticky until a
- * round newer than the decision arrives.
- */
- recomputeStatus = async (acceptanceId: string): Promise<AcceptanceStatus | null> => {
- const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);
- if (!acceptance) return null;
- if (acceptance.status === 'accepted' || acceptance.status === 'closed') {
- return acceptance.status;
- }
-
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- const current = runs.at(-1);
- if (!current) return acceptance.status as AcceptanceStatus;
-
- // The rejected round stays rejected; only a NEWER round re-opens the loop.
- if (acceptance.status === 'rejected' && current.userDecision === 'reject') return 'rejected';
-
- const report = await this.reportModel.findByRun(current.id);
- const status = statusFromRound(current, Boolean(report));
- if (status !== acceptance.status) {
- await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);
- notifyAcceptance(acceptanceId, 'session');
- log('acceptance %s β†’ %s (from round %d)', acceptanceId, status, current.roundIndex);
- }
-
- // Rounds settled outside the verifier pipeline β€” an ingested round (no
- // status, settled by its report) or a completed acceptance flow
- // (`delivered`) β€” have nothing else to drive the task. Rounds the server
- // verifier runs (`passed` / `failed` / `errored`) are driven once, after
- // any auto-repair, by `driveTaskFromVerify`; completing here would race it.
- //
- // Reconciled on every recompute of a delivered aggregate, not only on the
- // transition: a completion that failed once is retried by the next round,
- // report or flow event instead of leaving the task open for good. An
- // already-completed task is a no-op.
- if (
- status === 'delivered' &&
- (!current.status || current.status === 'delivered') &&
- acceptance.subjectType === 'task'
- )
- await this.completeTaskForDelivery(acceptanceId, acceptance.subjectId);
- return status;
- };
-
- /** Latest round of an aggregate β€” the row `stampDecision` would write to. */
- latestRound = async (acceptanceId: string) => {
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- return runs.at(-1) ?? null;
- };
-
- regroupChecks = async (
- acceptanceId: string,
- groups: AcceptanceCheckGroup[],
- expectedVersion: number,
- ) => {
- const acceptance = await this.acceptanceModel.findById(acceptanceId);
- if (!acceptance) throw new Error('Acceptance not found');
- const { results, runs } = await this.loadRounds(acceptanceId);
- const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
- 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 })),
- );
- const known = new Set(checks.map((check) => check.id));
- const assigned = new Set<string>();
- const titles = new Set<string>();
- const normalized = groups.map((group) => {
- const title = group.title.trim();
- if (!title || titles.has(title) || group.checkItemIds.length === 0)
- throw new Error('Check groups need unique, non-empty titles and members');
- titles.add(title);
- for (const id of group.checkItemIds) {
- if (!known.has(id)) throw new Error(`Unknown check item: ${id}`);
- if (assigned.has(id)) throw new Error(`Check assigned to multiple groups: ${id}`);
- assigned.add(id);
- }
- return { ...group, title };
- });
- return this.acceptanceModel.setCheckGroups(acceptanceId, normalized, expectedVersion);
- };
-
- /**
- * Hands one settled round to distillation, fire-and-forget.
- *
- * Never awaited and never allowed to throw: this rides on the reviewer's own paths, and losing a
- * distillation is a missed lesson, while failing the caller loses their decision. Triggering the
- * same round twice is harmless β€” a round is distilled under a reflection key, and the second pass
- * finds the run already recorded and returns.
- */
- private distilSettledRound = (acceptanceId: string, verifyRunId: string) => {
- void ExpertiseRejectionWorkflow.trigger({
- acceptanceId,
- userId: this.userId,
- verifyRunId,
- workspaceId: this.workspaceId,
- });
- };
-
- /**
- * The user accepts the delivery β€” the terminal business event (P-12). Stamps
- * the decision on the current round, closes the aggregate, and best-effort
- * completes a task subject that verification alone didn't settle.
- */
- accept = async (acceptanceId: string, comment?: string): Promise<AcceptanceItem> => {
- const acceptance = await requireDecidableAcceptance(this.acceptanceModel, acceptanceId);
-
- const settled = await this.stampDecision(acceptanceId, 'accept', comment);
- await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
- notifyAcceptance(acceptanceId, 'session', this.actorUserId);
-
- // A terminal decision settles the current round as surely as a new round landing does β€” and it
- // is the ONLY thing that settles the last one, which no later round will ever follow. Without
- // this, every acceptance silently loses whatever its final round taught. Accepting the delivery
- // still settles it: a reviewer can accept overall while individual checks were rejected along
- // the way, and those rejections are exactly the material.
- this.distilSettledRound(acceptanceId, settled);
-
- if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);
-
- return (await this.acceptanceModel.findById(acceptanceId))!;
- };
-
- /**
- * A merged pull request accepts the delivery it was linked to. Merging is
- * the strongest signal a user can give, so unlike {@link accept} this does
- * not wait for the round to settle: any non-accepted status becomes
- * `accepted`, a round still in flight is stamped as decided by the merge,
- * and an acceptance that never had a round is simply closed as accepted.
- * The decision detail records the merge so the acceptance board and the
- * verifier-training pipeline can tell it apart from a human verdict.
- *
- * Idempotent: an already-accepted acceptance is returned unchanged.
- */
- acceptFromScmMerge = async (
- acceptanceId: string,
- changeRequest: NonNullable<VerifyRunDecisionDetail['changeRequest']>,
- ): Promise<AcceptanceItem | null> => {
- const acceptance = await this.acceptanceModel.findById(acceptanceId);
- if (!acceptance) return null;
- if (acceptance.status === 'accepted') return acceptance;
-
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- const current = runs.at(-1);
- if (current) {
- const detail: VerifyRunDecisionDetail = {
- changeRequest,
- decidedAt: new Date().toISOString(),
- decidedBy: this.actorUserId,
- source: 'scm_merge',
- };
- await this.runModel.setDecision(current.id, 'accept', detail);
- }
-
- await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
- notifyAcceptance(acceptanceId, 'session', this.actorUserId);
- if (current) this.distilSettledRound(acceptanceId, current.id);
- if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);
-
- log(
- 'acceptance %s accepted by merge of %s#%d (was %s)',
- acceptanceId,
- changeRequest.repoFullName,
- changeRequest.number,
- acceptance.status,
- );
- return (await this.acceptanceModel.findById(acceptanceId))!;
- };
-
- /**
- * The user rejects the delivery. An optional comment is a re-tasking input: it is
- * recorded on the round's decision detail, where the next repair/verify round
- * picks it up. (Spawning the repair run is the caller's job β€” the
- * `acceptance.reject` procedure sends it back to the origin agent when the
- * rounds name one; see `dispatchAcceptanceRepair`.)
- *
- * A Goal Task is no exception: its next attempt is started by the Goal
- * coordinator on the following tick, which reads the rejected round's
- * decision detail through the prompt builder.
- */
- reject = async (acceptanceId: string, comment?: string): Promise<AcceptanceItem> => {
- const acceptance = await requireDecidableAcceptance(this.acceptanceModel, acceptanceId);
-
- const settled = await this.stampDecision(acceptanceId, 'reject', comment);
- await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');
- notifyAcceptance(acceptanceId, 'session', this.actorUserId);
-
- this.distilSettledRound(acceptanceId, settled);
-
- if (acceptance.subjectType === 'task')
- await this.reopenRejectedTaskSubject(acceptance.subjectId);
-
- return (await this.acceptanceModel.findById(acceptanceId))!;
- };
-
- /**
- * Record the user's verdict on one or more union checks (a group-level
- * "accept all" is just many ids). Stamps `user_decision` +
- * `user_decision_detail` on each check's FINAL result row β€” the same data
- * flywheel every other decision path writes (FP/FN flags included). Unlike
- * the aggregate-level accept/reject, a per-check review is allowed at any
- * lifecycle state β€” confirming a check mid-chain is exactly the point.
- */
- reviewChecks = async (
- acceptanceId: string,
- input: {
- action: AcceptanceCheckReviewAction;
- annotations?: AcceptanceReviewAnnotation[];
- checkItemIds: string[];
- comment?: string;
- fileIds?: string[];
- /** Recorded when this decision answered a model proposal. */
- proposal?: Omit<ReviewProposalOutcome, 'respondedAt'>;
- /** Which of the three jobs a reject is doing; absent means unclassified. */
- rejectIntent?: AcceptanceRejectIntent;
- },
- ): Promise<{ resultIds: string[] }> => {
- const acceptance = await this.acceptanceModel.findById(acceptanceId);
- if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
-
- const { results, runs } = await this.loadRounds(acceptanceId);
-
- // Reviews address union rows β€” resolve each id (or a superseded alias) to
- // its row, so a stale client can't stamp junk ids.
- const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
- 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 })),
- );
- const rowById = new Map<string, AcceptanceCheckRow>();
- for (const check of checks) {
- rowById.set(check.id, check);
- for (const oldId of check.supersededIds) rowById.set(oldId, check);
- }
-
- const unknown = input.checkItemIds.filter((id) => !rowById.has(id));
- if (unknown.length > 0) {
- throw new Error(`Unknown check item(s): ${unknown.join(', ')}`);
- }
-
- // The decision is stamped on evidence β€” a never-executed check has no
- // result row to judge, so it cannot be reviewed yet.
- const targets = new Map<string, VerifyCheckResultItem>();
- const notExecuted: string[] = [];
- for (const id of input.checkItemIds) {
- const row = rowById.get(id)!;
- if (row.result) targets.set(row.result.id, row.result);
- else notExecuted.push(id);
- }
- if (notExecuted.length > 0) {
- throw new Error(`Check(s) never executed β€” nothing to review: ${notExecuted.join(', ')}`);
- }
-
- const decision =
- input.action === 'accept'
- ? 'accepted'
- : input.action === 'ignore'
- ? 'overridden'
- : 'rejected';
- const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;
- const detail: VerifyCheckDecisionDetail = {
- decidedAt: new Date().toISOString(),
- decidedBy: this.actorUserId,
- roundIndex: currentRoundIndex,
- ...(input.comment ? { comment: input.comment } : {}),
- ...(input.annotations?.length ? { annotations: input.annotations } : {}),
- ...(input.fileIds?.length ? { fileIds: input.fileIds } : {}),
- // Only meaningful on a reject β€” an accept has no intent to classify.
- ...(input.rejectIntent && input.action === 'reject'
- ? { rejectIntent: input.rejectIntent }
- : {}),
- ...(input.proposal
- ? { proposal: { ...input.proposal, respondedAt: new Date().toISOString() } }
- : {}),
- };
-
- // One transaction for the decision AND the proposal's answer. Written
- // separately, a failing second write left the check rejected while its
- // prediction stayed unanswered β€” and the decision then HIDES the proposal,
- // so nothing could ever reconcile the pair again. Agreement analysis reads
- // those two rows as a matched set; a durable split is worse than failing.
- await this.db.transaction(async (tx) => {
- const resultModel = new VerifyCheckResultModel(tx, this.userId, this.workspaceId);
-
- await Promise.all(
- [...targets.values()].map((result) => {
- const { isFalsePositive, isFalseNegative } = computeFalseFlags(result.verdict, decision);
- return resultModel.update(result.id, {
- isFalseNegative,
- isFalsePositive,
- userDecision: decision,
- userDecisionDetail: detail,
- });
- }),
- );
-
- if (input.proposal) {
- const answered = await new VerifyReviewPredictionModel(
- tx,
- this.userId,
- this.workspaceId,
- ).adjudicate(input.proposal.predictionId, {
- adjudication: input.proposal.adjudication,
- edit: input.proposal.edit,
- });
- // A zero-row update means the id was wrong or not ours; committing the
- // decision alone would produce exactly the split this transaction exists
- // to prevent.
- if (!answered) throw new Error(`Proposal "${input.proposal.predictionId}" not found`);
- }
- });
-
- log('acceptance %s: %d check result(s) marked %s', acceptanceId, targets.size, decision);
- return { resultIds: [...targets.keys()] };
- };
-
- /** Stamps the decision on the current round and returns it β€” the round that decision settles. */
- private stampDecision = async (
- acceptanceId: string,
- decision: 'accept' | 'reject',
- comment?: string,
- ): Promise<string> => {
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- const current = runs.at(-1);
- if (!current) throw new Error('This acceptance has no verification round to decide on');
-
- const detail: VerifyRunDecisionDetail = {
- decidedAt: new Date().toISOString(),
- decidedBy: this.actorUserId,
- ...(comment ? { comment } : {}),
- };
- await this.runModel.setDecision(current.id, decision, detail);
-
- return current.id;
- };
-
- /**
- * Completes a task subject that verification didn't already settle β€” on
- * accept (e.g. the round failed but the user accepted anyway) and when an
- * ingested round delivers. Best-effort: a task error must not undo the
- * recorded acceptance.
- */
- private completeTaskSubject = async (subjectId: string): Promise<void> => {
- try {
- const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
- const task = await taskModel.resolve(subjectId);
- if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) return;
-
- // TaskService cascades checkpoint / sibling rollup / downstream unlock β€”
- // the same completion path settle.ts drives on a passed verify. Loaded
- // lazily because `TaskService` reaches this module through its acceptance
- // resolution, so a static import would close a module cycle.
- const { TaskService } = await import('../task');
- await new TaskService(this.db, this.userId, this.workspaceId).updateStatus({
- id: task.id,
- status: 'completed',
- });
- log('acceptance β†’ task %s completed', task.id);
- } catch (error) {
- log('completeTaskSubject failed (non-fatal): %O', error);
- }
- };
-
- /**
- * The task whose status follows its acceptance's lifecycle: delivered β†’
- * completed, rejected β†’ reopened. Goal graph tasks are driven by their
- * coordinator (a paused task is its retry signal) and recurring tasks stay
- * on their schedule, so neither follows the acceptance.
- */
- private resolveLifecycleTask = async (subjectId: string) => {
- const task = await new TaskModel(this.db, this.userId, this.workspaceId).resolve(subjectId);
- if (!task || task.automationMode) return null;
-
- const goal = await new GoalModel(this.db, this.userId, this.workspaceId).findByGraphTask(
- task.id,
- );
- return goal ? null : task;
- };
-
- /**
- * A delivered acceptance completes its task: the delivery is in, and the
- * user's accept / reject decides from here. Shared by every settlement path.
- *
- * A reject can land at any point around the completion, so the decision is
- * read on both sides of the write: rejected before β†’ the task is left alone;
- * rejected in between β†’ the reject saw an unfinished task and did not reopen
- * it, so it is reopened here. Best-effort β€” never fails the caller.
- *
- * @returns `completed` when the task now reads completed, `rejected` when a
- * reject won, `skipped` when the task does not follow the acceptance or could
- * not be completed.
- */
- completeTaskForDelivery = async (
- acceptanceId: string,
- subjectId: string,
- ): Promise<'completed' | 'rejected' | 'skipped'> => {
- try {
- const task = await this.resolveLifecycleTask(subjectId);
- if (!task) return 'skipped';
-
- const before = await this.acceptanceModel.findPolicyById(acceptanceId);
- if (before?.status === 'rejected') return 'rejected';
- if (before?.status !== 'delivered') return 'skipped';
-
- await this.completeTaskSubject(task.id);
- // `completeTaskSubject` is best-effort and swallows its own failures (e.g. a
- // running operation that could not be interrupted). Only a task that really
- // reads completed counts β€” anything else lets the caller fall back.
- const written = await new TaskModel(this.db, this.userId, this.workspaceId).findById(task.id);
- if (written?.status !== 'completed') return 'skipped';
-
- const after = await this.acceptanceModel.findPolicyById(acceptanceId);
- if (after?.status === 'rejected') {
- await this.reopenRejectedTaskSubject(task.id);
- return 'rejected';
- }
- return 'completed';
- } catch (error) {
- log('completeTaskForDelivery failed (non-fatal): %O', error);
- return 'skipped';
- }
- };
-
- /**
- * Rejecting a delivery reopens the task it completed, so the task is not left
- * reading "done" while its repair is pending. Only a completed task moves β€”
- * one the user already paused, canceled or restarted keeps its own state.
- */
- private reopenRejectedTaskSubject = async (subjectId: string): Promise<void> => {
- try {
- const task = await this.resolveLifecycleTask(subjectId);
- if (task?.status !== 'completed') return;
-
- await new TaskModel(this.db, this.userId, this.workspaceId).updateStatusIfCurrent(
- task.id,
- 'completed',
- 'paused',
- { completedAt: null },
- );
- log('acceptance rejected β†’ task %s reopened as paused', task.id);
- } catch (error) {
- log('reopenRejectedTaskSubject failed (non-fatal): %O', error);
- }
- };
-
- /** Best-effort subject header info for the bundle (title may be gone). */
- resolveSubject = async (acceptance: AcceptanceItem): Promise<AcceptanceSubjectSummary> => {
- // A user rename wins over the subject's own title β€” the sidebar entry is
- // renamed without touching the source topic/task/document.
- const override = acceptance.metadata?.title;
- let title: string | null =
- typeof override === 'string' && override.trim() ? override.trim() : null;
- if (!title) {
- try {
- title =
- (
- await this.findSubject(
- acceptance.subjectType as AcceptanceSubjectType,
- acceptance.subjectId,
- )
- )?.title ?? null;
- } catch (error) {
- log('resolveSubject failed (non-fatal): %O', error);
- }
- }
- return {
- id: acceptance.subjectId,
- title,
- type: acceptance.subjectType as AcceptanceSubjectType,
- };
- };
-
- /** Resolve list subjects in one query per entity type, regardless of history size. */
- private resolveSubjects = async (
- acceptances: AcceptanceItem[],
- ): Promise<Map<string, AcceptanceSubjectSummary>> => {
- const result = new Map<string, AcceptanceSubjectSummary>();
- const idsByType = new Map<AcceptanceSubjectType, string[]>();
- for (const acceptance of acceptances) {
- const type = acceptance.subjectType as AcceptanceSubjectType;
- const ids = idsByType.get(type) ?? [];
- ids.push(acceptance.subjectId);
- idsByType.set(type, ids);
- }
-
- try {
- const [tasks, topics, documents] = await Promise.all([
- new TaskModel(this.db, this.userId, this.workspaceId).resolveMany(
- idsByType.get('task') ?? [],
- ),
- // Creator-facing lookup: exclude agent-share visitor topics from the
- // subject summary batch.
- new TopicModel(this.db, this.userId, this.workspaceId).findOwnTopicsByIds(
- idsByType.get('topic') ?? [],
- ),
- new DocumentModel(this.db, this.userId, this.workspaceId).findByIds(
- idsByType.get('document') ?? [],
- ),
- ]);
- const taskTitles = new Map<string, string | null>();
- for (const task of tasks) {
- const title = task.name ?? task.identifier;
- taskTitles.set(task.id, title);
- taskTitles.set(task.identifier, title);
- }
- const topicTitles = new Map(topics.map((topic) => [topic.id, topic.title ?? null]));
- const documentTitles = new Map(
- documents.map((document) => [document.id, document.title ?? null]),
- );
-
- for (const acceptance of acceptances) {
- const type = acceptance.subjectType as AcceptanceSubjectType;
- const override = acceptance.metadata?.title;
- const overrideTitle =
- typeof override === 'string' && override.trim() ? override.trim() : null;
- const title =
- overrideTitle ??
- (type === 'task'
- ? taskTitles.get(acceptance.subjectId)
- : type === 'topic'
- ? topicTitles.get(acceptance.subjectId)
- : type === 'document'
- ? documentTitles.get(acceptance.subjectId)
- : null) ??
- null;
- result.set(acceptance.id, { id: acceptance.subjectId, title, type });
- }
- } catch (error) {
- log('resolveSubjects failed (non-fatal): %O', error);
- for (const acceptance of acceptances) {
- result.set(acceptance.id, {
- id: acceptance.subjectId,
- title: typeof acceptance.metadata?.title === 'string' ? acceptance.metadata.title : null,
- type: acceptance.subjectType as AcceptanceSubjectType,
- });
- }
- }
- return result;
- };
-
- /** Resolve the projects referenced directly by acceptances in one bounded read. */
- private resolveProjects = async (
- acceptances: AcceptanceItem[],
- ): Promise<Map<string, { id: string; name: string }>> => {
- const result = new Map<string, { id: string; name: string }>();
- const projectIds = [
- ...new Set(acceptances.map(({ projectId }) => projectId).filter((id): id is string => !!id)),
- ];
- if (projectIds.length === 0) return result;
-
- try {
- const projects = await new ProjectModel(this.db, this.userId, this.workspaceId).findByIds(
- projectIds,
- );
- const projectById = new Map(projects.map((project) => [project.id, project]));
-
- for (const acceptance of acceptances) {
- if (!acceptance.projectId) continue;
- const project = projectById.get(acceptance.projectId);
- if (project) result.set(acceptance.id, { id: project.id, name: project.name });
- }
- } catch (error) {
- log('resolveProjects failed (non-fatal): %O', error);
- }
- return result;
- };
-
- /**
- * The latest round's total-check count per acceptance β€” a cheap glance for the
- * list panel (two batched reads, never a per-row union recompute). The signed-
- * off/accepted count would need the cross-round union per row, which is far too
- * heavy for a list, so the panel shows the total and leans on the row's status
- * glyph for the decision state.
- */
- private latestCheckCounts = async (acceptanceIds: string[]): Promise<Map<string, number>> => {
- const out = new Map<string, number>();
- if (acceptanceIds.length === 0) return out;
-
- const runs = await this.db.query.verifyRuns.findMany({
- columns: { acceptanceId: true, id: true, roundIndex: true },
- where: (run, { inArray }) => inArray(run.acceptanceId, acceptanceIds),
- });
- const latest = new Map<string, { id: string; round: number }>();
- for (const run of runs) {
- if (!run.acceptanceId) continue;
- const round = run.roundIndex ?? 0;
- const cur = latest.get(run.acceptanceId);
- if (!cur || round > cur.round) latest.set(run.acceptanceId, { id: run.id, round });
- }
-
- // Unscoped on purpose, like the run read above: the run ids derive from
- // acceptance ids the caller's list query already authorized, and a
- // participated row's report belongs to its owner β€” an owner-scoped read
- // would need one query per owner.
- const runIds = [...latest.values()].map((v) => v.id);
- const reports =
- runIds.length > 0
- ? await this.db.query.verifyReports.findMany({
- columns: { totalChecks: true, verifyRunId: true },
- where: (report, { inArray }) => inArray(report.verifyRunId, runIds),
- })
- : [];
- const totalByRun = new Map(reports.map((report) => [report.verifyRunId, report.totalChecks]));
- for (const [acceptanceId, { id: runId }] of latest) {
- const total = totalByRun.get(runId);
- if (total != null) out.set(acceptanceId, total);
- }
- return out;
- };
-
- /**
- * Recent aggregates with their subject headers β€” the list-panel payload.
- * Titles resolve in batches by subject type; a deleted
- * subject degrades to a null title instead of dropping the row. Each row also
- * carries the latest round's check count for the panel's at-a-glance line.
- */
- listWithSubjects = async (
- options: AcceptanceListOptions & {
- limit?: number;
- q?: string;
- } = {},
- ) => {
- const { filter = 'all', limit = 50, q } = options;
- const normalizedQuery = q?.trim().toLocaleLowerCase();
-
- // A title search must span the complete owned set. Subject titles live in
- // their source entities (task/topic/document), so resolve them before
- // applying the result cap instead of searching only the latest page.
- const candidates = await this.acceptanceModel.query({
- limit: normalizedQuery ? undefined : limit,
- projectId: options.projectId,
- scope: options.scope,
- source: options.source,
- statuses: statusesForFilter(filter),
- unbounded: Boolean(normalizedQuery),
- });
- const subjects = await this.resolveSubjectsForList(candidates);
- const matched = normalizedQuery
- ? candidates
- .filter((row) =>
- (subjects.get(row.id)?.title || row.subjectId)
- .toLocaleLowerCase()
- .includes(normalizedQuery),
- )
- .slice(0, limit)
- : candidates;
-
- return this.decorateListRows(matched, subjects);
- };
-
- /**
- * The paged twin of {@link listWithSubjects} β€” one scroll page of the list
- * panel, newest first.
- *
- * Takes the same filter vocabulary, applied in the QUERY: a page of
- * "in progress" is thirty in-progress rows, not thirty rows of which some
- * happen to be in progress. Search deliberately has no paged form β€” a title
- * search must span the whole owned set, which is what `listWithSubjects`
- * already does; the panel asks that one when a query is active.
- */
- listPageWithSubjects = async (
- options: AcceptanceListOptions & {
- cursor?: string;
- limit?: number;
- },
- ) => {
- const { items, nextCursor } = await this.acceptanceModel.queryPage({
- cursor: options.cursor,
- limit: options.limit,
- projectId: options.projectId,
- scope: options.scope,
- source: options.source,
- statuses: statusesForFilter(options.filter ?? 'all'),
- });
-
- return {
- items: await this.decorateListRows(items, await this.resolveSubjectsForList(items)),
- nextCursor,
- };
- };
-
- private isInOwnScope = (row: AcceptanceItem) =>
- row.workspaceId
- ? row.workspaceId === this.workspaceId
- : !this.workspaceId && row.userId === this.userId;
-
- /**
- * Subject headers for a mixed list. Rows in the caller's own scope go through
- * the scoped models as before. A participated row may belong to any number of
- * other owners, whose task/topic/document the caller's models cannot see β€”
- * those resolve in ONE unscoped read per subject type, so the cost stays
- * fixed however many owners a page spans. Safe because the list query has
- * already applied the read rule to these rows, and the bundle shows the same
- * title to anyone who can open them.
- */
- private resolveSubjectsForList = async (
- rows: AcceptanceItem[],
- ): Promise<Map<string, AcceptanceSubjectSummary>> => {
- const own = rows.filter(this.isInOwnScope);
- const foreign = rows.filter((row) => !this.isInOwnScope(row));
- const [ownSubjects, foreignSubjects] = await Promise.all([
- own.length > 0 ? this.resolveSubjects(own) : new Map<string, AcceptanceSubjectSummary>(),
- this.resolveForeignSubjects(foreign),
- ]);
- return new Map([...ownSubjects, ...foreignSubjects]);
- };
-
- private resolveForeignSubjects = async (
- rows: AcceptanceItem[],
- ): Promise<Map<string, AcceptanceSubjectSummary>> => {
- const result = new Map<string, AcceptanceSubjectSummary>();
- if (rows.length === 0) return result;
-
- const idsOf = (type: AcceptanceSubjectType) =>
- rows.filter((row) => row.subjectType === type).map((row) => row.subjectId);
- const titles = new Map<string, string | null>();
- try {
- const [taskIds, topicIds, documentIds] = [idsOf('task'), idsOf('topic'), idsOf('document')];
- const [taskRows, topicRows, documentRows] = await Promise.all([
- taskIds.length > 0
- ? this.db.query.tasks.findMany({
- columns: { id: true, identifier: true, name: true },
- where: (task, { and, inArray }) =>
- and(inArray(task.id, taskIds), notTrashed(task.isDeleted)),
- })
- : [],
- topicIds.length > 0
- ? this.db.query.topics.findMany({
- columns: { id: true, title: true },
- where: (topic, { and, inArray }) =>
- and(inArray(topic.id, topicIds), notTrashed(topic.isDeleted)),
- })
- : [],
- documentIds.length > 0
- ? this.db.query.documents.findMany({
- columns: { id: true, title: true },
- where: (document, { and, inArray }) =>
- and(inArray(document.id, documentIds), notTrashed(document.isDeleted)),
- })
- : [],
- ]);
- for (const task of taskRows) titles.set(`task:${task.id}`, task.name ?? task.identifier);
- for (const topic of topicRows) titles.set(`topic:${topic.id}`, topic.title ?? null);
- for (const document of documentRows)
- titles.set(`document:${document.id}`, document.title ?? null);
- } catch (error) {
- log('resolveForeignSubjects failed (non-fatal): %O', error);
- }
-
- for (const row of rows) {
- const override = row.metadata?.title;
- const overrideTitle =
- typeof override === 'string' && override.trim() ? override.trim() : null;
- result.set(row.id, {
- id: row.subjectId,
- title: overrideTitle ?? titles.get(`${row.subjectType}:${row.subjectId}`) ?? null,
- type: row.subjectType as AcceptanceSubjectType,
- });
- }
- return result;
- };
-
- private decorateListRows = async (
- rows: AcceptanceItem[],
- subjects: Map<string, AcceptanceSubjectSummary>,
- ) => {
- const [checkCounts, projects] = await Promise.all([
- this.latestCheckCounts(rows.map((row) => row.id)),
- // Projects stay in the caller's scope: another owner's project name is
- // theirs, and a row filed under it simply reads as unfiled here.
- this.resolveProjects(rows),
- ]);
-
- return rows.map((row) => ({
- ...row,
- checkCount: checkCounts.get(row.id) ?? null,
- project: projects.get(row.id) ?? null,
- subject: subjects.get(row.id)!,
- }));
- };
-
- /**
- * The authoring conversation behind the round chain, resolved to displayable
- * entities (agent avatar/title, topic title). Owner-only header data β€” the
- * bundle must not include it for anonymous link holders.
- */
- resolveOrigin = async (
- runs: VerifyRunItem[],
- ): Promise<{
- agent: {
- avatar: string | null;
- backgroundColor: string | null;
- id: string;
- title: string | null;
- } | null;
- topic: { id: string; title: string | null } | null;
- } | null> => {
- const origin = [...runs].reverse().find((run) => run.metadata?.origin)?.metadata?.origin;
- if (!origin?.agentId && !origin?.topicId) return null;
-
- const topicRowPromise = origin.topicId
- ? new TopicModel(this.db, this.userId, this.workspaceId)
- .findById(origin.topicId)
- .catch(() => null)
- : Promise.resolve(null);
- // Dispatched runs (task / goal / device) record only the topic β€” the
- // connector strips the ambient agent id β€” so the topic's own agent stands in.
- // A recorded agent does not wait on the topic read.
- const agentPromise = (
- origin.agentId ? Promise.resolve(origin.agentId) : topicRowPromise.then((row) => row?.agentId)
- ).then((agentId) =>
- agentId
- ? new AgentModel(this.db, this.userId, this.workspaceId)
- .getAgentAvatarsByIds([agentId])
- .then((rows) => rows[0] ?? null)
- .catch(() => null)
- : null,
- );
- const [topicRow, agent] = await Promise.all([topicRowPromise, agentPromise]);
- const topic = topicRow ? { id: topicRow.id, title: topicRow.title ?? null } : null;
- if (!agent && !topic) return null;
- return { agent, topic };
- };
-
- /**
- * The raw authoring conversation behind the latest round that recorded one β€”
- * the ids a rejected delivery is sent back to. Unlike {@link resolveOrigin}
- * nothing is hydrated: the dispatcher re-reads the topic under the caller's
- * own scope.
- */
- findRepairOrigin = async (
- acceptanceId: string,
- ): Promise<{ agentId?: string; topicId?: string } | null> => {
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- const origin = [...runs].reverse().find((run) => run.metadata?.origin)?.metadata?.origin;
- if (!origin?.topicId) return null;
- return { agentId: origin.agentId || undefined, topicId: origin.topicId };
- };
-
- /** The rounds + their per-round data the bundle and the union both read. */
- loadRounds = async (acceptanceId: string) => {
- const runs = await this.runModel.listByAcceptance(acceptanceId);
- const runIds = runs.map((r) => r.id);
- const [results, evidence, reports] = await Promise.all([
- this.resultModel.listByRuns(runIds),
- this.evidenceModel.listByRuns(runIds),
- this.reportModel.findByRuns(runIds),
- ]);
- return { evidence, reports, results, runs };
- };
-
- /**
- * The union tally of several acceptances at once, counted from the SAME check
- * union each acceptance page renders (`tallyCheckUnion` over
- * `buildAcceptanceCheckUnion`), so a summary row and the list it expands to
- * can never disagree about what a round chain judged.
- *
- * Batched on purpose: a surface that summarises many acceptances runs on a
- * poll, so this is two statements regardless of how many it covers. An
- * acceptance with no round at all is ABSENT from the map β€” a caller must not
- * read "absent" as "nothing passed".
- */
- getCheckTalliesByAcceptances = async (
- acceptanceIds: string[],
- ): Promise<Map<string, VerifyCheckTally>> => {
- const ids = [...new Set(acceptanceIds.filter(Boolean))];
- const tallies = new Map<string, VerifyCheckTally>();
- if (ids.length === 0) return tallies;
-
- const runs = await this.runModel.listByAcceptances(ids);
- const results = await this.resultModel.listByRuns(runs.map((run) => run.id));
-
- const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
- for (const result of results) {
- if (!result.verifyRunId) continue;
- const bucket = resultsByRun.get(result.verifyRunId) ?? [];
- bucket.push(result);
- resultsByRun.set(result.verifyRunId, bucket);
- }
-
- const runsByAcceptance = new Map<string, VerifyRunItem[]>();
- for (const run of runs) {
- if (!run.acceptanceId) continue;
- const bucket = runsByAcceptance.get(run.acceptanceId) ?? [];
- bucket.push(run);
- runsByAcceptance.set(run.acceptanceId, bucket);
- }
-
- for (const [acceptanceId, acceptanceRuns] of runsByAcceptance) {
- const checks = buildAcceptanceCheckUnion(
- acceptanceRuns.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),
- );
- tallies.set(acceptanceId, tallyCheckUnion(checks));
- }
- return tallies;
- };
-}
diff --git a/apps/server/src/services/verify/acceptanceService/attachGuards.ts b/apps/server/src/services/verify/acceptanceService/attachGuards.ts
new file mode 100644
index 00000000000..cf617d6a4cc
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/attachGuards.ts
@@ -0,0 +1,136 @@
+import type { VerifyCheckItem } from '@lobechat/types';
+
+import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';
+
+import { findUnresolvedSupersedes } from '../acceptanceMerge';
+import { buildAcceptanceCheckUnion } from './checkUnion';
+import type { AcceptanceServiceDeps } from './deps';
+import { buildCheckReviewOverlay } from './reviewOverlay';
+
+/** A run chained onto an acceptance, with anything the author should fix. */
+export type AttachedRun = VerifyRunItem & {
+ /** `supersedes` ids naming no check of this acceptance; they fold nothing. */
+ unresolvedSupersedes?: string[];
+};
+
+/**
+ * An accepted check is settled and its verdict is sticky: a later result on
+ * the same id inherits the tick, so the round publishes green and the
+ * reviewer is never told there is anything new to look at. That is only safe
+ * while nothing writes to a settled check, which is what this enforces β€”
+ * refusing the whole round rather than letting the write through, because a
+ * partially attached round is harder to reason about than a rejected one.
+ *
+ * The escape hatch is a new check id: a criterion the reviewer has not ruled
+ * on gets its own row and shows up unreviewed, which is what "there is more
+ * to look at here" should look like.
+ */
+export const assertPlanLeavesAcceptedChecksAlone = async (
+ deps: AcceptanceServiceDeps,
+ run: VerifyRunItem,
+ acceptanceId: string,
+): Promise<void> => {
+ // Every identity by which an incoming item could come to rest on an
+ // existing row. The union keys rows by `sourceCriterionId ?? id`, and a
+ // `supersedes` declaration folds the named row into this one β€” so comparing
+ // physical ids alone lets both routes write into a settled row unblocked.
+ const candidates = new Map<string, string>();
+ for (const item of run.plan ?? []) {
+ const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
+ if (logicalId) candidates.set(logicalId, item.id);
+ if (item.id) candidates.set(item.id, item.id);
+ for (const superseded of item.supersedes ?? []) {
+ if (superseded) candidates.set(superseded, item.id);
+ }
+ }
+ if (candidates.size === 0) return;
+
+ const runs = await deps.runModel.listByAcceptance(acceptanceId);
+ if (runs.length === 0) return;
+
+ const results = await deps.resultModel.listByRuns(runs.map((item) => item.id));
+ const resultsById = new Map(results.map((result) => [result.id, result]));
+ const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
+ for (const result of results) {
+ if (!result.verifyRunId) continue;
+ const bucket = resultsByRun.get(result.verifyRunId) ?? [];
+ bucket.push(result);
+ resultsByRun.set(result.verifyRunId, bucket);
+ }
+
+ const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;
+ const checks = buildAcceptanceCheckUnion(
+ runs.map((item) => ({ results: resultsByRun.get(item.id) ?? [], run: item })),
+ );
+
+ // Read the standing verdict exactly the way the page renders it, so the
+ // rule cannot diverge from the tick the reviewer actually sees.
+ const settled = checks.filter((check) => {
+ const { userReview } = buildCheckReviewOverlay(check, resultsById, currentRoundIndex);
+ return userReview?.action === 'accept' && !userReview.stale;
+ });
+
+ // A superseded generation's id is folded into its successor's row, so match
+ // on both β€” re-running `old-id` after `new-id supersedes: [old-id]` was
+ // accepted is the same write to the same settled row.
+ const blocked = new Set<string>();
+ for (const check of settled) {
+ blocked.add(check.id);
+ for (const superseded of check.supersededIds ?? []) blocked.add(superseded);
+ }
+ // Rows are keyed by criterion, but an author names a check by the plan item
+ // id they wrote β€” in `supersedes` as much as in a re-run. Block those too.
+ for (const { plan } of runs) {
+ for (const item of (plan ?? []) as VerifyCheckItem[]) {
+ const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
+ if (blocked.has(logicalId)) blocked.add(item.id);
+ }
+ }
+
+ // Report the plan item the author has to change, not the internal identity
+ // it collided through β€” those can differ, and only the former is editable.
+ const offenders = [
+ ...new Set(
+ [...candidates]
+ .filter(([identity]) => blocked.has(identity))
+ .map(([, planItemId]) => planItemId),
+ ),
+ ];
+ if (offenders.length === 0) return;
+
+ throw new Error(
+ `Already accepted, so ${offenders.length === 1 ? 'this check' : 'these checks'} cannot take another result: ` +
+ `${offenders.join(', ')}. An accepted check is settled β€” publish new work under a new check id instead.`,
+ );
+};
+
+/**
+ * Attach `unresolvedSupersedes` β€” `supersedes` ids of `source`'s plan that
+ * name no check of the acceptance β€” to the run handed back to the caller.
+ * The source run itself is excluded from the chain it is resolved against.
+ */
+export const withUnresolvedSupersedes = async (
+ deps: AcceptanceServiceDeps,
+ attached: VerifyRunItem,
+ acceptanceId: string,
+ source: VerifyRunItem = attached,
+): Promise<AttachedRun> => {
+ const plan = (source.plan ?? []) as VerifyCheckItem[];
+ if (!plan.some((item) => item.supersedes?.length)) return attached;
+
+ const priorRuns = (await deps.runModel.listByAcceptance(acceptanceId)).filter(
+ (run) => run.id !== source.id,
+ );
+ // Results of the earlier rounds and of the source run itself: an executed
+ // run may supersede one of its own result-only checks.
+ const priorResults = await deps.resultModel.listByRuns([
+ ...priorRuns.map((run) => run.id),
+ source.id,
+ ]);
+ const unresolvedSupersedes = findUnresolvedSupersedes(
+ plan,
+ priorRuns,
+ priorResults.map((result) => result.checkItemId),
+ );
+ return unresolvedSupersedes.length ? { ...attached, unresolvedSupersedes } : attached;
+};
diff --git a/apps/server/src/services/verify/acceptanceService/checkUnion.ts b/apps/server/src/services/verify/acceptanceService/checkUnion.ts
new file mode 100644
index 00000000000..b8756cfe7f6
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/checkUnion.ts
@@ -0,0 +1,278 @@
+import { normalizeVerifySurface } from '@lobechat/const/verify';
+import type {
+ AcceptanceCheckGroup,
+ VerifyAgentPlanConfig,
+ VerifyCheckItem,
+ VerifyCheckTally,
+ VerifySurface,
+} from '@lobechat/types';
+
+import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';
+
+// ============================================
+// Union view β€” the cross-round check merge (P-14: the complete inventory of
+// acceptance checks, each with its final verdict + evidence; rounds demoted to
+// provenance). Deterministically computed at read time β€” never stored, so it
+// can't go stale.
+// ============================================
+
+type CheckState = 'passed' | 'failed' | 'uncertain' | 'not_executed';
+
+const resultState = (result: VerifyCheckResultItem): CheckState => {
+ const v = result.verdict ?? result.status;
+ if (v === 'passed' || v === 'failed' || v === 'uncertain') return v;
+ return 'uncertain';
+};
+
+export interface AcceptanceCheckHistoryEntry {
+ roundIndex: number;
+ state: CheckState;
+ verifyRunId: string;
+}
+
+/**
+ * One executed step of a check's iteration timeline. Carries the title THAT
+ * round used (a superseded item keeps its own wording) so the evolution reads
+ * as written, newest rendered first by the viewer.
+ */
+export interface AcceptanceTimelineEntry {
+ /** The result row backing this step β€” the key its evidence attaches by. */
+ resultId: string;
+ roundIndex: number;
+ state: CheckState;
+ title: string;
+ verifyRunId: string;
+}
+
+/** One row of the acceptance union: a check item merged across every round. */
+export interface AcceptanceCheckRow {
+ /**
+ * Set when the item was planned in rounds AFTER the one that produced its
+ * final result (it was carried forward without a re-run): the round the
+ * evidence actually comes from.
+ */
+ carriedFromRound?: number;
+ /** Grouping key for the union view (harness-authored page section / domain). */
+ category: string | null;
+ /** Passed now, but failed in at least one earlier round β€” a repaired check. */
+ fixed: boolean;
+ /** Verdict trail across rounds, oldest first β€” only rounds that produced a result. */
+ history: AcceptanceCheckHistoryEntry[];
+ /** The `checkItemId` every round agrees on (the successor id after folding). */
+ id: string;
+ /** First round whose plan (or results) named this check (or one it supersedes). */
+ introducedAtRound: number;
+ /** The latest plan snapshot of this item (carries method/expected/requiredEvidence). */
+ planItem?: VerifyCheckItem;
+ required: boolean;
+ /** The final (latest-round) result row, or undefined when the item never ran. */
+ result?: VerifyCheckResultItem;
+ /** Round the final result came from. */
+ resultRound?: number;
+ /** How many executed steps the timeline holds (re-runs + folded generations). */
+ revisions: number;
+ /**
+ * Stable 1-based label across the whole union ("C3") β€” first-appearance
+ * order over the round chain, so earlier rounds' numbering never shifts when
+ * a new round lands. Feedback and annotations reference checks by it.
+ * (Folding a superseded generation removes its row, so numbering after the
+ * folded id shifts by one β€” the successor keeps its own slot.)
+ */
+ seq: number;
+ /** Final cross-round state β€” what the decision is made on. */
+ state: CheckState;
+ /** Ids folded into this row via `supersedes` declarations. */
+ supersededIds: string[];
+ /** Per-item product surface (from the plan item's `verifierConfig.surface`). */
+ surface: VerifySurface | null;
+ /** The executed steps, oldest first β€” drives the iteration-history timeline. */
+ timeline: AcceptanceTimelineEntry[];
+ title: string;
+ /** The wording evolved across the timeline (a real iteration, not a re-run). */
+ titleChanged: boolean;
+}
+
+interface RoundInput {
+ results: VerifyCheckResultItem[];
+ run: VerifyRunItem;
+}
+
+const itemSurface = (item: VerifyCheckItem | undefined): VerifySurface | null => {
+ const raw = (item?.verifierConfig as VerifyAgentPlanConfig | undefined)?.surface;
+ return typeof raw === 'string' ? normalizeVerifySurface(raw) : null;
+};
+
+/**
+ * Merge a whole round chain into the union check list.
+ *
+ * Alignment is two-layered, both harness-authored (no fuzzy matching):
+ * - the stable `checkItemId` aligns re-runs of the same check across rounds;
+ * - a plan item's `supersedes` folds the ids of checks it REPLACES into this
+ * item's iteration timeline, so a semantically-dead older wording stops
+ * showing up as its own row.
+ */
+export const buildAcceptanceCheckUnion = (
+ rounds: RoundInput[],
+ groups: AcceptanceCheckGroup[] = [],
+): AcceptanceCheckRow[] => {
+ const ordered = [...rounds].sort((a, b) => (a.run.roundIndex ?? 0) - (b.run.roundIndex ?? 0));
+
+ const rows = new Map<string, AcceptanceCheckRow>();
+ // Last round whose PLAN named each item β€” drives the carried-forward flag.
+ const lastPlannedRound = new Map<string, number>();
+ // A `supersedes` entry names the check the author knew: often the plan item id
+ // they wrote, while the row is keyed by the criterion minted for it. Remember
+ // every plan item id's row so the fold below resolves either spelling.
+ const logicalIdByPlanItemId = new Map<string, string>();
+
+ const ensureRow = (id: string, roundIndex: number): AcceptanceCheckRow => {
+ const existing = rows.get(id);
+ if (existing) return existing;
+ const row: AcceptanceCheckRow = {
+ category: null,
+ fixed: false,
+ history: [],
+ id,
+ introducedAtRound: roundIndex,
+ required: true,
+ revisions: 0,
+ seq: 0,
+ state: 'not_executed',
+ supersededIds: [],
+ surface: null,
+ timeline: [],
+ title: id,
+ titleChanged: false,
+ };
+ rows.set(id, row);
+ return row;
+ };
+
+ for (const { results, run } of ordered) {
+ const roundIndex = run.roundIndex ?? 0;
+ const plan = (run.plan ?? []) as VerifyCheckItem[];
+ const planById = new Map(plan.map((item) => [item.id, item]));
+ const logicalIdByCheckItemId = new Map(
+ plan.map((item) => [
+ item.id,
+ item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id),
+ ]),
+ );
+
+ for (const item of plan) {
+ const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
+ const row = ensureRow(logicalId, roundIndex);
+ logicalIdByPlanItemId.set(item.id, logicalId);
+ // The latest snapshot wins: repair rounds may refine method/expected.
+ if (item.sourceFlowNode) {
+ // A rerun is a fresh execution; historical evidence stays in the timeline.
+ row.result = undefined;
+ row.resultRound = undefined;
+ }
+ row.planItem = item;
+ row.title = item.title;
+ row.required = item.required;
+ row.category = item.category ?? row.category;
+ row.surface = itemSurface(item) ?? row.surface;
+ lastPlannedRound.set(logicalId, roundIndex);
+ }
+
+ for (const result of results) {
+ const logicalId = logicalIdByCheckItemId.get(result.checkItemId) ?? result.checkItemId;
+ const row = ensureRow(logicalId, roundIndex);
+ const state = resultState(result);
+ // The title THIS round used β€” the current round's snapshot, not the final one.
+ const roundTitle =
+ planById.get(result.checkItemId)?.title ?? result.checkItemTitle ?? row.title;
+ row.history.push({ roundIndex, state, verifyRunId: run.id });
+ row.timeline.push({
+ resultId: result.id,
+ roundIndex,
+ state,
+ title: roundTitle,
+ verifyRunId: run.id,
+ });
+ row.result = result;
+ row.resultRound = roundIndex;
+ if (!row.planItem && result.checkItemTitle) row.title = result.checkItemTitle;
+ if (!row.planItem) row.required = result.required;
+ }
+ }
+
+ // Fold superseded generations into their successor's timeline, in round
+ // order so a chain (C replaced by B replaced by A) collapses fully into A.
+ const foldOrder = [...rows.values()].sort((a, b) => a.introducedAtRound - b.introducedAtRound);
+ for (const row of foldOrder) {
+ const supersedes = (row.planItem?.supersedes ?? []).map((id) =>
+ rows.has(id) ? id : (logicalIdByPlanItemId.get(id) ?? id),
+ );
+ for (const oldId of supersedes) {
+ const old = rows.get(oldId);
+ if (!old || old === row) continue;
+ row.timeline = [...old.timeline, ...row.timeline].sort((a, b) => a.roundIndex - b.roundIndex);
+ row.history = [...old.history, ...row.history].sort((a, b) => a.roundIndex - b.roundIndex);
+ row.introducedAtRound = Math.min(row.introducedAtRound, old.introducedAtRound);
+ row.supersededIds = [...row.supersededIds, ...old.supersededIds, old.id];
+ // The successor's own state stands; a never-run successor inherits the
+ // superseded item's final result so the row still shows evidence.
+ if (!row.result && old.result) {
+ row.result = old.result;
+ row.resultRound = old.resultRound;
+ }
+ rows.delete(oldId);
+ }
+ }
+
+ // Number the surviving rows by first appearance (Map insertion order) β€”
+ // stable as rounds accrue, because a new round only appends new ids.
+ let seq = 0;
+ for (const row of rows.values()) row.seq = ++seq;
+
+ for (const row of rows.values()) {
+ row.state = row.result ? resultState(row.result) : 'not_executed';
+ row.fixed = row.state === 'passed' && row.history.some((entry) => entry.state === 'failed');
+ row.revisions = row.timeline.length;
+ row.titleChanged = row.timeline.some((entry) => entry.title !== row.title);
+ // Carried forward: a later round still planned the item but never re-ran it,
+ // so the final evidence predates the current round.
+ const planned = lastPlannedRound.get(row.id);
+ if (row.resultRound !== undefined && planned !== undefined && planned > row.resultRound) {
+ row.carriedFromRound = row.resultRound;
+ }
+ }
+
+ // Organization belongs to the current acceptance, not its immutable execution
+ // snapshots. Preserve IDs, numbering and result references when a check moves.
+ const grouped = new Map<string, AcceptanceCheckRow>();
+ for (const group of groups) {
+ for (const id of group.checkItemIds) {
+ const row = rows.get(id);
+ if (row) grouped.set(id, { ...row, category: group.title });
+ }
+ }
+ return [...grouped.values(), ...[...rows.values()].filter((row) => !grouped.has(row.id))];
+};
+
+/**
+ * The union's own three-way split, counted β€” the number a summary can show
+ * without opening the list.
+ *
+ * It counts UNION ROWS, not one round's result rows. A repair round re-runs the
+ * check it was asked to fix and carries the rest forward, so the current round's
+ * rows are a subset of the union: counting them would print "1 passed" beside a
+ * list that expands to the repaired check plus everything it carried, and the
+ * two readings of one acceptance would contradict each other.
+ */
+export const tallyCheckUnion = (checks: AcceptanceCheckRow[]): VerifyCheckTally => {
+ let failed = 0;
+ let passed = 0;
+ let unjudged = 0;
+ for (const check of checks) {
+ if (check.state === 'passed') passed++;
+ else if (check.state === 'failed') failed++;
+ // `uncertain` and `not_executed` are both "planned, never judged" β€” the same
+ // split the acceptance's criteria list draws.
+ else unjudged++;
+ }
+ return { failed, passed, total: checks.length, unjudged };
+};
diff --git a/apps/server/src/services/verify/acceptanceService/deps.ts b/apps/server/src/services/verify/acceptanceService/deps.ts
new file mode 100644
index 00000000000..ddf8fcc9825
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/deps.ts
@@ -0,0 +1,35 @@
+import type { AcceptanceModel } from '@/database/models/acceptance';
+import type { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import type { VerifyRunModel } from '@/database/models/verifyRun';
+import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+
+/**
+ * What the `AcceptanceService` sub-domain modules read from the service.
+ *
+ * Use when:
+ * - A function under `acceptanceService/` needs the caller scope, the actor,
+ * or one of the models the service instance owns
+ *
+ * Expects:
+ * - The service builds it on every call, so a field replaced after
+ * construction (and a spied `loadRounds`) is what the function sees
+ */
+export interface AcceptanceServiceDeps {
+ acceptanceModel: AcceptanceModel;
+ /** Who is credited for the writes; see `AcceptanceService.actorUserId`. */
+ actorUserId: string;
+ db: LobeChatDatabase;
+ loadRounds: (
+ acceptanceId: string,
+ ) => Promise<{ results: VerifyCheckResultItem[]; runs: VerifyRunItem[] }>;
+ resultModel: VerifyCheckResultModel;
+ runModel: VerifyRunModel;
+ userId: string;
+ workspaceId?: string;
+}
+
+/** The parameters of a sub-domain function after its leading `deps`. */
+export type WithoutDeps<F> = F extends (deps: AcceptanceServiceDeps, ...args: infer A) => unknown
+ ? A
+ : never;
diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.ts
new file mode 100644
index 00000000000..f4bea1ebe5e
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/index.ts
@@ -0,0 +1,728 @@
+import { isDraftVerifyRun } from '@lobechat/const/verify';
+import type {
+ AcceptanceCheckGroup,
+ AcceptanceConfig,
+ AcceptanceStatus,
+ AcceptanceSubjectType,
+ VerifyCheckTally,
+ VerifyRunDecisionDetail,
+} from '@lobechat/types';
+import debug from 'debug';
+
+import { AcceptanceModel } from '@/database/models/acceptance';
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
+import { VerifyReportModel } from '@/database/models/verifyReport';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type {
+ AcceptanceItem,
+ VerifyCheckResultItem,
+ VerifyRunItem,
+} from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+import { notifyAcceptance } from '@/server/services/acceptanceReview/events';
+import { ExpertiseRejectionWorkflow } from '@/server/workflows/expertiseRejection';
+
+import { requireDecidableAcceptance } from '../acceptanceDecision';
+import { type AcceptanceMergeSummary, mergeAcceptanceRounds } from '../acceptanceMerge';
+import {
+ assertPlanLeavesAcceptedChecksAlone,
+ type AttachedRun,
+ withUnresolvedSupersedes,
+} from './attachGuards';
+import { buildAcceptanceCheckUnion, tallyCheckUnion } from './checkUnion';
+import type { AcceptanceServiceDeps, WithoutDeps } from './deps';
+import {
+ type AcceptanceListOptions,
+ isInOwnScope,
+ latestCheckCounts,
+ resolveForeignSubjects,
+ resolveProjects,
+ resolveSubjects,
+ statusesForFilter,
+} from './listing';
+import { findRepairOrigin, resolveOrigin } from './origin';
+import { reviewChecks } from './reviewChecks';
+import { statusFromRound } from './statusRollup';
+import {
+ type AcceptanceSubjectSummary,
+ assertSubjectExists,
+ resolveRunTopicTaskId,
+ resolveSubject,
+ resolveSubjectProjectId,
+} from './subjects';
+import {
+ completeTaskForDelivery,
+ completeTaskSubject,
+ reopenRejectedTaskSubject,
+} from './taskLifecycle';
+
+export type { AttachedRun } from './attachGuards';
+export type {
+ AcceptanceCheckHistoryEntry,
+ AcceptanceCheckRow,
+ AcceptanceTimelineEntry,
+} from './checkUnion';
+export { buildAcceptanceCheckUnion, tallyCheckUnion } from './checkUnion';
+export type { AcceptanceListFilter, AcceptanceListOptions } from './listing';
+export type {
+ AcceptanceCheckReviewEvent,
+ AcceptanceCheckReviewOverlay,
+ AcceptanceCheckUserReview,
+} from './reviewOverlay';
+export { buildCheckReviewOverlay } from './reviewOverlay';
+export type { AcceptanceSubjectSummary } from './subjects';
+
+const log = debug('lobe-server:verify-acceptance');
+
+export class AcceptanceService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ readonly acceptanceModel: AcceptanceModel;
+ private readonly runModel: VerifyRunModel;
+ private readonly resultModel: VerifyCheckResultModel;
+ private readonly evidenceModel: VerifyEvidenceModel;
+ private readonly reportModel: VerifyReportModel;
+
+ /**
+ * Who is CREDITED for the writes this service performs.
+ *
+ * Normally the same person the service is scoped to. They diverge for an
+ * elevated write β€” a workspace owner acting on a teammate's delivery β€” where
+ * the scope has to be the row's owner for the ownership predicate to resolve
+ * it at all, while `decidedBy` must still name the human who decided. An
+ * audit trail that credits a teammate's verdict to the author is worse than
+ * one nobody can sign.
+ */
+ private readonly actorUserId: string;
+
+ constructor(
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+ options?: { actorUserId?: string },
+ ) {
+ this.db = db;
+ this.userId = userId;
+ this.actorUserId = options?.actorUserId ?? userId;
+ this.workspaceId = workspaceId;
+ this.acceptanceModel = new AcceptanceModel(db, userId, workspaceId);
+ this.runModel = new VerifyRunModel(db, userId, workspaceId);
+ this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
+ this.evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
+ this.reportModel = new VerifyReportModel(db, userId, workspaceId);
+ }
+
+ /** Collaborators the extracted sub-domain functions read β€” resolved on every call. */
+ private get deps(): AcceptanceServiceDeps {
+ return {
+ acceptanceModel: this.acceptanceModel,
+ actorUserId: this.actorUserId,
+ db: this.db,
+ loadRounds: this.loadRounds,
+ resultModel: this.resultModel,
+ runModel: this.runModel,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ };
+ }
+
+ /** Get (or create) the aggregate for a subject, validating the subject first. */
+ ensureForSubject = async (
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+ defaults?: { config?: AcceptanceConfig; requirement?: string; title?: string },
+ ): Promise<AcceptanceItem> => {
+ await assertSubjectExists(this.deps, subjectType, subjectId);
+ const projectId = await resolveSubjectProjectId(this.deps, subjectType, subjectId);
+ return this.acceptanceModel.ensureForSubject(subjectType, subjectId, {
+ config: defaults?.config,
+ projectId,
+ requirement: defaults?.requirement,
+ ...(subjectType === 'standalone' && defaults?.title
+ ? { metadata: { title: defaults.title } }
+ : {}),
+ });
+ };
+
+ /**
+ * The ingest entry point (`lh acceptance run ingest`). An agent authoring its
+ * own report inside a Task run only knows its topic, so a topic subject that
+ * is a Task's run topic is folded onto that Task β€” otherwise the delivery
+ * lands on a topic aggregate no task surface reads, and the Task page shows
+ * no acceptance at all. A topic that already owns an acceptance keeps it, so
+ * its earlier rounds are not split across two aggregates; recurring
+ * (automation) tasks stay on their per-tick topic.
+ */
+ ensureForIngest = async (
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+ defaults?: { requirement?: string; title?: string },
+ ): Promise<AcceptanceItem> => {
+ const taskId =
+ subjectType === 'topic' ? await resolveRunTopicTaskId(this.deps, subjectId) : undefined;
+ if (taskId) return this.ensureForSubject('task', taskId, defaults);
+ return this.ensureForSubject(subjectType, subjectId, defaults);
+ };
+
+ /**
+ * Chain a run onto an acceptance as its next round, then re-derive the
+ * aggregate status (a new round re-opens a rejected loop).
+ */
+ attachRun = async (runId: string, acceptanceId: string): Promise<AttachedRun> => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
+
+ return this.attachResolvedRun(runId, acceptance);
+ };
+
+ /** Attach a Task run using policy scope while preserving report visibility. */
+ attachPolicyRun = async (runId: string, acceptanceId: string): Promise<AttachedRun> => {
+ const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);
+ if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
+
+ return this.attachResolvedRun(runId, acceptance);
+ };
+
+ private attachResolvedRun = async (
+ runId: string,
+ acceptance: AcceptanceItem,
+ ): Promise<AttachedRun> => {
+ const acceptanceId = acceptance.id;
+
+ // Idempotent for the re-ingest path (the CLI sidecar remembers the run):
+ // an already-chained round keeps its index instead of being re-appended.
+ const existing = await this.runModel.findById(runId);
+ if (!existing) throw new Error(`Verify run "${runId}" not found in the current workspace`);
+ // A retried attach (the response of the first one was lost) still reports
+ // the warnings the first one did.
+ if (existing.acceptanceId === acceptanceId)
+ return withUnresolvedSupersedes(this.deps, existing, acceptanceId);
+ if (existing.acceptanceId) {
+ throw new Error('This verify run already belongs to another acceptance');
+ }
+ if (acceptance.status === 'accepted' || acceptance.status === 'closed') {
+ throw new Error(
+ `This acceptance has already been ${acceptance.status} β€” reopen it before attaching another round`,
+ );
+ }
+
+ await assertPlanLeavesAcceptedChecksAlone(this.deps, existing, acceptanceId);
+
+ // A round that is still only planned has nothing to preserve: the incoming
+ // run folds into it instead of pushing the ledger to yet another number.
+ // Only the newest round counts β€” `listByAcceptance` is ascending, and an
+ // older draft the chain has moved past is an abandoned ledger position.
+ const latest = (await this.runModel.listByAcceptance(acceptanceId)).at(-1);
+ // Resolved against the chain as it stood before this run joined it.
+ const withWarnings = (attached: VerifyRunItem): Promise<AttachedRun> =>
+ withUnresolvedSupersedes(this.deps, attached, acceptanceId, existing);
+ // A run that already executed cannot fold (`foldIntoRound` refuses any source
+ // with results): its verdicts belong to its own round. It is appended after
+ // the draft instead β€” the path a verification driven by the CLI takes, since
+ // it writes its results before the Task drive binds the round.
+ const draft =
+ latest && isDraftVerifyRun(latest) && (await this.resultModel.listByRun(runId)).length === 0
+ ? latest
+ : undefined;
+ if (draft) {
+ const folded = await this.runModel.foldIntoRound(runId, draft.id);
+ await this.recomputeStatus(acceptanceId);
+ log(
+ 'run %s folded into draft round %d of acceptance %s',
+ runId,
+ folded.roundIndex,
+ acceptanceId,
+ );
+ return await withWarnings(folded);
+ }
+
+ // Rounds inherit the aggregate's visibility so a private acceptance's new
+ // round never leaks through its own report URL.
+ const run = await this.runModel.attachToAcceptance(runId, acceptanceId, acceptance.visibility);
+ notifyAcceptance(acceptanceId, 'session');
+ await this.recomputeStatus(acceptanceId);
+ log('run %s attached to acceptance %s as round %d', runId, acceptanceId, run.roundIndex);
+
+ // A new round landing is the first server-side proof that the reviewer is done with the
+ // previous one: rejecting a check ends at a clipboard copy, so nothing else marks "I finished
+ // reviewing".
+ if (latest) this.distilSettledRound(acceptanceId, latest.id);
+
+ return await withWarnings(run);
+ };
+
+ /**
+ * Fold one acceptance into another β€” the source's checks (with their rounds,
+ * verdicts and evidence) become part of the target's inventory, and the
+ * source entry goes away.
+ *
+ * The two aggregates are the same delivery arriving twice: a second CLI
+ * ingest that minted a new standalone acceptance, or a topic and the task it
+ * was promoted into. Merging is what makes them one review surface again.
+ */
+ merge = async (sourceId: string, targetId: string): Promise<AcceptanceMergeSummary> => {
+ if (sourceId === targetId) throw new Error('An acceptance cannot be merged into itself');
+
+ const source = await this.acceptanceModel.findById(sourceId);
+ if (!source) throw new Error(`Acceptance "${sourceId}" not found`);
+ const target = await this.acceptanceModel.findById(targetId);
+ if (!target) throw new Error(`Acceptance "${targetId}" not found`);
+
+ // Same rule as attaching a single round: a settled aggregate must be
+ // re-opened deliberately before more checks land in it, or an `accepted`
+ // sign-off would silently start covering checks nobody signed off on.
+ if (target.status === 'accepted' || target.status === 'closed') {
+ throw new Error(
+ `This acceptance has already been ${target.status} β€” reopen it before merging into it`,
+ );
+ }
+
+ const summary = await mergeAcceptanceRounds({
+ db: this.db,
+ source,
+ target,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+
+ // Past this point the merge is COMMITTED and the source no longer exists β€”
+ // so a failure here must not be reported as a failed merge. The caller
+ // would surface a retry that can only ever fail ("Acceptance not found"),
+ // for a rollup that is derived and re-derived by every later round,
+ // decision and sweep. Log it and return the merge that did happen.
+ try {
+ await this.recomputeStatus(targetId);
+ } catch (error) {
+ log('acceptance %s merged, but status recompute failed (non-fatal): %O', targetId, error);
+ }
+
+ return summary;
+ };
+
+ /**
+ * Re-derive the aggregate's lifecycle state from its current round. The
+ * user's `accepted` / `closed` are terminal; `rejected` is sticky until a
+ * round newer than the decision arrives.
+ */
+ recomputeStatus = async (acceptanceId: string): Promise<AcceptanceStatus | null> => {
+ const acceptance = await this.acceptanceModel.findPolicyById(acceptanceId);
+ if (!acceptance) return null;
+ if (acceptance.status === 'accepted' || acceptance.status === 'closed') {
+ return acceptance.status;
+ }
+
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const current = runs.at(-1);
+ if (!current) return acceptance.status as AcceptanceStatus;
+
+ // The rejected round stays rejected; only a NEWER round re-opens the loop.
+ if (acceptance.status === 'rejected' && current.userDecision === 'reject') return 'rejected';
+
+ const report = await this.reportModel.findByRun(current.id);
+ const status = statusFromRound(current, Boolean(report));
+ if (status !== acceptance.status) {
+ await this.acceptanceModel.updatePolicyStatus(acceptanceId, status);
+ notifyAcceptance(acceptanceId, 'session');
+ log('acceptance %s β†’ %s (from round %d)', acceptanceId, status, current.roundIndex);
+ }
+
+ // Rounds settled outside the verifier pipeline β€” an ingested round (no
+ // status, settled by its report) or a completed acceptance flow
+ // (`delivered`) β€” have nothing else to drive the task. Rounds the server
+ // verifier runs (`passed` / `failed` / `errored`) are driven once, after
+ // any auto-repair, by `driveTaskFromVerify`; completing here would race it.
+ //
+ // Reconciled on every recompute of a delivered aggregate, not only on the
+ // transition: a completion that failed once is retried by the next round,
+ // report or flow event instead of leaving the task open for good. An
+ // already-completed task is a no-op.
+ if (
+ status === 'delivered' &&
+ (!current.status || current.status === 'delivered') &&
+ acceptance.subjectType === 'task'
+ )
+ await this.completeTaskForDelivery(acceptanceId, acceptance.subjectId);
+ return status;
+ };
+
+ /** Latest round of an aggregate β€” the row `stampDecision` would write to. */
+ latestRound = async (acceptanceId: string) => {
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ return runs.at(-1) ?? null;
+ };
+
+ regroupChecks = async (
+ acceptanceId: string,
+ groups: AcceptanceCheckGroup[],
+ expectedVersion: number,
+ ) => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) throw new Error('Acceptance not found');
+ const { results, runs } = await this.loadRounds(acceptanceId);
+ const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
+ 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 })),
+ );
+ const known = new Set(checks.map((check) => check.id));
+ const assigned = new Set<string>();
+ const titles = new Set<string>();
+ const normalized = groups.map((group) => {
+ const title = group.title.trim();
+ if (!title || titles.has(title) || group.checkItemIds.length === 0)
+ throw new Error('Check groups need unique, non-empty titles and members');
+ titles.add(title);
+ for (const id of group.checkItemIds) {
+ if (!known.has(id)) throw new Error(`Unknown check item: ${id}`);
+ if (assigned.has(id)) throw new Error(`Check assigned to multiple groups: ${id}`);
+ assigned.add(id);
+ }
+ return { ...group, title };
+ });
+ return this.acceptanceModel.setCheckGroups(acceptanceId, normalized, expectedVersion);
+ };
+
+ /**
+ * Hands one settled round to distillation, fire-and-forget.
+ *
+ * Never awaited and never allowed to throw: this rides on the reviewer's own paths, and losing a
+ * distillation is a missed lesson, while failing the caller loses their decision. Triggering the
+ * same round twice is harmless β€” a round is distilled under a reflection key, and the second pass
+ * finds the run already recorded and returns.
+ */
+ private distilSettledRound = (acceptanceId: string, verifyRunId: string) => {
+ void ExpertiseRejectionWorkflow.trigger({
+ acceptanceId,
+ userId: this.userId,
+ verifyRunId,
+ workspaceId: this.workspaceId,
+ });
+ };
+
+ /**
+ * The user accepts the delivery β€” the terminal business event (P-12). Stamps
+ * the decision on the current round, closes the aggregate, and best-effort
+ * completes a task subject that verification alone didn't settle.
+ */
+ accept = async (acceptanceId: string, comment?: string): Promise<AcceptanceItem> => {
+ const acceptance = await requireDecidableAcceptance(this.acceptanceModel, acceptanceId);
+
+ const settled = await this.stampDecision(acceptanceId, 'accept', comment);
+ await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
+ notifyAcceptance(acceptanceId, 'session', this.actorUserId);
+
+ // A terminal decision settles the current round as surely as a new round landing does β€” and it
+ // is the ONLY thing that settles the last one, which no later round will ever follow. Without
+ // this, every acceptance silently loses whatever its final round taught. Accepting the delivery
+ // still settles it: a reviewer can accept overall while individual checks were rejected along
+ // the way, and those rejections are exactly the material.
+ this.distilSettledRound(acceptanceId, settled);
+
+ if (acceptance.subjectType === 'task')
+ await completeTaskSubject(this.deps, acceptance.subjectId);
+
+ return (await this.acceptanceModel.findById(acceptanceId))!;
+ };
+
+ /**
+ * A merged pull request accepts the delivery it was linked to. Merging is
+ * the strongest signal a user can give, so unlike {@link accept} this does
+ * not wait for the round to settle: any non-accepted status becomes
+ * `accepted`, a round still in flight is stamped as decided by the merge,
+ * and an acceptance that never had a round is simply closed as accepted.
+ * The decision detail records the merge so the acceptance board and the
+ * verifier-training pipeline can tell it apart from a human verdict.
+ *
+ * Idempotent: an already-accepted acceptance is returned unchanged.
+ */
+ acceptFromScmMerge = async (
+ acceptanceId: string,
+ changeRequest: NonNullable<VerifyRunDecisionDetail['changeRequest']>,
+ ): Promise<AcceptanceItem | null> => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) return null;
+ if (acceptance.status === 'accepted') return acceptance;
+
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const current = runs.at(-1);
+ if (current) {
+ const detail: VerifyRunDecisionDetail = {
+ changeRequest,
+ decidedAt: new Date().toISOString(),
+ decidedBy: this.actorUserId,
+ source: 'scm_merge',
+ };
+ await this.runModel.setDecision(current.id, 'accept', detail);
+ }
+
+ await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
+ notifyAcceptance(acceptanceId, 'session', this.actorUserId);
+ if (current) this.distilSettledRound(acceptanceId, current.id);
+ if (acceptance.subjectType === 'task')
+ await completeTaskSubject(this.deps, acceptance.subjectId);
+
+ log(
+ 'acceptance %s accepted by merge of %s#%d (was %s)',
+ acceptanceId,
+ changeRequest.repoFullName,
+ changeRequest.number,
+ acceptance.status,
+ );
+ return (await this.acceptanceModel.findById(acceptanceId))!;
+ };
+
+ /**
+ * The user rejects the delivery. An optional comment is a re-tasking input: it is
+ * recorded on the round's decision detail, where the next repair/verify round
+ * picks it up. (Spawning the repair run is the caller's job β€” the
+ * `acceptance.reject` procedure sends it back to the origin agent when the
+ * rounds name one; see `dispatchAcceptanceRepair`.)
+ *
+ * A Goal Task is no exception: its next attempt is started by the Goal
+ * coordinator on the following tick, which reads the rejected round's
+ * decision detail through the prompt builder.
+ */
+ reject = async (acceptanceId: string, comment?: string): Promise<AcceptanceItem> => {
+ const acceptance = await requireDecidableAcceptance(this.acceptanceModel, acceptanceId);
+
+ const settled = await this.stampDecision(acceptanceId, 'reject', comment);
+ await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');
+ notifyAcceptance(acceptanceId, 'session', this.actorUserId);
+
+ this.distilSettledRound(acceptanceId, settled);
+
+ if (acceptance.subjectType === 'task')
+ await reopenRejectedTaskSubject(this.deps, acceptance.subjectId);
+
+ return (await this.acceptanceModel.findById(acceptanceId))!;
+ };
+
+ /** Records the user's verdict on one or more union checks β€” see {@link reviewChecks}. */
+ reviewChecks = (...args: WithoutDeps<typeof reviewChecks>) => reviewChecks(this.deps, ...args);
+
+ /** Stamps the decision on the current round and returns it β€” the round that decision settles. */
+ private stampDecision = async (
+ acceptanceId: string,
+ decision: 'accept' | 'reject',
+ comment?: string,
+ ): Promise<string> => {
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const current = runs.at(-1);
+ if (!current) throw new Error('This acceptance has no verification round to decide on');
+
+ const detail: VerifyRunDecisionDetail = {
+ decidedAt: new Date().toISOString(),
+ decidedBy: this.actorUserId,
+ ...(comment ? { comment } : {}),
+ };
+ await this.runModel.setDecision(current.id, decision, detail);
+
+ return current.id;
+ };
+
+ /** Completes the task a delivered acceptance settles β€” see {@link completeTaskForDelivery}. */
+ completeTaskForDelivery = (...args: WithoutDeps<typeof completeTaskForDelivery>) =>
+ completeTaskForDelivery(this.deps, ...args);
+
+ /** Best-effort subject header info for the bundle (title may be gone). */
+ resolveSubject = (...args: WithoutDeps<typeof resolveSubject>) =>
+ resolveSubject(this.deps, ...args);
+
+ private resolveSubjects = (...args: WithoutDeps<typeof resolveSubjects>) =>
+ resolveSubjects(this.deps, ...args);
+
+ private resolveProjects = (...args: WithoutDeps<typeof resolveProjects>) =>
+ resolveProjects(this.deps, ...args);
+
+ private latestCheckCounts = (...args: WithoutDeps<typeof latestCheckCounts>) =>
+ latestCheckCounts(this.deps, ...args);
+
+ /**
+ * Recent aggregates with their subject headers β€” the list-panel payload.
+ * Titles resolve in batches by subject type; a deleted
+ * subject degrades to a null title instead of dropping the row. Each row also
+ * carries the latest round's check count for the panel's at-a-glance line.
+ */
+ listWithSubjects = async (
+ options: AcceptanceListOptions & {
+ limit?: number;
+ q?: string;
+ } = {},
+ ) => {
+ const { filter = 'all', limit = 50, q } = options;
+ const normalizedQuery = q?.trim().toLocaleLowerCase();
+
+ // A title search must span the complete owned set. Subject titles live in
+ // their source entities (task/topic/document), so resolve them before
+ // applying the result cap instead of searching only the latest page.
+ const candidates = await this.acceptanceModel.query({
+ limit: normalizedQuery ? undefined : limit,
+ projectId: options.projectId,
+ scope: options.scope,
+ source: options.source,
+ statuses: statusesForFilter(filter),
+ unbounded: Boolean(normalizedQuery),
+ });
+ const subjects = await this.resolveSubjectsForList(candidates);
+ const matched = normalizedQuery
+ ? candidates
+ .filter((row) =>
+ (subjects.get(row.id)?.title || row.subjectId)
+ .toLocaleLowerCase()
+ .includes(normalizedQuery),
+ )
+ .slice(0, limit)
+ : candidates;
+
+ return this.decorateListRows(matched, subjects);
+ };
+
+ /**
+ * The paged twin of {@link listWithSubjects} β€” one scroll page of the list
+ * panel, newest first.
+ *
+ * Takes the same filter vocabulary, applied in the QUERY: a page of
+ * "in progress" is thirty in-progress rows, not thirty rows of which some
+ * happen to be in progress. Search deliberately has no paged form β€” a title
+ * search must span the whole owned set, which is what `listWithSubjects`
+ * already does; the panel asks that one when a query is active.
+ */
+ listPageWithSubjects = async (
+ options: AcceptanceListOptions & {
+ cursor?: string;
+ limit?: number;
+ },
+ ) => {
+ const { items, nextCursor } = await this.acceptanceModel.queryPage({
+ cursor: options.cursor,
+ limit: options.limit,
+ projectId: options.projectId,
+ scope: options.scope,
+ source: options.source,
+ statuses: statusesForFilter(options.filter ?? 'all'),
+ });
+
+ return {
+ items: await this.decorateListRows(items, await this.resolveSubjectsForList(items)),
+ nextCursor,
+ };
+ };
+
+ private isInOwnScope = (...args: WithoutDeps<typeof isInOwnScope>) =>
+ isInOwnScope(this.deps, ...args);
+
+ /**
+ * Subject headers for a mixed list. Rows in the caller's own scope go through
+ * the scoped models as before. A participated row may belong to any number of
+ * other owners, whose task/topic/document the caller's models cannot see β€”
+ * those resolve in ONE unscoped read per subject type, so the cost stays
+ * fixed however many owners a page spans. Safe because the list query has
+ * already applied the read rule to these rows, and the bundle shows the same
+ * title to anyone who can open them.
+ */
+ private resolveSubjectsForList = async (
+ rows: AcceptanceItem[],
+ ): Promise<Map<string, AcceptanceSubjectSummary>> => {
+ const own = rows.filter(this.isInOwnScope);
+ const foreign = rows.filter((row) => !this.isInOwnScope(row));
+ const [ownSubjects, foreignSubjects] = await Promise.all([
+ own.length > 0 ? this.resolveSubjects(own) : new Map<string, AcceptanceSubjectSummary>(),
+ this.resolveForeignSubjects(foreign),
+ ]);
+ return new Map([...ownSubjects, ...foreignSubjects]);
+ };
+
+ private resolveForeignSubjects = (...args: WithoutDeps<typeof resolveForeignSubjects>) =>
+ resolveForeignSubjects(this.deps, ...args);
+
+ private decorateListRows = async (
+ rows: AcceptanceItem[],
+ subjects: Map<string, AcceptanceSubjectSummary>,
+ ) => {
+ const [checkCounts, projects] = await Promise.all([
+ this.latestCheckCounts(rows.map((row) => row.id)),
+ // Projects stay in the caller's scope: another owner's project name is
+ // theirs, and a row filed under it simply reads as unfiled here.
+ this.resolveProjects(rows),
+ ]);
+
+ return rows.map((row) => ({
+ ...row,
+ checkCount: checkCounts.get(row.id) ?? null,
+ project: projects.get(row.id) ?? null,
+ subject: subjects.get(row.id)!,
+ }));
+ };
+
+ /** The authoring conversation behind the round chain β€” see {@link resolveOrigin}. */
+ resolveOrigin = (...args: WithoutDeps<typeof resolveOrigin>) => resolveOrigin(this.deps, ...args);
+
+ /** The raw origin a rejected delivery is sent back to β€” see {@link findRepairOrigin}. */
+ findRepairOrigin = (...args: WithoutDeps<typeof findRepairOrigin>) =>
+ findRepairOrigin(this.deps, ...args);
+
+ /** The rounds + their per-round data the bundle and the union both read. */
+ loadRounds = async (acceptanceId: string) => {
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const runIds = runs.map((r) => r.id);
+ const [results, evidence, reports] = await Promise.all([
+ this.resultModel.listByRuns(runIds),
+ this.evidenceModel.listByRuns(runIds),
+ this.reportModel.findByRuns(runIds),
+ ]);
+ return { evidence, reports, results, runs };
+ };
+
+ /**
+ * The union tally of several acceptances at once, counted from the SAME check
+ * union each acceptance page renders (`tallyCheckUnion` over
+ * `buildAcceptanceCheckUnion`), so a summary row and the list it expands to
+ * can never disagree about what a round chain judged.
+ *
+ * Batched on purpose: a surface that summarises many acceptances runs on a
+ * poll, so this is two statements regardless of how many it covers. An
+ * acceptance with no round at all is ABSENT from the map β€” a caller must not
+ * read "absent" as "nothing passed".
+ */
+ getCheckTalliesByAcceptances = async (
+ acceptanceIds: string[],
+ ): Promise<Map<string, VerifyCheckTally>> => {
+ const ids = [...new Set(acceptanceIds.filter(Boolean))];
+ const tallies = new Map<string, VerifyCheckTally>();
+ if (ids.length === 0) return tallies;
+
+ const runs = await this.runModel.listByAcceptances(ids);
+ const results = await this.resultModel.listByRuns(runs.map((run) => run.id));
+
+ const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
+ for (const result of results) {
+ if (!result.verifyRunId) continue;
+ const bucket = resultsByRun.get(result.verifyRunId) ?? [];
+ bucket.push(result);
+ resultsByRun.set(result.verifyRunId, bucket);
+ }
+
+ const runsByAcceptance = new Map<string, VerifyRunItem[]>();
+ for (const run of runs) {
+ if (!run.acceptanceId) continue;
+ const bucket = runsByAcceptance.get(run.acceptanceId) ?? [];
+ bucket.push(run);
+ runsByAcceptance.set(run.acceptanceId, bucket);
+ }
+
+ for (const [acceptanceId, acceptanceRuns] of runsByAcceptance) {
+ const checks = buildAcceptanceCheckUnion(
+ acceptanceRuns.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),
+ );
+ tallies.set(acceptanceId, tallyCheckUnion(checks));
+ }
+ return tallies;
+ };
+}
diff --git a/apps/server/src/services/verify/acceptanceService/listing.ts b/apps/server/src/services/verify/acceptanceService/listing.ts
new file mode 100644
index 00000000000..80d233b64ff
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/listing.ts
@@ -0,0 +1,241 @@
+import type { AcceptanceStatus, AcceptanceSubjectType } from '@lobechat/types';
+import debug from 'debug';
+
+import type {
+ AcceptanceListProject,
+ AcceptanceListScope,
+ AcceptanceListSource,
+} from '@/database/models/acceptance';
+import { DocumentModel } from '@/database/models/document';
+import { ProjectModel } from '@/database/models/project';
+import { TaskModel } from '@/database/models/task';
+import { TopicModel } from '@/database/models/topic';
+import type { AcceptanceItem } from '@/database/schemas/verify';
+import { notTrashed } from '@/database/utils/softDelete';
+
+import type { AcceptanceServiceDeps } from './deps';
+import type { AcceptanceSubjectSummary } from './subjects';
+
+const log = debug('lobe-server:verify-acceptance');
+
+/** The list filter as a status set β€” one definition for the flat and paged reads. */
+export type AcceptanceListFilter = 'active' | 'all' | 'completed';
+
+/** Every narrowing the list panel can apply, shared by the flat and paged reads. */
+export interface AcceptanceListOptions {
+ filter?: AcceptanceListFilter;
+ /** A project id, or `null` for acceptances filed under no project. */
+ projectId?: AcceptanceListProject;
+ scope?: AcceptanceListScope;
+ source?: AcceptanceListSource;
+}
+
+export const statusesForFilter = (filter: AcceptanceListFilter): AcceptanceStatus[] | undefined => {
+ if (filter === 'active')
+ return ['pending', 'planned', 'verifying', 'repairing', 'delivered', 'rejected', 'errored'];
+ if (filter === 'completed') return ['accepted', 'closed'];
+ return undefined;
+};
+
+/** Resolve list subjects in one query per entity type, regardless of history size. */
+export const resolveSubjects = async (
+ deps: AcceptanceServiceDeps,
+ acceptances: AcceptanceItem[],
+): Promise<Map<string, AcceptanceSubjectSummary>> => {
+ const result = new Map<string, AcceptanceSubjectSummary>();
+ const idsByType = new Map<AcceptanceSubjectType, string[]>();
+ for (const acceptance of acceptances) {
+ const type = acceptance.subjectType as AcceptanceSubjectType;
+ const ids = idsByType.get(type) ?? [];
+ ids.push(acceptance.subjectId);
+ idsByType.set(type, ids);
+ }
+
+ try {
+ const [tasks, topics, documents] = await Promise.all([
+ new TaskModel(deps.db, deps.userId, deps.workspaceId).resolveMany(
+ idsByType.get('task') ?? [],
+ ),
+ // Creator-facing lookup: exclude agent-share visitor topics from the
+ // subject summary batch.
+ new TopicModel(deps.db, deps.userId, deps.workspaceId).findOwnTopicsByIds(
+ idsByType.get('topic') ?? [],
+ ),
+ new DocumentModel(deps.db, deps.userId, deps.workspaceId).findByIds(
+ idsByType.get('document') ?? [],
+ ),
+ ]);
+ const taskTitles = new Map<string, string | null>();
+ for (const task of tasks) {
+ const title = task.name ?? task.identifier;
+ taskTitles.set(task.id, title);
+ taskTitles.set(task.identifier, title);
+ }
+ const topicTitles = new Map(topics.map((topic) => [topic.id, topic.title ?? null]));
+ const documentTitles = new Map(
+ documents.map((document) => [document.id, document.title ?? null]),
+ );
+
+ for (const acceptance of acceptances) {
+ const type = acceptance.subjectType as AcceptanceSubjectType;
+ const override = acceptance.metadata?.title;
+ const overrideTitle =
+ typeof override === 'string' && override.trim() ? override.trim() : null;
+ const title =
+ overrideTitle ??
+ (type === 'task'
+ ? taskTitles.get(acceptance.subjectId)
+ : type === 'topic'
+ ? topicTitles.get(acceptance.subjectId)
+ : type === 'document'
+ ? documentTitles.get(acceptance.subjectId)
+ : null) ??
+ null;
+ result.set(acceptance.id, { id: acceptance.subjectId, title, type });
+ }
+ } catch (error) {
+ log('resolveSubjects failed (non-fatal): %O', error);
+ for (const acceptance of acceptances) {
+ result.set(acceptance.id, {
+ id: acceptance.subjectId,
+ title: typeof acceptance.metadata?.title === 'string' ? acceptance.metadata.title : null,
+ type: acceptance.subjectType as AcceptanceSubjectType,
+ });
+ }
+ }
+ return result;
+};
+
+/** Resolve the projects referenced directly by acceptances in one bounded read. */
+export const resolveProjects = async (
+ deps: AcceptanceServiceDeps,
+ acceptances: AcceptanceItem[],
+): Promise<Map<string, { id: string; name: string }>> => {
+ const result = new Map<string, { id: string; name: string }>();
+ const projectIds = [
+ ...new Set(acceptances.map(({ projectId }) => projectId).filter((id): id is string => !!id)),
+ ];
+ if (projectIds.length === 0) return result;
+
+ try {
+ const projects = await new ProjectModel(deps.db, deps.userId, deps.workspaceId).findByIds(
+ projectIds,
+ );
+ const projectById = new Map(projects.map((project) => [project.id, project]));
+
+ for (const acceptance of acceptances) {
+ if (!acceptance.projectId) continue;
+ const project = projectById.get(acceptance.projectId);
+ if (project) result.set(acceptance.id, { id: project.id, name: project.name });
+ }
+ } catch (error) {
+ log('resolveProjects failed (non-fatal): %O', error);
+ }
+ return result;
+};
+
+/**
+ * The latest round's total-check count per acceptance β€” a cheap glance for the
+ * list panel (two batched reads, never a per-row union recompute). The signed-
+ * off/accepted count would need the cross-round union per row, which is far too
+ * heavy for a list, so the panel shows the total and leans on the row's status
+ * glyph for the decision state.
+ */
+export const latestCheckCounts = async (
+ deps: AcceptanceServiceDeps,
+ acceptanceIds: string[],
+): Promise<Map<string, number>> => {
+ const out = new Map<string, number>();
+ if (acceptanceIds.length === 0) return out;
+
+ const runs = await deps.db.query.verifyRuns.findMany({
+ columns: { acceptanceId: true, id: true, roundIndex: true },
+ where: (run, { inArray }) => inArray(run.acceptanceId, acceptanceIds),
+ });
+ const latest = new Map<string, { id: string; round: number }>();
+ for (const run of runs) {
+ if (!run.acceptanceId) continue;
+ const round = run.roundIndex ?? 0;
+ const cur = latest.get(run.acceptanceId);
+ if (!cur || round > cur.round) latest.set(run.acceptanceId, { id: run.id, round });
+ }
+
+ // Unscoped on purpose, like the run read above: the run ids derive from
+ // acceptance ids the caller's list query already authorized, and a
+ // participated row's report belongs to its owner β€” an owner-scoped read
+ // would need one query per owner.
+ const runIds = [...latest.values()].map((v) => v.id);
+ const reports =
+ runIds.length > 0
+ ? await deps.db.query.verifyReports.findMany({
+ columns: { totalChecks: true, verifyRunId: true },
+ where: (report, { inArray }) => inArray(report.verifyRunId, runIds),
+ })
+ : [];
+ const totalByRun = new Map(reports.map((report) => [report.verifyRunId, report.totalChecks]));
+ for (const [acceptanceId, { id: runId }] of latest) {
+ const total = totalByRun.get(runId);
+ if (total != null) out.set(acceptanceId, total);
+ }
+ return out;
+};
+
+export const isInOwnScope = (deps: AcceptanceServiceDeps, row: AcceptanceItem) =>
+ row.workspaceId
+ ? row.workspaceId === deps.workspaceId
+ : !deps.workspaceId && row.userId === deps.userId;
+
+export const resolveForeignSubjects = async (
+ deps: AcceptanceServiceDeps,
+ rows: AcceptanceItem[],
+): Promise<Map<string, AcceptanceSubjectSummary>> => {
+ const result = new Map<string, AcceptanceSubjectSummary>();
+ if (rows.length === 0) return result;
+
+ const idsOf = (type: AcceptanceSubjectType) =>
+ rows.filter((row) => row.subjectType === type).map((row) => row.subjectId);
+ const titles = new Map<string, string | null>();
+ try {
+ const [taskIds, topicIds, documentIds] = [idsOf('task'), idsOf('topic'), idsOf('document')];
+ const [taskRows, topicRows, documentRows] = await Promise.all([
+ taskIds.length > 0
+ ? deps.db.query.tasks.findMany({
+ columns: { id: true, identifier: true, name: true },
+ where: (task, { and, inArray }) =>
+ and(inArray(task.id, taskIds), notTrashed(task.isDeleted)),
+ })
+ : [],
+ topicIds.length > 0
+ ? deps.db.query.topics.findMany({
+ columns: { id: true, title: true },
+ where: (topic, { and, inArray }) =>
+ and(inArray(topic.id, topicIds), notTrashed(topic.isDeleted)),
+ })
+ : [],
+ documentIds.length > 0
+ ? deps.db.query.documents.findMany({
+ columns: { id: true, title: true },
+ where: (document, { and, inArray }) =>
+ and(inArray(document.id, documentIds), notTrashed(document.isDeleted)),
+ })
+ : [],
+ ]);
+ for (const task of taskRows) titles.set(`task:${task.id}`, task.name ?? task.identifier);
+ for (const topic of topicRows) titles.set(`topic:${topic.id}`, topic.title ?? null);
+ for (const document of documentRows)
+ titles.set(`document:${document.id}`, document.title ?? null);
+ } catch (error) {
+ log('resolveForeignSubjects failed (non-fatal): %O', error);
+ }
+
+ for (const row of rows) {
+ const override = row.metadata?.title;
+ const overrideTitle = typeof override === 'string' && override.trim() ? override.trim() : null;
+ result.set(row.id, {
+ id: row.subjectId,
+ title: overrideTitle ?? titles.get(`${row.subjectType}:${row.subjectId}`) ?? null,
+ type: row.subjectType as AcceptanceSubjectType,
+ });
+ }
+ return result;
+};
diff --git a/apps/server/src/services/verify/acceptanceService/origin.ts b/apps/server/src/services/verify/acceptanceService/origin.ts
new file mode 100644
index 00000000000..a39f5566db4
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/origin.ts
@@ -0,0 +1,65 @@
+import { AgentModel } from '@/database/models/agent';
+import { TopicModel } from '@/database/models/topic';
+import type { VerifyRunItem } from '@/database/schemas/verify';
+
+import type { AcceptanceServiceDeps } from './deps';
+
+/**
+ * The authoring conversation behind the round chain, resolved to displayable
+ * entities (agent avatar/title, topic title). Owner-only header data β€” the
+ * bundle must not include it for anonymous link holders.
+ */
+export const resolveOrigin = async (
+ deps: AcceptanceServiceDeps,
+ runs: VerifyRunItem[],
+): Promise<{
+ agent: {
+ avatar: string | null;
+ backgroundColor: string | null;
+ id: string;
+ title: string | null;
+ } | null;
+ topic: { id: string; title: string | null } | null;
+} | null> => {
+ const origin = [...runs].reverse().find((run) => run.metadata?.origin)?.metadata?.origin;
+ if (!origin?.agentId && !origin?.topicId) return null;
+
+ const topicRowPromise = origin.topicId
+ ? new TopicModel(deps.db, deps.userId, deps.workspaceId)
+ .findById(origin.topicId)
+ .catch(() => null)
+ : Promise.resolve(null);
+ // Dispatched runs (task / goal / device) record only the topic β€” the
+ // connector strips the ambient agent id β€” so the topic's own agent stands in.
+ // A recorded agent does not wait on the topic read.
+ const agentPromise = (
+ origin.agentId ? Promise.resolve(origin.agentId) : topicRowPromise.then((row) => row?.agentId)
+ ).then((agentId) =>
+ agentId
+ ? new AgentModel(deps.db, deps.userId, deps.workspaceId)
+ .getAgentAvatarsByIds([agentId])
+ .then((rows) => rows[0] ?? null)
+ .catch(() => null)
+ : null,
+ );
+ const [topicRow, agent] = await Promise.all([topicRowPromise, agentPromise]);
+ const topic = topicRow ? { id: topicRow.id, title: topicRow.title ?? null } : null;
+ if (!agent && !topic) return null;
+ return { agent, topic };
+};
+
+/**
+ * The raw authoring conversation behind the latest round that recorded one β€”
+ * the ids a rejected delivery is sent back to. Unlike {@link resolveOrigin}
+ * nothing is hydrated: the dispatcher re-reads the topic under the caller's
+ * own scope.
+ */
+export const findRepairOrigin = async (
+ deps: AcceptanceServiceDeps,
+ acceptanceId: string,
+): Promise<{ agentId?: string; topicId?: string } | null> => {
+ const runs = await deps.runModel.listByAcceptance(acceptanceId);
+ const origin = [...runs].reverse().find((run) => run.metadata?.origin)?.metadata?.origin;
+ if (!origin?.topicId) return null;
+ return { agentId: origin.agentId || undefined, topicId: origin.topicId };
+};
diff --git a/apps/server/src/services/verify/acceptanceService/reviewChecks.ts b/apps/server/src/services/verify/acceptanceService/reviewChecks.ts
new file mode 100644
index 00000000000..ba1bc564466
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/reviewChecks.ts
@@ -0,0 +1,147 @@
+import type {
+ AcceptanceCheckReviewAction,
+ AcceptanceRejectIntent,
+ AcceptanceReviewAnnotation,
+ ReviewProposalOutcome,
+ VerifyCheckDecisionDetail,
+} from '@lobechat/types';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyReviewPredictionModel } from '@/database/models/verifyReviewPrediction';
+import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+
+import { computeFalseFlags } from '../feedbackService';
+import { type AcceptanceCheckRow, buildAcceptanceCheckUnion } from './checkUnion';
+import type { AcceptanceServiceDeps } from './deps';
+
+const log = debug('lobe-server:verify-acceptance');
+
+const CHECK_DECISION_WRITE_CONCURRENCY = 10;
+
+/**
+ * Record the user's verdict on one or more union checks (a group-level
+ * "accept all" is just many ids). Stamps `user_decision` +
+ * `user_decision_detail` on each check's FINAL result row β€” the same data
+ * flywheel every other decision path writes (FP/FN flags included). Unlike
+ * the aggregate-level accept/reject, a per-check review is allowed at any
+ * lifecycle state β€” confirming a check mid-chain is exactly the point.
+ */
+export const reviewChecks = async (
+ deps: AcceptanceServiceDeps,
+ acceptanceId: string,
+ input: {
+ action: AcceptanceCheckReviewAction;
+ annotations?: AcceptanceReviewAnnotation[];
+ checkItemIds: string[];
+ comment?: string;
+ fileIds?: string[];
+ /** Recorded when this decision answered a model proposal. */
+ proposal?: Omit<ReviewProposalOutcome, 'respondedAt'>;
+ /** Which of the three jobs a reject is doing; absent means unclassified. */
+ rejectIntent?: AcceptanceRejectIntent;
+ },
+): Promise<{ resultIds: string[] }> => {
+ const acceptance = await deps.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
+
+ const { results, runs } = await deps.loadRounds(acceptanceId);
+
+ // Reviews address union rows β€” resolve each id (or a superseded alias) to
+ // its row, so a stale client can't stamp junk ids.
+ const resultsByRun = new Map<string, VerifyCheckResultItem[]>();
+ 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 })),
+ );
+ const rowById = new Map<string, AcceptanceCheckRow>();
+ for (const check of checks) {
+ rowById.set(check.id, check);
+ for (const oldId of check.supersededIds) rowById.set(oldId, check);
+ }
+
+ const unknown = input.checkItemIds.filter((id) => !rowById.has(id));
+ if (unknown.length > 0) {
+ throw new Error(`Unknown check item(s): ${unknown.join(', ')}`);
+ }
+
+ // The decision is stamped on evidence β€” a never-executed check has no
+ // result row to judge, so it cannot be reviewed yet.
+ const targets = new Map<string, VerifyCheckResultItem>();
+ const notExecuted: string[] = [];
+ for (const id of input.checkItemIds) {
+ const row = rowById.get(id)!;
+ if (row.result) targets.set(row.result.id, row.result);
+ else notExecuted.push(id);
+ }
+ if (notExecuted.length > 0) {
+ throw new Error(`Check(s) never executed β€” nothing to review: ${notExecuted.join(', ')}`);
+ }
+
+ const decision =
+ input.action === 'accept' ? 'accepted' : input.action === 'ignore' ? 'overridden' : 'rejected';
+ const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;
+ const detail: VerifyCheckDecisionDetail = {
+ decidedAt: new Date().toISOString(),
+ decidedBy: deps.actorUserId,
+ roundIndex: currentRoundIndex,
+ ...(input.comment ? { comment: input.comment } : {}),
+ ...(input.annotations?.length ? { annotations: input.annotations } : {}),
+ ...(input.fileIds?.length ? { fileIds: input.fileIds } : {}),
+ // Only meaningful on a reject β€” an accept has no intent to classify.
+ ...(input.rejectIntent && input.action === 'reject'
+ ? { rejectIntent: input.rejectIntent }
+ : {}),
+ ...(input.proposal
+ ? { proposal: { ...input.proposal, respondedAt: new Date().toISOString() } }
+ : {}),
+ };
+
+ // One transaction for the decision AND the proposal's answer. Written
+ // separately, a failing second write left the check rejected while its
+ // prediction stayed unanswered β€” and the decision then HIDES the proposal,
+ // so nothing could ever reconcile the pair again. Agreement analysis reads
+ // those two rows as a matched set; a durable split is worse than failing.
+ await deps.db.transaction(async (tx) => {
+ const resultModel = new VerifyCheckResultModel(tx, deps.userId, deps.workspaceId);
+
+ // `checkItemIds` is request-supplied (a group-level accept can carry many),
+ // so the per-row writes are capped rather than fanned out unbounded.
+ await pMap(
+ [...targets.values()],
+ (result) => {
+ const { isFalsePositive, isFalseNegative } = computeFalseFlags(result.verdict, decision);
+ return resultModel.update(result.id, {
+ isFalseNegative,
+ isFalsePositive,
+ userDecision: decision,
+ userDecisionDetail: detail,
+ });
+ },
+ { concurrency: CHECK_DECISION_WRITE_CONCURRENCY },
+ );
+
+ if (input.proposal) {
+ const answered = await new VerifyReviewPredictionModel(
+ tx,
+ deps.userId,
+ deps.workspaceId,
+ ).adjudicate(input.proposal.predictionId, {
+ adjudication: input.proposal.adjudication,
+ edit: input.proposal.edit,
+ });
+ // A zero-row update means the id was wrong or not ours; committing the
+ // decision alone would produce exactly the split this transaction exists
+ // to prevent.
+ if (!answered) throw new Error(`Proposal "${input.proposal.predictionId}" not found`);
+ }
+ });
+
+ log('acceptance %s: %d check result(s) marked %s', acceptanceId, targets.size, decision);
+ return { resultIds: [...targets.keys()] };
+};
diff --git a/apps/server/src/services/verify/acceptanceService/reviewOverlay.ts b/apps/server/src/services/verify/acceptanceService/reviewOverlay.ts
new file mode 100644
index 00000000000..575861176e3
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/reviewOverlay.ts
@@ -0,0 +1,114 @@
+import type {
+ AcceptanceAttachment,
+ AcceptanceCheckReviewAction,
+ AcceptanceReviewAnnotation,
+} from '@lobechat/types';
+
+import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+
+import type { AcceptanceCheckRow } from './checkUnion';
+
+// ============================================
+// User review overlay β€” the per-check human verdict layered onto the union.
+// An accept or ignore is sticky across rounds; a reject binds to the round it
+// judged and demotes to iteration history once a newer round lands.
+// ============================================
+
+/** The standing user verdict on one union row, derived from its result rows. */
+export interface AcceptanceCheckUserReview {
+ action: AcceptanceCheckReviewAction;
+ annotations?: AcceptanceReviewAnnotation[];
+ /** Attachments backing a reject, resolved to URLs by the bundle read. */
+ attachments?: AcceptanceAttachment[];
+ comment?: string;
+ createdAt: string;
+ roundIndex: number;
+ /**
+ * A reject made against a round older than the current one β€” the feedback
+ * was (or is being) consumed by a newer round, so the check is back to
+ * awaiting the user's confirmation instead of standing rejected.
+ */
+ stale: boolean;
+}
+
+/**
+ * One user decision on one executed step of a check, projected out of the
+ * result rows (`user_decision` + `user_decision_detail`) β€” no dedicated store:
+ * each round's row keeps the decision the user made on THAT round's evidence.
+ */
+export interface AcceptanceCheckReviewEvent {
+ action: AcceptanceCheckReviewAction;
+ annotations?: AcceptanceReviewAnnotation[];
+ /** Attachments backing the reject, resolved to URLs by the bundle read. */
+ attachments?: AcceptanceAttachment[];
+ comment?: string;
+ /** When the decision was made (ISO 8601; falls back to the row's timestamps). */
+ createdAt: string;
+ /** Who decided (user id). Absent on legacy rows, which only the owner could write. */
+ decidedBy?: string;
+ /** Uploaded/pasted screenshots backing the reject (FKs to files). */
+ fileIds?: string[];
+ /** The result row the decision is stamped on. */
+ id: string;
+ roundIndex: number;
+}
+
+export interface AcceptanceCheckReviewOverlay {
+ /** The full review trail for this check, oldest first β€” the iteration history input. */
+ reviews: AcceptanceCheckReviewEvent[];
+ /** The newest review, with its staleness resolved against the current round. */
+ userReview?: AcceptanceCheckUserReview;
+}
+
+/**
+ * Project a union row's review trail + standing user verdict from its result
+ * rows. Superseded generations' decisions ride along automatically β€” the union
+ * already folded their results into this row's timeline.
+ */
+export const buildCheckReviewOverlay = (
+ check: Pick<AcceptanceCheckRow, 'timeline'> & Partial<Pick<AcceptanceCheckRow, 'planItem'>>,
+ resultsById: Map<string, VerifyCheckResultItem>,
+ currentRoundIndex: number,
+): AcceptanceCheckReviewOverlay => {
+ const reviews: AcceptanceCheckReviewEvent[] = [];
+ for (const entry of check.timeline) {
+ const result = resultsById.get(entry.resultId);
+ const decision = result?.userDecision;
+ if (
+ !result ||
+ (decision !== 'accepted' && decision !== 'rejected' && decision !== 'overridden')
+ )
+ continue;
+ const detail = result.userDecisionDetail ?? undefined;
+ reviews.push({
+ action: decision === 'accepted' ? 'accept' : decision === 'overridden' ? 'ignore' : 'reject',
+ annotations: detail?.annotations,
+ comment: detail?.comment,
+ createdAt: detail?.decidedAt ?? (result.completedAt ?? result.createdAt)?.toISOString() ?? '',
+ decidedBy: detail?.decidedBy,
+ fileIds: detail?.fileIds,
+ id: result.id,
+ // A carried-forward check is judged at the CURRENT round even though its
+ // evidence row belongs to an older one β€” the detail records that round.
+ roundIndex: detail?.roundIndex ?? entry.roundIndex,
+ });
+ }
+ // ISO strings order lexically; ties (legacy rows without decidedAt) keep round order.
+ reviews.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.roundIndex - b.roundIndex);
+
+ const latest = reviews.at(-1);
+ if (!latest) return { reviews };
+ return {
+ reviews,
+ userReview: {
+ action: latest.action,
+ annotations: latest.annotations,
+ comment: latest.comment,
+ createdAt: latest.createdAt,
+ roundIndex: latest.roundIndex,
+ stale:
+ (Boolean(check.planItem?.sourceFlowNode) || latest.action === 'reject') &&
+ latest.roundIndex < currentRoundIndex,
+ },
+ };
+};
diff --git a/apps/server/src/services/verify/acceptanceService/statusRollup.ts b/apps/server/src/services/verify/acceptanceService/statusRollup.ts
new file mode 100644
index 00000000000..a775018d909
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/statusRollup.ts
@@ -0,0 +1,39 @@
+import type { AcceptanceStatus } from '@lobechat/types';
+
+import type { VerifyRunItem } from '@/database/schemas/verify';
+
+// ============================================
+// Status rollup β€” the aggregate's user-facing lifecycle state, derived from the
+// current (highest) round. `accepted` is terminal and user-owned: recompute
+// never overwrites it. `rejected` holds until a newer round re-opens the loop.
+// ============================================
+
+/** Derive the aggregate status from the current round's pipeline state. */
+export const statusFromRound = (run: VerifyRunItem, hasReport: boolean): AcceptanceStatus => {
+ switch (run.status) {
+ case 'planned': {
+ return 'planned';
+ }
+ case 'verifying': {
+ return 'verifying';
+ }
+ case 'repairing': {
+ return 'repairing';
+ }
+ case 'errored': {
+ return 'errored';
+ }
+ // Both settled outcomes await the same human decision β€” the verdict is
+ // advice, acceptance is the user's event (P-12).
+ case 'passed':
+ case 'failed':
+ case 'delivered': {
+ return 'delivered';
+ }
+ default: {
+ // Ingested rounds carry no rollup status: a published report means the
+ // round has settled and awaits the decision; otherwise it is still open.
+ return hasReport ? 'delivered' : 'verifying';
+ }
+ }
+};
diff --git a/apps/server/src/services/verify/acceptanceService/subjects.ts b/apps/server/src/services/verify/acceptanceService/subjects.ts
new file mode 100644
index 00000000000..8abfd813b48
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/subjects.ts
@@ -0,0 +1,152 @@
+import type { AcceptanceSubjectType } from '@lobechat/types';
+import debug from 'debug';
+
+import { DocumentModel } from '@/database/models/document';
+import { GoalModel } from '@/database/models/goal';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import { TopicModel } from '@/database/models/topic';
+import type { AcceptanceItem } from '@/database/schemas/verify';
+
+import type { AcceptanceServiceDeps } from './deps';
+
+const log = debug('lobe-server:verify-acceptance');
+
+export interface AcceptanceSubjectSummary {
+ id: string;
+ title: string | null;
+ type: AcceptanceSubjectType;
+}
+
+/**
+ * Validate the subject exists in the caller's scope before creating an
+ * aggregate for it β€” the table deliberately has no FK (polymorphic subject),
+ * so this is where dangling aggregates are prevented.
+ */
+export const assertSubjectExists = async (
+ deps: AcceptanceServiceDeps,
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+): Promise<void> => {
+ // Standalone acceptances are the subject themselves. They deliberately do
+ // not require a Task/Topic/Document row, which keeps external repositories
+ // from having to manufacture a LobeHub task before publishing evidence.
+ if (subjectType === 'standalone') return;
+
+ const found = await findSubject(deps, subjectType, subjectId);
+ if (!found) {
+ throw new Error(`${subjectType} "${subjectId}" not found in the current workspace`);
+ }
+};
+
+export const findSubject = async (
+ deps: AcceptanceServiceDeps,
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+): Promise<{ title: string | null } | null> => {
+ switch (subjectType) {
+ case 'task': {
+ const task = await new TaskModel(deps.db, deps.userId, deps.workspaceId).resolve(subjectId);
+ return task ? { title: task.name ?? task.identifier } : null;
+ }
+ case 'topic': {
+ // Creator-facing lookup: an agent-share visitor topic must not be
+ // treated as a valid acceptance subject for the creator.
+ const topic = await new TopicModel(deps.db, deps.userId, deps.workspaceId).findOwnTopicById(
+ subjectId,
+ );
+ return topic ? { title: topic.title ?? null } : null;
+ }
+ case 'document': {
+ const doc = await new DocumentModel(deps.db, deps.userId, deps.workspaceId).findById(
+ subjectId,
+ );
+ return doc ? { title: doc.title ?? null } : null;
+ }
+ case 'goal_gate': {
+ const goal = await goalOfGate(deps, subjectId);
+ return goal ? { title: goal.title } : null;
+ }
+ case 'standalone': {
+ return null;
+ }
+ }
+};
+
+export const resolveRunTopicTaskId = async (
+ deps: AcceptanceServiceDeps,
+ topicId: string,
+): Promise<string | undefined> => {
+ const taskTopic = await new TaskTopicModel(deps.db, deps.userId, deps.workspaceId).findByTopicId(
+ topicId,
+ );
+ if (!taskTopic) return;
+ if (await deps.acceptanceModel.findBySubject('topic', topicId)) return;
+ const task = await new TaskModel(deps.db, deps.userId, deps.workspaceId).findById(
+ taskTopic.taskId,
+ );
+ if (!task || task.automationMode) return;
+ return task.id;
+};
+
+/** The Goal a release-gate subject (its review node) belongs to. */
+export const goalOfGate = (deps: AcceptanceServiceDeps, nodeId: string) =>
+ new GoalModel(deps.db, deps.userId, deps.workspaceId).findByNode(nodeId);
+
+export const resolveSubjectProjectId = async (
+ deps: AcceptanceServiceDeps,
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+): Promise<string | null> => {
+ if (subjectType === 'task') {
+ return (
+ (await new TaskModel(deps.db, deps.userId, deps.workspaceId).resolve(subjectId))?.projectId ??
+ null
+ );
+ }
+ if (subjectType === 'goal_gate') return (await goalOfGate(deps, subjectId))?.projectId ?? null;
+ if (subjectType === 'topic') {
+ const taskTopic = await new TaskTopicModel(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).findByTopicId(subjectId);
+ if (!taskTopic) return null;
+ return (
+ (await new TaskModel(deps.db, deps.userId, deps.workspaceId).resolve(taskTopic.taskId))
+ ?.projectId ?? null
+ );
+ }
+ return null;
+};
+
+/** Best-effort subject header info for the bundle (title may be gone). */
+export const resolveSubject = async (
+ deps: AcceptanceServiceDeps,
+ acceptance: AcceptanceItem,
+): Promise<AcceptanceSubjectSummary> => {
+ // A user rename wins over the subject's own title β€” the sidebar entry is
+ // renamed without touching the source topic/task/document.
+ const override = acceptance.metadata?.title;
+ let title: string | null =
+ typeof override === 'string' && override.trim() ? override.trim() : null;
+ if (!title) {
+ try {
+ title =
+ (
+ await findSubject(
+ deps,
+ acceptance.subjectType as AcceptanceSubjectType,
+ acceptance.subjectId,
+ )
+ )?.title ?? null;
+ } catch (error) {
+ log('resolveSubject failed (non-fatal): %O', error);
+ }
+ }
+ return {
+ id: acceptance.subjectId,
+ title,
+ type: acceptance.subjectType as AcceptanceSubjectType,
+ };
+};
diff --git a/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts b/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
new file mode 100644
index 00000000000..41b0f59683a
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService/taskLifecycle.ts
@@ -0,0 +1,120 @@
+import debug from 'debug';
+
+import { GoalModel } from '@/database/models/goal';
+import { TaskModel } from '@/database/models/task';
+import { TaskService } from '@/server/services/task';
+
+import type { AcceptanceServiceDeps } from './deps';
+
+const log = debug('lobe-server:verify-acceptance');
+
+/**
+ * Completes a task subject that verification didn't already settle β€” on
+ * accept (e.g. the round failed but the user accepted anyway) and when an
+ * ingested round delivers. Best-effort: a task error must not undo the
+ * recorded acceptance.
+ */
+export const completeTaskSubject = async (
+ deps: AcceptanceServiceDeps,
+ subjectId: string,
+): Promise<void> => {
+ try {
+ const taskModel = new TaskModel(deps.db, deps.userId, deps.workspaceId);
+ const task = await taskModel.resolve(subjectId);
+ if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) return;
+
+ // TaskService cascades checkpoint / sibling rollup / downstream unlock β€”
+ // the same completion path settle.ts drives on a passed verify.
+ await new TaskService(deps.db, deps.userId, deps.workspaceId).updateStatus({
+ id: task.id,
+ status: 'completed',
+ });
+ log('acceptance β†’ task %s completed', task.id);
+ } catch (error) {
+ log('completeTaskSubject failed (non-fatal): %O', error);
+ }
+};
+
+/**
+ * The task whose status follows its acceptance's lifecycle: delivered β†’
+ * completed, rejected β†’ reopened. Goal graph tasks are driven by their
+ * coordinator (a paused task is its retry signal) and recurring tasks stay
+ * on their schedule, so neither follows the acceptance.
+ */
+export const resolveLifecycleTask = async (deps: AcceptanceServiceDeps, subjectId: string) => {
+ const task = await new TaskModel(deps.db, deps.userId, deps.workspaceId).resolve(subjectId);
+ if (!task || task.automationMode) return null;
+
+ const goal = await new GoalModel(deps.db, deps.userId, deps.workspaceId).findByGraphTask(task.id);
+ return goal ? null : task;
+};
+
+/**
+ * A delivered acceptance completes its task: the delivery is in, and the
+ * user's accept / reject decides from here. Shared by every settlement path.
+ *
+ * A reject can land at any point around the completion, so the decision is
+ * read on both sides of the write: rejected before β†’ the task is left alone;
+ * rejected in between β†’ the reject saw an unfinished task and did not reopen
+ * it, so it is reopened here. Best-effort β€” never fails the caller.
+ *
+ * @returns `completed` when the task now reads completed, `rejected` when a
+ * reject won, `skipped` when the task does not follow the acceptance or could
+ * not be completed.
+ */
+export const completeTaskForDelivery = async (
+ deps: AcceptanceServiceDeps,
+ acceptanceId: string,
+ subjectId: string,
+): Promise<'completed' | 'rejected' | 'skipped'> => {
+ try {
+ const task = await resolveLifecycleTask(deps, subjectId);
+ if (!task) return 'skipped';
+
+ const before = await deps.acceptanceModel.findPolicyById(acceptanceId);
+ if (before?.status === 'rejected') return 'rejected';
+ if (before?.status !== 'delivered') return 'skipped';
+
+ await completeTaskSubject(deps, task.id);
+ // `completeTaskSubject` is best-effort and swallows its own failures (e.g. a
+ // running operation that could not be interrupted). Only a task that really
+ // reads completed counts β€” anything else lets the caller fall back.
+ const written = await new TaskModel(deps.db, deps.userId, deps.workspaceId).findById(task.id);
+ if (written?.status !== 'completed') return 'skipped';
+
+ const after = await deps.acceptanceModel.findPolicyById(acceptanceId);
+ if (after?.status === 'rejected') {
+ await reopenRejectedTaskSubject(deps, task.id);
+ return 'rejected';
+ }
+ return 'completed';
+ } catch (error) {
+ log('completeTaskForDelivery failed (non-fatal): %O', error);
+ return 'skipped';
+ }
+};
+
+/**
+ * Rejecting a delivery reopens the task it completed, so the task is not left
+ * reading "done" while its repair is pending. Only a completed task moves β€”
+ * one the user already paused, canceled or restarted keeps its own state.
+ */
+export const reopenRejectedTaskSubject = async (
+ deps: AcceptanceServiceDeps,
+ subjectId: string,
+): Promise<void> => {
+ try {
+ const task = await resolveLifecycleTask(deps, subjectId);
+ if (task?.status !== 'completed') return;
+
+ await new TaskModel(deps.db, deps.userId, deps.workspaceId).updateStatusIfCurrent(
+ task.id,
+ 'completed',
+ 'paused',
+ { completedAt: null },
+ );
+ log('acceptance rejected β†’ task %s reopened as paused', task.id);
+ } catch (error) {
+ log('reopenRejectedTaskSubject failed (non-fatal): %O', error);
+ }
+};
diff --git a/apps/server/src/services/verify/taskAcceptance.ts b/apps/server/src/services/verify/taskAcceptance.ts
index 08141ed347f..95e22b6e755 100644
--- a/apps/server/src/services/verify/taskAcceptance.ts
+++ b/apps/server/src/services/verify/taskAcceptance.ts
@@ -1,108 +1,14 @@
-import type { AcceptanceConfig, TaskVerifyConfig } from '@lobechat/types';
import debug from 'debug';
-import { AcceptanceModel } from '@/database/models/acceptance';
-import { TaskModel } from '@/database/models/task';
-import type { AcceptanceItem, VerifyRunItem } from '@/database/schemas/verify';
+import type { VerifyRunItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
import { AcceptanceService } from './acceptanceService';
-const log = debug('lobe-server:verify-task-acceptance');
-
-export interface ResolvedTaskAcceptance {
- acceptance: AcceptanceItem;
- config: AcceptanceConfig;
- requirement?: string;
-}
-
-const toAcceptanceConfig = (verify: TaskVerifyConfig): AcceptanceConfig => ({
- enabled: verify.enabled,
- maxIterations: verify.maxIterations,
- verifierAgentId: verify.verifierAgentId,
- verifyCriteriaIds: verify.verifyCriteriaIds,
- verifyRubricId: verify.verifyRubricId,
-});
-
-/**
- * Resolve the Acceptance that owns a Task's completion contract.
- *
- * `tasks.config.verify` is read only as a legacy compatibility source. The first
- * read materializes it into the Task's Acceptance; all new flows write the
- * Acceptance directly.
- */
-export const resolveTaskAcceptance = async (
- db: LobeChatDatabase,
- userId: string,
- taskId: string,
- workspaceId?: string,
-): Promise<ResolvedTaskAcceptance | undefined> => {
- const acceptanceModel = new AcceptanceModel(db, userId, workspaceId);
- const taskModel = new TaskModel(db, userId, workspaceId);
- const ownAcceptance = await acceptanceModel.findPolicyBySubject('task', taskId);
- const seen = new Set<string>();
- let currentTaskId: string | null = taskId;
- let inheritedConfig: AcceptanceConfig | undefined;
- let inheritedRequirement: string | undefined;
- let policyAcceptance: AcceptanceItem | undefined;
- let taskProjectId: string | null | undefined;
-
- while (currentTaskId && !seen.has(currentTaskId)) {
- seen.add(currentTaskId);
- const task = await taskModel.findById(currentTaskId);
- if (!task) break;
- if (currentTaskId === taskId) taskProjectId = task.projectId;
+export type { ResolvedTaskAcceptance } from './taskAcceptanceResolution';
+export { resolveTaskAcceptance } from './taskAcceptanceResolution';
- const acceptance =
- currentTaskId === taskId
- ? ownAcceptance
- : await acceptanceModel.findPolicyBySubject('task', currentTaskId);
- const acceptanceConfig = acceptance?.config ?? {};
- const acceptanceRequirement = acceptance?.requirement?.trim() || undefined;
- if (Object.keys(acceptanceConfig).length > 0 || acceptanceRequirement) {
- policyAcceptance = acceptance;
- inheritedConfig = acceptanceConfig;
- inheritedRequirement = acceptanceRequirement;
- break;
- }
-
- const legacyVerify = taskModel.getVerifyConfig(task);
- if (legacyVerify) {
- inheritedConfig = toAcceptanceConfig(legacyVerify);
- inheritedRequirement = legacyVerify.requirement?.trim() || undefined;
- break;
- }
-
- currentTaskId = task.parentTaskId;
- }
-
- if (!inheritedConfig && !inheritedRequirement) return undefined;
-
- if (policyAcceptance && currentTaskId === taskId) {
- return {
- acceptance: policyAcceptance,
- config: policyAcceptance.config ?? {},
- requirement: policyAcceptance.requirement ?? undefined,
- };
- }
-
- const acceptance = ownAcceptance
- ? (await acceptanceModel.updatePolicy(ownAcceptance.id, {
- config: inheritedConfig ?? {},
- requirement: inheritedRequirement,
- }))!
- : await acceptanceModel.ensureForSubject('task', taskId, {
- config: inheritedConfig,
- projectId: taskProjectId,
- requirement: inheritedRequirement,
- });
-
- return {
- acceptance,
- config: acceptance.config ?? {},
- requirement: acceptance.requirement ?? undefined,
- };
-};
+const log = debug('lobe-server:verify-task-acceptance');
/**
* Bind a task-bound verification round to the Acceptance that owns the Task's
diff --git a/apps/server/src/services/verify/taskAcceptanceResolution.ts b/apps/server/src/services/verify/taskAcceptanceResolution.ts
new file mode 100644
index 00000000000..09c10d2ea4e
--- /dev/null
+++ b/apps/server/src/services/verify/taskAcceptanceResolution.ts
@@ -0,0 +1,104 @@
+import type { AcceptanceConfig, TaskVerifyConfig } from '@lobechat/types';
+
+import { AcceptanceModel } from '@/database/models/acceptance';
+import { TaskModel } from '@/database/models/task';
+import type { AcceptanceItem } from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+
+// Leaf module: it must not import AcceptanceService (or anything that reaches
+// TaskService), because TaskService resolves task acceptances through here and
+// AcceptanceService completes tasks through TaskService.
+
+export interface ResolvedTaskAcceptance {
+ acceptance: AcceptanceItem;
+ config: AcceptanceConfig;
+ requirement?: string;
+}
+
+const toAcceptanceConfig = (verify: TaskVerifyConfig): AcceptanceConfig => ({
+ enabled: verify.enabled,
+ maxIterations: verify.maxIterations,
+ verifierAgentId: verify.verifierAgentId,
+ verifyCriteriaIds: verify.verifyCriteriaIds,
+ verifyRubricId: verify.verifyRubricId,
+});
+
+/**
+ * Resolve the Acceptance that owns a Task's completion contract.
+ *
+ * `tasks.config.verify` is read only as a legacy compatibility source. The first
+ * read materializes it into the Task's Acceptance; all new flows write the
+ * Acceptance directly.
+ */
+export const resolveTaskAcceptance = async (
+ db: LobeChatDatabase,
+ userId: string,
+ taskId: string,
+ workspaceId?: string,
+): Promise<ResolvedTaskAcceptance | undefined> => {
+ const acceptanceModel = new AcceptanceModel(db, userId, workspaceId);
+ const taskModel = new TaskModel(db, userId, workspaceId);
+ const ownAcceptance = await acceptanceModel.findPolicyBySubject('task', taskId);
+ const seen = new Set<string>();
+ let currentTaskId: string | null = taskId;
+ let inheritedConfig: AcceptanceConfig | undefined;
+ let inheritedRequirement: string | undefined;
+ let policyAcceptance: AcceptanceItem | undefined;
+ let taskProjectId: string | null | undefined;
+
+ while (currentTaskId && !seen.has(currentTaskId)) {
+ seen.add(currentTaskId);
+ const task = await taskModel.findById(currentTaskId);
+ if (!task) break;
+ if (currentTaskId === taskId) taskProjectId = task.projectId;
+
+ const acceptance =
+ currentTaskId === taskId
+ ? ownAcceptance
+ : await acceptanceModel.findPolicyBySubject('task', currentTaskId);
+ const acceptanceConfig = acceptance?.config ?? {};
+ const acceptanceRequirement = acceptance?.requirement?.trim() || undefined;
+ if (Object.keys(acceptanceConfig).length > 0 || acceptanceRequirement) {
+ policyAcceptance = acceptance;
+ inheritedConfig = acceptanceConfig;
+ inheritedRequirement = acceptanceRequirement;
+ break;
+ }
+
+ const legacyVerify = taskModel.getVerifyConfig(task);
+ if (legacyVerify) {
+ inheritedConfig = toAcceptanceConfig(legacyVerify);
+ inheritedRequirement = legacyVerify.requirement?.trim() || undefined;
+ break;
+ }
+
+ currentTaskId = task.parentTaskId;
+ }
+
+ if (!inheritedConfig && !inheritedRequirement) return undefined;
+
+ if (policyAcceptance && currentTaskId === taskId) {
+ return {
+ acceptance: policyAcceptance,
+ config: policyAcceptance.config ?? {},
+ requirement: policyAcceptance.requirement ?? undefined,
+ };
+ }
+
+ const acceptance = ownAcceptance
+ ? (await acceptanceModel.updatePolicy(ownAcceptance.id, {
+ config: inheritedConfig ?? {},
+ requirement: inheritedRequirement,
+ }))!
+ : await acceptanceModel.ensureForSubject('task', taskId, {
+ config: inheritedConfig,
+ projectId: taskProjectId,
+ requirement: inheritedRequirement,
+ });
+
+ return {
+ acceptance,
+ config: acceptance.config ?? {},
+ requirement: acceptance.requirement ?? undefined,
+ };
+};