🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(goal): migrate goal implementation from task.config.goal to the goals table (#18374)
Arvin Xu71441698d4a9
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 8448a356170..32b0306d693 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -1327,3 +1327,22 @@ server-auth 200、`isUserStateInit` true。It is private IP address.` 与紧随其后的 `Error converting image to base64`。生产用真实对象存储域名,不受影响,所以这纯粹是本地验证环境的门槛,不是产品缺陷 ——不要把它当 bug 报上去,也不要为了绕开它改用 inline base64 从而验证了一条产品不会走的路径。++### Goals 页面入口与 Labs 开关++**Situation:** 验收 goal (目标) 相关功能需要进入 Goals 页面。++**Doesn't work:** 直接打开 `/agent/goals` —— goals 路由嵌套在 `/agent/:aid/goals`+下,`goals` 会被当成 agentId 解析成「助理不可用」; 页面还门控在 Labs 开关+`enableTopicAcceptance` 后面,关闭时路由静默 replace 回 `/agent/:aid`。++**Works:** 先查 seeded 用户的 agentId (`select id from agents where user_id=...`),+用公开 store action 打开 Labs 开关 (持久化到用户偏好,全会话生效):++```js+window.__LOBE_STORES.user().updateLab({ enableTopicAcceptance: true });+```++再开 `/agent/<agentId>/goals`。创建 Goal 弹窗中「从空白开始」可跳过 AI 生成验收+标准 (本地无 LLM key 时必用); 标准编辑、预算输入均为普通 input, 目标描述为+contenteditable (用 `fill`,`type` 不支持 contenteditable)。diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 12b52ad0fc8..d279dced6fc 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -7,6 +7,7 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPerimport { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { AgentModel } from '@/database/models/agent';import { BriefModel } from '@/database/models/brief';+import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';import { TopicModel } from '@/database/models/topic';@@ -32,6 +33,7 @@ const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),briefModel: new BriefModel(ctx.serverDB, ctx.userId, wsId),editLockService: new EditLockService(ctx.userId),+ goalModel: new GoalModel(ctx.serverDB, ctx.userId, wsId),taskLifecycle: new TaskLifecycleService(ctx.serverDB, ctx.userId, wsId),taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),taskService: new TaskService(ctx.serverDB, ctx.userId, wsId),@@ -62,6 +64,16 @@ const createSchema = z.object({createdByAgentId: z.string().optional(),description: z.string().optional(),editorData: z.unknown().optional(),+ // Bind a goal entity (`goals` row) to the created task; the task becomes the+ // goal's execution carrier and the outer verify-driven round loop applies.+ goal: z+ .object({+ maxRounds: z.number().int().nullish(),+ maxTotalCost: z.number().nullish(),+ requirement: z.string().nullish(),+ title: z.string().optional(),+ })+ .optional(),identifierPrefix: z.string().optional(),instruction: z.string().min(1),name: z.string().optional(),@@ -470,7 +482,8 @@ export const taskRouter = router({try {const model = ctx.taskModel;const task = await resolveOrThrow(model, input.id);- if (!(task.config as { goal?: unknown } | null)?.goal) {+ const goal = await ctx.goalModel.findBySubject('task', task.id);+ if (!goal) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'Task is not a goal root' });}assertWorkspaceRowManageable(ctx, task.createdByUserId, 'task');diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex dee337b291c..2925c8320eb 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -35,6 +35,15 @@ vi.mock('@/database/models/user', () => ({UserModel: { findByIds: vi.fn().mockResolvedValue([]) },}));+const { goalCreate, goalFindBySubject } = vi.hoisted(() => ({+ goalCreate: vi.fn(),+ goalFindBySubject: vi.fn().mockResolvedValue(undefined),+}));++vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(() => ({ create: goalCreate, findBySubject: goalFindBySubject })),+}));+// AiAgentService pulls in ~14 sub-dependencies in its constructor; mock it so// the running-status branch in updateStatus doesn't drag them in.vi.mock('@/server/services/aiAgent', () => ({@@ -69,6 +78,7 @@ describe('TaskService', () => {const mockTaskModel = {create: vi.fn(),+ delete: vi.fn(),findById: vi.fn(),findByIds: vi.fn(),findAllDescendants: vi.fn(),@@ -1580,6 +1590,57 @@ describe('TaskService', () => {});});+ describe('createTask goal binding', () => {+ beforeEach(() => {+ mockTaskModel.create.mockResolvedValue({+ assigneeAgentId: 'agent-1',+ id: 'task_goal_1',+ identifier: 'T-9',+ instruction: 'reach the goal',+ name: 'Goal task',+ projectId: null,+ });+ mockTaskModel.delete.mockResolvedValue(true);+ goalCreate.mockReset();+ });++ it('creates the bound goals row and returns it on the task', async () => {+ goalCreate.mockResolvedValue({ id: 'goal-1', status: 'planning' });++ const service = new TaskService(db, userId);+ const result = await service.createTask({+ goal: { maxRounds: 4, maxTotalCost: 10, requirement: 'done means done' },+ instruction: 'reach the goal',+ });++ expect(goalCreate).toHaveBeenCalledWith(+ expect.objectContaining({+ maxRounds: 4,+ maxTotalCost: 10,+ requirement: 'done means done',+ subjectId: 'task_goal_1',+ subjectType: 'task',+ }),+ );+ expect((result as any).goal).toEqual({ id: 'goal-1', status: 'planning' });+ expect(mockTaskModel.delete).not.toHaveBeenCalled();+ });++ it('compensates a failed goal insert by deleting the just-created task', async () => {+ // Regression (codex review): a task committed without its promised goal+ // is a user-visible ghost — it never lists on goal surfaces, and a retry+ // stacks another plain task.+ goalCreate.mockRejectedValue(new Error('db down'));++ const service = new TaskService(db, userId);+ await expect(+ service.createTask({ goal: { maxRounds: 3 }, instruction: 'reach the goal' }),+ ).rejects.toThrow('db down');++ expect(mockTaskModel.delete).toHaveBeenCalledWith('task_goal_1');+ });+ });+describe('parent ↔ child visibility compat', () => {beforeEach(() => {mockTaskModel.create.mockImplementation(async (data: any) => ({diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex 240c814b084..47c45c72464 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -1,6 +1,9 @@import { randomUUID } from 'node:crypto';+import { DEFAULT_GOAL_MAX_ROUNDS } from '@lobechat/const/verify';import type {+ CreateTaskGoalInput,+ GoalItem,TaskContext,TaskDetailActivity,TaskDetailActivityAuthor,@@ -16,6 +19,7 @@ import type {import { TRPCError } from '@trpc/server';import { AgentModel } from '@/database/models/agent';+import { GoalModel } from '@/database/models/goal';import { ProjectModel } from '@/database/models/project';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';@@ -61,6 +65,11 @@ export interface CreateTaskInput {description?: string;editorData?: unknown;fileIds?: string[];+ /**+ * Bind a goal entity (`goals` row) to the created task — the task becomes the+ * goal's execution carrier and the outer verify-driven round loop applies.+ */+ goal?: CreateTaskGoalInput;identifierPrefix?: string;instruction: string;name?: string;@@ -123,7 +132,10 @@ export class TaskService {async createTask(input: CreateTaskInput): Promise<TaskItem> {await this.assertAssigneeAgentBelongsToUser(input.assigneeAgentId);- const createData: CreateTaskInput & { config?: Record<string, unknown> } = { ...input };+ const { goal, ...taskInput } = input;+ const createData: Omit<CreateTaskInput, 'goal'> & { config?: Record<string, unknown> } = {+ ...taskInput,+ };let parentVisibility: 'private' | 'public' | undefined;if (createData.parentTaskId) {@@ -181,7 +193,42 @@ export class TaskService {// produce a `Private parent + Public child` combo if the caller insists.this.assertParentVisibilityCompat(createData.visibility, parentVisibility);- return this.taskModel.create(createData);+ const task = await this.taskModel.create(createData);++ if (goal) {+ // Not a transaction on purpose: TaskModel.create's identifier-conflict+ // retry loop relies on continuing after a 23505, which an enclosing+ // transaction would abort. Compensate instead — a task committed without+ // its promised goal is a ghost on goal surfaces (it never lists as a+ // goal), and a retry would stack another one.+ let created: GoalItem;+ try {+ created = await new GoalModel(this.db, this.userId, this.workspaceId).create({+ agentId: task.assigneeAgentId,+ // `null` is the user's explicit "no cap"; `undefined` means they never+ // chose, which falls back to the documented default. The floor keeps a+ // degenerate 1-round loop from ever passing verify-then-stop.+ maxRounds:+ goal.maxRounds === undefined+ ? DEFAULT_GOAL_MAX_ROUNDS+ : goal.maxRounds === null+ ? null+ : Math.max(2, goal.maxRounds),+ maxTotalCost: goal.maxTotalCost ?? null,+ projectId: task.projectId,+ requirement: goal.requirement ?? null,+ subjectId: task.id,+ subjectType: 'task',+ title: goal.title?.trim() || task.name?.trim() || task.instruction,+ });+ } catch (error) {+ await this.taskModel.delete(task.id).catch(() => {});+ throw error;+ }+ return { ...task, goal: created };+ }++ return task;}/**@@ -388,6 +435,20 @@ export class TaskService {const task = await this.taskModel.updateStatus(resolved.id, status, extra);if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ // Canceling the carrier task cancels its goal: the loop has no executor+ // left, and a "running" goal over a canceled task would be a lie. The+ // user's positive sign-off (`achieved`) is never downgraded. Best-effort —+ // goal state must not block the task transition.+ if (status === 'canceled') {+ try {+ const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);+ const goal = await goalModel.findBySubject('task', task.id);+ if (goal && goal.status !== 'achieved') await goalModel.updateStatus(goal.id, 'canceled');+ } catch (err) {+ console.error('[TaskService.updateStatus] goal cancel mirror failed:', err);+ }+ }+// Stamp the schedule run-count window each time the user (re)starts a// scheduled task. The cron dispatcher itself flips a task running →// scheduled on every tick, so we exclude that natural cycle by only@@ -591,13 +652,19 @@ export class TaskService {// brief-type activities — the UI converges on Task Run. Briefs are therefore// not fetched/enriched here (see the omitted brief spread below). The brief// lifecycle, model and data are untouched; revert this to bring them back.- const [allDescendants, dependencies, directTopics, comments, workspace] = await Promise.all([- this.taskModel.findAllDescendants(task.id),- this.taskModel.getDependencies(task.id),- this.taskTopicModel.findWithHandoff(task.id, TASK_DETAIL_DIRECT_TOPIC_LIMIT).catch(() => []),- this.taskModel.getComments(task.id).catch(() => []),- this.taskModel.getTreePinnedDocuments(task.id).catch(() => emptyWorkspace),- ]);+ const [allDescendants, dependencies, directTopics, comments, workspace, goal] =+ await Promise.all([+ this.taskModel.findAllDescendants(task.id),+ this.taskModel.getDependencies(task.id),+ this.taskTopicModel+ .findWithHandoff(task.id, TASK_DETAIL_DIRECT_TOPIC_LIMIT)+ .catch(() => []),+ this.taskModel.getComments(task.id).catch(() => []),+ this.taskModel.getTreePinnedDocuments(task.id).catch(() => emptyWorkspace),+ new GoalModel(this.db, this.userId, this.workspaceId)+ .findBySubject('task', task.id)+ .catch(() => undefined),+ ]);const allDescendantIds = allDescendants.map((s) => s.id);const descendantTaskMap = new Map(allDescendants.map((s) => [s.id, s]));@@ -903,6 +970,7 @@ export class TaskService {editorData: task.editorData ?? undefined,error: task.error,files: taskFiles.length > 0 ? taskFiles : undefined,+ goal: goal ?? null,heartbeat:task.heartbeatInterval || task.heartbeatTimeout || task.lastHeartbeatAt? {diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.tsindex e6ae23b6b5f..ee93d958aee 100644--- a/apps/server/src/services/taskLifecycle/index.ts+++ b/apps/server/src/services/taskLifecycle/index.ts@@ -31,6 +31,7 @@ import { ChatErrorType, DEFAULT_BRIEF_ACTIONS } from '@lobechat/types';import debug from 'debug';import { BriefModel } from '@/database/models/brief';+import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { TaskTopicModel } from '@/database/models/taskTopic';import { TopicModel } from '@/database/models/topic';@@ -199,7 +200,12 @@ export class TaskLifecycleService {// that actually needs the user. The settle path owns those moments:// `driveTaskFromVerify` raises "delivery ready for sign-off" when the// loop succeeds and the budget-exhausted alert when it stops.- const isGoalLoopRound = !!currentTask && !!this.taskModel.getGoalConfig(currentTask);+ const isGoalLoopRound =+ !!currentTask &&+ !!(await new GoalModel(this.db, this.userId, this.workspaceId).findBySubject(+ 'task',+ currentTask.id,+ ));if (!isGoalLoopRound &&getBriefMode(currentTask) === 'auto' &&diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.tsindex af06e8a8469..c286b3428b1 100644--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts@@ -20,6 +20,13 @@ vi.mock('@/database/models/verifyRun', () => ({VerifyRunModel: vi.fn(() => ({ findByOperation: verifyFindByOperation })),}));+// Goal-loop rounds suppress the per-topic brief; onTopicComplete asks the+// goals table whether this task carries a goal. Default = plain task.+const goalFindBySubject = vi.fn().mockResolvedValue(undefined);+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(() => ({ findBySubject: goalFindBySubject })),+}));+// Error-brief copy is localized at the source via the server translator; mock it// with a tiny table so the error-branch tests can assert both the friendly-copy// mapping (a known error code → its human message) and the raw-message fallbackdiff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.tsindex fa4f6ba7f73..fefeee7f946 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts@@ -3,6 +3,7 @@ import type { TaskItem, TaskTopicHandoff, WorkspaceData } from '@lobechat/types'import { AcceptanceModel } from '@/database/models/acceptance';import type { BriefModel } from '@/database/models/brief';+import { GoalModel } from '@/database/models/goal';import type { TaskModel } from '@/database/models/task';import type { TaskTopicModel } from '@/database/models/taskTopic';import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';@@ -28,8 +29,8 @@ const resolveGoalLoopContext = async (task: TaskItem,deps: BuildTaskPromptDeps,): Promise<TaskRunPromptGoalLoop | undefined> => {- const { db, taskModel, userId, workspaceId } = deps;- const goal = taskModel.getGoalConfig(task);+ const { db, userId, workspaceId } = deps;+ const goal = await new GoalModel(db, userId, workspaceId).findBySubject('task', task.id);if (!goal || !task.totalTopics) return undefined;const budget = resolveGoalRoundBudget(goal);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.tsindex 6e769ea5f41..b4f83d4739e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts@@ -63,9 +63,10 @@ describe('createTaskRuntime', () => {});// `null` means "uncapped"; coercing an omitted budget into it would let a- // failing goal spawn rounds forever.- const [, config] = taskModel.updateTaskConfig.mock.calls[0];- expect(config.goal.maxIterations).toBeUndefined();+ // failing goal spawn rounds forever. The service resolves `undefined`+ // into the documented default at write time.+ const [createInput] = taskService.createTask.mock.calls[0];+ expect(createInput.goal.maxRounds).toBeUndefined();});it('creates, configures, and starts one verified task', async () => {@@ -115,13 +116,19 @@ describe('createTaskRuntime', () => {verifyCriteriaIds: ['criterion-1'],}),});- expect(taskModel.updateTaskConfig).toHaveBeenCalledWith('task-db-1', {- goal: { maxIterations: 3, maxTotalCost: 12, originTopicId: 'origin-topic' },- });- expect(taskCaller.run).toHaveBeenCalledWith({ id: 'task-db-1' });- expect(taskModel.updateTaskConfig.mock.invocationCallOrder[0]).toBeLessThan(- taskCaller.updateVerifyConfig.mock.invocationCallOrder[0],+ // The goal entity is bound at task creation, not merged into config later.+ expect(taskService.createTask).toHaveBeenCalledWith(+ expect.objectContaining({+ goal: {+ maxRounds: 3,+ maxTotalCost: 12,+ requirement: 'Ship homepage',+ title: 'Ship homepage',+ },+ }),);+ expect(taskModel.updateTaskConfig).not.toHaveBeenCalled();+ expect(taskCaller.run).toHaveBeenCalledWith({ id: 'task-db-1' });// The success branch is the only one carrying `state`; narrow to it so// this asserts the shape rather than the union.expect(result).toHaveProperty('state');diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.tsindex dd3573ed109..6eda94fbd7e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts@@ -117,6 +117,13 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {type CreateTaskArgs = {instruction: string;assigneeAgentId?: string;+ // Bind a goal entity to the created task (see TaskService.createTask).+ goal?: {+ maxRounds?: number | null;+ maxTotalCost?: number | null;+ requirement?: string | null;+ title?: string;+ };name: string;parentIdentifier?: string;priority?: number;@@ -162,6 +169,7 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),context: origin ? { origin } : undefined,createdByAgentId: agentId,+ goal: args.goal,instruction: args.instruction,name: args.name,parentTaskId,@@ -255,6 +263,14 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {const created = await createTaskImpl({assigneeAgentId: agentId,+ // The goals row is created together with the task, so the "is a goal"+ // marker can never race the verify-config write below.+ goal: {+ maxRounds: args.maxIterations,+ maxTotalCost: args.maxTotalCost ?? null,+ requirement: args.name,+ title: args.name,+ },instruction: args.instruction,name: args.name,});@@ -278,19 +294,6 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {);const maxIterations = Math.min(10, Math.max(2, args.maxIterations ?? 3));- // Both operations merge into tasks.config. Running them concurrently- // can lose either the goal marker or verify config to last-write-wins.- await taskModel().updateTaskConfig(created.taskId, {- goal: {- // `null` is the user's explicit "no cap"; `undefined` means they- // never chose, which must fall back to the documented default.- // Coercing the second into the first made an uncapped loop the- // default for every goal that omitted the field.- maxIterations: args.maxIterations,- maxTotalCost: args.maxTotalCost ?? null,- originTopicId: topicId ?? null,- },- });await taskCaller().updateVerifyConfig({id: created.taskId,verify: {diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.tsindex 3781183fffd..a2c5c1f1d8e 100644--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts@@ -6,8 +6,11 @@ import { AcceptanceService } from '../acceptanceService';const mocks = vi.hoisted(() => ({attachToAcceptance: vi.fn(),findById: vi.fn(),+ findReportByRun: vi.fn(),findRunById: vi.fn(),ensureForSubject: vi.fn(),+ goalFindBySubject: vi.fn(),+ goalUpdateStatus: vi.fn(),listByAcceptance: vi.fn(),setDecision: vi.fn(),taskResolve: vi.fn(),@@ -31,7 +34,15 @@ vi.mock('@/database/models/verifyRun', () => ({}));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/verifyReport', () => ({+ VerifyReportModel: vi.fn(() => ({ findByRun: mocks.findReportByRun })),+}));+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(() => ({+ findBySubject: mocks.goalFindBySubject,+ updateStatus: mocks.goalUpdateStatus,+ })),+}));vi.mock('@/database/models/task', () => ({TaskModel: vi.fn(() => ({ resolve: mocks.taskResolve })),}));@@ -147,3 +158,53 @@ describe('AcceptanceService decision gating', () => {expect(mocks.updateStatus).toHaveBeenCalledWith('acc-1', 'rejected');});});++describe('AcceptanceService goal-status mirroring', () => {+ const taskAcceptance = (status: string) => ({+ id: 'acc-1',+ status,+ subjectId: 'task-1',+ subjectType: 'task',+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mocks.findReportByRun.mockResolvedValue(null);+ mocks.goalFindBySubject.mockResolvedValue({ id: 'goal-1', status: 'running' });+ });++ it('does NOT flip a running goal to verifying when the round is merely planned', async () => {+ // Regression (caught by the E2E acceptance run): the verify plan is+ // instantiated and confirmed at RUN START, so the acceptance recompute goes+ // pending → planned while the round is still executing. Mirroring `planned`+ // to `verifying` showed 验证中 for the whole execution phase.+ mocks.findById.mockResolvedValue(taskAcceptance('pending'));+ mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'planned' }]);++ await expect(service().recomputeStatus('acc-1')).resolves.toBe('planned');+ expect(mocks.goalUpdateStatus).not.toHaveBeenCalled();+ });++ it('mirrors a genuinely verifying round onto the goal', async () => {+ mocks.findById.mockResolvedValue(taskAcceptance('planned'));+ mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'verifying' }]);++ await expect(service().recomputeStatus('acc-1')).resolves.toBe('verifying');+ expect(mocks.goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'verifying');+ });++ it('mirrors a delivered round as review, but never re-opens a terminal goal', async () => {+ mocks.findById.mockResolvedValue(taskAcceptance('verifying'));+ mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1, status: 'passed' }]);++ await expect(service().recomputeStatus('acc-1')).resolves.toBe('delivered');+ expect(mocks.goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'review');++ mocks.goalUpdateStatus.mockClear();+ mocks.goalFindBySubject.mockResolvedValue({ id: 'goal-1', status: 'achieved' });+ mocks.findById.mockResolvedValue(taskAcceptance('verifying'));++ await expect(service().recomputeStatus('acc-1')).resolves.toBe('delivered');+ expect(mocks.goalUpdateStatus).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.tsindex cda887f632c..e0c172b9380 100644--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts@@ -16,7 +16,6 @@ const {runSetMetadata,opFindById,taskFindById,- taskGetGoalConfig,taskUpdateStatus,briefCreate,serviceUpdateStatus,@@ -24,11 +23,15 @@ const {deliverMock,goalContinueMock,goalSyncMock,+ goalFindBySubject,+ goalUpdateStatus,} = vi.hoisted(() => ({briefCreate: vi.fn(),deliverMock: vi.fn(),goalContinueMock: vi.fn(),+ goalFindBySubject: vi.fn(),goalSyncMock: vi.fn(),+ goalUpdateStatus: vi.fn(),opFindById: vi.fn(),runFindByOperation: vi.fn(),runClaimTaskDrive: vi.fn().mockResolvedValue(true),@@ -36,7 +39,6 @@ const {serviceUpdateStatus: vi.fn(),statusRecompute: vi.fn(),taskFindById: vi.fn(),- taskGetGoalConfig: vi.fn(),taskUpdateStatus: vi.fn(),}));@@ -61,7 +63,7 @@ vi.mock('../goalLoop', () => ({}),maybeContinueGoalLoop: goalContinueMock,resolveGoalRoundBudget: (goal: any) =>- goal.maxIterations === null ? Number.POSITIVE_INFINITY : (goal.maxIterations ?? 3),+ goal.maxRounds === null ? Number.POSITIVE_INFINITY : goal.maxRounds,syncGoalToolState: goalSyncMock,}));@@ -82,10 +84,15 @@ vi.mock('@/database/models/agentOperation', () => ({vi.mock('@/database/models/task', () => ({TaskModel: vi.fn(() => ({findById: taskFindById,- getGoalConfig: taskGetGoalConfig,updateStatus: taskUpdateStatus,})),}));+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(() => ({+ findBySubject: goalFindBySubject,+ updateStatus: goalUpdateStatus,+ })),+}));vi.mock('@/database/models/brief', () => ({BriefModel: vi.fn(() => ({ create: briefCreate })),}));@@ -108,7 +115,6 @@ describe('driveTaskFromVerify', () => {runSetMetadata,opFindById,taskFindById,- taskGetGoalConfig,taskUpdateStatus,briefCreate,serviceUpdateStatus,@@ -116,6 +122,8 @@ describe('driveTaskFromVerify', () => {deliverMock,goalContinueMock,goalSyncMock,+ goalFindBySubject,+ goalUpdateStatus,].forEach((m) => m.mockReset());// The drive is claimed before any side effect; unclaimed means "someone// else is driving this run", which every test here is not.@@ -127,7 +135,7 @@ describe('driveTaskFromVerify', () => {identifier: 'T-1',status: 'running',});- taskGetGoalConfig.mockReturnValue(undefined);+ goalFindBySubject.mockResolvedValue(undefined);});afterEach(() => vi.restoreAllMocks());@@ -280,11 +288,11 @@ describe('driveTaskFromVerify', () => {status: 'running',totalTopics: 1,};- const goal = { maxIterations: 3, maxTotalCost: null, originTopicId: 'origin-t' };+ const goal = { id: 'goal-1', maxRounds: 3, maxTotalCost: null, status: 'running' };beforeEach(() => {taskFindById.mockResolvedValue(goalTask);- taskGetGoalConfig.mockReturnValue(goal);+ goalFindBySubject.mockResolvedValue(goal);});it('failed + budget left → spawns the next round silently (no brief, no pause, no callback)', async () => {@@ -334,6 +342,8 @@ describe('driveTaskFromVerify', () => {});const briefArg = briefCreate.mock.calls[0][0];expect(briefArg.summary).toContain('budget exhausted (exhausted-rounds)');+ // An exhausted budget parks the goal for the user, it does not fail it.+ expect(goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'paused');expect(goalSyncMock).toHaveBeenCalledWith(expect.objectContaining({state: expect.objectContaining({ pausedReason: 'exhausted-rounds', phase: 'paused' }),@@ -364,6 +374,9 @@ describe('driveTaskFromVerify', () => {'paused',expect.objectContaining({ error: expect.stringContaining('could not run') }),);+ // Infra gave up without evaluating the delivery → the goal is `failed`,+ // distinct from the user-actionable `paused` of an exhausted budget.+ expect(goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'failed');});it('passed → parks for sign-off instead of completing (the verifier only recommends)', async () => {@@ -383,6 +396,8 @@ describe('driveTaskFromVerify', () => {expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {error: 'ready for your sign-off',});+ // The goal's own lifecycle records the sign-off wait.+ expect(goalUpdateStatus).toHaveBeenCalledWith('goal-1', 'review');expect(goalSyncMock).toHaveBeenCalledWith(expect.objectContaining({ state: expect.objectContaining({ phase: 'review' }) }),);@@ -415,7 +430,7 @@ describe('driveTaskFromVerify', () => {});it('non-goal task still completes on a passing verify (contract unchanged)', async () => {- taskGetGoalConfig.mockReturnValue(undefined);+ goalFindBySubject.mockResolvedValue(undefined);runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'passed' });await driveTaskFromVerify(db, 'u1', 'op-1');diff --git a/apps/server/src/services/verify/__tests__/goalLoop.test.ts b/apps/server/src/services/verify/__tests__/goalLoop.test.tsindex 4e33d61ba0a..efb5b5e6af3 100644--- a/apps/server/src/services/verify/__tests__/goalLoop.test.ts+++ b/apps/server/src/services/verify/__tests__/goalLoop.test.ts@@ -1,17 +1,22 @@// @vitest-environment nodeimport { beforeEach, describe, expect, it, vi } from 'vitest';-import { DEFAULT_GOAL_MAX_ROUNDS, resolveGoalRoundBudget } from '../goalBudget';+import { resolveGoalRoundBudget } from '../goalBudget';import { maybeContinueGoalLoop, syncGoalToolState } from '../goalLoop';-const { runTaskMock, sumCostMock, findToolMessageIdMock, updateToolMessageMock } = vi.hoisted(- () => ({- findToolMessageIdMock: vi.fn(),- runTaskMock: vi.fn(),- sumCostMock: vi.fn(),- updateToolMessageMock: vi.fn(),- }),-);+const {+ runTaskMock,+ sumCostMock,+ findToolMessageIdMock,+ updateToolMessageMock,+ updateGoalStatusMock,+} = vi.hoisted(() => ({+ findToolMessageIdMock: vi.fn(),+ runTaskMock: vi.fn(),+ sumCostMock: vi.fn(),+ updateGoalStatusMock: vi.fn(),+ updateToolMessageMock: vi.fn(),+}));vi.mock('@/server/services/taskRunner', () => ({TaskRunnerService: vi.fn(() => ({ runTask: runTaskMock })),@@ -19,6 +24,9 @@ vi.mock('@/server/services/taskRunner', () => ({vi.mock('@/database/models/agentOperation', () => ({AgentOperationModel: vi.fn(() => ({ sumCostByTask: sumCostMock })),}));+vi.mock('@/database/models/goal', () => ({+ GoalModel: vi.fn(() => ({ updateStatus: updateGoalStatusMock })),+}));vi.mock('@/database/models/message', () => ({MessageModel: vi.fn(() => ({findToolMessageIdByToolCallId: findToolMessageIdMock,@@ -28,53 +36,54 @@ vi.mock('@/database/models/message', () => ({const db = {} as any;const baseTask = { id: 'task-1', identifier: 'T-1', totalTopics: 1 } as any;+const goalItem = (partial: Record<string, unknown>) =>+ ({ id: 'goal-1', maxRounds: null, maxTotalCost: null, ...partial }) as any;describe('resolveGoalRoundBudget', () => {- it('null → uncapped', () => {- expect(resolveGoalRoundBudget({ maxIterations: null })).toBe(Number.POSITIVE_INFINITY);- });- it('absent → default', () => {- expect(resolveGoalRoundBudget({})).toBe(DEFAULT_GOAL_MAX_ROUNDS);+ it('null → uncapped (write time already resolved the default)', () => {+ expect(resolveGoalRoundBudget({ maxRounds: null })).toBe(Number.POSITIVE_INFINITY);});it('numbers are floored at 2', () => {- expect(resolveGoalRoundBudget({ maxIterations: 1 })).toBe(2);- expect(resolveGoalRoundBudget({ maxIterations: 5 })).toBe(5);+ expect(resolveGoalRoundBudget({ maxRounds: 1 })).toBe(2);+ expect(resolveGoalRoundBudget({ maxRounds: 5 })).toBe(5);});});describe('maybeContinueGoalLoop', () => {beforeEach(() => {- [runTaskMock, sumCostMock].forEach((m) => m.mockReset());+ [runTaskMock, sumCostMock, updateGoalStatusMock].forEach((m) => m.mockReset());});it('spawns the next round with the goal trigger while budgets last', async () => {runTaskMock.mockResolvedValue({});const outcome = await maybeContinueGoalLoop({db,- goal: { maxIterations: 3 },+ goal: goalItem({ maxRounds: 3 }),task: baseTask,userId: 'u1',});expect(outcome).toBe('continued');expect(runTaskMock).toHaveBeenCalledWith({ taskId: 'task-1', trigger: 'goal' });+ expect(updateGoalStatusMock).toHaveBeenCalledWith('goal-1', 'running');});it('stops at the round budget', async () => {const outcome = await maybeContinueGoalLoop({db,- goal: { maxIterations: 3 },+ goal: goalItem({ maxRounds: 3 }),task: { ...baseTask, totalTopics: 3 },userId: 'u1',});expect(outcome).toBe('exhausted-rounds');expect(runTaskMock).not.toHaveBeenCalled();+ expect(updateGoalStatusMock).not.toHaveBeenCalled();});it('uncapped rounds (null) keep looping', async () => {runTaskMock.mockResolvedValue({});const outcome = await maybeContinueGoalLoop({db,- goal: { maxIterations: null },+ goal: goalItem({ maxRounds: null }),task: { ...baseTask, totalTopics: 42 },userId: 'u1',});@@ -85,7 +94,7 @@ describe('maybeContinueGoalLoop', () => {sumCostMock.mockResolvedValue(21.5);const outcome = await maybeContinueGoalLoop({db,- goal: { maxIterations: 5, maxTotalCost: 20 },+ goal: goalItem({ maxRounds: 5, maxTotalCost: 20 }),task: baseTask,userId: 'u1',});@@ -97,7 +106,7 @@ describe('maybeContinueGoalLoop', () => {runTaskMock.mockResolvedValue({});const outcome = await maybeContinueGoalLoop({db,- goal: { maxIterations: 5, maxTotalCost: null },+ goal: goalItem({ maxRounds: 5, maxTotalCost: null }),task: baseTask,userId: 'u1',});@@ -109,11 +118,12 @@ describe('maybeContinueGoalLoop', () => {runTaskMock.mockRejectedValue(new Error('CONFLICT'));const outcome = await maybeContinueGoalLoop({db,- goal: { maxIterations: 3 },+ goal: goalItem({ maxRounds: 3 }),task: baseTask,userId: 'u1',});expect(outcome).toBe('spawn-failed');+ expect(updateGoalStatusMock).not.toHaveBeenCalled();});});diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.tsindex 84ac49f4eb3..3551b4bd27a 100644--- a/apps/server/src/services/verify/acceptanceService.ts+++ b/apps/server/src/services/verify/acceptanceService.ts@@ -6,6 +6,7 @@ import type {AcceptanceReviewAnnotation,AcceptanceStatus,AcceptanceSubjectType,+ GoalStatus,ReviewProposalOutcome,VerifyAgentPlanConfig,VerifyCheckDecisionDetail,@@ -18,6 +19,7 @@ import debug from 'debug';import { AcceptanceModel } from '@/database/models/acceptance';import { AgentModel } from '@/database/models/agent';import { DocumentModel } from '@/database/models/document';+import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { TopicModel } from '@/database/models/topic';import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';@@ -534,11 +536,47 @@ export class AcceptanceService {const status = statusFromRound(current, Boolean(report));if (status !== acceptance.status) {await this.acceptanceModel.updateStatus(acceptanceId, status);+ await this.mirrorGoalStatus(acceptance.subjectType, acceptance.subjectId, status);log('acceptance %s → %s (from round %d)', acceptanceId, status, current.roundIndex);}return status;};+ /**+ * Keep a task-carried goal's live phase in lockstep with the acceptance+ * lifecycle. Only the in-flight phases are mirrored here — the decision+ * transitions (`achieved` / `paused` / `running` next round / `failed`) are+ * written by their owning flows (accept / reject / settle / goal loop).+ * Best-effort: goal state must never break acceptance recompute.+ */+ private mirrorGoalStatus = async (+ subjectType: string,+ subjectId: string,+ status: AcceptanceStatus,+ ): Promise<void> => {+ if (subjectType !== 'task') return;+ // `planned` is deliberately NOT mirrored: the plan being confirmed at run+ // start says nothing about verification running — the round is still+ // executing, and flipping the goal to `verifying` here would show 验证中+ // for the whole execution phase (caught by the E2E acceptance run).+ const mirrored: Partial<Record<AcceptanceStatus, GoalStatus>> = {+ delivered: 'review',+ repairing: 'verifying',+ verifying: 'verifying',+ };+ const next = mirrored[status];+ if (!next) return;++ try {+ const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);+ const goal = await goalModel.findBySubject('task', subjectId);+ if (!goal || goal.status === 'achieved' || goal.status === 'canceled') return;+ if (goal.status !== next) await goalModel.updateStatus(goal.id, next);+ } catch (error) {+ log('mirrorGoalStatus failed (non-fatal): %O', error);+ }+ };+/** Latest round of an aggregate — the row `stampDecision` would write to. */latestRound = async (acceptanceId: string) => {const runs = await this.runModel.listByAcceptance(acceptanceId);@@ -564,15 +602,17 @@ export class AcceptanceService {return (await this.acceptanceModel.findById(acceptanceId))!;};- /** Flip a goal task's origin card to its terminal "done" state. Best-effort. */+ /** Flip a goal (and its origin card) to the terminal "achieved" state. Best-effort. */private syncGoalStateOnAccept = async (subjectId: string): Promise<void> => {try {const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);const task = await taskModel.findById(subjectId);if (!task) return;- const goal = taskModel.getGoalConfig(task);+ const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);+ const goal = await goalModel.findBySubject('task', task.id);if (!goal) return;+ await goalModel.updateStatus(goal.id, 'achieved');await syncGoalToolState({db: this.db,state: { phase: 'done', roundsRun: task.totalTopics || 0 },@@ -620,7 +660,8 @@ export class AcceptanceService {const task = await taskModel.findById(subjectId);if (!task) return;- const goal = taskModel.getGoalConfig(task);+ const goalModel = new GoalModel(this.db, this.userId, this.workspaceId);+ const goal = await goalModel.findBySubject('task', task.id);if (!goal) return;const outcome = await maybeContinueGoalLoop({@@ -630,6 +671,11 @@ export class AcceptanceService {userId: this.userId,workspaceId: this.workspaceId,});+ // `continued` already flipped the goal to `running` inside the loop; a+ // budget-blocked or failed spawn leaves the rejected goal parked on the+ // user (raise the budget / retry), which is `paused` in the goal+ // vocabulary.+ if (outcome !== 'continued') await goalModel.updateStatus(goal.id, 'paused');log('reject on goal task %s → loop outcome: %s', task.identifier, outcome);} catch (error) {log('spawnGoalRoundOnReject failed (non-fatal): %O', error);diff --git a/apps/server/src/services/verify/goalBudget.ts b/apps/server/src/services/verify/goalBudget.tsindex 494c668fa47..9efb681b57a 100644--- a/apps/server/src/services/verify/goalBudget.ts+++ b/apps/server/src/services/verify/goalBudget.ts@@ -1,5 +1,5 @@import { DEFAULT_GOAL_MAX_ROUNDS } from '@lobechat/const/verify';-import type { TaskGoalConfig } from '@lobechat/types';+import type { GoalItem } from '@lobechat/types';/*** Pure goal-budget helpers, dependency-free on purpose: both the outer loop@@ -9,18 +9,17 @@ import type { TaskGoalConfig } from '@lobechat/types';*//**- * Applied when the user left the round budget untouched. `null` in the config- * means the user explicitly opted out of a cap — that maps to Infinity, not to- * this default.+ * Applied at goal creation when the user left the round budget untouched+ * (`goals.max_rounds` is resolved at write time; `null` in the row means the+ * user explicitly opted out of a cap).** Re-exported from `@lobechat/const/verify` so the create-goal UI and this loop* agree on one number; the const package is the single source of truth.*/export { DEFAULT_GOAL_MAX_ROUNDS };-/** Round budget: `null` = user opted out of a cap, absent = default. */-export const resolveGoalRoundBudget = (goal: TaskGoalConfig): number => {- if (goal.maxIterations === null) return Number.POSITIVE_INFINITY;- if (typeof goal.maxIterations === 'number') return Math.max(2, goal.maxIterations);- return DEFAULT_GOAL_MAX_ROUNDS;+/** Round budget: `null` = user opted out of a cap. */+export const resolveGoalRoundBudget = (goal: Pick<GoalItem, 'maxRounds'>): number => {+ if (typeof goal.maxRounds === 'number') return Math.max(2, goal.maxRounds);+ return Number.POSITIVE_INFINITY;};diff --git a/apps/server/src/services/verify/goalLoop.ts b/apps/server/src/services/verify/goalLoop.tsindex 8c5092161ad..c5c2094c41c 100644--- a/apps/server/src/services/verify/goalLoop.ts+++ b/apps/server/src/services/verify/goalLoop.ts@@ -1,7 +1,8 @@-import type { BriefAction, TaskContext, TaskGoalConfig, TaskItem } from '@lobechat/types';+import type { BriefAction, GoalItem, TaskContext, TaskItem } from '@lobechat/types';import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalModel } from '@/database/models/goal';import { MessageModel } from '@/database/models/message';import type { LobeChatDatabase } from '@/database/type';import { TaskRunnerService } from '@/server/services/taskRunner';@@ -25,7 +26,7 @@ export type GoalLoopOutcome = 'continued' | 'exhausted-cost' | 'exhausted-rounds*/export const maybeContinueGoalLoop = async (params: {db: LobeChatDatabase;- goal: TaskGoalConfig;+ goal: GoalItem;task: TaskItem;userId: string;workspaceId?: string;@@ -52,6 +53,10 @@ export const maybeContinueGoalLoop = async (params: {taskId: task.id,trigger: 'goal',});+ // The spawned round makes the goal `running` right away, instead of+ // waiting for the runner's async start notification to flip it — the+ // UI should never show a paused/review goal that is already looping.+ await new GoalModel(db, userId, workspaceId).updateStatus(goal.id, 'running');log('task %s → goal round %d spawned', task.identifier, roundsRun + 1);return 'continued';} catch (error) {@@ -66,7 +71,7 @@ export const maybeContinueGoalLoop = async (params: {export const goalExhaustedBriefCopy = (task: TaskItem,outcome: Extract<GoalLoopOutcome, 'exhausted-cost' | 'exhausted-rounds'>,- goal: TaskGoalConfig,+ goal: GoalItem,): { summary: string; title: string } =>outcome === 'exhausted-cost'? {diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.tsindex 0a3ecbc92fb..73d46d0a4d0 100644--- a/apps/server/src/services/verify/planInstantiation.ts+++ b/apps/server/src/services/verify/planInstantiation.ts@@ -1,5 +1,6 @@import debug from 'debug';+import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { VerifyRunModel } from '@/database/models/verifyRun';import type { LobeChatDatabase } from '@/database/type';@@ -35,6 +36,26 @@ export const instantiateVerifyPlanOnStart = async (): Promise<void> => {try {const taskModel = new TaskModel(db, userId, workspaceId);++ // A goal task entering a run round is `running` — the single transition+ // point shared by round 1, reject-spawned rounds and manual restarts.+ // Terminal decisions stay terminal: an accepted (`achieved`) or canceled+ // goal is never silently re-opened by a stray run.+ try {+ const goalModel = new GoalModel(db, userId, workspaceId);+ const goal = await goalModel.findBySubject('task', params.taskId);+ if (+ goal &&+ goal.status !== 'running' &&+ goal.status !== 'achieved' &&+ goal.status !== 'canceled'+ ) {+ await goalModel.updateStatus(goal.id, 'running');+ }+ } catch (error) {+ log('goal running transition failed for task %s (non-fatal): %O', params.taskId, error);+ }+const verifyConfig = await taskModel.resolveVerifyConfig(params.taskId);// Opt-in to verify, then pick the plan shape:diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.tsindex 47bedbb192c..f4bf16699f8 100644--- a/apps/server/src/services/verify/settle.ts+++ b/apps/server/src/services/verify/settle.ts@@ -3,6 +3,7 @@ import debug from 'debug';import { AgentOperationModel } from '@/database/models/agentOperation';import { BriefModel } from '@/database/models/brief';+import { GoalModel } from '@/database/models/goal';import { TaskModel } from '@/database/models/task';import { VerifyRunModel } from '@/database/models/verifyRun';import type { LobeChatDatabase } from '@/database/type';@@ -105,7 +106,8 @@ export const driveTaskFromVerify = async (const task = await taskModel.findById(taskOperation.taskId);if (!task || TERMINAL_TASK_STATUS.has(task.status)) return; // task already settled- const goal = taskModel.getGoalConfig(task);+ const goalModel = new GoalModel(db, userId, workspaceId);+ const goal = await goalModel.findBySubject('task', task.id);if (run.status === 'passed') {if (goal) {@@ -128,6 +130,7 @@ export const driveTaskFromVerify = async (await taskModel.updateStatus(taskOperation.taskId, 'paused', {error: review.summary,});+ await goalModel.updateStatus(goal.id, 'review');await new BriefModel(db, userId, workspaceId).create({actions: review.actions,agentId: task.assigneeAgentId || undefined,@@ -185,7 +188,7 @@ export const driveTaskFromVerify = async (db,state: {phase: 'running',- roundBudget: goal.maxIterations === null ? null : resolveGoalRoundBudget(goal),+ roundBudget: goal.maxRounds === null ? null : resolveGoalRoundBudget(goal),roundsRun: (task.totalTopics || 0) + 1,},task,@@ -227,6 +230,10 @@ export const driveTaskFromVerify = async (// briefs, so a brief-only explanation is invisible from the task page.await taskModel.updateStatus(taskOperation.taskId, 'paused', { error: pauseSummary });if (goal) {+ // The goal's own lifecycle: an errored run means verification never+ // evaluated the delivery — `failed` (infra gave up), while an exhausted+ // budget or spawn failure parks the goal for the user (`paused`).+ await goalModel.updateStatus(goal.id, isErrored ? 'failed' : 'paused');await syncGoalToolState({db,state: {diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex d8e9fbb97a6..aebca155f79 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -298,6 +298,7 @@"criterion.descriptionPlaceholder": "Add extra context for the checker (optional)","criterion.editTitle": "Edit acceptance criterion","criterion.instructionLabel": "Judge prompt",+ "criterion.instructionLinked": "The judging rule is kept in a linked document and cannot be edited here.","criterion.instructionPlaceholder": "Describe the exact pass conditions and required evidence","criterion.optional": "Optional","criterion.required": "Required",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex a0463cb4c6f..808ee7b3bbd 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -298,6 +298,7 @@"criterion.descriptionPlaceholder": "为检查方补充更多上下文(可选)","criterion.editTitle": "编辑验收标准","criterion.instructionLabel": "判定说明",+ "criterion.instructionLinked": "判定说明保存在关联文档中,此处不可编辑。","criterion.instructionPlaceholder": "描述明确的通过条件和所需证据","criterion.optional": "可选","criterion.required": "必选",diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.tsindex faac05247f7..5136a995343 100644--- a/packages/builtin-tool-task/src/client/executor/index.ts+++ b/packages/builtin-tool-task/src/client/executor/index.ts@@ -187,6 +187,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {params: {instruction: string;assigneeAgentId?: string;+ // Bind a goal entity to the created task (see TaskService.createTask).+ goal?: {+ maxRounds?: number | null;+ maxTotalCost?: number | null;+ requirement?: string | null;+ title?: string;+ };name: string;parentIdentifier?: string;priority?: number;@@ -202,6 +209,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {assigneeAgentId:params.assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),createdByAgentId: ctx?.agentId,+ goal: params.goal,instruction: params.instruction,name: params.name,parentTaskId: parentIdentifier,@@ -305,6 +313,14 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {const created = await this.#createTask({assigneeAgentId: ctx.agentId,+ // The goals row is created together with the task, so the "is a goal"+ // marker can never race the verify-config write below.+ goal: {+ maxRounds: params.maxIterations,+ maxTotalCost: params.maxTotalCost ?? null,+ requirement: params.name,+ title: params.name,+ },instruction: params.instruction,name: params.name,},@@ -328,19 +344,6 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {);const maxIterations = Math.min(10, Math.max(2, params.maxIterations ?? 3));- // Both APIs merge into tasks.config with a read-modify-write cycle. Keep- // them sequential so the verify write cannot overwrite the goal metadata.- await taskService.updateConfig(identifier, {- goal: {- // `null` is the user's explicit "no cap"; `undefined` means they- // never chose, which must fall back to the documented default.- // Coercing the second into the first made an uncapped loop the- // default for every goal that omitted the field.- maxIterations: params.maxIterations,- maxTotalCost: params.maxTotalCost ?? null,- originTopicId: ctx.topicId ?? null,- },- });await taskService.updateVerifyConfig({id: identifier,verify: {diff --git a/packages/const/src/goal.test.ts b/packages/const/src/goal.test.tsnew file mode 100644index 00000000000..ddca9bdc70c--- /dev/null+++ b/packages/const/src/goal.test.ts@@ -0,0 +1,19 @@+import type {+ GoalStatus as GoalStatusType,+ GoalSubjectType as GoalSubjectTypeType,+} from '@lobechat/types';+import { describe, expect, expectTypeOf, it } from 'vitest';++import { goalStatuses, goalSubjectTypes } from './goal';++describe('goal consts', () => {+ it('stays in sync with the @lobechat/types unions', () => {+ expectTypeOf<(typeof goalStatuses)[number]>().toEqualTypeOf<GoalStatusType>();+ expectTypeOf<(typeof goalSubjectTypes)[number]>().toEqualTypeOf<GoalSubjectTypeType>();+ });++ it('keeps terminal states last-ish sanity', () => {+ expect(goalStatuses).toContain('achieved');+ expect(goalSubjectTypes).toContain('task');+ });+});diff --git a/packages/database/src/models/__tests__/goal.test.ts b/packages/database/src/models/__tests__/goal.test.tsnew file mode 100644index 00000000000..48bac3b3d1c--- /dev/null+++ b/packages/database/src/models/__tests__/goal.test.ts@@ -0,0 +1,149 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { goals, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { GoalModel } from '../goal';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'goal-model-test-user-id';+const otherUserId = 'goal-model-test-user-2';+const goalModel = new GoalModel(serverDB, userId);++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+});++describe('GoalModel', () => {+ describe('create', () => {+ it('creates a goal with defaults', async () => {+ const result = await goalModel.create({+ subjectId: 'tsk_1',+ subjectType: 'task',+ title: 'Ship the goals table',+ });++ expect(result.id).toMatch(/^goal_/);+ expect(result).toMatchObject({+ status: 'planning',+ subjectId: 'tsk_1',+ subjectType: 'task',+ title: 'Ship the goals table',+ userId,+ });+ });++ it('persists budget and requirement', async () => {+ const result = await goalModel.create({+ maxRounds: 5,+ maxTotalCost: 12.5,+ requirement: 'All tests pass',+ subjectId: 'tsk_2',+ subjectType: 'task',+ title: 'Budgeted goal',+ });++ expect(result.maxRounds).toBe(5);+ expect(result.maxTotalCost).toBe(12.5);+ expect(result.requirement).toBe('All tests pass');+ });+ });++ describe('findBySubject', () => {+ it('finds the goal bound to a carrier', async () => {+ const created = await goalModel.create({+ subjectId: 'tsk_3',+ subjectType: 'task',+ title: 'Carrier goal',+ });++ const found = await goalModel.findBySubject('task', 'tsk_3');+ expect(found?.id).toBe(created.id);+ });++ it('does not cross user boundaries', async () => {+ const otherModel = new GoalModel(serverDB, otherUserId);+ await otherModel.create({ subjectId: 'tsk_4', subjectType: 'task', title: 'Not mine' });++ const found = await goalModel.findBySubject('task', 'tsk_4');+ expect(found).toBeUndefined();+ });+ });++ describe('listBySubjects', () => {+ it('returns goals for the asked carriers only', async () => {+ await goalModel.create({ subjectId: 'tsk_a', subjectType: 'task', title: 'A' });+ await goalModel.create({ subjectId: 'tsk_b', subjectType: 'task', title: 'B' });+ await goalModel.create({ subjectId: 'tsk_c', subjectType: 'task', title: 'C' });++ const rows = await goalModel.listBySubjects('task', ['tsk_a', 'tsk_c']);+ expect(rows.map((r) => r.subjectId).sort()).toEqual(['tsk_a', 'tsk_c']);+ });++ it('returns empty for an empty id list', async () => {+ expect(await goalModel.listBySubjects('task', [])).toEqual([]);+ });+ });++ describe('updateStatus', () => {+ it('stamps startedAt on first entry into running', async () => {+ const { id } = await goalModel.create({+ subjectId: 'tsk_5',+ subjectType: 'task',+ title: 'Lifecycle goal',+ });++ const running = await goalModel.updateStatus(id, 'running');+ expect(running?.status).toBe('running');+ expect(running?.startedAt).toBeInstanceOf(Date);++ // A later transition keeps the original startedAt.+ const verifying = await goalModel.updateStatus(id, 'verifying');+ expect(verifying?.startedAt).toEqual(running?.startedAt);+ });++ it('stamps completedAt on terminal states and clears it on re-open', async () => {+ const { id } = await goalModel.create({+ subjectId: 'tsk_6',+ subjectType: 'task',+ title: 'Terminal goal',+ });++ const achieved = await goalModel.updateStatus(id, 'achieved');+ expect(achieved?.completedAt).toBeInstanceOf(Date);++ const reopened = await goalModel.updateStatus(id, 'running');+ expect(reopened?.completedAt).toBeNull();+ });++ it('returns undefined for a goal outside the scope', async () => {+ const otherModel = new GoalModel(serverDB, otherUserId);+ const { id } = await otherModel.create({+ subjectId: 'tsk_7',+ subjectType: 'task',+ title: 'Not mine',+ });++ expect(await goalModel.updateStatus(id, 'running')).toBeUndefined();+ });+ });++ describe('deleteBySubject', () => {+ it('removes the goal bound to the carrier', async () => {+ await goalModel.create({ subjectId: 'tsk_8', subjectType: 'task', title: 'Doomed' });++ await goalModel.deleteBySubject('task', 'tsk_8');++ const rows = await serverDB.query.goals.findMany({ where: eq(goals.userId, userId) });+ expect(rows).toHaveLength(0);+ });+ });+});diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex d4cefcf4246..d080e75047f 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -8,6 +8,7 @@ import {agents,briefs,documents,+ goals,tasks,topics,users,@@ -16,6 +17,7 @@ import {import { taskTopics } from '../../schemas/task';import { works } from '../../schemas/work';import type { LobeChatDatabase } from '../../type';+import { GoalModel } from '../goal';import { ProjectModel } from '../project';import { TaskModel } from '../task';import { WorkModel } from '../work';@@ -565,11 +567,16 @@ describe('TaskModel', () => {expect(result[0].tasks).toHaveLength(1);});- it('should filter tasks by the goal marker', async () => {+ it('should filter tasks by their bound goal entity', async () => {const model = new TaskModel(serverDB, userId);- const goal = await model.create({ instruction: 'Persistent objective' });- await model.update(goal.id, { config: { goal: { maxIterations: 5 } } });+ const goalTask = await model.create({ instruction: 'Persistent objective' });+ const goalRow = await new GoalModel(serverDB, userId).create({+ maxRounds: 5,+ subjectId: goalTask.id,+ subjectType: 'task',+ title: 'Persistent objective',+ });await model.create({ instruction: 'Ordinary task' });const goals = await model.groupList({@@ -581,9 +588,13 @@ describe('TaskModel', () => {hasGoal: false,});- expect(goals[0].tasks.map((task) => task.id)).toEqual([goal.id]);+ expect(goals[0].tasks.map((task) => task.id)).toEqual([goalTask.id]);+ // The goal entity rides along on the returned task row.+ expect(goals[0].tasks[0].goal?.id).toBe(goalRow.id);+ expect(goals[0].tasks[0].goal?.maxRounds).toBe(5);expect(ordinary[0].tasks).toHaveLength(1);expect(ordinary[0].tasks[0].instruction).toBe('Ordinary task');+ expect(ordinary[0].tasks[0].goal).toBeNull();});it('should group only tasks from the requested project', async () => {@@ -1265,6 +1276,24 @@ describe('TaskModel', () => {expect(total1).toBe(0);expect(total2).toBe(1);});++ it('sweeps the goals bound to bulk-deleted tasks', async () => {+ // Regression (codex review): the FK-less goals rows survived clearAll,+ // orphaning every cleared goal — only single and subtree deletion swept.+ const model = new TaskModel(serverDB, userId);+ const goalModel = new GoalModel(serverDB, userId);+ const goalTask = await model.create({ instruction: 'Goal task' });+ await goalModel.create({ subjectId: goalTask.id, subjectType: 'task', title: 'Doomed' });+ const otherUsers = new GoalModel(serverDB, userId2);+ await otherUsers.create({ subjectId: 'task_foreign', subjectType: 'task', title: 'Keep' });++ await model.deleteAll();++ const mine = await serverDB.query.goals.findMany({ where: eq(goals.userId, userId) });+ const theirs = await serverDB.query.goals.findMany({ where: eq(goals.userId, userId2) });+ expect(mine).toHaveLength(0);+ expect(theirs).toHaveLength(1);+ });});describe('getDependenciesByTaskIds', () => {diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsnew file mode 100644index 00000000000..027a7ddb1e5--- /dev/null+++ b/packages/database/src/models/goal.ts@@ -0,0 +1,125 @@+import type { GoalStatus, GoalSubjectType } from '@lobechat/const/goal';+import { and, desc, eq, inArray } from 'drizzle-orm';++import type { GoalItem, NewGoal } from '../schemas/goal';+import { goals } from '../schemas/goal';+import type { LobeChatDatabase } from '../type';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';++/** States after which a goal's loop no longer advances. */+const TERMINAL_GOAL_STATUSES = new Set<GoalStatus>(['achieved', 'failed', 'canceled']);++/**+ * Owns the `goals` table: one row per goal — an independent target entity with+ * its own definition (title / requirement), budget and lifecycle state. The+ * execution carrier is a polymorphic (`subjectType`, `subjectId`) link (task /+ * topic / standalone); everything execution-specific (rounds run, cost spent,+ * acceptance checks) stays on the carrier and its tables and is derived at+ * read time, never denormalized here.+ */+export class GoalModel {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ }++ private ownership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, goals);++ create = async (params: Omit<NewGoal, 'userId' | 'workspaceId'>): Promise<GoalItem> => {+ const [row] = await this.db+ .insert(goals)+ .values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, params))+ .returning();+ return row;+ };++ findById = async (id: string): Promise<GoalItem | undefined> => {+ return this.db.query.goals.findFirst({ where: and(eq(goals.id, id), this.ownership()) });+ };++ /** The goal bound to a carrier, or undefined when the subject carries none. */+ findBySubject = async (+ subjectType: GoalSubjectType,+ subjectId: string,+ ): Promise<GoalItem | undefined> => {+ return this.db.query.goals.findFirst({+ where: and(+ eq(goals.subjectType, subjectType),+ eq(goals.subjectId, subjectId),+ this.ownership(),+ ),+ });+ };++ /**+ * The goals of many carriers in one read — for list surfaces (goal rail /+ * goals page) that already queried the carriers and need each row's goal+ * without a request per row.+ */+ listBySubjects = async (subjectType: GoalSubjectType, subjectIds: string[]) => {+ if (subjectIds.length === 0) return [];++ return this.db+ .select()+ .from(goals)+ .where(+ and(+ eq(goals.subjectType, subjectType),+ inArray(goals.subjectId, subjectIds),+ this.ownership(),+ ),+ );+ };++ /** Recent goals for the current scope, newest first. */+ query = async (limit = 50) => {+ return this.db.query.goals.findMany({+ limit,+ orderBy: [desc(goals.createdAt)],+ where: this.ownership(),+ });+ };++ update = async (id: string, value: Partial<Omit<GoalItem, 'id' | 'userId'>>) => {+ const [row] = await this.db+ .update(goals)+ .set({ ...value, updatedAt: new Date() })+ .where(and(eq(goals.id, id), this.ownership()))+ .returning();+ return row as GoalItem | undefined;+ };++ /**+ * Advance the lifecycle state, stamping the boundary timestamps as a side+ * effect: first entry into `running` records `startedAt`, any terminal state+ * records `completedAt` (and re-opening a terminal goal clears it).+ */+ updateStatus = async (id: string, status: GoalStatus) => {+ const existing = await this.findById(id);+ if (!existing) return undefined;++ return this.update(id, {+ completedAt: TERMINAL_GOAL_STATUSES.has(status) ? (existing.completedAt ?? new Date()) : null,+ startedAt: existing.startedAt ?? (status === 'running' ? new Date() : null),+ status,+ });+ };++ delete = async (id: string) => {+ return this.db.delete(goals).where(and(eq(goals.id, id), this.ownership()));+ };++ deleteBySubject = async (subjectType: GoalSubjectType, subjectId: string) => {+ return this.db+ .delete(goals)+ .where(+ and(eq(goals.subjectType, subjectType), eq(goals.subjectId, subjectId), this.ownership()),+ );+ };+}diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex 74c450a55bc..4e740b6154f 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -4,6 +4,7 @@ import { and, asc, desc, eq, inArray, isNull, max, sql } from 'drizzle-orm';import { agents } from '../schemas/agent';import { knowledgeBases } from '../schemas/file';+import { goals } from '../schemas/goal';import {projectAgents,projectCompletionReviews,@@ -322,7 +323,7 @@ export class ProjectModel {async listTasks(projectId: string) {if (!(await this.findById(projectId))) return null;- return this.db+ const rows = await this.db.select().from(tasks).where(@@ -339,6 +340,26 @@ export class ProjectModel {),).orderBy(asc(tasks.sortOrder), asc(tasks.seq));++ // Attach the goal entity carried by each task so project surfaces can tell+ // goal roots apart from plain tasks without re-querying per row.+ const goalRows =+ rows.length === 0+ ? []+ : await this.db+ .select()+ .from(goals)+ .where(+ and(+ eq(goals.subjectType, 'task'),+ inArray(+ goals.subjectId,+ rows.map(({ id }) => id),+ ),+ ),+ );+ const goalByTaskId = new Map(goalRows.map((row) => [row.subjectId!, row]));+ return rows.map((row) => ({ ...row, goal: goalByTaskId.get(row.id) ?? null }));}async getEnabledKnowledgeBaseIdsForTask(taskId: string) {diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex e51670c4be3..fe406f66740 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -1,7 +1,6 @@import type {CheckpointConfig,NewTask,- TaskGoalConfig,TaskItem,TaskVerifyConfig,WorkspaceData,@@ -28,12 +27,13 @@ import type { AnyPgColumn } from 'drizzle-orm/pg-core';import { merge } from '@/utils/merge';import { documents } from '../schemas/file';+import { goals } from '../schemas/goal';import type { NewTaskComment, TaskCommentItem } from '../schemas/task';import { taskComments, taskDependencies, taskDocuments, tasks, taskTopics } from '../schemas/task';import { topics } from '../schemas/topic';import { acceptances } from '../schemas/verify';import { works } from '../schemas/work';-import type { LobeChatDatabase } from '../type';+import type { LobeChatDatabase, Transaction } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';/**@@ -85,6 +85,16 @@ const RUNNABLE_AUTOMATION = and(),)!;+/**+ * A goal task is one carrying a `goals` row as its execution subject. Ownership+ * is not re-checked inside the EXISTS — the outer query already scopes `tasks`,+ * and a goal always belongs to its carrier's owner.+ */+const HAS_GOAL = sql`EXISTS (+ SELECT 1 FROM ${goals}+ WHERE ${goals.subjectType} = 'task' AND ${goals.subjectId} = ${tasks.id}+)`;+export class TaskModel {private readonly userId: string;private readonly db: LobeChatDatabase;@@ -285,12 +295,39 @@ export class TaskModel {* to render as "resource deleted" from its version snapshot. See.*/async delete(id: string): Promise<boolean> {- const deleted = await this.db- .delete(tasks)- .where(and(eq(tasks.id, id), this.ownership()))- .returning({ id: tasks.id });+ // The goal carried by this task has no FK on the polymorphic subject link,+ // so its row must be swept explicitly — in the same transaction, or a+ // failure between the two statements would orphan it.+ return this.db.transaction(async (tx) => {+ const deleted = await tx+ .delete(tasks)+ .where(and(eq(tasks.id, id), this.ownership()))+ .returning({ id: tasks.id });- return deleted.length > 0;+ if (deleted.length > 0) await this.deleteGoalsOfTasks([id], tx);++ return deleted.length > 0;+ });+ }++ /** Sweep the goals bound to the given (already deleted) tasks. */+ private async deleteGoalsOfTasks(+ taskIds: string[],+ tx: LobeChatDatabase | Transaction = this.db,+ ) {+ if (taskIds.length === 0) return;+ await tx+ .delete(goals)+ .where(+ and(+ eq(goals.subjectType, 'task'),+ inArray(goals.subjectId, taskIds),+ buildWorkspaceWhere(+ { userId: this.userId, workspaceId: this.workspaceId },+ { userId: goals.userId, workspaceId: goals.workspaceId },+ ),+ ),+ );}/**@@ -457,9 +494,17 @@ export class TaskModel {const where = options?.restrictToCreator? and(this.ownership(), eq(tasks.createdByUserId, this.userId)): this.ownership();- const result = await this.db.delete(tasks).where(where).returning();- return result.length;+ // One transaction so the FK-less goals rows can never outlive their+ // swept carriers (see deleteGoalsOfTasks).+ return this.db.transaction(async (tx) => {+ const result = await tx.delete(tasks).where(where).returning({ id: tasks.id });+ await this.deleteGoalsOfTasks(+ result.map(({ id }) => id),+ tx,+ );+ return result.length;+ });}/** Delete a task and every descendant in one transaction. */@@ -480,6 +525,7 @@ export class TaskModel {),),);+ await this.deleteGoalsOfTasks(taskIds, tx);const result = await tx.delete(tasks).where(and(inArray(tasks.id, taskIds), this.ownership()))@@ -500,7 +546,7 @@ export class TaskModel {statuses: string[];}>;parentTaskId?: string | null;- /** Only return tasks carrying the goal-controller marker in `config.goal`. */+ /** Only return tasks carrying a bound goal entity (`goals` row). */hasGoal?: boolean;projectId?: string;/** Same semantics as `list({ visibility })` — UI narrowing on top of the@@ -520,8 +566,8 @@ export class TaskModel {const baseConditions = [this.ownership()];if (assigneeAgentId) baseConditions.push(eq(tasks.assigneeAgentId, assigneeAgentId));- if (hasGoal === true) baseConditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);- if (hasGoal === false) baseConditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);+ if (hasGoal === true) baseConditions.push(HAS_GOAL);+ if (hasGoal === false) baseConditions.push(sql`NOT ${HAS_GOAL}`);if (projectId) baseConditions.push(eq(tasks.projectId, projectId));if (visibility) baseConditions.push(eq(tasks.visibility, visibility));if (parentTaskId === null) {@@ -616,16 +662,31 @@ export class TaskModel {]),);+ const goalByTaskId = await this.goalsByTaskIds(taskIds);+return results.map((group) => ({...group,tasks: group.tasks.map((task) => ({...task,+ goal: goalByTaskId.get(task.id) ?? null,totalRunCost: runStatsByTaskId.get(task.id)?.totalRunCost ?? 0,totalRunDuration: runStatsByTaskId.get(task.id)?.totalRunDuration ?? 0,})),}));}+ /** The goal entities carried by the given tasks, keyed by task id. */+ private async goalsByTaskIds(taskIds: string[]) {+ if (taskIds.length === 0) return new Map<string, typeof goals.$inferSelect>();++ const rows = await this.db+ .select()+ .from(goals)+ .where(and(eq(goals.subjectType, 'task'), inArray(goals.subjectId, taskIds)));++ return new Map(rows.map((row) => [row.subjectId!, row]));+ }+async list(options?: {assigneeAgentId?: string;/**@@ -679,8 +740,8 @@ export class TaskModel {// still NULL — which WHERE drops. That would make `automated: false` return// nothing at all for exactly the rows it is meant to return.if (automated === false) conditions.push(sql`${RUNNABLE_AUTOMATION} IS NOT TRUE`);- if (hasGoal === true) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') <> ''`);- if (hasGoal === false) conditions.push(sql`COALESCE(${tasks.config} ->> 'goal', '') = ''`);+ if (hasGoal === true) conditions.push(HAS_GOAL);+ if (hasGoal === false) conditions.push(sql`NOT ${HAS_GOAL}`);if (projectId) conditions.push(eq(tasks.projectId, projectId));if (visibility) conditions.push(eq(tasks.visibility, visibility));@@ -898,19 +959,6 @@ export class TaskModel {return this.updateTaskConfig(id, { review });}- // ========== Goal Config ==========-- /**- * Read this task's goal-loop config from `config.goal`. Presence marks a- * goal-driven task (created via the `createGoal` builtin tool) and enables- * the outer verify-driven round loop. No inheritance — a goal belongs to the- * exact task it was created on.- */- getGoalConfig(task: TaskItem): TaskGoalConfig | undefined {- const config = task.config as Record<string, any> | undefined;- return config?.goal ? (config.goal as TaskGoalConfig) : undefined;- }-// ========== Verify Config ==========/**diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex 886f9456810..fc9fe9f01c9 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -338,6 +338,8 @@ export default {'criterion.descriptionPlaceholder': 'Add extra context for the checker (optional)','criterion.editTitle': 'Edit acceptance criterion','criterion.instructionLabel': 'Judge prompt',+ 'criterion.instructionLinked':+ 'The judging rule is kept in a linked document and cannot be edited here.','criterion.instructionPlaceholder': 'Describe the exact pass conditions and required evidence','criterion.optional': 'Optional','criterion.required': 'Required',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsnew file mode 100644index 00000000000..871a3f6f3b6--- /dev/null+++ b/packages/types/src/goal.ts@@ -0,0 +1,62 @@+// ============================================+// Goal — independent target entity (`goals` table)+// ============================================++/**+ * Goal lifecycle states. Unlike `tasks`, whose status is about execution, a+ * goal's status is about the whole acceptance loop — including human review+ * (`review`) and the terminal `achieved` outcome.+ *+ * Kept in sync with `goalStatuses` in `@lobechat/const/goal` (type-tested+ * there), mirroring the AcceptanceStatus convention.+ */+export type GoalStatus =+ 'planning' | 'running' | 'verifying' | 'review' | 'paused' | 'achieved' | 'failed' | 'canceled';++/**+ * The execution carrier a goal is optionally bound to:+ * - `task` — the `/goal` flow: the goal runs inside a dedicated task.+ * - `topic` — a goal declared directly in a conversation.+ * - `standalone` — a pure goal declaration with no carrier attached.+ */+export type GoalSubjectType = 'task' | 'topic' | 'standalone';++/**+ * The goal entity as exposed to clients — a mirror of the `goals` table row.+ * Everything execution-specific (rounds run, cost spent, acceptance checks)+ * stays on the carrier and is derived at read time, never denormalized here.+ */+export interface GoalItem {+ agentId: string | null;+ completedAt: Date | null;+ createdAt: Date;+ id: string;+ /** Round budget; null = uncapped. */+ maxRounds: number | null;+ /** Total USD budget across all rounds; null = uncapped. */+ maxTotalCost: number | null;+ projectId: string | null;+ /** "What counts as done" — the acceptance requirement source. */+ requirement: string | null;+ startedAt: Date | null;+ status: GoalStatus;+ subjectId: string | null;+ subjectType: GoalSubjectType | null;+ title: string;+ updatedAt: Date;+ userId: string;+ workspaceId: string | null;+}++/**+ * Goal creation payload accepted by `TaskService.createTask` / the `task.create`+ * procedure: binds a new goals row to the created task in the same flow.+ * `maxRounds: null` is the user's explicit "no cap"; `undefined` means they+ * never chose, and the service falls back to the documented default.+ */+export interface CreateTaskGoalInput {+ maxRounds?: number | null;+ maxTotalCost?: number | null;+ requirement?: string | null;+ title?: string;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 5196a58f233..185bf886898 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -24,6 +24,7 @@ export * from './fetch';export * from './files';export * from './followUpAction';export * from './generation';+export * from './goal';export * from './heteroSessionImport';export * from './home';export * from './hotkey';diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex 350d99595d9..b5ee4d62fc0 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -1,4 +1,5 @@import type { BriefArtifacts } from '../brief';+import type { GoalItem } from '../goal';import type { ChatFileItem } from '../message/ui/chat';// ── Task type aliases ──@@ -53,21 +54,6 @@ export interface CheckpointConfig {* config when present, otherwise the nearest ancestor's config in full (never a* field-level merge). Resolved at runtime via `TaskModel.resolveVerifyConfig`.*/-/**- * Goal-driven loop config, persisted under `tasks.config.goal`. Written by the- * `createGoal` builtin tool; its presence marks the task as a goal task and- * enables the outer verify-driven round loop (a failed verify run spawns a new- * task topic instead of pausing, until a budget below runs out).- */-export interface TaskGoalConfig {- /** Max execution rounds (task topics). Null = uncapped by the user. */- maxIterations?: number | null;- /** Total USD budget across all rounds and their verify runs. Null = uncapped. */- maxTotalCost?: number | null;- /** Conversation topic that spawned the goal — terminal callbacks post back here. */- originTopicId?: string | null;-}-export interface TaskVerifyConfig {/** Whether the verify gate runs on topic completion. */enabled?: boolean;@@ -254,6 +240,12 @@ export interface TaskItem {description: string | null;editorData: unknown;error: string | null;+ /**+ * The goal entity bound to this task (`goals.subjectType='task'`), attached+ * by list/detail reads. Presence marks a goal-driven task; the goal owns its+ * budget, requirement and lifecycle status.+ */+ goal?: GoalItem | null;heartbeatInterval: number | null;heartbeatTimeout: number | null;id: string;@@ -486,6 +478,8 @@ export interface TaskDetailData {error?: string | null;/** Files attached to the task instruction (persistent context for every run). */files?: ChatFileItem[];+ /** The goal entity carried by this task (`goals` row); null when not a goal task. */+ goal?: GoalItem | null;// heartbeat.interval: periodic execution interval | heartbeat.timeout+lastAt: watchdog monitoring (detects stuck tasks)heartbeat?: {interval?: number | null;diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxindex 0e99c20d7ae..ef3f7b7fc5a 100644--- a/src/features/AgentGoals/AgentGoalsPage.tsx+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -96,11 +96,11 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {return goals.filter((goal) => {const acceptance = acceptanceBySubjectMap[`task:${goal.id}`];const bundle = acceptance ? acceptanceBundleMap[acceptance.id] : undefined;- const config = goal.config as { goal?: { maxIterations?: number | null } } | null;const presentation = getGoalPresentation({acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- maxRounds: config?.goal?.maxIterations,+ goalStatus: goal.goal?.status,+ maxRounds: goal.goal?.maxRounds,rounds: goal.totalTopics ?? 0,taskStatus: goal.status,});diff --git a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsxindex 585a62dd50d..47e9d1e8476 100644--- a/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx+++ b/src/features/AgentGoals/CreateGoalModal/CreateGoalContent.tsx@@ -385,16 +385,18 @@ const CreateGoalContent = memo<CreateGoalContentProps>((props) => {let verifyCriteriaIds: string[] = [];try {verifyCriteriaIds = await verifyService.createCriteria(reviewedCriteria);+ const { config, goal } = buildGoalTaskConfig({+ costBudget: plan.maxTotalCost,+ instruction,+ requirement,+ roundBudget: plan.maxIterations,+ verifyCriteriaIds,+ });const result = await createTask({assigneeAgentId: agentId,- config: buildGoalTaskConfig({- costBudget: plan.maxTotalCost,- instruction,- requirement,- roundBudget: plan.maxIterations,- verifyCriteriaIds,- }),+ config,editorData,+ goal,instruction,name: plan.name.trim() || undefined,projectId,diff --git a/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts b/src/features/AgentGoals/CreateGoalModal/goalConfig.test.tsindex ce015778ec4..ead9396ef49 100644--- a/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalConfig.test.ts@@ -22,34 +22,34 @@ describe('buildGoalTaskConfig', () => {// Regression: the create-goal path used to reuse the task modal and write the// same number into both caps, so a 10-round goal also bought 10 auto-repair// re-runs per round (up to 100 agent runs).- const config = buildGoalTaskConfig({ instruction: 'ship it', roundBudget: 10 });+ const payload = buildGoalTaskConfig({ instruction: 'ship it', roundBudget: 10 });- expect(config.goal.maxIterations).toBe(10);- expect(config.verify.maxIterations).toBe(DEFAULT_MAX_REPAIR_ROUNDS);+ expect(payload.goal.maxRounds).toBe(10);+ expect(payload.config.verify.maxIterations).toBe(DEFAULT_MAX_REPAIR_ROUNDS);});it('falls back to the documented round default when the budget is untouched', () => {- expect(buildGoalTaskConfig({ instruction: 'ship it' }).goal.maxIterations).toBe(+ expect(buildGoalTaskConfig({ instruction: 'ship it' }).goal.maxRounds).toBe(DEFAULT_GOAL_MAX_ROUNDS,);});it('preserves an explicit opt-out of the round cap', () => {expect(- buildGoalTaskConfig({ instruction: 'ship it', roundBudget: null }).goal.maxIterations,+ buildGoalTaskConfig({ instruction: 'ship it', roundBudget: null }).goal.maxRounds,).toBeNull();});it('clamps a round budget to the supported range', () => {- expect(buildGoalTaskConfig({ instruction: 'x', roundBudget: 1 }).goal.maxIterations).toBe(2);- expect(buildGoalTaskConfig({ instruction: 'x', roundBudget: 99 }).goal.maxIterations).toBe(10);+ expect(buildGoalTaskConfig({ instruction: 'x', roundBudget: 1 }).goal.maxRounds).toBe(2);+ expect(buildGoalTaskConfig({ instruction: 'x', roundBudget: 99 }).goal.maxRounds).toBe(10);});it('writes a positive cost budget and leaves it independent of the round budget', () => {- const config = buildGoalTaskConfig({ instruction: 'x', roundBudget: 5, costBudget: 2.5 });+ const payload = buildGoalTaskConfig({ instruction: 'x', roundBudget: 5, costBudget: 2.5 });- expect(config.goal.maxTotalCost).toBe(2.5);- expect(config.goal.maxIterations).toBe(5);+ expect(payload.goal.maxTotalCost).toBe(2.5);+ expect(payload.goal.maxRounds).toBe(5);});it('maps a blank or non-positive cost budget to uncapped (null)', () => {@@ -63,32 +63,34 @@ describe('buildGoalTaskConfig', () => {});it('uses the acceptance requirement when given', () => {- const config = buildGoalTaskConfig({+ const payload = buildGoalTaskConfig({instruction: 'clear the P0 backlog',requirement: 'every P0 has a linked PR with green CI',});- expect(config.verify.requirement).toBe('every P0 has a linked PR with green CI');- expect(config.verify.enabled).toBe(true);+ expect(payload.config.verify.requirement).toBe('every P0 has a linked PR with green CI');+ expect(payload.goal.requirement).toBe('every P0 has a linked PR with green CI');+ expect(payload.config.verify.enabled).toBe(true);});it('associates user-reviewed acceptance criteria with the goal', () => {- const config = buildGoalTaskConfig({+ const payload = buildGoalTaskConfig({instruction: 'clear the P0 backlog',verifyCriteriaIds: ['criterion-1', 'criterion-2'],});- expect(config.verify.verifyCriteriaIds).toEqual(['criterion-1', 'criterion-2']);+ expect(payload.config.verify.verifyCriteriaIds).toEqual(['criterion-1', 'criterion-2']);});it('falls back to the instruction so the goal stays judgeable', () => {// An empty requirement would leave `planInstantiation` with no source for the// holistic check, i.e. a goal that can never be accepted.- const config = buildGoalTaskConfig({+ const payload = buildGoalTaskConfig({instruction: 'clear the P0 backlog',requirement: ' ',});- expect(config.verify.requirement).toBe('clear the P0 backlog');+ expect(payload.config.verify.requirement).toBe('clear the P0 backlog');+ expect(payload.goal.requirement).toBe('clear the P0 backlog');});});diff --git a/src/features/AgentGoals/CreateGoalModal/goalConfig.ts b/src/features/AgentGoals/CreateGoalModal/goalConfig.tsindex 3d02d25bf1a..b599cc46d1f 100644--- a/src/features/AgentGoals/CreateGoalModal/goalConfig.ts+++ b/src/features/AgentGoals/CreateGoalModal/goalConfig.ts@@ -3,16 +3,16 @@ import {DEFAULT_MAX_REPAIR_ROUNDS,GOAL_MAX_ROUNDS_RANGE,} from '@lobechat/const/verify';-import type { TaskGoalConfig, TaskVerifyConfig } from '@lobechat/types';+import type { CreateTaskGoalInput, TaskVerifyConfig } from '@lobechat/types';/**- * A type alias rather than an interface on purpose: `createTask` takes- * `config?: Record<string, unknown>`, and only aliases get the implicit index- * signature that makes them assignable to it.+ * The goal-creation payload split along the storage boundary: `goal` becomes a+ * `goals` row bound to the created task, `config` stays a `tasks.config` merge+ * (`Record<string, unknown>`-shaped for `createTask`).*/-export type GoalTaskConfig = {- goal: TaskGoalConfig;- verify: TaskVerifyConfig;+export type GoalTaskPayload = {+ config: { verify: TaskVerifyConfig } & Record<string, unknown>;+ goal: CreateTaskGoalInput;};export interface BuildGoalTaskConfigParams {@@ -41,17 +41,18 @@ export const deriveInitialGoalCriterionTitle = (): string => requirement?.trim() || instruction.trim();/**- * Build the `tasks.config` payload that marks a task as a goal root.+ * Build the goal-task creation payload: the goal entity (budget + requirement,+ * persisted as a `goals` row) and the verify gate config (`tasks.config.verify`).*- * The two `maxIterations` under this config look alike and mean different- * things, which is exactly how they got conflated before this existed: the- * create-goal modal reused the task modal and wrote the *same* number into both,- * so a goal created with a 10-round budget also bought 10 auto-repair re-runs- * inside every round — up to 100 agent runs for one goal.+ * The two round-ish numbers look alike and mean different things, which is+ * exactly how they got conflated before this existed: the create-goal modal+ * reused the task modal and wrote the *same* number into both, so a goal+ * created with a 10-round budget also bought 10 auto-repair re-runs inside+ * every round — up to 100 agent runs for one goal.*- * - `goal.maxIterations` — outer loop, rounds. User-facing ("轮次预算").- * - `goal.maxTotalCost` — outer loop, total USD across all rounds. User-facing ("成本预算").- * - `verify.maxIterations` — inner loop, repair re-runs within one round.+ * - `goal.maxRounds` — outer loop, rounds. User-facing ("轮次预算").+ * - `goal.maxTotalCost` — outer loop, total USD across all rounds. User-facing ("成本预算").+ * - `verify.maxIterations` — inner loop, repair re-runs within one round.* Not user-facing; pinned to the platform default.*/export const buildGoalTaskConfig = ({@@ -60,14 +61,24 @@ export const buildGoalTaskConfig = ({requirement,roundBudget,verifyCriteriaIds,-}: BuildGoalTaskConfigParams): GoalTaskConfig => {+}: BuildGoalTaskConfigParams): GoalTaskPayload => {const acceptance = requirement?.trim() || instruction.trim();return {+ config: {+ verify: {+ enabled: true,+ maxIterations: DEFAULT_MAX_REPAIR_ROUNDS,+ // Drives criteria generation on the first run (`planInstantiation`'s+ // holistic fallback), so an empty one would leave the goal unjudgeable.+ requirement: acceptance,+ verifyCriteriaIds,+ },+ },goal: {// `null` is the user's explicit "no cap" and must survive; `undefined`// means they never chose, which falls back to the documented default.- maxIterations:+ maxRounds:roundBudget === null? null: typeof roundBudget === 'number'@@ -76,14 +87,7 @@ export const buildGoalTaskConfig = ({// No cap unless the user set a positive number; the loop reads `null` as// uncapped, so an empty / non-positive input maps back to `null`.maxTotalCost: typeof costBudget === 'number' && costBudget > 0 ? costBudget : null,- },- verify: {- enabled: true,- maxIterations: DEFAULT_MAX_REPAIR_ROUNDS,- // Drives criteria generation on the first run (`planInstantiation`'s- // holistic fallback), so an empty one would leave the goal unjudgeable.requirement: acceptance,- verifyCriteriaIds,},};};diff --git a/src/features/AgentGoals/GoalCardItem.tsx b/src/features/AgentGoals/GoalCardItem.tsxindex db668d81fe0..b6f49532b6a 100644--- a/src/features/AgentGoals/GoalCardItem.tsx+++ b/src/features/AgentGoals/GoalCardItem.tsx@@ -1,6 +1,5 @@'use client';-import type { TaskStatus } from '@lobechat/types';import { ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { ArrowRightIcon, RefreshCwIcon } from 'lucide-react';@@ -8,14 +7,14 @@ import type { KeyboardEvent } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { GoalAcceptance } from './GoalAcceptance';import { getGoalPresentation } from './goalPresentation';import { GoalProgress } from './GoalProgress';-import { getGoalDescription, goalStatusToTaskStatus, shouldShowGoal } from './goalViewModel';+import GoalStatusGlyph from './GoalStatusGlyph';+import { getGoalDescription, shouldShowGoal } from './goalViewModel';import type { GoalItemProps } from './types';const styles = createStaticStyles(({ css }) => ({@@ -39,7 +38,7 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {const navigate = useWorkspaceAwareNavigate();const { aid } = useActiveRouteParams<{ aid?: string }>();const { hideAchieved = false, projectId, task } = props;- const config = task.config as { goal?: { maxIterations?: number | null } } | null;+ const goal = task.goal;const title = task.name?.trim() || task.instruction.trim() || task.identifier;const description = getGoalDescription(task);const handleClick = () => {@@ -58,15 +57,13 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {const presentation = getGoalPresentation({acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- maxRounds: config?.goal?.maxIterations,+ goalStatus: goal?.status,+ maxRounds: goal?.maxRounds,rounds: task.totalTopics ?? 0,taskStatus: task.status,});if (!isLoading && !shouldShowGoal(presentation.statusKey, hideAchieved ? 'active' : 'all'))return null;- const visual =- TASK_STATUS_VISUALS[goalStatusToTaskStatus(presentation.statusKey) as TaskStatus] ??- TASK_STATUS_VISUALS.backlog;return (<Block@@ -89,12 +86,7 @@ export const GoalCardItem = memo<GoalItemProps>((props) => {><Flexbox gap={4} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={7}>- <Icon- color={visual.color}- icon={visual.icon}- size={13}- style={{ flexShrink: 0 }}- />+ <GoalStatusGlyph size={13} statusKey={presentation.statusKey} /><Text ellipsis fontSize={15} weight={600}>{title}</Text>diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 2720f173fb5..caaefc30ff4 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -35,13 +35,13 @@ import { useVerifyStore, verifySelectors } from '@/store/verify';import GoalDetailActions from './GoalDetailActions';import { getGoalPresentation } from './goalPresentation';+import GoalStatusGlyph from './GoalStatusGlyph';import {formatGoalCost,formatGoalDuration,getGoalRunMetrics,getGoalRuns,getRecentGoalRuns,- goalStatusToTaskStatus,} from './goalViewModel';const styles = createStaticStyles(({ css }) => ({@@ -150,7 +150,6 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const bundle = useVerifyStore(verifySelectors.acceptanceBundle(acceptance?.id));const acceptanceQuery = useFetchAcceptanceBySubject('task', task?.id);const bundleQuery = useFetchAcceptanceBundle(acceptance?.id);- const config = task?.config as { goal?: { maxIterations?: number | null } } | undefined;const runs = useMemo(() => getGoalRuns(task?.activities), [task?.activities]);const recentRuns = useMemo(() => getRecentGoalRuns(task?.activities), [task?.activities]);const runMetrics = useMemo(() => getGoalRunMetrics(task?.activities), [task?.activities]);@@ -158,11 +157,11 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const presentation = getGoalPresentation({acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- maxRounds: config?.goal?.maxIterations,+ goalStatus: task?.goal?.status,+ maxRounds: task?.goal?.maxRounds,rounds: task?.topicCount ?? 0,taskStatus: task?.status ?? 'backlog',});- const visual = statusVisual(goalStatusToTaskStatus(presentation.statusKey));const title = task?.name?.trim() || task?.instruction.trim() || goalId;if (error) return <AsyncError error={error} variant={'page'} onRetry={onRetry} />;@@ -342,7 +341,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {</Flexbox><Flexbox gap={4}><Flexbox horizontal align={'center'} className={styles.treeRow} gap={8}>- <Icon color={visual.color} icon={visual.icon} size={14} />+ <GoalStatusGlyph size={14} statusKey={presentation.statusKey} /><Text fontSize={12} type={'secondary'}>{task.identifier}</Text>diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsxindex d033bbb5eb9..6551679b84d 100644--- a/src/features/AgentGoals/GoalListItem.tsx+++ b/src/features/AgentGoals/GoalListItem.tsx@@ -1,6 +1,5 @@'use client';-import type { TaskStatus } from '@lobechat/types';import { ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';import { ArrowRightIcon, RefreshCwIcon } from 'lucide-react';@@ -8,14 +7,14 @@ import type { KeyboardEvent } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import { GoalAcceptance } from './GoalAcceptance';import { getGoalPresentation } from './goalPresentation';import { GoalProgress } from './GoalProgress';-import { getGoalDescription, goalStatusToTaskStatus, shouldShowGoal } from './goalViewModel';+import GoalStatusGlyph from './GoalStatusGlyph';+import { getGoalDescription, shouldShowGoal } from './goalViewModel';import type { GoalItemProps } from './types';const styles = createStaticStyles(({ css }) => ({@@ -38,7 +37,7 @@ export const GoalListItem = memo<GoalItemProps>((props) => {const navigate = useWorkspaceAwareNavigate();const { aid } = useActiveRouteParams<{ aid?: string }>();const { hideAchieved = false, projectId, task } = props;- const config = task.config as { goal?: { maxIterations?: number | null } } | null;+ const goal = task.goal;const title = task.name?.trim() || task.instruction.trim() || task.identifier;const description = getGoalDescription(task);const handleClick = () => {@@ -57,15 +56,13 @@ export const GoalListItem = memo<GoalItemProps>((props) => {const presentation = getGoalPresentation({acceptanceStatus: bundle?.acceptance.status,checks: bundle?.checks,- maxRounds: config?.goal?.maxIterations,+ goalStatus: goal?.status,+ maxRounds: goal?.maxRounds,rounds: task.totalTopics ?? 0,taskStatus: task.status,});if (!isLoading && !shouldShowGoal(presentation.statusKey, hideAchieved ? 'active' : 'all'))return null;- const visual =- TASK_STATUS_VISUALS[goalStatusToTaskStatus(presentation.statusKey) as TaskStatus] ??- TASK_STATUS_VISUALS.backlog;return (<Block@@ -93,12 +90,7 @@ export const GoalListItem = memo<GoalItemProps>((props) => {><Flexbox gap={4} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={7}>- <Icon- color={visual.color}- icon={visual.icon}- size={13}- style={{ flexShrink: 0 }}- />+ <GoalStatusGlyph size={13} statusKey={presentation.statusKey} /><Text ellipsis fontSize={15} weight={600}>{title}</Text>diff --git a/src/features/AgentGoals/GoalStatusGlyph.tsx b/src/features/AgentGoals/GoalStatusGlyph.tsxnew file mode 100644index 00000000000..f4d03e60069--- /dev/null+++ b/src/features/AgentGoals/GoalStatusGlyph.tsx@@ -0,0 +1,26 @@+import type { TaskStatus } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { memo } from 'react';++import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';+import RunningGlyph from '@/features/Home/components/RunningGlyph';++import { goalStatusToTaskStatus } from './goalViewModel';++/**+ * The goal surfaces' status glyph. A live goal shows the same spinning ring as+ * running task topics — animation is the "executing right now" signal shared+ * across the app — while every other state keeps its canonical static glyph+ * from `ExecutionStatus`.+ */+const GoalStatusGlyph = memo<{ size?: number; statusKey: string }>(({ statusKey, size = 13 }) => {+ if (statusKey === 'goalList.status.running') return <RunningGlyph size={size} />;++ const visual =+ TASK_STATUS_VISUALS[goalStatusToTaskStatus(statusKey) as TaskStatus] ??+ TASK_STATUS_VISUALS.backlog;++ return <Icon color={visual.color} icon={visual.icon} size={size} style={{ flexShrink: 0 }} />;+});++export default GoalStatusGlyph;diff --git a/src/features/AgentGoals/goalPresentation.test.ts b/src/features/AgentGoals/goalPresentation.test.tsindex 07194cf92a1..11beeb864dd 100644--- a/src/features/AgentGoals/goalPresentation.test.ts+++ b/src/features/AgentGoals/goalPresentation.test.ts@@ -42,4 +42,25 @@ describe('getGoalPresentation', () => {},);});++ it('keeps an executing round shown as running while the verify plan is only planned', () => {+ // Regression (caught by the E2E acceptance run): the verify plan is+ // confirmed at run start, so the acceptance phase reads `planned` for the+ // whole executing round. That phase must fall through to the goal entity+ // status (`running`) instead of rendering 验证中.+ expect(+ getGoalPresentation({+ acceptanceStatus: 'planned',+ goalStatus: 'running',+ rounds: 1,+ taskStatus: 'running',+ }).statusKey,+ ).toBe('goalList.status.running');+ });++ it('prefers the goal entity status over the task-status heuristic', () => {+ expect(+ getGoalPresentation({ goalStatus: 'paused', rounds: 1, taskStatus: 'running' }).statusKey,+ ).toBe('goalList.status.paused');+ });});diff --git a/src/features/AgentGoals/goalPresentation.ts b/src/features/AgentGoals/goalPresentation.tsindex 947a455207c..f6cac8c2441 100644--- a/src/features/AgentGoals/goalPresentation.ts+++ b/src/features/AgentGoals/goalPresentation.ts@@ -1,6 +1,8 @@export interface GoalPresentationInput {acceptanceStatus?: string;checks?: Array<{ state: string }>;+ /** The goal entity's own lifecycle state (`goals.status`), when loaded. */+ goalStatus?: string;maxRounds?: number | null;rounds: number;taskStatus: string;@@ -21,7 +23,9 @@ const acceptanceStatusKey = (status?: string) => {case 'errored': {return 'goalList.status.error';}- case 'planned':+ // `planned` deliberately falls through to the goal/task tiers: the verify+ // plan is confirmed at RUN START, so this phase spans the whole executing+ // round — showing 验证中 for it misreads an executing goal as verifying.case 'repairing':case 'verifying': {return 'goalList.status.verifying';@@ -32,6 +36,32 @@ const acceptanceStatusKey = (status?: string) => {}};+/**+ * `goals.status` is the server-written goal state machine — a direct 1:1 onto+ * the display vocabulary (only `failed` renders through the `error` key). It+ * sits between the live acceptance phase (fresher, refetched per subject) and+ * the task-status heuristic (coarsest, kept as the final fallback).+ */+const goalStatusKey = (status?: string) => {+ switch (status) {+ case 'achieved':+ case 'canceled':+ case 'paused':+ case 'planning':+ case 'review':+ case 'running':+ case 'verifying': {+ return `goalList.status.${status}`;+ }+ case 'failed': {+ return 'goalList.status.error';+ }+ default: {+ return undefined;+ }+ }+};+const taskStatusKey = (status: string) => {switch (status) {case 'backlog': {@@ -68,7 +98,10 @@ export const getGoalPresentation = (input: GoalPresentationInput) => {passed,progress: total > 0 ? Math.round((passed / total) * 100) : 0,rounds: input.rounds,- statusKey: acceptanceStatusKey(input.acceptanceStatus) ?? taskStatusKey(input.taskStatus),+ statusKey:+ acceptanceStatusKey(input.acceptanceStatus) ??+ goalStatusKey(input.goalStatus) ??+ taskStatusKey(input.taskStatus),total,};};diff --git a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.tsindex 017c21eacff..1e8b1687606 100644--- a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts+++ b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.test.ts@@ -4,7 +4,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useGoalWorkStatus } from './useGoalWorkStatus';const mocks = vi.hoisted(() => ({- taskDetailMap: {} as Record<string, { config?: unknown; name?: string; startedAt?: string }>,+ taskDetailMap: {} as Record<+ string,+ { config?: unknown; goal?: unknown; name?: string; startedAt?: string }+ >,useAcceptanceBundle: vi.fn(() => ({ data: undefined })),useAcceptanceBySubject: vi.fn(() => ({ data: undefined })),useFetchTaskDetail: vi.fn(),@@ -40,7 +43,7 @@ describe('useGoalWorkStatus', () => {it('polls acceptance after task detail identifies a Goal task', () => {mocks.taskDetailMap['T-2'] = {- config: { goal: {} },+ goal: { id: 'goal-1', status: 'running' },startedAt: '2026-08-14T08:00:00.000Z',};diff --git a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.tsindex d4e658eba68..12ab0a5c45e 100644--- a/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts+++ b/src/features/Conversation/Messages/GoalWorkCard/useGoalWorkStatus.ts@@ -28,8 +28,7 @@ export const useGoalWorkStatus = ({const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);useFetchTaskDetail(identifier);const task = useTaskStore((s) => (identifier ? s.taskDetailMap[identifier] : undefined));- const config = task?.config as { goal?: { maxIterations?: number | null } } | undefined;- const isGoal = goalKnown || !!config?.goal;+ const isGoal = goalKnown || !!task?.goal;const { data: acceptance } = useAcceptanceBySubject('task', isGoal ? (taskId ?? null) : null);const { data: bundle } = useAcceptanceBundle(acceptance?.id ?? null);@@ -37,7 +36,7 @@ export const useGoalWorkStatus = ({acceptanceStatus: acceptance?.status,checks: bundle?.checks,criteriaCount,- maxRounds: config?.goal?.maxIterations ?? maxRounds,+ maxRounds: task?.goal?.maxRounds ?? maxRounds,rounds: task?.topicCount ?? 0,taskStatus: task?.status,});diff --git a/src/features/HomeInbox/homeGoals.test.ts b/src/features/HomeInbox/homeGoals.test.tsindex 42f45929c40..5a93605764f 100644--- a/src/features/HomeInbox/homeGoals.test.ts+++ b/src/features/HomeInbox/homeGoals.test.ts@@ -12,7 +12,9 @@ import {const goal = (overrides: Partial<GoalListItem> & Pick<GoalListItem, 'id'>): GoalListItem =>({assigneeAgentId: 'agt_1',- config: { goal: { maxIterations: 3 } },+ // No `status` on the entity here: these cases exercise the task-status+ // fallback tier of the derivation (legacy rows before the backfill ran).+ goal: { maxRounds: 3 },identifier: `T-${overrides.id}`,instruction: 'do the thing',name: `goal ${overrides.id}`,@@ -88,9 +90,7 @@ describe('buildHomeGoalEntries', () => {});it('carries the round budget and falls back to the identifier for an unnamed goal', () => {- const goals = [- goal({ config: { goal: { maxIterations: 5 } }, id: 'x', instruction: '', name: null }),- ];+ const goals = [goal({ goal: { maxRounds: 5 } as any, id: 'x', instruction: '', name: null })];expect(buildHomeGoalEntries(goals)[0]).toMatchObject({agentId: 'agt_1',@@ -100,8 +100,8 @@ describe('buildHomeGoalEntries', () => {});});- it('reports no round budget when the goal config carries none', () => {- const goals = [goal({ config: {}, id: 'x' })];+ it('reports no round budget when the goal entity carries none', () => {+ const goals = [goal({ goal: { maxRounds: null } as any, id: 'x' })];expect(buildHomeGoalEntries(goals)[0].maxRounds).toBeNull();});diff --git a/src/features/HomeInbox/homeGoals.ts b/src/features/HomeInbox/homeGoals.tsindex b7c28521ea6..43e811d3f00 100644--- a/src/features/HomeInbox/homeGoals.ts+++ b/src/features/HomeInbox/homeGoals.ts@@ -65,11 +65,11 @@ export const buildHomeGoalEntries = (acceptanceStatusByTaskId: Record<string, string> = {},): HomeGoalEntry[] => {const entries = goals.flatMap<HomeGoalEntry>((goal) => {- const config = goal.config as { goal?: { maxIterations?: number | null } } | null;- const maxRounds = config?.goal?.maxIterations ?? null;+ const maxRounds = goal.goal?.maxRounds ?? null;const rounds = goal.totalTopics ?? 0;const { statusKey } = getGoalPresentation({acceptanceStatus: acceptanceStatusByTaskId[goal.id],+ goalStatus: goal.goal?.status,maxRounds,rounds,taskStatus: goal.status,diff --git a/src/features/Projects/Workspace/ProjectDashboard.tsx b/src/features/Projects/Workspace/ProjectDashboard.tsxindex 52c1a46d42f..a12f4b3dca6 100644--- a/src/features/Projects/Workspace/ProjectDashboard.tsx+++ b/src/features/Projects/Workspace/ProjectDashboard.tsx@@ -107,10 +107,7 @@ const styles = createStaticStyles(({ css }) => ({const TERMINAL_STATUSES = new Set<TaskStatus | string>(['canceled', 'completed']);const ATTENTION_STATUSES = new Set<TaskStatus | string>(['failed', 'paused']);-const isGoalTask = (task: NonNullable<ProjectDetail['tasks']>[number]) => {- if (!task.config || typeof task.config !== 'object') return false;- return Boolean((task.config as { goal?: unknown }).goal);-};+const isGoalTask = (task: NonNullable<ProjectDetail['tasks']>[number]) => Boolean(task.goal);interface ProjectDashboardProps {detail: ProjectDetail;diff --git a/src/features/Verify/CriterionList/CriterionEditor.tsx b/src/features/Verify/CriterionList/CriterionEditor.tsxindex b99b0b09607..9e900ad836f 100644--- a/src/features/Verify/CriterionList/CriterionEditor.tsx+++ b/src/features/Verify/CriterionList/CriterionEditor.tsx@@ -8,6 +8,16 @@ import { useTranslation } from 'react-i18next';import type { VerifyCriterionDraft } from '@/services/verify';+/**+ * True when the criterion's judging rule lives in a linked document this editor+ * neither loads nor can update (`updateCriterion` carries no instruction+ * field). Rendering an editable blank box in that state would silently discard+ * whatever the user types into it, so the editor shows a read-only note.+ */+export const hasLinkedInstruction = (+ initial: Pick<VerifyCriterionDraft, 'documentId' | 'instruction'>,+) => Boolean(initial.documentId) && !initial.instruction;+export interface CriterionEditorProps {initial: VerifyCriterionDraft;/** Create flow: the criterion only exists once it is saved. */@@ -35,6 +45,7 @@ export const CriterionEditor = ({const [draft, setDraft] = useState<VerifyCriterionDraft>(initial);const verifierType = draft.verifierType ?? 'llm';const isProgram = verifierType === 'program';+ const instructionLinked = hasLinkedInstruction(initial);const patch = (value: Partial<VerifyCriterionDraft>) =>setDraft((previous) => ({ ...previous, ...value }));@@ -119,6 +130,10 @@ export const CriterionEditor = ({patch({ verifierConfig: { ...draft.verifierConfig, command: event.target.value } })}/>+ ) : instructionLinked ? (+ <Text fontSize={12} type={'secondary'}>+ {t('criterion.instructionLinked')}+ </Text>) : (<TextAreaautoSize={{ maxRows: 10, minRows: 3 }}diff --git a/src/features/Verify/CriterionList/CriterionList.test.ts b/src/features/Verify/CriterionList/CriterionList.test.tsnew file mode 100644index 00000000000..ca33347e566--- /dev/null+++ b/src/features/Verify/CriterionList/CriterionList.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';++import { hasLinkedInstruction } from './CriterionEditor';+import { rowKeyDownHandler } from './CriterionRow';++describe('rowKeyDownHandler', () => {+ it('ignores Enter/Space bubbling from a nested action control', () => {+ const onOpen = vi.fn();+ const row = {};+ const nestedControl = {};++ const handler = rowKeyDownHandler(onOpen);+ handler({ currentTarget: row, key: 'Enter', target: nestedControl });+ handler({ currentTarget: row, key: ' ', target: nestedControl });++ expect(onOpen).not.toHaveBeenCalled();+ });++ it('activates on Enter/Space originating from the row itself', () => {+ const onOpen = vi.fn();+ const row = {};++ const handler = rowKeyDownHandler(onOpen);+ handler({ currentTarget: row, key: 'Enter', target: row });+ handler({ currentTarget: row, key: ' ', target: row });+ handler({ currentTarget: row, key: 'a', target: row });++ expect(onOpen).toHaveBeenCalledTimes(2);+ });+});++describe('hasLinkedInstruction', () => {+ it('is true for an existing criterion whose rule lives only in a linked document', () => {+ expect(hasLinkedInstruction({ documentId: 'doc_1' })).toBe(true);+ });++ it('is false when the draft carries an inline instruction or no linked document', () => {+ expect(hasLinkedInstruction({ documentId: 'doc_1', instruction: 'must be markdown' })).toBe(+ false,+ );+ expect(hasLinkedInstruction({})).toBe(false);+ expect(hasLinkedInstruction({ documentId: null })).toBe(false);+ });+});diff --git a/src/features/Verify/CriterionList/CriterionRow.tsx b/src/features/Verify/CriterionList/CriterionRow.tsxindex 6f641d06b04..1f5e7f4f8ec 100644--- a/src/features/Verify/CriterionList/CriterionRow.tsx+++ b/src/features/Verify/CriterionList/CriterionRow.tsx@@ -63,6 +63,18 @@ export const CriterionRequiredChip = ({ onToggle, required }: CriterionRequiredC);};+/**+ * Keyboard activation for the row. A nested action control's Enter/Space+ * bubbles up here; acting on it would open the row on top of (or instead of)+ * the control's own click, so only events originating from the row itself+ * activate it.+ */+export const rowKeyDownHandler =+ (onOpen: () => void) => (event: { currentTarget: unknown; key: string; target: unknown }) => {+ if (event.target !== event.currentTarget) return;+ if (event.key === 'Enter' || event.key === ' ') onOpen();+ };+export interface CriterionRowProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {/** e2e / automation anchors, forwarded onto the row element. */[dataAttribute: `data-${string}`]: string | undefined;@@ -101,12 +113,7 @@ export const CriterionRow = ({role={onOpen ? 'button' : undefined}tabIndex={onOpen ? 0 : undefined}onClick={onOpen}- onKeyDown={- onOpen &&- ((event) => {- if (event.key === 'Enter' || event.key === ' ') onOpen();- })- }+ onKeyDown={onOpen && rowKeyDownHandler(onOpen)}{...rest}>{icon}diff --git a/src/services/task.ts b/src/services/task.tsindex ed24e3659bc..6f316f997ac 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -1,4 +1,9 @@-import type { CheckpointConfig, TaskAutomationMode, TaskStatus } from '@lobechat/types';+import type {+ CheckpointConfig,+ CreateTaskGoalInput,+ TaskAutomationMode,+ TaskStatus,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';@@ -64,6 +69,8 @@ class TaskService {createdByAgentId?: string;description?: string;editorData?: unknown;+ /** Bind a goal entity (`goals` row) to the created task. */+ goal?: CreateTaskGoalInput;identifierPrefix?: string;instruction: string;name?: string;diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 7625c8574ba..cc27a30f89a 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -1,4 +1,4 @@-import type { TaskDetailData, TaskDetailSubtask } from '@lobechat/types';+import type { CreateTaskGoalInput, TaskDetailData, TaskDetailSubtask } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';import { t } from 'i18next';@@ -187,6 +187,8 @@ export class TaskDetailSliceActionImpl {createdByAgentId?: string;description?: string;editorData?: unknown;+ /** Bind a goal entity (`goals` row) to the created task. */+ goal?: CreateTaskGoalInput;instruction: string;name?: string;parentTaskId?: string;