🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(verify): merge one acceptance into another (#18548)
Arvin Xud3d6853bea8b
diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.tsindex 2da4ca18a76..a710a98705c 100644--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts@@ -15,6 +15,7 @@ const modelMocks = vi.hoisted(() => ({findRunById: vi.fn(),findResultById: vi.fn(),generateCriteria: vi.fn(),+ generateGoalCriteria: vi.fn(),getFullFileUrl: vi.fn(),getServerDB: vi.fn(async () => ({})),updateRun: vi.fn(),@@ -59,6 +60,12 @@ vi.mock('@/server/services/verify', async (importOriginal) => ({VerifyReporterService: class VerifyReporterService {},}));+vi.mock('@/server/services/goal/criteriaGenerator', () => ({+ GoalCriteriaGeneratorService: class GoalCriteriaGeneratorService {+ generate = modelMocks.generateGoalCriteria;+ },+}));+vi.mock('@/server/services/file', () => ({FileService: vi.fn(() => ({getFullFileUrl: modelMocks.getFullFileUrl,@@ -129,6 +136,18 @@ describe('verifyRouter', () => {});});+ describe('generateGoalCriteria', () => {+ it('does not accept a caller-selected model config', async () => {+ modelMocks.generateGoalCriteria.mockResolvedValueOnce([]);++ await createCaller().generateGoalCriteria({ goal: 'Ship a responsive task board' });++ expect(modelMocks.generateGoalCriteria).toHaveBeenCalledWith({+ goal: 'Ship a responsive task board',+ });+ });+ });+describe('ingestResult', () => {it("rejects a run outside the caller's scope before upserting the result", async () => {modelMocks.findRunById.mockResolvedValueOnce(undefined);diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex 684ad67edaf..c5abea01426 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -486,8 +486,44 @@ export const acceptanceRouter = router({};}),- /** Recent acceptances (with subject headers), newest first — list panel + CLI. */- list: acceptanceProcedure.query(async ({ ctx }) => ctx.acceptanceService.listWithSubjects()),+ /**+ * Recent acceptances (with subject headers), newest first — list panel + CLI.+ *+ * `limit` is capped rather than open: the read resolves each row's subject+ * title one by one, so an unbounded window would fan out. The merge picker+ * asks for the wide end because a target it cannot list is a target the user+ * cannot merge into.+ */+ list: acceptanceProcedure+ .input(z.object({ limit: z.number().int().min(1).max(200) }).optional())+ .query(async ({ ctx, input }) => ctx.acceptanceService.listWithSubjects(input?.limit)),++ /**+ * Fold one acceptance into another: the source's verification rounds (and+ * with them its checks, verdicts and evidence) re-chain onto the target, and+ * the source entry is deleted.+ *+ * Both sides are creator-scoped like every other verify write — a merge+ * rewrites BOTH aggregates, so a workspace member must not be able to fold+ * another member's acceptance into (or out of) their own.+ */+ merge: acceptanceWriteProcedure+ .input(z.object({ sourceId: z.string(), targetId: z.string() }))+ .mutation(async ({ ctx, input }) => {+ const source = await resolveAcceptance(ctx, input.sourceId);+ assertWorkspaceRowManageable(ctx, source.userId, 'acceptance');+ const target = await resolveAcceptance(ctx, input.targetId);+ assertWorkspaceRowManageable(ctx, target.userId, 'acceptance');++ try {+ return await ctx.acceptanceService.merge(source.id, target.id);+ } catch (error) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: error instanceof Error ? error.message : 'Failed to merge acceptance',+ });+ }+ }),/*** Acceptance status for a known set of subjects, in one read.diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex 8a4b72b025f..18eb5ae1ef5 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -39,6 +39,7 @@ import { isUuid } from '@/database/utils/uuid';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { markSilentTRPCErrorLog } from '@/libs/trpc/utils/errorLogger';+import { GoalCriteriaGeneratorService } from '@/server/services/goal/criteriaGenerator';import {AcceptanceService,createEvidenceFileResolver,@@ -273,6 +274,11 @@ const verifyProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =executorService: new VerifyExecutorService(ctx.serverDB, ctx.userId, workspaceId),tracingModel: new LlmGenerationTracingModel(ctx.serverDB, ctx.userId, workspaceId),feedbackService: new VerifyFeedbackService(ctx.serverDB, ctx.userId, workspaceId),+ goalCriteriaGenerator: new GoalCriteriaGeneratorService(+ ctx.serverDB,+ ctx.userId,+ workspaceId,+ ),operationModel: new AgentOperationModel(ctx.serverDB, ctx.userId, workspaceId),planGenerator: new VerifyPlanGeneratorService(ctx.serverDB, ctx.userId, workspaceId),reportModel: new VerifyReportModel(ctx.serverDB, ctx.userId, workspaceId),@@ -512,6 +518,34 @@ export const verifyRouter = router({}}),+ /** Draft the standing acceptance contract for the create-goal flow. */+ generateGoalCriteria: verifyWriteProcedure+ .input(+ z.object({+ context: z.string().optional(),+ goal: z.string().min(1),+ maxCriteria: z.number().int().min(1).max(8).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ return await ctx.goalCriteriaGenerator.generate(input);+ } catch (error) {+ const errorType = (error as { errorType?: unknown } | null)?.errorType;+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {+ const trpcError = new TRPCError({+ cause: error,+ code: 'PRECONDITION_FAILED',+ message: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });+ markSilentTRPCErrorLog(trpcError.cause);+ throw trpcError;+ }++ throw error;+ }+ }),+/** Persist (user-edited) drafts as standalone criteria; returns their ids in order. */createCriteria: verifyWriteProcedure.input(diff --git a/apps/server/src/services/goal/criteriaGenerator.test.ts b/apps/server/src/services/goal/criteriaGenerator.test.tsnew file mode 100644index 00000000000..31661dc1ffc--- /dev/null+++ b/apps/server/src/services/goal/criteriaGenerator.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GoalCriteriaGeneratorService } from './criteriaGenerator';++const { generateObject, resolveGoalModelConfig } = vi.hoisted(() => ({+ generateObject: vi.fn(),+ resolveGoalModelConfig: vi.fn(),+}));++vi.mock('@/server/services/aiGeneration', () => ({+ AiGenerationService: vi.fn(() => ({ generateObject })),+}));++vi.mock('./modelConfig', () => ({ resolveGoalModelConfig }));++describe('GoalCriteriaGeneratorService', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resolveGoalModelConfig.mockResolvedValue({ model: 'goal-model', provider: 'goal-provider' });+ generateObject.mockResolvedValue({ criteria: [] });+ });++ it('uses the dedicated goal model, prompt version, schema, and tracing scenario', async () => {+ await new GoalCriteriaGeneratorService({} as any, 'user-1', 'workspace-1').generate({+ goal: 'Publish a benchmark paper',+ });++ expect(resolveGoalModelConfig).toHaveBeenCalledWith({}, 'user-1');+ expect(generateObject).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'goal-model',+ provider: 'goal-provider',+ schema: expect.objectContaining({ name: 'goal_criteria_draft' }),+ }),+ expect.objectContaining({+ tracing: {+ promptVersion: 'v1',+ scenario: 'goal_criteria_gen',+ schemaName: 'goal_criteria_draft',+ },+ }),+ );+ });++ it('rejects criteria containing evidence values outside the supported enums', async () => {+ generateObject.mockResolvedValue({+ criteria: [+ {+ description: 'The release is visible',+ instruction: 'Inspect the release.',+ onFail: 'auto_repair',+ required: true,+ requiredEvidence: [+ { hint: 'Capture it', modality: 'hologram', scope: 'somewhere', type: 'binary' },+ ],+ title: 'Release shipped',+ verifierType: 'agent',+ },+ ],+ });++ await expect(+ new GoalCriteriaGeneratorService({} as any, 'user-1').generate({ goal: 'Ship it' }),+ ).resolves.toEqual([]);+ });+});diff --git a/apps/server/src/services/goal/criteriaGenerator.ts b/apps/server/src/services/goal/criteriaGenerator.tsnew file mode 100644index 00000000000..c52464868bb--- /dev/null+++ b/apps/server/src/services/goal/criteriaGenerator.ts@@ -0,0 +1,101 @@+import { TRACING_SCENARIOS } from '@lobechat/const';+import { isProgrammaticTestCheck } from '@lobechat/const/verify';+import type { TracingOptions } from '@lobechat/llm-generation-tracing';+import {+ chainGoalCriteriaDraft,+ GOAL_CRITERIA_DRAFT_JSON_SCHEMA,+ GOAL_CRITERIA_DRAFT_PROMPT_VERSION,+ VERIFY_EVIDENCE_MODALITIES,+ VERIFY_EVIDENCE_SCOPES,+ VERIFY_EVIDENCE_TYPES,+ VERIFY_ON_FAIL_ACTIONS,+ VERIFY_VERIFIER_TYPES,+} from '@lobechat/prompts';+import type { RequiredEvidenceSpec, VerifyCheckItem } from '@lobechat/types';+import debug from 'debug';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { AiGenerationService } from '@/server/services/aiGeneration';++import { resolveGoalModelConfig } from './modelConfig';++const log = debug('lobe-server:goal-criteria-generator');+const DEFAULT_MAX_CRITERIA = 4;++const generatedCriteriaSchema = z.object({+ criteria: z.array(+ z.object({+ description: z.string().optional(),+ instruction: z.string().optional(),+ onFail: z.enum(VERIFY_ON_FAIL_ACTIONS).optional(),+ requiredEvidence: z+ .array(+ z.object({+ hint: z.string().optional(),+ modality: z.enum(VERIFY_EVIDENCE_MODALITIES).optional(),+ scope: z.enum(VERIFY_EVIDENCE_SCOPES).optional(),+ type: z.enum(VERIFY_EVIDENCE_TYPES),+ }),+ )+ .optional(),+ required: z.boolean().optional(),+ title: z.string(),+ verifierType: z.enum(VERIFY_VERIFIER_TYPES),+ }),+ ),+});++export interface GoalCriterionDraft {+ description?: string;+ instruction?: string;+ onFail?: VerifyCheckItem['onFail'];+ required?: boolean;+ requiredEvidence?: RequiredEvidenceSpec[];+ title: string;+ verifierType?: VerifyCheckItem['verifierType'];+}++export class GoalCriteriaGeneratorService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ async generate(params: {+ context?: string;+ goal: string;+ maxCriteria?: number;+ }): Promise<GoalCriterionDraft[]> {+ const maxCriteria = params.maxCriteria ?? DEFAULT_MAX_CRITERIA;+ const modelConfig = await resolveGoalModelConfig(this.db, this.userId);+ const ai = new AiGenerationService(this.db, this.userId, this.workspaceId);+ const raw = await ai.generateObject(+ {+ ...chainGoalCriteriaDraft({ ...params, maxCriteria }),+ ...modelConfig,+ schema: GOAL_CRITERIA_DRAFT_JSON_SCHEMA,+ thinking: { type: 'disabled' },+ },+ {+ metadata: { trigger: 'goal_criteria_draft' },+ tracing: {+ promptVersion: GOAL_CRITERIA_DRAFT_PROMPT_VERSION,+ scenario: TRACING_SCENARIOS.GoalCriteriaGen,+ schemaName: GOAL_CRITERIA_DRAFT_JSON_SCHEMA.name,+ } satisfies TracingOptions,+ },+ );++ const parsed = generatedCriteriaSchema.safeParse(raw);+ if (!parsed.success) {+ log('goal criteria draft did not match schema: %O', parsed.error.flatten());+ return [];+ }++ return parsed.data.criteria+ .slice(0, maxCriteria)+ .filter((criterion) => !isProgrammaticTestCheck(criterion.title, criterion.description));+ }+}diff --git a/apps/server/src/services/goal/modelConfig.ts b/apps/server/src/services/goal/modelConfig.tsnew file mode 100644index 00000000000..b0b9f449ce0--- /dev/null+++ b/apps/server/src/services/goal/modelConfig.ts@@ -0,0 +1,15 @@+import type { UserSystemAgentConfig } from '@lobechat/types';++import { UserModel } from '@/database/models/user';+import type { LobeChatDatabase } from '@/database/type';+import { resolveSystemAgentModelConfig } from '@/server/services/systemAgent/modelConfig';++export const resolveGoalModelConfig = async (db: LobeChatDatabase, userId: string) => {+ const settings = await new UserModel(db, userId).getUserSettings();+ const systemAgent = settings?.systemAgent as Partial<UserSystemAgentConfig> | undefined;++ return resolveSystemAgentModelConfig({+ taskConfig: systemAgent?.goal,+ taskKey: 'goal',+ });+};diff --git a/apps/server/src/services/verify/__tests__/acceptanceMerge.test.ts b/apps/server/src/services/verify/__tests__/acceptanceMerge.test.tsnew file mode 100644index 00000000000..8a4186b7a00--- /dev/null+++ b/apps/server/src/services/verify/__tests__/acceptanceMerge.test.ts@@ -0,0 +1,300 @@+// @vitest-environment node+import type { VerifyCheckItem } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type {+ AcceptanceItem,+ VerifyCheckResultItem,+ VerifyRunItem,+} from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';++import {+ collectCheckIds,+ countLogicalChecks,+ mergeAcceptanceRounds,+ planCheckIdRemap,+ remapPlanItem,+} from '../acceptanceMerge';++const mocks = vi.hoisted(() => ({+ acceptanceDelete: vi.fn(),+ acceptanceUpdate: vi.fn(),+ attachToAcceptance: vi.fn(),+ listByAcceptance: vi.fn(),+ listByRuns: vi.fn(),+ resultUpdate: vi.fn(),+ runUpdate: vi.fn(),+}));++vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(() => ({+ attachToAcceptance: mocks.attachToAcceptance,+ listByAcceptance: mocks.listByAcceptance,+ update: mocks.runUpdate,+ })),+}));++vi.mock('@/database/models/verifyCheckResult', () => ({+ VerifyCheckResultModel: vi.fn(() => ({+ listByRuns: mocks.listByRuns,+ update: mocks.resultUpdate,+ })),+}));++vi.mock('@/database/models/acceptance', () => ({+ AcceptanceModel: vi.fn(() => ({+ delete: mocks.acceptanceDelete,+ update: mocks.acceptanceUpdate,+ })),+}));++const planItem = (id: string, overrides: Partial<VerifyCheckItem> = {}): VerifyCheckItem => ({+ id,+ index: 0,+ onFail: 'manual',+ required: true,+ title: `check ${id}`,+ verifierConfig: {},+ verifierType: 'agent',+ ...overrides,+});++const run = (id: string, roundIndex: number, plan: VerifyCheckItem[]): VerifyRunItem =>+ ({ id, plan, roundIndex }) as VerifyRunItem;++const result = (id: string, verifyRunId: string, checkItemId: string): VerifyCheckResultItem =>+ ({ checkItemId, id, verifyRunId }) as VerifyCheckResultItem;++const acceptance = (id: string, overrides: Partial<AcceptanceItem> = {}): AcceptanceItem =>+ ({ config: {}, id, status: 'delivered', visibility: 'private', ...overrides }) as AcceptanceItem;++const SOURCE_ID = '11111111-2222-3333-4444-555555555555';+const TARGET_ID = '99999999-8888-7777-6666-555555555555';++/** How many rounds the unscoped integrity count sees still chained to the source. */+let leftBehindRounds = 0;++/**+ * `db.transaction(fn)` runs its body inline — the models are mocked, so the only+ * real query in the body is the unscoped left-behind count.+ */+const fakeDb = {+ transaction: (fn: (tx: unknown) => unknown) =>+ fn({+ select: () => ({+ from: () => ({ where: async () => [{ value: leftBehindRounds }] }),+ }),+ }),+} as unknown as LobeChatDatabase;++const mergeWith = (source: AcceptanceItem, target: AcceptanceItem) =>+ mergeAcceptanceRounds({ db: fakeDb, source, target, userId: 'user-1' });++beforeEach(() => {+ vi.clearAllMocks();+ leftBehindRounds = 0;+ mocks.listByAcceptance.mockResolvedValue([]);+ mocks.listByRuns.mockResolvedValue([]);+ mocks.attachToAcceptance.mockResolvedValue({});+});++describe('planCheckIdRemap', () => {+ it('re-keys only the ids the target already uses', () => {+ const remap = planCheckIdRemap(['case-1', 'case-2'], new Set(['case-1']), 'abcd1234');++ expect(remap.get('case-1')).toBe('case-1~abcd1234');+ expect(remap.has('case-2')).toBe(false);+ });++ it('keeps generating until the replacement is free on both sides', () => {+ const remap = planCheckIdRemap(+ ['case-1', 'case-1~abcd1234'],+ new Set(['case-1', 'case-1~abcd1234']),+ 'abcd1234',+ );++ // The obvious replacement is itself a source id, so it must not be reused.+ expect(remap.get('case-1')).toBe('case-1~abcd1234-2');+ expect(remap.get('case-1~abcd1234')).toBe('case-1~abcd1234~abcd1234');+ });+});++describe('collectCheckIds', () => {+ it('collects plan ids, their logical criterion ids and result-only ids', () => {+ const ids = collectCheckIds(+ [run('run-1', 1, [planItem('plan-1', { sourceCriterionId: 'criterion-a' })])],+ [result('res-1', 'run-1', 'ingested-only')],+ );++ expect([...ids].sort()).toEqual(['criterion-a', 'ingested-only', 'plan-1']);+ });+});++describe('countLogicalChecks', () => {+ it('counts one check once even when it carries a separate criterion id', () => {+ // `collectCheckIds` holds both ids for collision purposes — the user-facing+ // count must not read that as two checks.+ const runs = [run('run-1', 1, [planItem('plan-1', { sourceCriterionId: 'criterion-a' })])];++ expect(collectCheckIds(runs, []).size).toBe(2);+ expect(countLogicalChecks(runs, [])).toBe(1);+ });++ it('does not count a generation folded away by supersedes', () => {+ const runs = [+ run('run-1', 1, [planItem('old')]),+ run('run-2', 2, [planItem('new', { supersedes: ['old'] })]),+ ];++ expect(countLogicalChecks(runs, [])).toBe(1);+ });++ it('counts a result that names an item no plan carries', () => {+ expect(+ countLogicalChecks(+ [run('run-1', 1, [planItem('planned')])],+ [result('res-1', 'run-1', 'ingested-only')],+ ),+ ).toBe(2);+ });+});++describe('remapPlanItem', () => {+ it('rewrites the item id, its criterion id and its supersedes references', () => {+ const remap = new Map([+ ['a', 'a~m'],+ ['old', 'old~m'],+ ['crit', 'crit~m'],+ ]);++ expect(+ remapPlanItem(+ planItem('a', { sourceCriterionId: 'crit', supersedes: ['old', 'untouched'] }),+ remap,+ ),+ ).toMatchObject({+ id: 'a~m',+ sourceCriterionId: 'crit~m',+ supersedes: ['old~m', 'untouched'],+ });+ });+});++describe('mergeAcceptanceRounds', () => {+ it('re-chains every source round onto the target in order, then drops the source', async () => {+ const sourceRuns = [run('run-a', 1, [planItem('s1')]), run('run-b', 2, [planItem('s2')])];+ mocks.listByAcceptance.mockImplementation(async (id: string) =>+ id === SOURCE_ID ? sourceRuns : [run('run-t', 1, [planItem('t1')])],+ );++ const summary = await mergeWith(acceptance(SOURCE_ID), acceptance(TARGET_ID));++ expect(mocks.attachToAcceptance.mock.calls).toEqual([+ ['run-a', TARGET_ID, 'private'],+ ['run-b', TARGET_ID, 'private'],+ ]);+ expect(mocks.acceptanceDelete).toHaveBeenCalledWith(SOURCE_ID);+ expect(summary).toMatchObject({ movedChecks: 2, movedRounds: 2, rekeyedChecks: 0 });+ });++ it('reports the logical check count, not the raw identifier set', async () => {+ mocks.listByAcceptance.mockImplementation(async (id: string) =>+ id === SOURCE_ID+ ? [run('run-a', 1, [planItem('plan-1', { sourceCriterionId: 'criterion-a' })])]+ : [],+ );++ const summary = await mergeWith(acceptance(SOURCE_ID), acceptance(TARGET_ID));++ // One check that happens to speak two ids is still one moved check.+ expect(summary.movedChecks).toBe(1);+ });++ it('re-keys colliding check ids on both the plan and its results', async () => {+ const sourceRun = run('run-a', 1, [planItem('case-1'), planItem('case-9')]);+ const targetRun = run('run-t', 1, [planItem('case-1')]);+ mocks.listByAcceptance.mockImplementation(async (id: string) =>+ id === SOURCE_ID ? [sourceRun] : [targetRun],+ );+ mocks.listByRuns.mockImplementation(async (runIds: string[]) =>+ runIds.includes('run-a')+ ? [result('res-1', 'run-a', 'case-1'), result('res-9', 'run-a', 'case-9')]+ : [result('res-t', 'run-t', 'case-1')],+ );++ const summary = await mergeWith(acceptance(SOURCE_ID), acceptance(TARGET_ID));++ const salt = SOURCE_ID.slice(0, 8);+ expect(mocks.runUpdate).toHaveBeenCalledWith('run-a', {+ plan: [+ expect.objectContaining({ id: `case-1~${salt}` }),+ expect.objectContaining({ id: 'case-9' }),+ ],+ });+ // Only the colliding result is rewritten — `case-9` keeps its wording.+ expect(mocks.resultUpdate).toHaveBeenCalledTimes(1);+ expect(mocks.resultUpdate).toHaveBeenCalledWith('res-1', { checkItemId: `case-1~${salt}` });+ expect(summary.rekeyedChecks).toBe(1);+ });++ it('leaves the plan untouched when nothing collides', async () => {+ mocks.listByAcceptance.mockImplementation(async (id: string) =>+ id === SOURCE_ID ? [run('run-a', 1, [planItem('s1')])] : [run('run-t', 1, [planItem('t1')])],+ );++ await mergeWith(acceptance(SOURCE_ID), acceptance(TARGET_ID));++ expect(mocks.runUpdate).not.toHaveBeenCalled();+ expect(mocks.resultUpdate).not.toHaveBeenCalled();+ });++ it('carries the standing checklist over, deduped by name, and adopts a missing goal', async () => {+ const source = acceptance(SOURCE_ID, {+ config: {+ checklist: [+ { id: 'c1', name: 'Login works' },+ { id: 'c2', name: ' shared item ' },+ ],+ },+ requirement: 'Ship the login flow',+ });+ const target = acceptance(TARGET_ID, {+ config: { checklist: [{ id: 't1', name: 'Shared Item' }] },+ requirement: null,+ });++ await mergeWith(source, target);++ expect(mocks.acceptanceUpdate).toHaveBeenCalledWith(TARGET_ID, {+ config: {+ checklist: [+ { id: 't1', name: 'Shared Item' },+ { id: 'c1', name: 'Login works' },+ ],+ },+ requirement: 'Ship the login flow',+ });+ });++ it('refuses to drop the source while a round the caller cannot see is still chained', async () => {+ mocks.listByAcceptance.mockImplementation(async (id: string) =>+ id === SOURCE_ID ? [run('run-a', 1, [planItem('s1')])] : [],+ );+ leftBehindRounds = 1;++ await expect(mergeWith(acceptance(SOURCE_ID), acceptance(TARGET_ID))).rejects.toThrow(+ /not visible to you/,+ );+ expect(mocks.acceptanceDelete).not.toHaveBeenCalled();+ });++ it('keeps the target goal when it already has one', async () => {+ await mergeWith(+ acceptance(SOURCE_ID, { requirement: 'source goal' }),+ acceptance(TARGET_ID, { requirement: 'target goal' }),+ );++ expect(mocks.acceptanceUpdate).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/verify/__tests__/acceptanceMergeService.test.ts b/apps/server/src/services/verify/__tests__/acceptanceMergeService.test.tsnew file mode 100644index 00000000000..3669f7dd87b--- /dev/null+++ b/apps/server/src/services/verify/__tests__/acceptanceMergeService.test.ts@@ -0,0 +1,71 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AcceptanceService } from '../acceptanceService';++const mocks = vi.hoisted(() => ({+ findById: vi.fn(),+ listByAcceptance: vi.fn(),+ mergeRounds: vi.fn(),+ updateStatus: vi.fn(),+}));++vi.mock('../acceptanceMerge', () => ({ mergeAcceptanceRounds: mocks.mergeRounds }));+vi.mock('@/database/models/acceptance', () => ({+ AcceptanceModel: vi.fn(() => ({+ findById: mocks.findById,+ updateStatus: mocks.updateStatus,+ })),+}));+vi.mock('@/database/models/verifyRun', () => ({+ VerifyRunModel: vi.fn(() => ({ listByAcceptance: mocks.listByAcceptance })),+}));+vi.mock('@/database/models/verifyCheckResult', () => ({ VerifyCheckResultModel: vi.fn() }));+vi.mock('@/database/models/verifyEvidence', () => ({ VerifyEvidenceModel: vi.fn() }));+vi.mock('@/database/models/verifyReport', () => ({ VerifyReportModel: vi.fn(() => ({})) }));+vi.mock('@/database/models/goal', () => ({ GoalModel: vi.fn() }));+vi.mock('@/database/models/task', () => ({ TaskModel: vi.fn() }));+vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));+vi.mock('../goalLoop', () => ({+ maybeContinueGoalLoop: vi.fn(),+ syncGoalToolState: vi.fn(),+}));+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));++const SUMMARY = { movedChecks: 3, movedRounds: 1, rekeyedChecks: 1 };++const service = () => new AcceptanceService({} as any, 'user-1');++const row = (id: string, status = 'delivered') => ({ id, status, subjectType: 'standalone' });++beforeEach(() => {+ vi.clearAllMocks();+ mocks.mergeRounds.mockResolvedValue(SUMMARY);+ mocks.listByAcceptance.mockResolvedValue([]);+ mocks.findById.mockImplementation(async (id: string) => row(id));+});++describe('AcceptanceService.merge', () => {+ it('refuses to merge an acceptance into itself', async () => {+ await expect(service().merge('acc-1', 'acc-1')).rejects.toThrow(/into itself/);+ expect(mocks.mergeRounds).not.toHaveBeenCalled();+ });++ it('refuses a target whose delivery is already settled', async () => {+ mocks.findById.mockImplementation(async (id: string) =>+ id === 'target' ? row('target', 'accepted') : row(id),+ );++ await expect(service().merge('source', 'target')).rejects.toThrow(/reopen it/);+ expect(mocks.mergeRounds).not.toHaveBeenCalled();+ });++ it('still reports success when the post-commit status recompute fails', async () => {+ // The merge has COMMITTED and the source is gone by then — surfacing this as+ // a failed mutation would offer a retry that can only ever 404.+ mocks.listByAcceptance.mockRejectedValue(new Error('connection reset'));++ await expect(service().merge('source', 'target')).resolves.toEqual(SUMMARY);+ });+});diff --git a/apps/server/src/services/verify/__tests__/holisticPlan.test.ts b/apps/server/src/services/verify/__tests__/holisticPlan.test.tsindex 8dfae46cee5..bf2d8b2fc32 100644--- a/apps/server/src/services/verify/__tests__/holisticPlan.test.ts+++ b/apps/server/src/services/verify/__tests__/holisticPlan.test.ts@@ -151,7 +151,7 @@ describe('generateDraftPlan — holistic fallback', () => {});describe('generateCriteria tracing', () => {- it('uses the createGoal criteria scenario instead of the run-time plan scenario', async () => {+ it('keeps generic task criteria generation on the verify-plan scenario', async () => {generateObjectMock.mockResolvedValue({ criteria: [] });await new VerifyPlanGeneratorService(db, 'user-1').generateCriteria({@@ -162,7 +162,7 @@ describe('generateCriteria tracing', () => {expect(generateObjectMock).toHaveBeenCalledWith(expect.any(Object),expect.objectContaining({- tracing: expect.objectContaining({ scenario: 'goal_criteria_gen' }),+ tracing: expect.objectContaining({ scenario: 'verify_plan_gen' }),}),);});diff --git a/apps/server/src/services/verify/acceptanceMerge.ts b/apps/server/src/services/verify/acceptanceMerge.tsnew file mode 100644index 00000000000..59747ca9a86--- /dev/null+++ b/apps/server/src/services/verify/acceptanceMerge.ts@@ -0,0 +1,273 @@+import type { VerifyCheckItem } from '@lobechat/types';+import debug from 'debug';+import { count, eq } from 'drizzle-orm';++import { AcceptanceModel } from '@/database/models/acceptance';+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';+import { VerifyRunModel } from '@/database/models/verifyRun';+import type {+ AcceptanceItem,+ VerifyCheckResultItem,+ VerifyRunItem,+} from '@/database/schemas/verify';+import { verifyRuns } from '@/database/schemas/verify';+import type { LobeChatDatabase } from '@/database/type';++const log = debug('lobe-server:verify-acceptance-merge');++/** What a merge moved — surfaced to the caller so the UI can report it. */+export interface AcceptanceMergeSummary {+ /** Distinct check items carried over from the source. */+ movedChecks: number;+ /** Verification rounds re-chained onto the target. */+ movedRounds: number;+ /** How many of those checks had to be re-keyed to avoid a target collision. */+ rekeyedChecks: number;+}++/**+ * Every check id a round chain speaks — plan item ids, the logical ids they+ * resolve to (`sourceCriterionId`), and the ids results are keyed by (an+ * ingested result may name an item no plan carries).+ *+ * The union view aligns checks across rounds by these ids, so they are exactly+ * what must not collide when two chains are merged into one.+ */+export const collectCheckIds = (+ runs: Pick<VerifyRunItem, 'plan'>[],+ results: Pick<VerifyCheckResultItem, 'checkItemId'>[],+): Set<string> => {+ const ids = new Set<string>();+ for (const run of runs) {+ for (const item of (run.plan ?? []) as VerifyCheckItem[]) {+ ids.add(item.id);+ if (item.sourceCriterionId) ids.add(item.sourceCriterionId);+ }+ }+ for (const result of results) ids.add(result.checkItemId);+ return ids;+};++/**+ * How many CHECKS the source chain holds, as the acceptance union counts rows.+ *+ * Deliberately not `collectCheckIds().size`: that set is the collision domain,+ * where one generated check contributes BOTH its plan-item id and the+ * `sourceCriterionId` it resolves to. Counting it would report a single check+ * twice — and this number is what the user is told moved ("N 项验收项").+ *+ * So it counts the same way the union builds rows: logical ids, with the+ * generations folded away by `supersedes` removed (they render inside their+ * successor's timeline, not as rows of their own).+ */+export const countLogicalChecks = (+ runs: Pick<VerifyRunItem, 'plan'>[],+ results: Pick<VerifyCheckResultItem, 'checkItemId'>[],+): number => {+ const logical = new Set<string>();+ const superseded = new Set<string>();+ const logicalByItemId = new Map<string, string>();++ for (const run of runs) {+ for (const item of (run.plan ?? []) as VerifyCheckItem[]) {+ const id = item.sourceCriterionId ?? item.id;+ logicalByItemId.set(item.id, id);+ logical.add(id);+ for (const replaced of item.supersedes ?? []) superseded.add(replaced);+ }+ }+ // A result may name an item no plan carries (a direct ingest).+ for (const result of results) {+ logical.add(logicalByItemId.get(result.checkItemId) ?? result.checkItemId);+ }+ for (const id of superseded) logical.delete(id);++ return logical.size;+};++/**+ * Assign a fresh id to every source check id the target already uses.+ *+ * Check ids are harness-authored strings (`case-1`, a slug, a uuid), so two+ * independently produced chains routinely share them. Left alone, the union+ * would read the source's `case-1` as a LATER ROUND of the target's `case-1` —+ * silently overwriting an unrelated check's verdict and evidence. Re-keying the+ * colliding ids is what keeps the two checks two rows.+ *+ * Only collisions are re-keyed: a source id the target never used keeps its+ * wording, so shared criterion ids (`sourceCriterionId`) still align on purpose.+ */+export const planCheckIdRemap = (+ sourceIds: Iterable<string>,+ takenIds: Set<string>,+ /** Stable, human-recognizable suffix — the source aggregate's short id. */+ salt: string,+): Map<string, string> => {+ const remap = new Map<string, string>();+ // Every id in play, so a generated replacement can't collide with a source id+ // that has not been visited yet either.+ const used = new Set([...takenIds, ...sourceIds]);++ for (const id of sourceIds) {+ if (!takenIds.has(id)) continue;+ let candidate = `${id}~${salt}`;+ let attempt = 2;+ while (used.has(candidate)) {+ candidate = `${id}~${salt}-${attempt}`;+ attempt += 1;+ }+ used.add(candidate);+ remap.set(id, candidate);+ }++ return remap;+};++/** Rewrite a plan item's own id and every id it references. */+export const remapPlanItem = (+ item: VerifyCheckItem,+ remap: Map<string, string>,+): VerifyCheckItem => {+ const next: VerifyCheckItem = { ...item, id: remap.get(item.id) ?? item.id };+ if (item.sourceCriterionId) {+ next.sourceCriterionId = remap.get(item.sourceCriterionId) ?? item.sourceCriterionId;+ }+ // `supersedes` folds an older generation into this row — the reference has to+ // follow the rename or the fold silently stops matching.+ if (item.supersedes?.length) {+ next.supersedes = item.supersedes.map((id) => remap.get(id) ?? id);+ }+ return next;+};++interface MergeRoundsParams {+ db: LobeChatDatabase;+ source: AcceptanceItem;+ target: AcceptanceItem;+ userId: string;+ workspaceId?: string;+}++/**+ * Move the source aggregate's whole round chain onto the target, then drop the+ * (now empty) source.+ *+ * Rounds are re-chained rather than copied: a check item's verdict, evidence,+ * per-check user decisions and round report all hang off the run, so moving the+ * run carries the entire acceptance ledger with it — nothing is duplicated and+ * no id in the evidence graph changes. Source rounds are appended AFTER the+ * target's existing ones, in their own order, so the target's check numbering+ * (`C3`, which feedback references) never shifts.+ */+export const mergeAcceptanceRounds = async ({+ db,+ source,+ target,+ userId,+ workspaceId,+}: MergeRoundsParams): Promise<AcceptanceMergeSummary> => {+ const runModel = new VerifyRunModel(db, userId, workspaceId);+ const resultModel = new VerifyCheckResultModel(db, userId, workspaceId);++ const [sourceRuns, targetRuns] = await Promise.all([+ runModel.listByAcceptance(source.id),+ runModel.listByAcceptance(target.id),+ ]);+ const [sourceResults, targetResults] = await Promise.all([+ resultModel.listByRuns(sourceRuns.map((run) => run.id)),+ resultModel.listByRuns(targetRuns.map((run) => run.id)),+ ]);++ const sourceIds = collectCheckIds(sourceRuns, sourceResults);+ const movedChecks = countLogicalChecks(sourceRuns, sourceResults);+ const remap = planCheckIdRemap(+ sourceIds,+ collectCheckIds(targetRuns, targetResults),+ source.id.slice(0, 8),+ );++ await db.transaction(async (tx) => {+ const txRunModel = new VerifyRunModel(tx, userId, workspaceId);+ const txResultModel = new VerifyCheckResultModel(tx, userId, workspaceId);++ if (remap.size > 0) {+ await Promise.all(+ sourceRuns+ .filter((run) => run.plan?.length)+ .map((run) =>+ txRunModel.update(run.id, {+ plan: (run.plan as VerifyCheckItem[]).map((item) => remapPlanItem(item, remap)),+ }),+ ),+ );+ await Promise.all(+ sourceResults+ .filter((result) => remap.has(result.checkItemId))+ .map((result) =>+ txResultModel.update(result.id, { checkItemId: remap.get(result.checkItemId)! }),+ ),+ );+ }++ // Sequentially: each attach reads the target chain's current max round+ // index, so the source rounds land in their own order behind the target's.+ for (const run of sourceRuns) {+ await txRunModel.attachToAcceptance(run.id, target.id, target.visibility);+ }++ // The standing checklist (the topic tray) lives on the aggregate, not on a+ // round — so it is carried over by hand. Deduped by name: the two lists+ // routinely describe the same delivery from two conversations.+ const targetChecklist = target.config?.checklist ?? [];+ const seenNames = new Set(targetChecklist.map((entry) => entry.name.trim().toLowerCase()));+ const carried = (source.config?.checklist ?? []).filter(+ (entry) => !seenNames.has(entry.name.trim().toLowerCase()),+ );++ // Ownership-scoped reads drive the move, so a round the caller cannot see+ // (a workspace member's private run chained by an owner) would stay behind+ // and be silently detached by the delete below. Count unscoped: if anything+ // is still chained, abort the whole merge rather than orphan a round.+ const [{ value: leftBehind }] = await tx+ .select({ value: count() })+ .from(verifyRuns)+ .where(eq(verifyRuns.acceptanceId, source.id));+ if (leftBehind > 0) {+ throw new Error(+ `Cannot merge: ${leftBehind} verification round(s) of this acceptance are not visible to you`,+ );+ }++ const txAcceptanceModel = new AcceptanceModel(tx, userId, workspaceId);++ if (carried.length > 0 || (!target.requirement && source.requirement)) {+ await txAcceptanceModel.update(target.id, {+ ...(carried.length > 0+ ? { config: { ...target.config, checklist: [...targetChecklist, ...carried] } }+ : {}),+ // A target that never recorded a goal adopts the source's, instead of+ // reading "尚未记录该对象的验收目标" after absorbing its checks.+ ...(!target.requirement && source.requirement ? { requirement: source.requirement } : {}),+ });+ }++ // The source is empty now — its rounds, results and evidence all live on the+ // target. Deleting it is what makes the merge one entry instead of two.+ await txAcceptanceModel.delete(source.id);+ });++ log(+ 'merged acceptance %s into %s: %d round(s), %d check(s), %d re-keyed',+ source.id,+ target.id,+ sourceRuns.length,+ movedChecks,+ remap.size,+ );++ return {+ movedChecks,+ movedRounds: sourceRuns.length,+ rekeyedChecks: remap.size,+ };+};diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex eaa5ce147bf..4d898333f17 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -37,6 +37,7 @@ import type {import type { LobeChatDatabase } from '@/database/type';import { TaskService } from '@/server/services/task';+import { type AcceptanceMergeSummary, mergeAcceptanceRounds } from './acceptanceMerge';import { computeFalseFlags } from './feedbackService';import { maybeContinueGoalLoop, syncGoalToolState } from './goalLoop';@@ -542,6 +543,54 @@ export class AcceptanceService {return 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 adiff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.tsindex 986e8569c61..8d5501093a9 100644--- a/apps/server/src/services/verify/index.ts+++ b/apps/server/src/services/verify/index.ts@@ -1,3 +1,9 @@+export {+ type AcceptanceMergeSummary,+ collectCheckIds,+ mergeAcceptanceRounds,+ planCheckIdRemap,+} from './acceptanceMerge';export {type AcceptanceCheckHistoryEntry,type AcceptanceCheckReviewEvent,diff --git a/apps/server/src/services/verify/planGenerator.ts b/apps/server/src/services/verify/planGenerator.tsindex 70eeecc55b3..9bf5646379c 100644--- a/apps/server/src/services/verify/planGenerator.ts+++ b/apps/server/src/services/verify/planGenerator.ts@@ -165,14 +165,7 @@ export class VerifyPlanGeneratorService {: {};}- /**- * Config-time AI generation: turn a one-sentence acceptance requirement into a- * set of proposed criteria for the user to review/edit before saving. Runs the- * same prompt and schema as the run-time plan path, but uses its own tracing- * scenario because drafting criteria in createGoal is a distinct product- * workflow from generating a frozen execution plan. Returns drafts only —- * nothing is persisted and no operation is required.- */+ /** Draft criteria for the generic task verification configuration surface. */async generateCriteria(params: {context?: string;goal: string;@@ -180,25 +173,21 @@ export class VerifyPlanGeneratorService {modelConfig: { model: string; provider: string };}): Promise<CriterionDraft[]> {const maxCriteria = params.maxCriteria ?? DEFAULT_MAX_AI_CRITERIA;- const chain = chainVerifyPlan({- context: params.context,- goal: params.goal,- maxCriteria,- });-- const ai = new AiGenerationService(this.db, this.userId);- const raw = await ai.generateObject(+ const raw = await new AiGenerationService(this.db, this.userId).generateObject({- ...chain,- model: params.modelConfig.model,- provider: params.modelConfig.provider,+ ...chainVerifyPlan({+ context: params.context,+ goal: params.goal,+ maxCriteria,+ }),+ ...params.modelConfig,schema: GENERATED_CRITERIA_JSON_SCHEMA,thinking: { type: 'disabled' },},{tracing: {promptVersion: VERIFY_PLAN_PROMPT_VERSION,- scenario: TRACING_SCENARIOS.GoalCriteriaGen,+ scenario: TRACING_SCENARIOS.VerifyPlanGen,schemaName: GENERATED_CRITERIA_JSON_SCHEMA.name,} satisfies TracingOptions,},@@ -209,15 +198,18 @@ export class VerifyPlanGeneratorService {log('config criteria-gen output did not match schema: %O', parsed.error.flatten());return [];}- return withoutProgrammaticTests(parsed.data.criteria.slice(0, maxCriteria)).map((c) => ({- description: c.description,- instruction: c.instruction,- onFail: c.onFail ?? 'manual',- requiredEvidence: c.requiredEvidence,- required: c.required ?? true,- title: c.title,- verifierType: c.verifierType,- }));++ return withoutProgrammaticTests(parsed.data.criteria.slice(0, maxCriteria)).map(+ (criterion) => ({+ description: criterion.description,+ instruction: criterion.instruction,+ onFail: criterion.onFail ?? 'manual',+ requiredEvidence: criterion.requiredEvidence,+ required: criterion.required ?? true,+ title: criterion.title,+ verifierType: criterion.verifierType,+ }),+ );}/**diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex 32374a43d40..483e54268d6 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "النموذج","systemAgent.generationTopic.modelDesc": "النموذج المخصص لتسمية مواضيع فن الذكاء الاصطناعي تلقائيًا","systemAgent.generationTopic.title": "وكيل تسمية مواضيع فن الذكاء الاصطناعي",+ "systemAgent.goal.modelDesc": "النموذج المستخدم لتحويل الهدف المستمر إلى معايير القبول الدائمة الخاصة به.",+ "systemAgent.goal.title": "إنشاء الهدف","systemAgent.helpInfo": "عند إنشاء وكيل جديد، سيتم استخدام إعدادات الوكيل الافتراضية كقيم مسبقة.","systemAgent.historyCompress.label": "النموذج","systemAgent.historyCompress.modelDesc": "تحديد النموذج المستخدم لضغط سجل المحادثة",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex a321b28c6ba..f7d19278564 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Модел","systemAgent.generationTopic.modelDesc": "Модел, използван за автоматично именуване на теми за AI изкуство","systemAgent.generationTopic.title": "Агент за именуване на теми за AI изкуство",+ "systemAgent.goal.modelDesc": "Модел, използван за превръщане на постоянна цел в нейни постоянни критерии за приемане.",+ "systemAgent.goal.title": "Създаване на цел","systemAgent.helpInfo": "При създаване на нов агент, настройките по подразбиране ще се използват като предварителни стойности.","systemAgent.historyCompress.label": "Модел","systemAgent.historyCompress.modelDesc": "Посочете модел за компресиране на историята на разговорите",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex 004d0c7090c..bd59b20ca1a 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Modell","systemAgent.generationTopic.modelDesc": "Modell zur automatischen Benennung von KI-Kunstthemen","systemAgent.generationTopic.title": "Agent zur Benennung von KI-Kunstthemen",+ "systemAgent.goal.modelDesc": "Modell, das verwendet wird, um ein dauerhaftes Ziel in seine ständigen Akzeptanzkriterien umzuwandeln.",+ "systemAgent.goal.title": "Zielerstellung","systemAgent.helpInfo": "Beim Erstellen eines neuen Agenten werden die Standardagenteneinstellungen als Voreinstellungen verwendet.","systemAgent.historyCompress.label": "Modell","systemAgent.historyCompress.modelDesc": "Modell zur Komprimierung des Gesprächsverlaufs",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex cdd2ef065fe..0c9884bc981 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1316,6 +1316,8 @@"systemAgent.generationTopic.label": "Model","systemAgent.generationTopic.modelDesc": "Model used to name AI image topics","systemAgent.generationTopic.title": "AI Image Topic Naming",+ "systemAgent.goal.modelDesc": "Model used to turn a persistent goal into its standing acceptance criteria.",+ "systemAgent.goal.title": "Goal Creation","systemAgent.helpInfo": "When creating a new agent, the default agent settings will be used as preset values.","systemAgent.historyCompress.label": "Model","systemAgent.historyCompress.modelDesc": "Model used to compress conversation history",diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex 3d2ba750c95..292c9939ebd 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -249,6 +249,7 @@"acceptance.workspace.actions.markAccepted": "Mark as accepted","acceptance.workspace.actions.markClosed": "Mark as closed","acceptance.workspace.actions.markRejected": "Mark as rejected",+ "acceptance.workspace.actions.merge": "Merge into…","acceptance.workspace.actions.more": "More actions","acceptance.workspace.actions.rename": "Rename","acceptance.workspace.actions.reopen": "Reopen for review",@@ -275,6 +276,17 @@"acceptance.workspace.groups.viewProject": "View project","acceptance.workspace.listEmpty": "Ingest a verification report with the CLI and its acceptance will show up here.","acceptance.workspace.listEmptyTitle": "No acceptances yet",+ "acceptance.workspace.merge.confirm": "Merge",+ "acceptance.workspace.merge.description": "Move the {{count}} checks of “{{title}}” into another acceptance. Pick where they should land.",+ "acceptance.workspace.merge.error": "Failed to merge acceptance",+ "acceptance.workspace.merge.hint": "The checks keep their verdicts, evidence and rounds. This acceptance is removed once they land.",+ "acceptance.workspace.merge.noCandidates": "No other acceptance to merge into.",+ "acceptance.workspace.merge.noSearchResults": "No acceptance matches “{{query}}”.",+ "acceptance.workspace.merge.searchPlaceholder": "Search acceptances",+ "acceptance.workspace.merge.settledHint": "settled — reopen it first",+ "acceptance.workspace.merge.success": "{{count}} checks merged",+ "acceptance.workspace.merge.title": "Merge acceptance",+ "acceptance.workspace.merge.windowHint": "Only the {{count}} most recent acceptances are listed here.","acceptance.workspace.project.add": "Add to project","acceptance.workspace.project.addSuccess": "Added to the project","acceptance.workspace.project.create": "New project with this delivery",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex b84af83f6f9..c28b3621b5e 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Modelo","systemAgent.generationTopic.modelDesc": "Modelo designado para nombrar automáticamente temas de arte IA","systemAgent.generationTopic.title": "Agente de Nombres para Temas de Arte IA",+ "systemAgent.goal.modelDesc": "Modelo utilizado para convertir un objetivo persistente en sus criterios de aceptación permanentes.",+ "systemAgent.goal.title": "Creación de Objetivos","systemAgent.helpInfo": "Al crear un nuevo agente, se usarán los valores predeterminados como configuración inicial.","systemAgent.historyCompress.label": "Modelo","systemAgent.historyCompress.modelDesc": "Especifica el modelo usado para comprimir el historial de conversación",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex ca9d9cc5cf0..0264ffc24c9 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "مدل","systemAgent.generationTopic.modelDesc": "مدلی که برای نامگذاری خودکار موضوعات هنر هوش مصنوعی استفاده میشود","systemAgent.generationTopic.title": "عامل نامگذاری موضوع هنر هوش مصنوعی",+ "systemAgent.goal.modelDesc": "مدلی که برای تبدیل یک هدف پایدار به معیارهای پذیرش دائمی آن استفاده میشود.",+ "systemAgent.goal.title": "ایجاد هدف","systemAgent.helpInfo": "هنگام ایجاد یک عامل جدید، تنظیمات پیشفرض عامل بهعنوان مقادیر اولیه استفاده میشوند.","systemAgent.historyCompress.label": "مدل","systemAgent.historyCompress.modelDesc": "مدلی که برای فشردهسازی تاریخچه گفتگو استفاده میشود",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex f175bd7eaea..beb2e7e33cd 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Modèle","systemAgent.generationTopic.modelDesc": "Modèle utilisé pour nommer automatiquement les sujets d’art IA","systemAgent.generationTopic.title": "Agent de nommage de sujet d’art IA",+ "systemAgent.goal.modelDesc": "Modèle utilisé pour transformer un objectif persistant en ses critères d'acceptation permanents.",+ "systemAgent.goal.title": "Création d'objectif","systemAgent.helpInfo": "Lors de la création d’un nouvel agent, les paramètres par défaut seront utilisés comme valeurs prédéfinies.","systemAgent.historyCompress.label": "Modèle","systemAgent.historyCompress.modelDesc": "Modèle utilisé pour compresser l’historique des conversations",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex 10ad3e86012..ab666c891ec 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Modello","systemAgent.generationTopic.modelDesc": "Modello designato per la denominazione automatica dei temi di arte AI","systemAgent.generationTopic.title": "Agente Denominazione Temi Arte AI",+ "systemAgent.goal.modelDesc": "Modello utilizzato per trasformare un obiettivo persistente nei suoi criteri di accettazione permanenti.",+ "systemAgent.goal.title": "Creazione Obiettivo","systemAgent.helpInfo": "Quando crei un nuovo agente, verranno utilizzate le impostazioni predefinite come valori iniziali.","systemAgent.historyCompress.label": "Modello","systemAgent.historyCompress.modelDesc": "Specifica il modello utilizzato per comprimere la cronologia delle conversazioni",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex 4ce25a19228..ce63ea47ac7 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "モデル","systemAgent.generationTopic.modelDesc": "AI絵画の自動トピック命名に使用されるモデルを指定します","systemAgent.generationTopic.title": "AIイラスト用トピック命名アシスタント",+ "systemAgent.goal.modelDesc": "持続的な目標をその恒久的な受け入れ基準に変換するために使用されるモデル。",+ "systemAgent.goal.title": "目標の作成","systemAgent.helpInfo": "新しいアシスタントを作成するとき、デフォルトのアシスタント設定がプリセット値として使用されます。","systemAgent.historyCompress.label": "モデル","systemAgent.historyCompress.modelDesc": "会話履歴を圧縮するために指定されたモデル",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex 9aedda94d50..d169f136354 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "모델","systemAgent.generationTopic.modelDesc": "AI 그림 자동 주제 명명에 사용되는 모델 지정","systemAgent.generationTopic.title": "AI 그림 주제 명명 도우미",+ "systemAgent.goal.modelDesc": "지속적인 목표를 해당 지속적인 수용 기준으로 전환하는 데 사용되는 모델입니다.",+ "systemAgent.goal.title": "목표 생성","systemAgent.helpInfo": "새 도우미를 생성할 때 기본 도우미 설정이 기본값으로 사용됩니다.","systemAgent.historyCompress.label": "모델","systemAgent.historyCompress.modelDesc": "대화 기록 압축에 사용되는 모델을 지정합니다",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex 764fec84150..b5bf425fea9 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Model","systemAgent.generationTopic.modelDesc": "Model dat wordt gebruikt voor automatische naamgeving van AI-kunstonderwerpen","systemAgent.generationTopic.title": "AI Kunstonderwerp Naamgevingsagent",+ "systemAgent.goal.modelDesc": "Model gebruikt om een persistent doel om te zetten in de bijbehorende acceptatiecriteria.",+ "systemAgent.goal.title": "Doelcreatie","systemAgent.helpInfo": "Bij het aanmaken van een nieuwe agent worden de standaardinstellingen als uitgangspunt gebruikt.","systemAgent.historyCompress.label": "Model","systemAgent.historyCompress.modelDesc": "Specificeer het model dat wordt gebruikt om gespreksgeschiedenis te comprimeren",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex 4550ac9b5f6..42e382ec6fb 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Model","systemAgent.generationTopic.modelDesc": "Model przeznaczony do automatycznego nadawania nazw tematom sztuki AI","systemAgent.generationTopic.title": "Agent nazewnictwa tematów sztuki AI",+ "systemAgent.goal.modelDesc": "Model używany do przekształcenia trwałego celu w jego stałe kryteria akceptacji.",+ "systemAgent.goal.title": "Tworzenie celu","systemAgent.helpInfo": "Podczas tworzenia nowego agenta domyślne ustawienia agenta będą używane jako wartości wstępne.","systemAgent.historyCompress.label": "Model","systemAgent.historyCompress.modelDesc": "Określ model używany do kompresji historii rozmów",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex ad5d756c810..9abb62dcb94 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Modelo","systemAgent.generationTopic.modelDesc": "Modelo designado para nomeação automática de tópicos de arte IA","systemAgent.generationTopic.title": "Agente de Nomeação de Tópicos de Arte IA",+ "systemAgent.goal.modelDesc": "Modelo usado para transformar um objetivo persistente em seus critérios de aceitação permanentes.",+ "systemAgent.goal.title": "Criação de Objetivo","systemAgent.helpInfo": "Ao criar um novo agente, as configurações padrão do agente serão usadas como valores predefinidos.","systemAgent.historyCompress.label": "Modelo","systemAgent.historyCompress.modelDesc": "Especifique o modelo usado para compactar o histórico de conversas",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 8a3318710b6..831f11dd2b3 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Модель","systemAgent.generationTopic.modelDesc": "Модель, используемая для автоматического наименования тем ИИ-арта","systemAgent.generationTopic.title": "Агент наименования тем ИИ-арта",+ "systemAgent.goal.modelDesc": "Модель, используемая для преобразования постоянной цели в её текущие критерии принятия.",+ "systemAgent.goal.title": "Создание цели","systemAgent.helpInfo": "При создании нового агента будут использоваться настройки агента по умолчанию.","systemAgent.historyCompress.label": "Модель","systemAgent.historyCompress.modelDesc": "Укажите модель для сжатия истории диалога",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex 279da69e8e8..4d3bc4d40a4 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Model","systemAgent.generationTopic.modelDesc": "Yapay zeka sanat konularının otomatik adlandırılması için belirlenen model","systemAgent.generationTopic.title": "Yapay Zeka Sanat Konusu Adlandırma Temsilcisi",+ "systemAgent.goal.modelDesc": "Kalıcı bir hedefi sürekli kabul kriterlerine dönüştürmek için kullanılan model.",+ "systemAgent.goal.title": "Hedef Oluşturma","systemAgent.helpInfo": "Yeni bir temsilci oluştururken, varsayılan temsilci ayarları ön ayar olarak kullanılacaktır.","systemAgent.historyCompress.label": "Model","systemAgent.historyCompress.modelDesc": "Konuşma geçmişini sıkıştırmak için kullanılacak modeli belirtin",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 10c7a7f28aa..998bdb75474 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "Mô Hình","systemAgent.generationTopic.modelDesc": "Mô hình được chỉ định để tự động đặt tên chủ đề nghệ thuật AI","systemAgent.generationTopic.title": "Tác Nhân Đặt Tên Chủ Đề Nghệ Thuật AI",+ "systemAgent.goal.modelDesc": "Mô hình được sử dụng để chuyển mục tiêu lâu dài thành tiêu chí chấp nhận hiện hành của nó.",+ "systemAgent.goal.title": "Tạo Mục Tiêu","systemAgent.helpInfo": "Khi tạo tác nhân mới, cài đặt mặc định của tác nhân sẽ được sử dụng làm giá trị thiết lập sẵn.","systemAgent.historyCompress.label": "Mô Hình","systemAgent.historyCompress.modelDesc": "Chỉ định mô hình dùng để nén lịch sử trò chuyện",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 3c64cd7697a..3d3c7f1daf1 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1316,6 +1316,8 @@"systemAgent.generationTopic.label": "模型","systemAgent.generationTopic.modelDesc": "用于自动命名 AI 图片话题的模型","systemAgent.generationTopic.title": "AI 图片话题命名",+ "systemAgent.goal.modelDesc": "用于将持久目标转化为其持续接受标准的模型。",+ "systemAgent.goal.title": "目标创建","systemAgent.helpInfo": "当创建新助理时,将以默认助理设置作为预设值。","systemAgent.historyCompress.label": "模型","systemAgent.historyCompress.modelDesc": "用于压缩会话历史的模型",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex 3e49fc75dc9..9a1f93df741 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -249,6 +249,7 @@"acceptance.workspace.actions.markAccepted": "标记为已验收","acceptance.workspace.actions.markClosed": "标记为关闭","acceptance.workspace.actions.markRejected": "标记为已打回",+ "acceptance.workspace.actions.merge": "合并到…","acceptance.workspace.actions.more": "更多操作","acceptance.workspace.actions.rename": "重命名","acceptance.workspace.actions.reopen": "重新打开验收",@@ -275,6 +276,17 @@"acceptance.workspace.groups.viewProject": "查看项目","acceptance.workspace.listEmpty": "用 CLI ingest 一份验证报告后,对应的验收会出现在这里。","acceptance.workspace.listEmptyTitle": "还没有验收记录",+ "acceptance.workspace.merge.confirm": "合并",+ "acceptance.workspace.merge.description": "将「{{title}}」的 {{count}} 项验收项转移到另一个验收,选择它们的去处。",+ "acceptance.workspace.merge.error": "合并验收失败",+ "acceptance.workspace.merge.hint": "验收项会连同结论、证据与轮次一起转移,转移后当前验收将被移除。",+ "acceptance.workspace.merge.noCandidates": "没有可合并的其他验收。",+ "acceptance.workspace.merge.noSearchResults": "没有匹配「{{query}}」的验收。",+ "acceptance.workspace.merge.searchPlaceholder": "搜索验收",+ "acceptance.workspace.merge.settledHint": "已结束 · 需先重新开启",+ "acceptance.workspace.merge.success": "已合并 {{count}} 项验收项",+ "acceptance.workspace.merge.title": "合并验收",+ "acceptance.workspace.merge.windowHint": "这里只列出最近 {{count}} 条验收。","acceptance.workspace.project.add": "添加到项目","acceptance.workspace.project.addSuccess": "已添加到项目","acceptance.workspace.project.create": "新建项目并添加",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex 2793f40c1d2..c3fa23957d5 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -1310,6 +1310,8 @@"systemAgent.generationTopic.label": "模型","systemAgent.generationTopic.modelDesc": "指定用於 AI 繪畫自動命名話題的模型","systemAgent.generationTopic.title": "AI 繪圖主題命名助手",+ "systemAgent.goal.modelDesc": "用於將持續目標轉化為其固定接受標準的模型。",+ "systemAgent.goal.title": "目標創建","systemAgent.helpInfo": "當創建新助手時,將以預設助手設定作為預設值。","systemAgent.historyCompress.label": "模型","systemAgent.historyCompress.modelDesc": "指定用於壓縮會話歷史的模型",diff --git a/packages/const/src/settings/systemAgent.ts b/packages/const/src/settings/systemAgent.tsindex 2eb9e25a97a..a77fe6a4bf4 100644--- a/packages/const/src/settings/systemAgent.ts+++ b/packages/const/src/settings/systemAgent.ts@@ -58,6 +58,7 @@ export const DEFAULT_SYSTEM_AGENT_CONFIG: UserServiceModelConfig = {expertise: DEFAULT_MINI_SYSTEM_AGENT_ITEM,followUpAction: DEFAULT_FOLLOW_UP_ACTION_SYSTEM_AGENT_ITEM,generationTopic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,+ goal: DEFAULT_MINI_SYSTEM_AGENT_ITEM,historyCompress: DEFAULT_SYSTEM_AGENT_ITEM,inputCompletion: DEFAULT_INPUT_COMPLETION_SYSTEM_AGENT_ITEM,memoryAnalysisAgentConfig: DEFAULT_MINI_SYSTEM_AGENT_ITEM,diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 13945776c11..f44e05629fb 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1535,6 +1535,9 @@ When I am ___, I need ___'systemAgent.expertise.modelDesc':'Model used to draft expertise domains and extract reusable experience from conversations.','systemAgent.expertise.title': 'Agent Self-Evolution',+ 'systemAgent.goal.modelDesc':+ 'Model used to turn a persistent goal into its standing acceptance criteria.',+ 'systemAgent.goal.title': 'Goal Creation','systemAgent.customPrompt.addPrompt': 'Add Custom Prompt','systemAgent.customPrompt.desc':'Once filled out, the system agent will use the custom prompt when generating content',diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex aeaa5616d8b..fc31f4c7319 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -281,6 +281,7 @@ export default {'acceptance.workspace.actions.markAccepted': 'Mark as accepted','acceptance.workspace.actions.markClosed': 'Mark as closed','acceptance.workspace.actions.markRejected': 'Mark as rejected',+ 'acceptance.workspace.actions.merge': 'Merge into…','acceptance.workspace.actions.more': 'More actions','acceptance.workspace.actions.rename': 'Rename','acceptance.workspace.actions.reopen': 'Reopen for review',@@ -321,6 +322,21 @@ export default {'acceptance.workspace.project.moveSuccess': 'Moved to the project','acceptance.workspace.project.remove': 'Remove from project','acceptance.workspace.project.removeSuccess': 'Removed from the project',+ 'acceptance.workspace.merge.title': 'Merge acceptance',+ 'acceptance.workspace.merge.windowHint':+ 'Only the {{count}} most recent acceptances are listed here.',++ 'acceptance.workspace.merge.description':+ 'Move the {{count}} checks of “{{title}}” into another acceptance. Pick where they should land.',+ 'acceptance.workspace.merge.noSearchResults': 'No acceptance matches “{{query}}”.',+ 'acceptance.workspace.merge.searchPlaceholder': 'Search acceptances',+ 'acceptance.workspace.merge.noCandidates': 'No other acceptance to merge into.',+ 'acceptance.workspace.merge.settledHint': 'settled — reopen it first',+ 'acceptance.workspace.merge.hint':+ 'The checks keep their verdicts, evidence and rounds. This acceptance is removed once they land.',+ 'acceptance.workspace.merge.confirm': 'Merge',+ 'acceptance.workspace.merge.success': '{{count}} checks merged',+ 'acceptance.workspace.merge.error': 'Failed to merge acceptance','acceptance.workspace.renameEmpty': 'The title cannot be empty','acceptance.workspace.renameError': 'Failed to rename','acceptance.workspace.renameSuccess': 'Renamed',diff --git a/packages/prompts/src/chains/goal.test.ts b/packages/prompts/src/chains/goal.test.tsnew file mode 100644index 00000000000..b3f44770d1a--- /dev/null+++ b/packages/prompts/src/chains/goal.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import {+ chainGoalCriteriaDraft,+ GOAL_CRITERIA_DRAFT_JSON_SCHEMA,+ GOAL_CRITERIA_DRAFT_PROMPT_VERSION,+} from './goal';++describe('chainGoalCriteriaDraft', () => {+ it('owns a dedicated version, schema, and standing-goal prompt', () => {+ const chain = chainGoalCriteriaDraft({+ context: 'Goal: Release the product',+ goal: 'Ship a polished v1',+ maxCriteria: 6,+ });++ expect(GOAL_CRITERIA_DRAFT_PROMPT_VERSION).toBe('v1');+ expect(GOAL_CRITERIA_DRAFT_JSON_SCHEMA.name).toBe('goal_criteria_draft');+ expect(chain.messages[0].content).toContain('persistent autonomous goal');+ expect(chain.messages[0].content).toContain('at most 6 criteria');+ expect(chain.messages[1].content).toContain('Ship a polished v1');+ });+});diff --git a/packages/prompts/src/chains/goal.ts b/packages/prompts/src/chains/goal.tsnew file mode 100644index 00000000000..9187d18e22a--- /dev/null+++ b/packages/prompts/src/chains/goal.ts@@ -0,0 +1,103 @@+import type { OpenAIChatMessage } from '@lobechat/types';++import {+ VERIFY_EVIDENCE_MODALITIES,+ VERIFY_EVIDENCE_SCOPES,+ VERIFY_EVIDENCE_TYPES,+ VERIFY_ON_FAIL_ACTIONS,+ VERIFY_VERIFIER_TYPES,+} from './verify';++/** Bump when the create-goal criteria drafting prompt meaningfully changes. */+export const GOAL_CRITERIA_DRAFT_PROMPT_VERSION = 'v1';++export const GOAL_CRITERIA_DRAFT_JSON_SCHEMA = {+ name: 'goal_criteria_draft',+ schema: {+ additionalProperties: false,+ properties: {+ criteria: {+ items: {+ additionalProperties: false,+ properties: {+ description: { maxLength: 280, type: 'string' },+ instruction: { type: 'string' },+ onFail: { enum: [...VERIFY_ON_FAIL_ACTIONS], type: 'string' },+ requiredEvidence: {+ items: {+ additionalProperties: false,+ properties: {+ hint: { type: 'string' },+ modality: { enum: [...VERIFY_EVIDENCE_MODALITIES], type: 'string' },+ scope: { enum: [...VERIFY_EVIDENCE_SCOPES], type: 'string' },+ type: { enum: [...VERIFY_EVIDENCE_TYPES], type: 'string' },+ },+ required: ['type', 'modality', 'scope', 'hint'],+ type: 'object',+ },+ type: 'array',+ },+ required: { type: 'boolean' },+ title: { maxLength: 80, minLength: 1, type: 'string' },+ verifierType: { enum: [...VERIFY_VERIFIER_TYPES], type: 'string' },+ },+ required: [+ 'title',+ 'description',+ 'instruction',+ 'verifierType',+ 'required',+ 'onFail',+ 'requiredEvidence',+ ],+ type: 'object',+ },+ maxItems: 8,+ type: 'array',+ },+ },+ required: ['criteria'],+ type: 'object' as const,+ },+ strict: true,+};++interface GoalCriteriaDraftInput {+ context?: string;+ goal: string;+ maxCriteria: number;+}++/** Draft the standing acceptance contract shown during goal creation. */+export const chainGoalCriteriaDraft = ({+ context,+ goal,+ maxCriteria,+}: GoalCriteriaDraftInput): { messages: OpenAIChatMessage[] } => ({+ messages: [+ {+ content: [+ 'You define the standing acceptance contract for a persistent autonomous goal.',+ 'Turn the goal into a concise set of durable, user-reviewable pass/fail criteria that can be applied after every iteration.',+ 'Guidelines:',+ `- Return at most ${maxCriteria} criteria. Prefer fewer independent criteria that together define success.`,+ '- Describe outcomes and delivered artifacts, not implementation steps or one particular execution plan.',+ '- Criteria must remain valid across multiple attempts. Do not mention the current round, temporary progress, or how the agent should work.',+ '- Never use unit tests, test suites, coverage, type-checks, lint, or a clean build as user-facing acceptance criteria.',+ '- List the evidence needed to judge each criterion. Use [] only when the final text answer alone is sufficient.',+ '- Use verifierType="agent" when judging requires active investigation, opening files, or multiple evidence types; use "llm" only for inline text or a directly inspectable image; use "program" only for deterministic command checks.',+ '- Set required=true when failure means the goal has not been achieved.',+ '- Set onFail="auto_repair" when another autonomous iteration can address the failure; otherwise use "manual".',+ '- description is a one-sentence summary. instruction is the exact, detailed judging rubric, including pass conditions, failure conditions, evidence, and important edge cases.',+ '- Write all human-facing fields in the language used by the goal.',+ ].join('\n'),+ role: 'system',+ },+ {+ content: [`## Goal\n${goal}`, context ? `\n## Context\n${context}` : '']+ .filter(Boolean)+ .join('\n'),+ role: 'user',+ },+ ],+});diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.tsindex 76a0f5941a1..32a6b6d0b68 100644--- a/packages/prompts/src/chains/index.ts+++ b/packages/prompts/src/chains/index.ts@@ -7,6 +7,7 @@ export * from './expertise';export * from './followUpAction';export * from './generateBrief';export * from './generateSkillMeta';+export * from './goal';export * from './inputCompletion';export * from './judgeBriefEmit';export * from './langDetect';diff --git a/packages/types/src/user/settings/systemAgent.ts b/packages/types/src/user/settings/systemAgent.tsindex c35965f0eab..354416a5241 100644--- a/packages/types/src/user/settings/systemAgent.ts+++ b/packages/types/src/user/settings/systemAgent.ts@@ -16,6 +16,8 @@ export interface UserSystemAgentConfig {expertise: SystemAgentItem;followUpAction: SystemAgentItem;generationTopic: SystemAgentItem;+ /** Model used to turn a persistent goal into its standing acceptance criteria. */+ goal: SystemAgentItem;historyCompress: SystemAgentItem;inputCompletion: SystemAgentItem;/** Model used to turn onboarding evidence into background-safe task recommendations. */diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex 47e9d1e8476..f0d3264f093 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -36,8 +36,6 @@ import {} from '@/features/Verify';import { usePermission } from '@/hooks/usePermission';import { verifyService } from '@/services/verify';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { useTaskStore } from '@/store/task';import { buildGoalTaskConfig } from './goalConfig';@@ -240,16 +238,6 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {const createTask = useTaskStore((s) => s.createTask);const isCreating = useTaskStore((s) => s.isCreatingTask);const activeWorkspaceId = useActiveWorkspaceId();- const model = useAgentStore((s) =>- agentId- ? agentByIdSelectors.getAgentModelById(agentId)(s)- : agentSelectors.currentAgentModel(s),- );- const provider = useAgentStore((s) =>- agentId- ? agentByIdSelectors.getAgentModelProviderById(agentId)(s)- : agentSelectors.currentAgentModelProvider(s),- );const [step, setStep] = useState<'describe' | 'preparing' | 'review'>('describe');const [plan, setPlan] = useState<CreateGoalParams>({@@ -286,7 +274,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {const handleNext = useCallback(async () => {const instruction = instructionRef.current.trim() || plan.instruction.trim();- if (!canCreate || !instruction || !model || !provider) return;+ if (!canCreate || !instruction) return;const name = plan.name.trim() || deriveGoalTitle(instruction);setPlan((current) => ({...current,@@ -299,8 +287,6 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {const generated = await generateGoalCriteria({context: name ? `Goal: ${name}` : undefined,goal: initialRequirement?.trim() || instruction,- model,- provider,});setPlan((current) => ({...current,@@ -318,7 +304,7 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {setStep('review');toast.warning(t('createGoal.generateFailed'));}- }, [canCreate, initialRequirement, model, plan.instruction, plan.name, provider, t]);+ }, [canCreate, initialRequirement, plan.instruction, plan.name, t]);const handleCreateBlank = useCallback(() => {if (!canCreate) return;diff --git a/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts b/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.tsindex 6d8ba0845c1..ca6f1e0e9b9 100644--- a/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalCriteria.test.ts@@ -11,7 +11,7 @@ describe('generateGoalCriteria', () => {it('generates and normalizes acceptance criteria for the goal review step', async () => {const generateCriteria = vi- .spyOn(verifyService, 'generateCriteria')+ .spyOn(verifyService, 'generateGoalCriteria').mockResolvedValue([{ title: 'Paper draft is complete' },{ required: false, title: 'Results are reproducible', verifierType: 'llm' },@@ -20,15 +20,12 @@ describe('generateGoalCriteria', () => {const result = await generateGoalCriteria({context: 'Goal: Publish an ICLR paper',goal: 'Complete an RSI benchmark paper in three months',- model: 'test-model',- provider: 'test-provider',});expect(generateCriteria).toHaveBeenCalledWith({context: 'Goal: Publish an ICLR paper',goal: 'Complete an RSI benchmark paper in three months',maxCriteria: 8,- modelConfig: { model: 'test-model', provider: 'test-provider' },});expect(result).toEqual([{@@ -47,13 +44,11 @@ describe('generateGoalCriteria', () => {});it('rejects an empty AI response instead of advancing with no criteria', async () => {- vi.spyOn(verifyService, 'generateCriteria').mockResolvedValue([]);+ vi.spyOn(verifyService, 'generateGoalCriteria').mockResolvedValue([]);await expect(generateGoalCriteria({goal: 'Ship the project',- model: 'test-model',- provider: 'test-provider',}),).rejects.toThrow('No acceptance criteria were generated.');});diff --git a/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts b/src/features/AgentGoals/CreateGoalModal/goalCriteria.tsindex e0a2cbd8442..c438acbb7f1 100644--- a/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalCriteria.ts@@ -6,8 +6,6 @@ import { verifyService } from '@/services/verify';interface GenerateGoalCriteriaParams {context?: string;goal: string;- model: string;- provider: string;}export const withGoalCriterionDefaults = (draft: VerifyCriterionDraft): GoalCriterionDraft => ({@@ -27,14 +25,11 @@ export const createFallbackGoalCriterion = (goal: string): GoalCriterionDraft =>export const generateGoalCriteria = async ({context,goal,- model,- provider,}: GenerateGoalCriteriaParams): Promise<GoalCriterionDraft[]> => {- const generated = await verifyService.generateCriteria({+ const generated = await verifyService.generateGoalCriteria({context,goal,maxCriteria: 8,- modelConfig: { model, provider },});if (generated.length === 0) throw new Error('No acceptance criteria were generated.');diff --git a/src/features/ServiceModel/ModelAssignmentsForm.tsx b/src/features/ServiceModel/ModelAssignmentsForm.tsxindex cf16a2c61ef..c5d43627ae1 100644--- a/src/features/ServiceModel/ModelAssignmentsForm.tsx+++ b/src/features/ServiceModel/ModelAssignmentsForm.tsx@@ -37,6 +37,7 @@ type SavingGroup = 'assignments' | 'memory' | 'optional';const SYSTEM_AGENT_MODEL_ITEMS: SystemAgentModelItem[] = [{ key: 'expertise' },+ { key: 'goal' },{ key: 'topic' },{ key: 'generationTopic' },{ key: 'translation' },diff --git a/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsx b/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsxindex b2e41fe5ecc..12bdd8f833c 100644--- a/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsx+++ b/src/features/Verify/Acceptance/Workspace/AcceptanceRow.tsx@@ -12,6 +12,7 @@ import {CircleDashed,CircleHelp,CircleX,+ GitMerge,LoaderCircle,MoreHorizontal,Pencil,@@ -31,6 +32,7 @@ import type { AcceptanceListItem } from '@/services/verify';import { verifyService } from '@/services/verify';import { getAcceptanceStatusActions } from '../statusActions';+import { openMergeAcceptanceModal } from './MergeAcceptanceModal';import { useAcceptanceProjectMenuItem } from './useAcceptanceProjectMenuItem';const styles = createStaticStyles(({ css }) => ({@@ -215,6 +217,34 @@ const AcceptanceRow = memo<{onSelect: (projectId) => void assignProject(projectId),});+ /**+ * Fold this entry into another acceptance — its checks (with rounds and+ * evidence) move over and this row disappears. Navigating the active row to+ * the target keeps the reviewer on the surface their checks just moved to,+ * instead of on a 404.+ */+ const mergeIntoAcceptance = () => {+ openMergeAcceptanceModal({+ source: item,+ onConfirm: async (targetId) => {+ setMutating(true);+ try {+ const summary = await verifyService.mergeAcceptance(item.id, targetId);+ if (active) navigate(`/acceptance/${targetId}`, { replace: true });+ await Promise.all([onChanged(), globalMutate(verifyKeys.acceptanceBundle(targetId))]);+ toast.success(t('acceptance.workspace.merge.success', { count: summary.movedChecks }));+ return true;+ } catch (error) {+ console.error('[acceptance:merge]', error);+ toast.error(t('acceptance.workspace.merge.error'));+ return false;+ } finally {+ setMutating(false);+ }+ },+ });+ };+const removeAcceptance = () => {confirmModal({cancelText: t('actions.cancel'),@@ -272,6 +302,12 @@ const AcceptanceRow = memo<{onClick: startRename,},projectItem,+ {+ icon: <Icon icon={GitMerge} />,+ key: 'merge',+ label: t('acceptance.workspace.actions.merge'),+ onClick: mergeIntoAcceptance,+ },...(statusItems.length > 0? [{diff --git a/src/features/Verify/Acceptance/Workspace/MergeAcceptanceModal.tsx b/src/features/Verify/Acceptance/Workspace/MergeAcceptanceModal.tsxnew file mode 100644index 00000000000..61f67fa3f12--- /dev/null+++ b/src/features/Verify/Acceptance/Workspace/MergeAcceptanceModal.tsx@@ -0,0 +1,306 @@+'use client';++import { Empty, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { t } from 'i18next';+import { Search, TriangleAlert } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { SkeletonList } from '@/features/NavPanel/components/SkeletonList';+import type { AcceptanceListItem } from '@/services/verify';++import { useAcceptanceList } from '../../hooks';+import { frostedModalStyles } from '../modals';++/** A settled aggregate cannot receive checks — the server refuses it too. */+const SETTLED_STATUSES = new Set(['accepted', 'closed']);++/**+ * How far back the picker reaches (the server caps the list read at 200).+ *+ * The sidebar's own feed stops at the newest 50, which is fine for a panel you+ * scroll — but a merge target that is not listed is a merge you cannot perform,+ * so this surface asks for the wide end. The list still has an end: when it is+ * reached, the footer says so instead of implying "this is everything".+ */+const TARGET_WINDOW = 200;++const styles = createStaticStyles(({ css }) => ({+ search: css`+ display: flex;+ gap: 7px;+ align-items: center;++ height: 32px;+ padding-inline: 10px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorBgContainer};++ svg {+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ }++ input {+ width: 100%;+ min-width: 0;+ border: none;++ font-size: 13px;+ color: ${cssVar.colorText};++ background: none;+ outline: none;+ }+ `,+ list: css`+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 2px;++ min-height: 120px;+ max-height: 320px;+ padding-block: 4px;+ `,+ option: css`+ cursor: pointer;++ display: flex;+ flex-direction: column;+ gap: 2px;+ align-items: flex-start;++ padding-block: 7px;+ padding-inline: 10px;+ border: 1px solid transparent;+ border-radius: ${cssVar.borderRadius};++ text-align: start;++ background: none;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ optionActive: css`+ border-color: ${cssVar.colorPrimary};+ background: ${cssVar.colorPrimaryBg};++ &:hover {+ background: ${cssVar.colorPrimaryBg};+ }+ `,+ optionDisabled: css`+ cursor: not-allowed;+ opacity: 0.45;++ &:hover {+ background: none;+ }+ `,+ optionTitle: css`+ overflow: hidden;+ display: block;++ width: 100%;++ font-size: 13px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ optionSub: css`+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ `,+ empty: css`+ padding-block: 28px;+ font-size: 12px;+ color: ${cssVar.colorTextTertiary};+ text-align: center;+ `,+ errorState: css`+ display: flex;+ flex-direction: column;+ gap: 10px;+ align-items: center;++ padding-block: 20px;+ `,+ retryBtn: css`+ cursor: pointer;++ padding-block: 4px;+ padding-inline: 10px;+ border: 1px solid ${cssVar.colorBorder};+ border-radius: 4px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorBgContainer};++ &:hover {+ border-color: ${cssVar.colorTextTertiary};+ color: ${cssVar.colorText};+ }+ `,+}));++const titleOf = (item: AcceptanceListItem) => item.subject.title || item.subjectId;++interface MergeContentProps {+ /** Perform the merge; resolve true to close the dialog. */+ onConfirm: (targetId: string) => Promise<boolean>;+ /** The acceptance being folded away. */+ source: AcceptanceListItem;+}++const MergeContent = memo<MergeContentProps>(({ onConfirm, source }) => {+ const { t: translate } = useTranslation('verify');+ const { close } = useModalContext();+ // Revalidate on open: the dialog is a decision surface, and the list's own+ // invalidations do not reach this wider window's cache key.+ const { data, error, isLoading, mutate } = useAcceptanceList(true, {+ limit: TARGET_WINDOW,+ revalidateOnMount: true,+ });+ const [query, setQuery] = useState('');+ const [targetId, setTargetId] = useState<string | null>(null);+ const [loading, setLoading] = useState(false);++ const keyword = query.trim().toLowerCase();+ const others = (data ?? []).filter((item) => item.id !== source.id);+ const candidates = others.filter(+ (item) => !keyword || titleOf(item).toLowerCase().includes(keyword),+ );+ // The window has an end, and a target past it is unreachable from here — say+ // so rather than letting the list read as the complete set.+ const windowFull = (data?.length ?? 0) >= TARGET_WINDOW;++ const handleConfirm = async () => {+ if (!targetId) return;+ setLoading(true);+ try {+ if (await onConfirm(targetId)) close();+ } finally {+ setLoading(false);+ }+ };++ return (+ <Flexbox gap={12}>+ <Text fontSize={13} type={'secondary'}>+ {translate('acceptance.workspace.merge.description', {+ count: source.checkCount ?? 0,+ title: titleOf(source),+ })}+ </Text>++ <label className={styles.search}>+ <Icon icon={Search} size={13} />+ <input+ autoFocus+ placeholder={translate('acceptance.workspace.merge.searchPlaceholder')}+ type={'search'}+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ />+ </label>++ {error ? (+ // A failed list read must not read as "there is nothing to merge into":+ // the two states lead to opposite conclusions about the delivery.+ <div className={styles.errorState}>+ <Empty+ description={translate('workspace.loadError')}+ icon={TriangleAlert}+ title={translate('workspace.loadErrorTitle')}+ />+ <button className={styles.retryBtn} type={'button'} onClick={() => void mutate()}>+ {translate('workspace.retry')}+ </button>+ </div>+ ) : isLoading ? (+ <SkeletonList rows={4} />+ ) : candidates.length === 0 ? (+ <div className={styles.empty}>+ {translate(+ others.length === 0+ ? 'acceptance.workspace.merge.noCandidates'+ : 'acceptance.workspace.merge.noSearchResults',+ { query: query.trim() },+ )}+ </div>+ ) : (+ <div className={styles.list}>+ {candidates.map((item) => {+ const settled = SETTLED_STATUSES.has(item.status);+ return (+ <button+ disabled={settled}+ key={item.id}+ type={'button'}+ className={[+ styles.option,+ item.id === targetId ? styles.optionActive : '',+ settled ? styles.optionDisabled : '',+ ]+ .filter(Boolean)+ .join(' ')}+ onClick={() => setTargetId(item.id)}+ >+ <span className={styles.optionTitle}>{titleOf(item)}</span>+ <span className={styles.optionSub}>+ {item.checkCount == null+ ? translate(`acceptance.status.${item.status}` as any)+ : translate('acceptance.workspace.checkCount', { count: item.checkCount })}+ {settled ? ` · ${translate('acceptance.workspace.merge.settledHint')}` : ''}+ </span>+ </button>+ );+ })}+ </div>+ )}++ <Text fontSize={12} type={'secondary'}>+ {translate('acceptance.workspace.merge.hint')}+ {windowFull+ ? ` ${translate('acceptance.workspace.merge.windowHint', { count: TARGET_WINDOW })}`+ : ''}+ </Text>++ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={loading} onClick={close}>+ {translate('acceptance.actions.cancel')}+ </Button>+ <Button disabled={!targetId} loading={loading} type={'primary'} onClick={handleConfirm}>+ {translate('acceptance.workspace.merge.confirm')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++MergeContent.displayName = 'AcceptanceMergeContent';++/**+ * Target picker for folding one acceptance into another. The source's checks+ * move; the source entry goes away — so the dialog names both sides and what+ * carries over before the click, and never pre-selects a target.+ */+export const openMergeAcceptanceModal = (options: MergeContentProps): ModalInstance =>+ createModal({+ content: <MergeContent {...options} />,+ footer: null,+ maskClosable: true,+ styles: frostedModalStyles,+ title: t('acceptance.workspace.merge.title', { ns: 'verify' }),+ width: 'min(90vw, 520px)',+ });diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.tsindex 83a7d9ede71..842cfe8a501 100644--- a/src/features/Verify/hooks.ts+++ b/src/features/Verify/hooks.ts@@ -80,12 +80,27 @@ export const useAcceptanceBySubject = (},);-/** The caller's recent acceptance aggregates (with subject headers) — the list panel. */-export const useAcceptanceList = (enabled: boolean) =>+/**+ * The caller's recent acceptance aggregates (with subject headers) — the list+ * panel. `limit` widens the recency window for surfaces that must reach further+ * back than the panel does (the merge target picker).+ *+ * A widened window is its own SWR key, and the list's invalidations+ * (`mutate(verifyKeys.acceptances())`) target the panel's key — so a surface+ * that opens on demand asks for `revalidateOnMount` rather than deciding from a+ * cache nothing refreshes.+ */+export const useAcceptanceList = (+ enabled: boolean,+ options?: { limit?: number; revalidateOnMount?: boolean },+) =>useClientDataSWR(- enabled ? verifyKeys.acceptances() : null,- () => verifyService.listAcceptances(),- VERIFY_REPORT_SWR_CONFIG,+ enabled ? verifyKeys.acceptances(options?.limit) : null,+ () => verifyService.listAcceptances({ limit: options?.limit }),+ {+ ...VERIFY_REPORT_SWR_CONFIG,+ ...(options?.revalidateOnMount ? { revalidateOnMount: true } : {}),+ },);/**diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 6c48718faed..2650a18d04a 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -956,7 +956,11 @@ export const verifyKeys = {[...subjectIds].sort().join(','),],),- acceptances: def('verify:acceptances', () => ['verify:acceptances']),+ /** `limit` is part of the key: the merge picker asks for a wider window than the panel. */+ acceptances: def('verify:acceptances', (limit?: number) => [+ 'verify:acceptances',+ String(limit ?? ''),+ ]),criteria: def('verify:criteria', () => ['verify:criteria']),instruction: def('verify:instruction', (documentId: string) => ['verify:instruction',diff --git a/src/services/verify.ts b/src/services/verify.tsindex cf74422ada4..1a580574b94 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -167,9 +167,13 @@ export class VerifyService {requirement: string,) => lambdaClient.acceptance.saveGoal.mutate({ requirement, subjectId, subjectType });- listAcceptances = (options?: { quiet?: boolean }): Promise<AcceptanceListItem[]> =>+ listAcceptances = (options?: {+ /** Widen the recency window (server-capped) — the merge picker asks for more. */+ limit?: number;+ quiet?: boolean;+ }): Promise<AcceptanceListItem[]> =>lambdaClient.acceptance.list.query(- undefined,+ options?.limit ? { limit: options.limit } : undefined,options?.quiet ? { context: { showNotification: false } } : undefined,);@@ -273,6 +277,14 @@ export class VerifyService {updateAcceptanceStatus = (id: string, status: 'accepted' | 'closed' | 'delivered' | 'rejected') =>lambdaClient.acceptance.updateStatus.mutate({ id, status });+ /**+ * Fold one acceptance into another — the source's checks (and the rounds /+ * evidence behind them) move onto the target, and the source entry is+ * removed. Returns what the merge actually moved.+ */+ mergeAcceptance = (sourceId: string, targetId: string) =>+ lambdaClient.acceptance.merge.mutate({ sourceId, targetId });+/** Delete the acceptance aggregate (its round reports detach, not delete). */deleteAcceptance = (id: string) => lambdaClient.acceptance.remove.mutate({ id });@@ -361,6 +373,14 @@ export class VerifyService {}): Promise<VerifyCriterionDraft[]> =>lambdaClient.verify.generateCriteria.mutate(input) as Promise<VerifyCriterionDraft[]>;+ /** Draft the standing acceptance criteria used by the create-goal review step. */+ generateGoalCriteria = (input: {+ context?: string;+ goal: string;+ maxCriteria?: number;+ }): Promise<VerifyCriterionDraft[]> =>+ lambdaClient.verify.generateGoalCriteria.mutate(input) as Promise<VerifyCriterionDraft[]>;+/** Persist (user-edited) drafts as standalone criteria; returns ids in order. */createCriteria = (drafts: VerifyCriterionDraft[]): Promise<string[]> =>lambdaClient.verify.createCriteria.mutate({ drafts }) as Promise<string[]>;diff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snapindex 0e13b39619d..89e76b6a624 100644--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap@@ -68,6 +68,10 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG"model": "gpt-5.6-luna","provider": "openai",},+ "goal": {+ "model": "gpt-5.6-luna",+ "provider": "openai",+ },"historyCompress": {"model": "deepseek-v4-flash","provider": "deepseek",