🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): archive goals and filter the goal list by Archived (#22172)
Rdmclin223451652103d
diff --git a/apps/cli/src/commands/goal/archive.test.ts b/apps/cli/src/commands/goal/archive.test.tsnew file mode 100644index 00000000000..3b08145c788--- /dev/null+++ b/apps/cli/src/commands/goal/archive.test.ts@@ -0,0 +1,84 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { registerGoalCommand } from '.';++const { mockClient } = vi.hoisted(() => ({+ mockClient: {+ goal: {+ archive: { mutate: vi.fn() },+ list: { query: vi.fn() },+ },+ },+}));++vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));+vi.mock('../task/url', () => ({+ resolveAppUrlBuilder: vi+ .fn()+ .mockResolvedValue((pathname: string) => `https://app.lobehub.com${pathname}`),+}));++const run = (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerGoalCommand(program);+ return program.parseAsync(['node', 'test', 'goal', ...args]);+};++describe('goal archive', () => {+ let info: ReturnType<typeof vi.spyOn>;+ beforeEach(() => {+ vi.clearAllMocks();+ info = vi.spyOn(log, 'info').mockImplementation(() => {});+ });+ afterEach(() => {+ info.mockRestore();+ });++ it.each([+ ['archive', true, 'Goal archived'],+ ['unarchive', false, 'Goal restored'],+ ] as const)(+ '%s sends the archived flag and prints the result',+ async (name, archived, message) => {+ mockClient.goal.archive.mutate.mockResolvedValue({ data: { id: 'goal-1' }, message });++ await run(name, 'goal-1');++ expect(mockClient.goal.archive.mutate).toHaveBeenCalledWith({ archived, id: 'goal-1' });+ expect(log.info).toHaveBeenCalledWith(message);+ },+ );++ it('links the goal in JSON output', async () => {+ const write = vi.spyOn(console, 'log').mockImplementation(() => {});+ mockClient.goal.archive.mutate.mockResolvedValue({+ data: { id: 'goal-1' },+ message: 'Goal archived',+ });++ await run('archive', 'goal-1', '--json');++ expect(JSON.parse(write.mock.calls[0][0] as string)).toMatchObject({+ id: 'goal-1',+ url: 'https://app.lobehub.com/goal/goal-1',+ });+ write.mockRestore();+ });++ it('lists archived goals only with --archived', async () => {+ mockClient.goal.list.query.mockResolvedValue({ goals: [], total: 0 });++ await run('list');+ expect(mockClient.goal.list.query).toHaveBeenLastCalledWith(+ expect.objectContaining({ archived: undefined }),+ );++ await run('list', '--archived');+ expect(mockClient.goal.list.query).toHaveBeenLastCalledWith(+ expect.objectContaining({ archived: true }),+ );+ });+});diff --git a/apps/cli/src/commands/goal/archive.ts b/apps/cli/src/commands/goal/archive.tsnew file mode 100644index 00000000000..be867c3f7af--- /dev/null+++ b/apps/cli/src/commands/goal/archive.ts@@ -0,0 +1,38 @@+import type { Command } from 'commander';++import { getTrpcClient } from '../../api/client';+import { outputJson } from '../../utils/format';+import { log } from '../../utils/logger';+import { resolveAppUrlBuilder } from '../task/url';++/**+ * `lh goal archive` / `unarchive`. Archiving is the user's call, like a task's:+ * it hides a signed-off or canceled goal from every list without changing its+ * status. Agents run it only when the user asks.+ */+export function registerGoalArchiveCommands(goal: Command) {+ const register = (name: 'archive' | 'unarchive', archived: boolean, description: string) =>+ goal+ .command(`${name} <id>`)+ .description(description)+ .option('--json [fields]', 'Output JSON')+ .action(async (id: string, options: { json?: boolean | string }) => {+ const client = await getTrpcClient();+ const result = await client.goal.archive.mutate({ archived, id });+ if (options.json !== undefined) {+ // Best-effort link, like every other goal command's.+ const url = await resolveAppUrlBuilder(client)+ .then((build) => build(`/goal/${encodeURIComponent(result.data.id)}`))+ .catch(() => undefined);+ return outputJson({ ...result.data, url }, options.json);+ }+ log.info(result.message);+ });++ register(+ 'archive',+ true,+ 'Archive a signed-off or canceled goal (hidden from lists; status unchanged)',+ );+ register('unarchive', false, 'Restore an archived goal to lists');+}diff --git a/apps/cli/src/commands/goal/index.ts b/apps/cli/src/commands/goal/index.tsindex eff6fa7219c..a9426f12712 100644--- a/apps/cli/src/commands/goal/index.ts+++ b/apps/cli/src/commands/goal/index.ts@@ -20,6 +20,7 @@ import { confirm, outputJson, printTable, truncate } from '../../utils/format';import { log } from '../../utils/logger';import { resolveAppUrlBuilder } from '../task/url';import { registerGoalAccessCommands } from './access';+import { registerGoalArchiveCommands } from './archive';import {ensureCreatedGoalTaskModel,parseGoalModelConfig,@@ -863,6 +864,7 @@ export function registerGoalCommand(program: Command) {.option('--agent <id>', 'Filter by responsible agent').option('--project <id>', 'Filter by project').option('--status <status...>', 'Filter by lifecycle status')+ .option('--archived', 'List only archived goals (hidden otherwise)').option('--limit <n>', 'Maximum rows', '50').option('--json [fields]', 'Output JSON').action(async (options) => {@@ -870,6 +872,7 @@ export function registerGoalCommand(program: Command) {await getTrpcClient()).goal.list.query({agentId: options.agent,+ archived: options.archived || undefined,limit: Number.parseInt(options.limit, 10),projectId: options.project,statuses: options.status,@@ -1185,6 +1188,7 @@ export function registerGoalCommand(program: Command) {);registerGoalAccessCommands(goal);+ registerGoalArchiveCommands(goal);registerGoalAssignmentCommands(goal);goaldiff --git a/apps/server/src/routers/lambda/__tests__/acceptance.signOffArchive.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.signOffArchive.test.tsdeleted file mode 100644index dc99a7cb88a..00000000000--- a/apps/server/src/routers/lambda/__tests__/acceptance.signOffArchive.test.ts+++ /dev/null@@ -1,95 +0,0 @@-// @vitest-environment node-import { randomUUID } from 'node:crypto';--import type { LobeChatDatabase } from '@lobechat/database';-import { acceptances, verifyRuns } from '@lobechat/database/schemas';-import { getTestDB } from '@lobechat/database/test-utils';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import type * as GoalServiceModule from '@/server/services/goal';--import { acceptanceRouter } from '../acceptance';-import { cleanupTestUser, createTestContext, createTestUser } from './integration/setup';--let serverDB: LobeChatDatabase;-vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: () => serverDB }));--const mockArchiveSignedOffTasks = vi.fn();-vi.mock('@/server/services/goal', async (importOriginal) => {- const actual = await importOriginal<typeof GoalServiceModule>();- return {- ...actual,- GoalService: vi.fn().mockImplementation(function () {- return { archiveSignedOffTasks: mockArchiveSignedOffTasks };- }),- };-});--describe('acceptanceRouter sign-off archives the goal Tasks', () => {- let userId: string;-- beforeEach(async () => {- serverDB = await getTestDB();- userId = await createTestUser(serverDB);- mockArchiveSignedOffTasks.mockResolvedValue([]);- });-- afterEach(async () => {- mockArchiveSignedOffTasks.mockReset();- await cleanupTestUser(serverDB, userId);- });-- const seedAcceptance = async (subjectType: 'standalone' | 'task' = 'task') => {- const subjectId = randomUUID();- const [acceptance] = await serverDB- .insert(acceptances)- .values({ status: 'delivered', subjectId, subjectType, userId })- .returning();- await serverDB- .insert(verifyRuns)- .values({ acceptanceId: acceptance.id, roundIndex: 1, status: 'passed', userId });- return { id: acceptance.id, subjectId };- };-- it('archives the signed Task’s goal on accept', async () => {- const { id, subjectId } = await seedAcceptance();- const caller = acceptanceRouter.createCaller(createTestContext(userId));-- const result = await caller.accept({ id });-- expect(result.status).toBe('accepted');- expect(mockArchiveSignedOffTasks).toHaveBeenCalledWith(subjectId);- });-- it('still records the sign-off when archiving fails', async () => {- const { id } = await seedAcceptance();- mockArchiveSignedOffTasks.mockRejectedValue(new Error('db down'));- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- const caller = acceptanceRouter.createCaller(createTestContext(userId));-- expect((await caller.accept({ id })).status).toBe('accepted');- expect(errorSpy).toHaveBeenCalledWith('[goal:sign-off:archive-tasks]', expect.any(Error));- errorSpy.mockRestore();- });-- it('archives on an accept from the list, but not on a close', async () => {- const accepted = await seedAcceptance();- const closed = await seedAcceptance();- const caller = acceptanceRouter.createCaller(createTestContext(userId));-- await caller.updateStatus({ id: closed.id, status: 'closed' });- expect(mockArchiveSignedOffTasks).not.toHaveBeenCalled();-- await caller.updateStatus({ id: accepted.id, status: 'accepted' });- expect(mockArchiveSignedOffTasks).toHaveBeenCalledWith(accepted.subjectId);- });-- it('leaves an acceptance that is not about a Task alone', async () => {- const { id } = await seedAcceptance('standalone');- const caller = acceptanceRouter.createCaller(createTestContext(userId));-- await caller.accept({ id });-- expect(mockArchiveSignedOffTasks).not.toHaveBeenCalled();- });-});diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceStatus.ts b/apps/server/src/routers/lambda/_helpers/acceptanceStatus.tsindex 5657aebf809..38cbd2538de 100644--- a/apps/server/src/routers/lambda/_helpers/acceptanceStatus.ts+++ b/apps/server/src/routers/lambda/_helpers/acceptanceStatus.ts@@ -5,13 +5,10 @@ import type { AcceptanceItem } from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';import { notifyAcceptance } from '@/server/services/acceptanceReview/events';import { GoalBriefService } from '@/server/services/goal/goalBriefs';-import { archiveSignedOffGoalTasks } from '@/server/services/goal/signOffArchive';import type { AcceptanceService } from '@/server/services/verify/acceptanceService';import { assertNotHoldingRelease } from './goalGateAcceptance';-export { archiveSignedOffGoalTasks };-export const acceptanceStatusOverrideSchema = z.enum(['delivered','accepted',@@ -57,7 +54,6 @@ export const applyAcceptanceStatus = async (if (status === 'accepted') {await service.accept(acceptance.id);await settleGoalSignOff(db, acceptance, 'signOff');- await archiveSignedOffGoalTasks(db, acceptance);return;}diff --git a/apps/server/src/routers/lambda/_helpers/goalBriefAction.test.ts b/apps/server/src/routers/lambda/_helpers/goalBriefAction.test.tsindex bd482326f29..12b9c32158f 100644--- a/apps/server/src/routers/lambda/_helpers/goalBriefAction.test.ts+++ b/apps/server/src/routers/lambda/_helpers/goalBriefAction.test.ts@@ -7,7 +7,6 @@ import { applyGoalBriefAction } from './goalBriefAction';const mocks = vi.hoisted(() => ({accept: vi.fn(),- archiveSignedOffGoalTasks: vi.fn(),dispatchAcceptanceRepair: vi.fn(),reject: vi.fn(),settleSignOff: vi.fn(),@@ -24,9 +23,6 @@ vi.mock('../acceptance', () => ({vi.mock('./acceptanceRepairDispatch', () => ({dispatchAcceptanceRepair: mocks.dispatchAcceptanceRepair,}));-vi.mock('./acceptanceStatus', () => ({- archiveSignedOffGoalTasks: mocks.archiveSignedOffGoalTasks,-}));vi.mock('@/server/services/goal/goalBriefs', () => ({GoalBriefService: vi.fn().mockImplementation(function () {return { settleSignOff: mocks.settleSignOff };@@ -45,17 +41,17 @@ describe('applyGoalBriefAction sign-off', () => {vi.clearAllMocks();});- it('archives the goal Tasks after signing off from the inbox', async () => {+ it('signs off from the inbox and settles the brief', async () => {expect(await applyGoalBriefAction(ctx, signOffBrief, 'signOff')).toBe(true);expect(mocks.accept).toHaveBeenCalledWith('acc_1', undefined);- expect(mocks.archiveSignedOffGoalTasks).toHaveBeenCalledWith(ctx.serverDB, acceptance);+ expect(mocks.settleSignOff).toHaveBeenCalledWith('acc_1', 'signOff', undefined);});- it('archives nothing when the delivery is sent back', async () => {+ it('sends the delivery back and hands it to the repair dispatch', async () => {expect(await applyGoalBriefAction(ctx, signOffBrief, 'requestChanges', 'Redo it')).toBe(true);- expect(mocks.reject).toHaveBeenCalled();- expect(mocks.archiveSignedOffGoalTasks).not.toHaveBeenCalled();+ expect(mocks.reject).toHaveBeenCalledWith('acc_1', 'Redo it');+ expect(mocks.dispatchAcceptanceRepair).toHaveBeenCalled();});});diff --git a/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts b/apps/server/src/routers/lambda/_helpers/goalBriefAction.tsindex 8c399f9e00a..7de2bce914b 100644--- a/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts+++ b/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts@@ -6,7 +6,6 @@ import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';import { resolveAcceptanceForWrite } from '../acceptance';import { dispatchAcceptanceRepair } from './acceptanceRepairDispatch';-import { archiveSignedOffGoalTasks } from './acceptanceStatus';type GoalBriefContext = Parameters<typeof dispatchAcceptanceRepair>[0] & {serverDB: LobeChatDatabase;@@ -66,7 +65,6 @@ export const applyGoalBriefAction = async (action,comment,);- if (action === 'signOff') await archiveSignedOffGoalTasks(ctx.serverDB, acceptance);return true;}diff --git a/apps/server/src/routers/lambda/acceptance/review.ts b/apps/server/src/routers/lambda/acceptance/review.tsindex bf485869c90..bd064555296 100644--- a/apps/server/src/routers/lambda/acceptance/review.ts+++ b/apps/server/src/routers/lambda/acceptance/review.ts@@ -27,7 +27,7 @@ import {readAcceptanceRepair,} from '../_helpers/acceptanceFeedbackRepair';import { type AcceptanceRepairDispatch } from '../_helpers/acceptanceRepairDispatch';-import { archiveSignedOffGoalTasks, settleGoalSignOff } from '../_helpers/acceptanceStatus';+import { settleGoalSignOff } from '../_helpers/acceptanceStatus';import * as goalGate from '../_helpers/goalGateAcceptance';import {acceptanceWriteProcedure,@@ -77,7 +77,6 @@ export const reviewRouter = router({);// Signed where it lives — the inbox stops asking for the same sign-off.await settleGoalSignOff(ctx.serverDB, acceptance, 'signOff', input.comment);- await archiveSignedOffGoalTasks(ctx.serverDB, acceptance);return acceptanceResponse(accepted);}),/**diff --git a/apps/server/src/routers/lambda/goal/index.procedures.test.ts b/apps/server/src/routers/lambda/goal/index.procedures.test.tsindex 041eee6459c..919c9d2e9a1 100644--- a/apps/server/src/routers/lambda/goal/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/goal/index.procedures.test.ts@@ -29,6 +29,7 @@ function expected(): Array<['addNode', 'mutation', 13],['advance', 'mutation', 13],['answerClarifications', 'mutation', 13],+ ['archive', 'mutation', 13],['bindOperationTopic', 'mutation', 8],['bindSubscription', 'mutation', 13],['bindTopic', 'mutation', 13],diff --git a/apps/server/src/routers/lambda/goal/lifecycle.ts b/apps/server/src/routers/lambda/goal/lifecycle.tsindex cc2c4544339..d8af5eb6ffa 100644--- a/apps/server/src/routers/lambda/goal/lifecycle.ts+++ b/apps/server/src/routers/lambda/goal/lifecycle.ts@@ -1,6 +1,7 @@import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { GoalArchiveRepository } from '@/database/repositories/goalArchive';import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { advanceGoal } from '@/server/services/goal/advanceGoal';@@ -165,6 +166,40 @@ export const lifecycleRouter = router({mapGoalError(error, 'delete');}}),+ /**+ * Put a goal away, or bring it back. User-only, like a task's archive: no+ * agent tool exposes it. Only a goal that is done with — signed off by its+ * owner, or canceled — can be archived: archived goals leave every list, so+ * one still waiting on a decision would wait out of sight. `status` is left+ * untouched.+ */+ archive: goalWriteProcedure+ .input(idInput.extend({ archived: z.boolean() }))+ .mutation(async ({ ctx, input: { archived, id } }) => {+ try {+ // Same ownership rule as close / delete: the creator or a workspace owner.+ const goal = await ctx.goalModel.findById(id);+ if (!goal) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertWorkspaceRowManageable(ctx, goal.userId, 'goal');++ const model = new GoalArchiveRepository(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ );+ // The status check is part of the UPDATE, so a resume racing it can't slip past.+ const data = archived ? await model.archive(id) : await model.unarchive(id);+ if (!data) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Only a signed-off or canceled goal can be archived',+ });+ }+ return { data, message: archived ? 'Goal archived' : 'Goal restored', success: true };+ } catch (error) {+ mapGoalError(error, archived ? 'archive' : 'unarchive');+ }+ }),pause: goalWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {try {return { data: await ctx.goalService.pause(input.id), message: 'Goal paused', success: true };diff --git a/apps/server/src/routers/lambda/goal/reads.ts b/apps/server/src/routers/lambda/goal/reads.tsindex 20446a72f65..68201834110 100644--- a/apps/server/src/routers/lambda/goal/reads.ts+++ b/apps/server/src/routers/lambda/goal/reads.ts@@ -271,6 +271,8 @@ export const readRouter = router({.input(z.object({agentId: z.string().optional(),+ /** List only archived goals; omitted, archived goals are left out. */+ archived: z.boolean().optional(),limit: z.number().optional(),offset: z.number().optional(),projectId: z.string().optional(),diff --git a/apps/server/src/routers/lambda/goalProcedures.ts b/apps/server/src/routers/lambda/goalProcedures.tsindex 88ebfd8500d..c48b4b243e8 100644--- a/apps/server/src/routers/lambda/goalProcedures.ts+++ b/apps/server/src/routers/lambda/goalProcedures.ts@@ -4,6 +4,7 @@ import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { GoalModel } from '@/database/models/goal';+import { GoalArchivedError } from '@/database/models/goalArchive';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { GoalService } from '@/server/services/goal';import { GoalSubscriptionService } from '@/server/services/goal/subscriptions';@@ -35,6 +36,8 @@ export const idInput = z.object({ id: z.string() });export function mapGoalError(error: unknown, operation: string): never {if (error instanceof TRPCError) throw error;+ if (error instanceof GoalArchivedError)+ throw new TRPCError({ cause: error, code: 'PRECONDITION_FAILED', message: error.message });console.error(`[goal:${operation}]`, error);throw new TRPCError({cause: error,diff --git a/apps/server/src/services/goal/GoalService/__tests__/archive.test.ts b/apps/server/src/services/goal/GoalService/__tests__/archive.test.tsnew file mode 100644index 00000000000..32a3539dc6d--- /dev/null+++ b/apps/server/src/services/goal/GoalService/__tests__/archive.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { describe, expect, it } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AcceptanceModel } from '@/database/models/acceptance';+import { GoalModel } from '@/database/models/goal';+import { GoalArchiveModel } from '@/database/models/goalArchive';+import { goals } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { AcceptanceService } from '../../../verify/acceptanceService';+import { GoalStartService } from '../../start';+import { registerGoalServiceTestCleanup } from '../../testUtils';+import { GoalService } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-archive-service-user';++registerGoalServiceTestCleanup(serverDB, userId);++const archived = { code: 'PRECONDITION_FAILED', message: expect.stringContaining('archived') };++describe('archived goals stay put', () => {+ it('refuses to resume, restart, pause or close an archived goal until it is restored', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Only'], title: 'Put away' });+ await service.close(graph.goal.id, 'canceled');+ const archive = new GoalArchiveModel(serverDB, userId);+ expect(await archive.archive(graph.goal.id)).not.toBeNull();++ await expect(service.resume(graph.goal.id)).rejects.toMatchObject(archived);+ await expect(service.restart(graph.goal.id)).rejects.toMatchObject(archived);+ await expect(service.pause(graph.goal.id)).rejects.toMatchObject(archived);+ // Nor marked achieved: an archived canceled goal was never signed off.+ await expect(service.close(graph.goal.id, 'achieved')).rejects.toMatchObject(archived);+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe(+ 'canceled',+ );++ await archive.unarchive(graph.goal.id);+ expect((await service.resume(graph.goal.id)).status).toBe('running');+ });++ it('refuses to start a draft that carries an archive mark', async () => {+ // Drafts cannot be archived; the start guard still holds if one ever is.+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Seed'], title: 'Draft' });+ await new GoalModel(serverDB, userId).update(graph.goal.id, { status: 'draft' });+ await serverDB.update(goals).set({ archivedAt: new Date() }).where(eq(goals.id, graph.goal.id));++ await expect(new GoalStartService(serverDB, userId).start(graph.goal.id)).rejects.toMatchObject(+ archived,+ );+ expect((await new GoalModel(serverDB, userId).findById(graph.goal.id))?.status).toBe('draft');+ });++ it('does not archive an achieved goal before its owner signs it off', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Only'], title: 'Awaiting sign-off' });+ await service.close(graph.goal.id, 'achieved');++ expect(await new GoalArchiveModel(serverDB, userId).archive(graph.goal.id)).toBeNull();+ });++ it('refuses a change request on a Task of an archived goal until it is restored', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Only'], title: 'Put away' });+ const { taskId } = await service.tick(graph.goal.id);+ const acceptanceModel = new AcceptanceModel(serverDB, userId);+ const acceptance = await acceptanceModel.ensureForSubject('task', taskId!);+ await acceptanceModel.updateStatus(acceptance.id, 'delivered');+ await service.close(graph.goal.id, 'canceled');+ expect(await new GoalArchiveModel(serverDB, userId).archive(graph.goal.id)).not.toBeNull();++ await expect(+ new AcceptanceService(serverDB, userId).reject(acceptance.id, 'Redo it'),+ ).rejects.toMatchObject(archived);+ expect((await acceptanceModel.findById(acceptance.id))?.status).toBe('delivered');+ });++ it('does not archive a goal that is still running', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ tasks: ['Busy'], title: 'Live' });+ await service.tick(graph.goal.id);++ expect(await new GoalArchiveModel(serverDB, userId).archive(graph.goal.id)).toBeNull();+ });+});diff --git a/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.tsindex 2a102abe6e8..6ff065612d0 100644--- a/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts@@ -6,10 +6,12 @@ import { getTestDB } from '@/database/core/getTestDB';import { AcceptanceModel } from '@/database/models/acceptance';import { AgentOperationModel } from '@/database/models/agentOperation';import { GoalModel } from '@/database/models/goal';+import { GoalArchiveModel } from '@/database/models/goalArchive';import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';import { TaskArchiveModel } from '@/database/models/taskArchive';import { TaskTopicModel } from '@/database/models/taskTopic';+import { GoalArchiveRepository } from '@/database/repositories/goalArchive';import { agents, goalEvents, goals, tasks, topics, users, workspaces } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';@@ -579,7 +581,7 @@ describe('GoalService', () => {});});-describe('GoalService.archiveSignedOffTasks', () => {+describe('archiving a signed-off goal with its Tasks', () => {/** The owner accepts the Goal-level acceptance for `taskId`. */const signOff = async (taskId: string) => {const model = new AcceptanceModel(serverDB, userId);@@ -623,96 +625,109 @@ describe('GoalService.archiveSignedOffTasks', () => {return ready;};- it('archives the finished Tasks of a goal once its Goal-level acceptance is signed off', async () => {- const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();+ it('leaves the Tasks in the task lists when the goal is signed off', async () => {+ const { acceptanceTaskId, taskModel, workTaskId } = await achieveGoal();await signOff(acceptanceTaskId);- const archived = await service.archiveSignedOffTasks(acceptanceTaskId);-- expect(archived.sort()).toEqual([acceptanceTaskId, workTaskId].sort());- expect((await taskModel.findById(workTaskId))?.archivedAt).toBeInstanceOf(Date);- expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeInstanceOf(Date);- // Status is untouched, so a restored Task reads exactly as it did.- expect((await taskModel.findById(workTaskId))?.status).toBe('completed');- // A repeated sign-off has nothing left to archive.- expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);+ // Signing off closes the goal; putting it and its Tasks away is the owner's archive.+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();+ expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeNull();});- it('archives on the achieved transition when the owner signed off before it', async () => {- const { acceptanceTaskId, goalId, service, taskModel, workTaskId } = await readyToAchieve();- // The sign-off lands while the goal is still running: nothing to archive yet.+ it('archives the goal’s Tasks with it, and restores them with it', async () => {+ const { acceptanceTaskId, goalId, taskModel, workTaskId } = await achieveGoal();await signOff(acceptanceTaskId);- expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);+ const archive = new GoalArchiveRepository(serverDB, userId);- expect((await service.tick(goalId)).outcome).toBe('achieved');+ const goal = await archive.archive(goalId);- expect((await taskModel.findById(workTaskId))?.archivedAt).toBeInstanceOf(Date);+ expect(goal?.archivedAt).toBeInstanceOf(Date);+ const work = await taskModel.findById(workTaskId);+ expect(work?.archivedAt?.getTime()).toBe(goal?.archivedAt?.getTime());expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeInstanceOf(Date);- });+ // Status is untouched, so a restored Task reads exactly as it did.+ expect(work?.status).toBe('completed');- it('archives nothing on the achieved transition until the owner signs off', async () => {- const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();+ await archive.unarchive(goalId);expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();- expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);- expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();+ expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeNull();});- it('leaves unfinished Tasks of a signed-off goal alone', async () => {- const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();+ it('leaves a Task archived on its own archived when the goal is restored', async () => {+ const { acceptanceTaskId, goalId, taskModel, workTaskId } = await achieveGoal();await signOff(acceptanceTaskId);- await taskModel.updateStatus(workTaskId, 'paused');+ expect(await new TaskArchiveModel(serverDB, userId).archive(workTaskId)).not.toBeNull();+ const archive = new GoalArchiveRepository(serverDB, userId);- expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([acceptanceTaskId]);- expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();+ await archive.archive(goalId);+ await archive.unarchive(goalId);++ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeInstanceOf(Date);+ expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeNull();});- it('archives nothing for an acceptance that is not the Goal-level one', async () => {- const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();+ it('keeps a Task that is still running live when its goal is archived', async () => {+ const { acceptanceTaskId, goalId, taskModel, workTaskId } = await achieveGoal();await signOff(acceptanceTaskId);- await signOff(workTaskId);+ await taskModel.updateStatus(workTaskId, 'running');++ expect(await new GoalArchiveRepository(serverDB, userId).archive(goalId)).not.toBeNull();- expect(await service.archiveSignedOffTasks(workTaskId)).toEqual([]);expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();- expect(await service.archiveSignedOffTasks('task_not_in_any_goal')).toEqual([]);+ expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeInstanceOf(Date);});it('restores the reworked Task when a signed-off goal is sent back for changes', async () => {- const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();+ const { acceptanceTaskId, service, taskModel } = await achieveGoal();await signOff(acceptanceTaskId);- await service.archiveSignedOffTasks(acceptanceTaskId);+ await new TaskArchiveModel(serverDB, userId).archive(acceptanceTaskId);+ // A further round reopens the acceptance so it can be decided again.+ const acceptanceModel = new AcceptanceModel(serverDB, userId);+ const acceptance = await acceptanceModel.ensureForSubject('task', acceptanceTaskId);+ await acceptanceModel.updateStatus(acceptance.id, 'delivered');expect(await service.reopenForChanges(acceptanceTaskId, 'Add a day-one agenda')).toBeDefined();// The runner refuses an archived Task, so the rework must be live again.expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeNull();expect((await taskModel.findById(acceptanceTaskId))?.status).toBe('backlog');- expect((await taskModel.findById(workTaskId))?.archivedAt).toBeInstanceOf(Date);});- it('never re-archives the reworked Task from a sign-off that read it before the reopen', async () => {- const { acceptanceTaskId, service, taskModel } = await achieveGoal();+ it('leaves an archived goal put when its sign-off is sent back for changes', async () => {+ const { acceptanceTaskId, goalId, service, taskModel } = await achieveGoal();await signOff(acceptanceTaskId);- // The sign-off read the Task as finished, then the reopen moved it back to backlog.- const stale = await taskModel.findById(acceptanceTaskId);- expect(stale?.status).toBe('completed');- await service.reopenForChanges(acceptanceTaskId, 'Add a day-one agenda');+ expect(await new GoalArchiveModel(serverDB, userId).archive(goalId)).not.toBeNull();expect(- await new TaskArchiveModel(serverDB, userId).archive(acceptanceTaskId, {- onlyStatuses: ['canceled', 'completed'],- }),- ).toBeNull();- expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeNull();+ await service.reopenForChanges(acceptanceTaskId, 'Add a day-one agenda'),+ ).toBeUndefined();++ // Nothing reworks it out of sight: the goal stays achieved, the Task done.+ expect((await new GoalModel(serverDB, userId).findById(goalId))?.status).toBe('achieved');+ expect((await taskModel.findById(acceptanceTaskId))?.status).toBe('completed');});- it('archives nothing while the goal is not achieved', async () => {- const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();+ it('writes nothing when an archive lands between the reopen’s read and its lock', async () => {+ const { acceptanceTaskId, goalId, service, taskModel } = await achieveGoal();await signOff(acceptanceTaskId);- const goal = await new GoalModel(serverDB, userId).findByGraphTask(acceptanceTaskId);- await new GoalModel(serverDB, userId).update(goal!.id, { status: 'running' });+ const goals = new GoalModel(serverDB, userId);+ const unarchived = await goals.findByGraphTask(acceptanceTaskId);+ expect(await new GoalArchiveModel(serverDB, userId).archive(goalId)).not.toBeNull();+ // The reopen read the goal before the archive committed.+ const serviceGoals = (service as unknown as { goalModel: GoalModel }).goalModel;+ vi.spyOn(serviceGoals, 'findByGraphTask').mockResolvedValueOnce(unarchived);- expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);- expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();+ expect(+ await service.reopenForChanges(acceptanceTaskId, 'Add a day-one agenda'),+ ).toBeUndefined();++ const goal = await goals.findById(goalId);+ expect(goal?.status).toBe('achieved');+ expect(goal?.config?.changeRequest).toBeUndefined();+ expect((await taskModel.findById(acceptanceTaskId))?.status).toBe('completed');+ const graph = await service.graph(goalId);+ const node = graph.nodes.find((candidate) => candidate.taskId === acceptanceTaskId);+ expect(node?.status).toBe('resolved');});});diff --git a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts b/apps/server/src/services/goal/GoalService/__tests__/surface.test.tsindex a6a978a67c3..1ba48785b4a 100644--- a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts@@ -40,7 +40,6 @@ const METHODS = ['addNode','answerClarifications','answerReleaseGate',- 'archiveSignedOffTasks','attachTaskDeliverables','bindTopic','buildTaskAcceptanceRequirement',diff --git a/apps/server/src/services/goal/GoalService/completion.ts b/apps/server/src/services/goal/GoalService/completion.tsindex 79ea42ca0eb..5e21f032234 100644--- a/apps/server/src/services/goal/GoalService/completion.ts+++ b/apps/server/src/services/goal/GoalService/completion.ts@@ -89,17 +89,6 @@ export const settleTerminalAcceptance = async (});if (!achieved) return measurementChanged;effects.push({ type: 'goal_status', detail: 'achieved' });- // The sign-off is asked for above, before the Goal turned terminal, so the- // owner may already have signed it; that sign-off found the Goal not yet- // achieved and archived nothing. Best-effort: the Goal is achieved either way.- const terminalTaskId = graph.nodes.find(- (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE,- )?.taskId;- if (terminalTaskId) {- await ctx- .archiveSignedOffTasks(terminalTaskId)- .catch((error) => console.error('[goal:sign-off:archive-tasks]', error));- }return { goalId, message: move.message, outcome: 'achieved' };}diff --git a/apps/server/src/services/goal/GoalService/decisions.ts b/apps/server/src/services/goal/GoalService/decisions.tsindex e80c74d93a5..6ce549c203a 100644--- a/apps/server/src/services/goal/GoalService/decisions.ts+++ b/apps/server/src/services/goal/GoalService/decisions.ts@@ -302,7 +302,9 @@ export const reopenForChanges = async (comment?: string,): Promise<string | undefined> => {const goal = await ctx.goalModel.findByGraphTask(taskId);- if (!goal || !REOPENABLE_GOAL_STATUSES.has(goal.status)) return undefined;+ // An archived goal stays put: the reject is recorded, but nothing reworks it+ // until the owner restores the goal. Rechecked under the row lock below.+ if (!goal || goal.archivedAt || !REOPENABLE_GOAL_STATUSES.has(goal.status)) return undefined;const graph = await ctx.requireGraph(goal.id);const node = graph.nodes.find((candidate) =>@@ -313,25 +315,45 @@ export const reopenForChanges = async (if (node?.status !== 'resolved') return undefined;const reason = comment ? `Changes requested: ${comment}` : 'Changes requested';- // A sign-off archived the Goal's finished Tasks (`archiveSignedOffTasks`);- // the runner refuses an archived Task, so the one being reworked comes back.- // Leave `completed` first: that archive only matches a finished Task, so one- // racing this reopen either lands before the unarchive or matches nothing.- await ctx.taskModel.updateStatus(taskId, 'backlog', { error: null });- await new TaskArchiveModel(ctx.db, ctx.userId, ctx.workspaceId).unarchive(taskId);- await ctx.graphModel.updateNodeStatus(goal.id, node.id, 'active', reason);- await ctx.goalModel.update(goal.id, {- config: {- ...graph.goal.config,- changeRequest: {- ...(comment ? { comment } : {}),- requestedAt: new Date().toISOString(),- taskId,+ // One transaction under the goal's row lock, so the reopen and an archive+ // serialize: an archive that committed first is seen here and nothing is+ // written; one that comes after waits for this commit and then finds a+ // running goal, which it does not match. No half-reopened archived goal.+ const reopened = await ctx.db.transaction(async (tx) => {+ const goals = new GoalRepository(tx, ctx.userId, ctx.workspaceId);+ const current = await goals.lockById(goal.id);+ if (!current || current.archivedAt || !REOPENABLE_GOAL_STATUSES.has(current.status))+ return false;++ // The runner refuses an archived Task, so the one being reworked comes back+ // even if it was archived on its own (or by an earlier sign-off).+ // Leave `completed` first: that archive only matches a finished Task, so one+ // racing this reopen either lands before the unarchive or matches nothing.+ await new TaskModel(tx, ctx.userId, ctx.workspaceId).updateStatus(taskId, 'backlog', {+ error: null,+ });+ await new TaskArchiveModel(tx, ctx.userId, ctx.workspaceId).unarchive(taskId);+ const graphModel = new GoalGraphModel(tx, ctx.userId, ctx.workspaceId);+ await graphModel.updateNodeStatus(goal.id, node.id, 'active', reason);+ await goals.update(goal.id, {+ config: {+ ...current.config,+ changeRequest: {+ ...(comment ? { comment } : {}),+ requestedAt: new Date().toISOString(),+ taskId,+ },},- },+ });+ if (current.status !== 'running') {+ await goals.updateStatus(goal.id, 'running');+ await graphModel+ .recordGoalStatus(goal.id, current.status, 'running', reason)+ .catch((error) => console.error('[GoalService] failed to record goal status:', error));+ }+ return true;});- await ctx.transitionStatus(graph.goal, 'running', reason, 'user');- return goal.id;+ return reopened ? goal.id : undefined;};/**diff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.tsindex e1d57259ae3..d41921e996c 100644--- a/apps/server/src/services/goal/GoalService/index.ts+++ b/apps/server/src/services/goal/GoalService/index.ts@@ -55,7 +55,6 @@ import {updateTitle,} from './editing';import {- archiveSignedOffTasks,close,deleteGoal,pause,@@ -191,7 +190,6 @@ export class GoalService {},answerClarifications: (...args) => self.answerClarifications(...args),answerReleaseGate: (...args) => self.answerReleaseGate(...args),- archiveSignedOffTasks: (...args) => self.archiveSignedOffTasks(...args),attachTaskDeliverables: (...args) => self.attachTaskDeliverables(...args),bindTopic: (...args) => self.bindTopic(...args),get briefs() {@@ -375,9 +373,6 @@ export class GoalService {delete = (...args: MethodArgs<typeof deleteGoal>) => deleteGoal(this.context, ...args);- archiveSignedOffTasks = (...args: MethodArgs<typeof archiveSignedOffTasks>) =>- archiveSignedOffTasks(this.context, ...args);-private transitionStatus = (...args: MethodArgs<typeof transitionStatus>) =>transitionStatus(this.context, ...args);diff --git a/apps/server/src/services/goal/GoalService/lifecycle.ts b/apps/server/src/services/goal/GoalService/lifecycle.tsindex 902b4d6ad79..d681029a5fa 100644--- a/apps/server/src/services/goal/GoalService/lifecycle.ts+++ b/apps/server/src/services/goal/GoalService/lifecycle.ts@@ -3,10 +3,10 @@ import { TRPCError } from '@trpc/server';import { GoalGraphModel } from '@/database/models/goalGraph';import { TaskModel } from '@/database/models/task';-import { TaskArchiveModel } from '@/database/models/taskArchive';import { TaskTopicModel } from '@/database/models/taskTopic';import { GoalRepository } from '@/database/repositories/goal';+import { assertGoalNotArchived } from '../archiveGuard';import { GoalAssignmentService } from '../assignment';import { GOAL_ACCEPTANCE_TASK_TITLE, TERMINAL_NODE_STATUSES } from '../decideNextMove';import { GoalManagerService } from '../manager';@@ -39,59 +39,6 @@ export const requestSignOff = async (ctx: GoalServiceContext, graph: GoalGraphSnawait ctx.briefs.openSignOff(graph.goal, acceptance.id);};-const SIGNED_OFF_ARCHIVABLE_TASK_STATUSES = ['canceled', 'completed'];--/**- * The owner signed the Goal off (accepted its Goal-level acceptance), so its- * finished Tasks are done with: archive them instead of leaving the owner to- * clear them by hand. Conservative on purpose — only an `achieved` Goal whose- * Goal-level acceptance is `accepted`, only Tasks that are completed or- * canceled, and only through the guarded archive write, which keeps anything- * running or scheduled live. An unfinished Task stays where its owner can see- * it, and every archived one can be restored on its own.- *- * The sign-off and the `achieved` transition can land in either order — the- * sign-off is asked for before the Goal turns terminal — so both call this and- * whichever comes second does the work. The finished-status check sits in the- * archive UPDATE itself, so a Task reopened for changes after this read is- * never archived again.- *- * `taskId` is the signed acceptance's Task; anything other than a Goal-level- * acceptance archives nothing. Returns the archived Task ids.- */-export const archiveSignedOffTasks = async (- ctx: GoalServiceContext,- taskId: string,-): Promise<string[]> => {- const goal = await ctx.goalModel.findByGraphTask(taskId);- if (goal?.status !== 'achieved') return [];- const graph = await ctx.graphModel.getGraph(goal.id);- if (!graph) return [];- const isGoalAcceptance = graph.nodes.some(- (node) =>- node.kind === 'task' && node.taskId === taskId && node.title === GOAL_ACCEPTANCE_TASK_TITLE,- );- if (!isGoalAcceptance) return [];- const acceptances = await ctx.acceptanceService.acceptanceModel.findBySubjects('task', [taskId]);- if (!acceptances.some((acceptance) => acceptance.status === 'accepted')) return [];-- const taskIds = [- ...new Set(- graph.nodes.flatMap((node) => (node.kind === 'task' && node.taskId ? [node.taskId] : [])),- ),- ];- const archiveModel = new TaskArchiveModel(ctx.db, ctx.userId, ctx.workspaceId);- const archived: string[] = [];- for (const task of await ctx.taskModel.findByIds(taskIds)) {- if (task.archivedAt || !SIGNED_OFF_ARCHIVABLE_TASK_STATUSES.includes(task.status)) continue;- const written = await archiveModel.archive(task.id, {- onlyStatuses: SIGNED_OFF_ARCHIVABLE_TASK_STATUSES,- });- if (written) archived.push(task.id);- }- return archived;-};-/*** Stop everything the goal has running, then delete it and its graph.*@@ -210,6 +157,8 @@ export const transitionStatus = async (export const pause = async (ctx: GoalServiceContext, goalId: string) => {const graph = await ctx.requireGraph(goalId);+ // An archived goal is done with (signed off or canceled); pausing would reopen it out of sight.+ assertGoalNotArchived(graph.goal);// A draft never ran; pausing it would let a later resume skip `start`.if (graph.goal.status === 'draft') throw draftNotStarted(goalId);// From here the pause is the person's, so no later measurement lifts it.@@ -236,6 +185,8 @@ export const restart = async (options?: { agentId?: string },): Promise<{ goal: GoalItem; restartedTaskIds: string[] }> => {const graph = await ctx.requireGraph(goalId);+ // Restarting resets Tasks and resumes the goal; an archived one stays put.+ assertGoalNotArchived(graph.goal);const assignment = new GoalAssignmentService(ctx.db, ctx.userId, ctx.workspaceId);if (options?.agentId) await assignment.assertUsableForGoal(graph.goal, options.agentId);@@ -341,6 +292,7 @@ export const resume = async (ctx: GoalServiceContext, goalId: string) => {const model = new GoalRepository(tx, ctx.userId, ctx.workspaceId);const current = await model.lockById(goalId);if (!current) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ assertGoalNotArchived(current);// Only `start` launches a draft: it settles the creating run's planning// turn and checks who may launch it, which a plain status flip skips.if (current.status === 'draft') throw draftNotStarted(goalId);@@ -381,6 +333,10 @@ export const close = async (await ctx.db.transaction(async (db) => {const model = new GoalRepository(db, ctx.userId, ctx.workspaceId);const current = await model.lockById(goalId);+ // An archived goal's status is frozen until it is restored; refuse before+ // interrupting anything. (`updateStatus` refuses it too, should an archive+ // land after this lock is released.)+ if (current) assertGoalNotArchived(current);// Only a goal that can still dispatch needs fencing.if (!current || ['paused', 'achieved', 'failed', 'canceled'].includes(current.status)) return;await model.updateStatus(goalId, 'paused');diff --git a/apps/server/src/services/goal/GoalService/types.ts b/apps/server/src/services/goal/GoalService/types.tsindex 78ce71a5657..bf51d3d9555 100644--- a/apps/server/src/services/goal/GoalService/types.ts+++ b/apps/server/src/services/goal/GoalService/types.ts@@ -59,7 +59,6 @@ import type {updateTitle,} from './editing';import type {- archiveSignedOffTasks,close,deleteGoal,pause,@@ -198,7 +197,6 @@ export interface GoalServiceContext {readonly agentModel: AgentModel;answerClarifications: Bound<typeof answerClarifications>;answerReleaseGate: GoalReleaseReview['answerReleaseGate'];- archiveSignedOffTasks: Bound<typeof archiveSignedOffTasks>;attachTaskDeliverables: Bound<typeof attachTaskDeliverables>;bindTopic: Bound<typeof bindTopic>;readonly briefs: GoalBriefService;diff --git a/apps/server/src/services/goal/archiveGuard.ts b/apps/server/src/services/goal/archiveGuard.tsnew file mode 100644index 00000000000..8157b3d4361--- /dev/null+++ b/apps/server/src/services/goal/archiveGuard.ts@@ -0,0 +1,15 @@+import { TRPCError } from '@trpc/server';++/**+ * An archived goal is hidden from every list, so it must stay put: starting,+ * resuming, restarting or pausing it would reopen work nobody can see. The caller+ * restores it first. Checked under the goal's row lock where the write takes+ * one, so it serializes with the guarded archive UPDATE (`GoalArchiveModel`).+ */+export const assertGoalNotArchived = (goal: { archivedAt?: Date | string | null; id: string }) => {+ if (!goal.archivedAt) return;+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: `Goal is archived; restore it first with lh goal unarchive ${goal.id}`,+ });+};diff --git a/apps/server/src/services/goal/signOffArchive.ts b/apps/server/src/services/goal/signOffArchive.tsdeleted file mode 100644index 2c48136e57e..00000000000--- a/apps/server/src/services/goal/signOffArchive.ts+++ /dev/null@@ -1,26 +0,0 @@-import type { AcceptanceItem } from '@/database/schemas/verify';-import type { LobeChatDatabase } from '@/database/type';-import { GoalService } from '@/server/services/goal';--/**- * A signed-off Goal-level acceptance closes its Goal for good, so the Goal's- * finished Tasks are archived with it (see `GoalService.archiveSignedOffTasks`- * for what qualifies). Called by every path that accepts an acceptance — the- * sign-off actions and a merged pull request. Best-effort: the acceptance is- * already recorded, so a failure here is logged, never thrown.- */-export const archiveSignedOffGoalTasks = async (- db: LobeChatDatabase,- acceptance: Pick<AcceptanceItem, 'subjectId' | 'subjectType' | 'userId' | 'workspaceId'>,-): Promise<void> => {- if (acceptance.subjectType !== 'task') return;- try {- await new GoalService(- db,- acceptance.userId,- acceptance.workspaceId ?? undefined,- ).archiveSignedOffTasks(acceptance.subjectId);- } catch (error) {- console.error('[goal:sign-off:archive-tasks]', error);- }-};diff --git a/apps/server/src/services/goal/start.ts b/apps/server/src/services/goal/start.tsindex e044c7c3250..35c3640d6b3 100644--- a/apps/server/src/services/goal/start.ts+++ b/apps/server/src/services/goal/start.ts@@ -7,6 +7,7 @@ import { GoalGraphModel } from '@/database/models/goalGraph';import { GoalRepository } from '@/database/repositories/goal';import type { LobeChatDatabase } from '@/database/type';+import { assertGoalNotArchived } from './archiveGuard';import { GoalManagerService } from './manager';import {materializeRolloutBatch,@@ -123,6 +124,7 @@ export class GoalStartService {const goalModel = new GoalRepository(db, this.userId, this.workspaceId);const goal = await goalModel.lockById(goalId);if (!goal) return refuse('Goal not found');+ assertGoalNotArchived(goal);if (goal.status !== 'draft')refuse(`Goal is ${goal.status}; only a draft goal can be started`, 'CONFLICT');diff --git a/apps/server/src/services/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.tsindex 334980245e1..b21506726ab 100644--- a/apps/server/src/services/scm/ScmControlService.ts+++ b/apps/server/src/services/scm/ScmControlService.ts@@ -12,7 +12,6 @@ import type { LobeChatDatabase } from '@/database/type';import { appEnv } from '@/envs/app';import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { AiAgentService } from '@/server/services/aiAgent';-import { archiveSignedOffGoalTasks } from '@/server/services/goal/signOffArchive';import { AcceptanceService } from '@/server/services/verify/acceptanceService';import type { GitHubReviewFeedback } from './github/app';@@ -426,8 +425,6 @@ export class ScmControlService {url: row.url,});if (!accepted) return { detail: 'acceptance no longer exists', outcome: 'skipped' };- // A merge signs a Goal-level acceptance off like the owner's own accept does.- await archiveSignedOffGoalTasks(this.db, accepted);return { acceptanceId: accepted.id, outcome: 'accepted' };};diff --git a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts b/apps/server/src/services/scm/__tests__/ScmControlService.test.tsindex 38db082c0ef..0a743dc00e1 100644--- a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts+++ b/apps/server/src/services/scm/__tests__/ScmControlService.test.ts@@ -25,7 +25,6 @@ const serverDB = await getTestDB();const userId = 'scm-control-user';const mocks = vi.hoisted(() => ({- archiveSignedOffGoalTasks: vi.fn(async () => {}),execAgent: vi.fn(),jobLog: vi.fn(),postComment: vi.fn(),@@ -39,9 +38,6 @@ vi.mock('@/server/services/aiAgent', () => ({return { execAgent: mocks.execAgent };}),}));-vi.mock('@/server/services/goal/signOffArchive', () => ({- archiveSignedOffGoalTasks: mocks.archiveSignedOffGoalTasks,-}));vi.mock('@/server/modules/AgentRuntime/redis', () => ({getAgentRuntimeRedisClient: () => ({ set: mocks.redisSet }),}));@@ -157,11 +153,6 @@ describe('ScmControlService — merge', () => {row,});expect(outcome).toEqual({ acceptanceId: acceptance.id, outcome: 'accepted' });- // A merge signs a Goal-level acceptance off, so its Goal's finished Tasks are archived too.- expect(mocks.archiveSignedOffGoalTasks).toHaveBeenCalledWith(- serverDB,- expect.objectContaining({ id: acceptance.id, status: 'accepted' }),- );const [after] = await serverDB.select()diff --git a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.tsindex f1f9e0a24b5..d02abe9d20d 100644--- a/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts+++ b/apps/server/src/services/verify/__tests__/acceptanceTaskLifecycle.test.ts@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({findPolicyById: vi.fn(),findReportByRun: vi.fn(),goalFindByGraphTask: vi.fn(),+ goalLockById: vi.fn(),listByAcceptance: vi.fn(),setDecision: vi.fn(),taskFindById: vi.fn(),@@ -59,7 +60,7 @@ vi.mock('@/database/models/task', () => ({}));vi.mock('@/database/models/goal', () => ({GoalModel: vi.fn(function () {- return { findByGraphTask: mocks.goalFindByGraphTask };+ return { findByGraphTask: mocks.goalFindByGraphTask, lockById: mocks.goalLockById };}),}));vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));@@ -73,7 +74,9 @@ vi.mock('@/server/workflows/expertiseRejection', () => ({ExpertiseRejectionWorkflow: { trigger: mocks.distilRejections },}));-const service = () => new AcceptanceService({} as any, 'user-1');+// A goal-guarded reject runs in a transaction; the mocked models ignore the handle.+const db = { transaction: (run: (tx: unknown) => unknown) => run(db) };+const service = () => new AcceptanceService(db as any, 'user-1');const taskAcceptance = (status: string) => ({id: 'acc-1',@@ -87,6 +90,7 @@ describe('AcceptanceService task lifecycle', () => {vi.clearAllMocks();mocks.findPolicyById.mockImplementation((...args: unknown[]) => mocks.findById(...args));mocks.goalFindByGraphTask.mockResolvedValue(undefined);+ mocks.goalLockById.mockImplementation(async (id: string) => ({ archivedAt: null, id }));mocks.taskResolve.mockResolvedValue({ automationMode: null, id: 'task_1', status: 'running' });// The row read back after the completion write.mocks.taskFindById.mockResolvedValue({ id: 'task_1', status: 'completed' });@@ -346,6 +350,18 @@ describe('AcceptanceService task lifecycle', () => {});});+ it('refuses a Task of a goal found archived under its lock, recording nothing', async () => {+ mocks.goalFindByGraphTask.mockResolvedValue({ archivedAt: null, id: 'goal-1' });+ mocks.goalLockById.mockResolvedValue({ archivedAt: new Date(), id: 'goal-1' });++ await expect(service().reject('acc-1', 'Fix the header')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });+ expect(mocks.setDecision).not.toHaveBeenCalled();+ expect(mocks.updateStatus).not.toHaveBeenCalled();+ expect(mocks.taskUpdateStatusIfCurrent).not.toHaveBeenCalled();+ });+it('moves the completed task back to paused', async () => {await service().reject('acc-1', 'Fix the header');diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.tsindex 7022390936b..1496d75378a 100644--- a/apps/server/src/services/verify/acceptanceService/index.ts+++ b/apps/server/src/services/verify/acceptanceService/index.ts@@ -8,9 +8,11 @@ import type {VerifyRunDecisionDetail,} from '@lobechat/types';import { statusFromRound } from '@lobechat/utils/verify/acceptanceStatus';+import { TRPCError } from '@trpc/server';import debug from 'debug';import { AcceptanceModel } from '@/database/models/acceptance';+import { GoalModel } from '@/database/models/goal';import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';import { VerifyReportModel } from '@/database/models/verifyReport';@@ -555,9 +557,41 @@ export class AcceptanceService {*/reject = async (acceptanceId: string, comment?: string): Promise<AcceptanceItem> => {const acceptance = await requireDecidableAcceptance(this.acceptanceModel, acceptanceId);+ const goal =+ acceptance.subjectType === 'task'+ ? await new GoalModel(this.db, this.userId, this.workspaceId).findByGraphTask(+ acceptance.subjectId,+ )+ : undefined;- const settled = await this.stampDecision(acceptanceId, 'reject', comment);- await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');+ // A rejected Goal Task is reworked by its goal's coordinator; an archived+ // goal stays put, so the rejection would be recorded and then lost. The+ // check and the decision share the goal's row lock, which the archive+ // UPDATE also takes: an archive landing first is seen here and nothing is+ // recorded; one landing after sees a goal whose Task was rejected before it.+ const settled = goal+ ? await this.db.transaction(async (tx) => {+ const locked = await new GoalModel(tx, this.userId, this.workspaceId).lockById(goal.id);+ if (locked?.archivedAt) {+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: `This goal is archived; restore it before requesting changes (lh goal unarchive ${goal.id})`,+ });+ }+ const runId = await this.stampDecision(+ acceptanceId,+ 'reject',+ comment,+ new VerifyRunModel(tx, this.userId, this.workspaceId),+ );+ await new AcceptanceModel(tx, this.userId, this.workspaceId).updateStatus(+ acceptanceId,+ 'rejected',+ );+ return runId;+ })+ : await this.stampDecision(acceptanceId, 'reject', comment);+ if (!goal) await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');notifyAcceptance(acceptanceId, 'session', this.actorUserId);this.distilSettledRound(acceptanceId, settled);@@ -576,8 +610,9 @@ export class AcceptanceService {acceptanceId: string,decision: 'accept' | 'reject',comment?: string,+ runModel: VerifyRunModel = this.runModel,): Promise<string> => {- const runs = await this.runModel.listByAcceptance(acceptanceId);+ const runs = await runModel.listByAcceptance(acceptanceId);const current = runs.at(-1);if (!current) throw new Error('This acceptance has no verification round to decide on');@@ -586,7 +621,7 @@ export class AcceptanceService {decidedBy: this.actorUserId,...(comment ? { comment } : {}),};- await this.runModel.setDecision(current.id, decision, detail);+ await runModel.setDecision(current.id, decision, detail);return current.id;};diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex b725fd2e429..efa3c9b3dbc 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -739,6 +739,12 @@"goalExperiment.unavailableInput": "Referenced work is unavailable","goalList.acceptanceProgress": "{{passed}}/{{total}} passed","goalList.agentRuns": "{{count}} runs",+ "goalList.archive": "Archive",+ "goalList.archiveBlocked": "Sign off or cancel the goal before archiving it",+ "goalList.archiveDenied": "Only the goal creator or a workspace owner can archive it",+ "goalList.archiveFailed": "Failed to archive goal",+ "goalList.archiveSuccess": "Goal archived",+ "goalList.archived": "Archived","goalList.contextMenu.copyConfirm": "Copy","goalList.contextMenu.copyDescription": "Copies the goal, its budget and acceptance criteria as a new draft. Progress, tasks and the agent are not copied; pick an agent there and start it.","goalList.contextMenu.copyFailed": "Failed to copy goal",@@ -764,6 +770,9 @@"goalList.status.waiting": "Waiting","goalList.taskProgress": "{{done}}/{{total}} tasks done","goalList.title": "Goals",+ "goalList.unarchive": "Unarchive",+ "goalList.unarchiveFailed": "Failed to unarchive goal",+ "goalList.unarchiveSuccess": "Goal restored","goalPage.activeGoals": "Open goals","goalPage.agentFilter.all": "All agents","goalPage.agentFilter.title": "Filter by agent",@@ -772,6 +781,7 @@"goalPage.description": "Track what this agent is pursuing and how close each goal is to acceptance.","goalPage.filter.achieved": "Completed","goalPage.filter.all": "All",+ "goalPage.filter.archived": "Archived","goalPage.filter.review": "Needs you","goalPage.filter.running": "In progress","goalPage.filteredEmptyDescription": "Switch to All to see every goal.",@@ -1228,6 +1238,7 @@"goalProcess.signOff.accept": "Sign off","goalProcess.signOff.acceptEffect": "Close the goal as delivered.","goalProcess.signOff.accepted": "Signed off",+ "goalProcess.signOff.archivedBlocked": "Restore this archived goal before requesting changes","goalProcess.signOff.description": "Goal-level acceptance passed. Your sign-off closes the goal.","goalProcess.signOff.islandSubtitle": "is done and waiting for your sign-off","goalProcess.signOff.islandSummary": "Goal-level acceptance passed. Read the delivery report, then sign off or request changes.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex e899dcb27db..f189680f118 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -739,6 +739,12 @@"goalExperiment.unavailableInput": "引用的产物当前不可访问","goalList.acceptanceProgress": "已通过 {{passed}}/{{total}}","goalList.agentRuns": "{{count}} 次运行",+ "goalList.archive": "归档",+ "goalList.archiveBlocked": "签收或取消目标后才能归档",+ "goalList.archiveDenied": "只有目标创建者或工作区所有者可以归档",+ "goalList.archiveFailed": "归档目标失败",+ "goalList.archiveSuccess": "目标已归档",+ "goalList.archived": "已归档","goalList.contextMenu.copyConfirm": "复制","goalList.contextMenu.copyDescription": "将目标及其预算和验收标准复制为一个新的草稿。进度、任务和智能体不会复制,请在目标位置选择智能体后再启动。","goalList.contextMenu.copyFailed": "复制目标失败",@@ -764,6 +770,9 @@"goalList.status.waiting": "等待中","goalList.taskProgress": "{{done}}/{{total}} 项任务完成","goalList.title": "目标",+ "goalList.unarchive": "取消归档",+ "goalList.unarchiveFailed": "取消归档失败",+ "goalList.unarchiveSuccess": "目标已恢复","goalPage.activeGoals": "待处理目标","goalPage.agentFilter.all": "全部 Agent","goalPage.agentFilter.title": "按 Agent 筛选",@@ -772,6 +781,7 @@"goalPage.description": "掌握 Agent 正在追逐什么,以及每个目标距离验收还有多远。","goalPage.filter.achieved": "已完成","goalPage.filter.all": "全部",+ "goalPage.filter.archived": "已归档","goalPage.filter.review": "等你处理","goalPage.filter.running": "进行中","goalPage.filteredEmptyDescription": "切换到“全部”可查看所有目标。",@@ -1228,6 +1238,7 @@"goalProcess.signOff.accept": "签收","goalProcess.signOff.acceptEffect": "目标按已交付结束","goalProcess.signOff.accepted": "已签收",+ "goalProcess.signOff.archivedBlocked": "请先取消归档,再提出修改","goalProcess.signOff.description": "目标验收已通过,你签收后目标正式结束。","goalProcess.signOff.islandSubtitle": "已完成,等你签收","goalProcess.signOff.islandSummary": "目标验收已通过。先看交付报告,再决定签收或提出修改。",diff --git a/packages/database/src/models/__tests__/goalArchive.test.ts b/packages/database/src/models/__tests__/goalArchive.test.tsnew file mode 100644index 00000000000..6cc9bf52359--- /dev/null+++ b/packages/database/src/models/__tests__/goalArchive.test.ts@@ -0,0 +1,206 @@+// @vitest-environment node+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { goalNodes, users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { AcceptanceModel } from '../acceptance';+import { GoalModel } from '../goal';+import { GoalArchivedError, GoalArchiveModel } from '../goalArchive';+import { GoalGraphModel } from '../goalGraph';+import { TaskModel } from '../task';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-archive-user';+const otherUserId = 'goal-archive-other';++const goalModel = new GoalModel(serverDB, userId);+const graphModel = new GoalGraphModel(serverDB, userId);+const archiveModel = new GoalArchiveModel(serverDB, userId);++/** A goal with a graph, so `list` shows it. */+const createListedGoal = async (title: string, status: string) => {+ const goal = await goalModel.create({+ status: status as never,+ subjectType: 'standalone',+ title,+ });+ await graphModel.createNode(goal.id, { kind: 'problem', title });+ return goal;+};++/** Give the goal its Goal-level acceptance Task, with that acceptance in `status`. */+const signOff = async (goalId: string, status: 'accepted' | 'delivered') => {+ const task = await new TaskModel(serverDB, userId).create({ instruction: 'Accept the goal' });+ const node = await graphModel.createNode(goalId, {+ kind: 'task',+ title: GOAL_ACCEPTANCE_TASK_TITLE,+ });+ await serverDB.update(goalNodes).set({ taskId: task.id }).where(eq(goalNodes.id, node!.id));+ const acceptanceModel = new AcceptanceModel(serverDB, userId);+ const acceptance = await acceptanceModel.ensureForSubject('task', task.id);+ await acceptanceModel.updateStatus(acceptance.id, status);+};++beforeEach(async () => {+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(users).where(eq(users.id, otherUserId));+});++describe('GoalArchiveModel', () => {+ it('archives a canceled goal', async () => {+ const goal = await createListedGoal('Dropped', 'canceled');++ const archived = await archiveModel.archive(goal.id);++ expect(archived?.archivedAt).toBeInstanceOf(Date);+ expect(archived?.status).toBe('canceled');+ });++ it('archives an achieved goal once its owner signed it off', async () => {+ const goal = await createListedGoal('Delivered', 'achieved');+ await signOff(goal.id, 'accepted');++ expect((await archiveModel.archive(goal.id))?.archivedAt).toBeInstanceOf(Date);+ });++ it('refuses an achieved goal whose sign-off is still open', async () => {+ const goal = await createListedGoal('Awaiting sign-off', 'achieved');+ await signOff(goal.id, 'delivered');++ expect(await archiveModel.archive(goal.id)).toBeNull();+ expect((await goalModel.findById(goal.id))?.archivedAt).toBeNull();+ });++ it.each(['draft', 'planning', 'running', 'verifying', 'review', 'paused', 'failed'])(+ 'refuses a %s goal',+ async (status) => {+ const goal = await createListedGoal('Not done with', status);+ await signOff(goal.id, 'accepted');++ expect(await archiveModel.archive(goal.id)).toBeNull();+ expect((await goalModel.findById(goal.id))?.archivedAt).toBeNull();+ },+ );++ it('keeps the original archive time when archived again', async () => {+ const goal = await createListedGoal('Dropped', 'canceled');+ const first = await archiveModel.archive(goal.id);++ const second = await archiveModel.archive(goal.id);++ expect(second?.archivedAt?.getTime()).toBe(first?.archivedAt?.getTime());+ });++ it('does not touch another user’s goal', async () => {+ const theirs = await new GoalModel(serverDB, otherUserId).create({+ status: 'canceled',+ title: 'Theirs',+ });++ expect(await archiveModel.archive(theirs.id)).toBeNull();+ expect(await archiveModel.unarchive(theirs.id)).toBeNull();+ });++ it('unarchives a goal', async () => {+ const goal = await createListedGoal('Dropped', 'canceled');+ await archiveModel.archive(goal.id);++ const restored = await archiveModel.unarchive(goal.id);++ expect(restored?.archivedAt).toBeNull();+ });+});++describe('GoalModel.updateStatus on an archived goal', () => {+ it('refuses to put it back in motion, whichever path asks', async () => {+ const goal = await createListedGoal('Put away', 'canceled');+ await archiveModel.archive(goal.id);++ for (const status of ['running', 'paused', 'planning', 'review', 'verifying'] as const) {+ await expect(goalModel.updateStatus(goal.id, status)).rejects.toBeInstanceOf(+ GoalArchivedError,+ );+ }+ expect((await goalModel.findById(goal.id))?.status).toBe('canceled');+ });++ it('freezes it in its archived status, ended ones included', async () => {+ const goal = await createListedGoal('Put away', 'canceled');+ await archiveModel.archive(goal.id);++ // A stale "mark achieved" would leave a hidden goal achieved but never signed off.+ for (const status of ['achieved', 'failed'] as const) {+ await expect(goalModel.updateStatus(goal.id, status)).rejects.toBeInstanceOf(+ GoalArchivedError,+ );+ }+ // Writing the status it already has is not a change.+ expect((await goalModel.updateStatus(goal.id, 'canceled'))?.status).toBe('canceled');+ expect((await goalModel.findById(goal.id))?.status).toBe('canceled');+ });++ it('moves an unarchived goal as before', async () => {+ const goal = await createListedGoal('Live', 'achieved');++ expect((await goalModel.updateStatus(goal.id, 'running'))?.status).toBe('running');+ });+});++describe('GoalModel.list archive filter', () => {+ it('hides archived goals by default and lists only them when asked', async () => {+ const kept = await createListedGoal('Kept', 'canceled');+ const putAway = await createListedGoal('Put away', 'canceled');+ await archiveModel.archive(putAway.id);++ const visible = await goalModel.list();+ expect(visible.total).toBe(1);+ expect(visible.goals.map((item) => item.goal.id)).toEqual([kept.id]);++ const archived = await goalModel.list({ archived: true });+ expect(archived.total).toBe(1);+ expect(archived.goals.map((item) => item.goal.id)).toEqual([putAway.id]);+ expect(archived.goals[0].goal.archivedAt).toBeInstanceOf(Date);+ });++ it('combines the archive filter with a status filter', async () => {+ const achieved = await createListedGoal('Achieved', 'achieved');+ await signOff(achieved.id, 'accepted');+ const canceled = await createListedGoal('Canceled', 'canceled');+ await archiveModel.archive(achieved.id);+ await archiveModel.archive(canceled.id);++ const { goals: rows } = await goalModel.list({ archived: true, statuses: ['achieved'] });++ expect(rows.map((item) => item.goal.id)).toEqual([achieved.id]);+ });++ it('lists a restored goal again', async () => {+ const goal = await createListedGoal('Back', 'canceled');+ await archiveModel.archive(goal.id);+ await archiveModel.unarchive(goal.id);++ expect((await goalModel.list()).goals.map((item) => item.goal.id)).toEqual([goal.id]);+ expect((await goalModel.list({ archived: true })).total).toBe(0);+ });+});++describe('GoalModel.list signedOff', () => {+ it('marks an achieved goal signed off only once its acceptance is accepted', async () => {+ const signed = await createListedGoal('Signed', 'achieved');+ await signOff(signed.id, 'accepted');+ const awaiting = await createListedGoal('Awaiting', 'achieved');+ await signOff(awaiting.id, 'delivered');++ const { goals: rows } = await goalModel.list();+ const byId = Object.fromEntries(rows.map((item) => [item.goal.id, item.signedOff]));++ expect(byId).toEqual({ [awaiting.id]: false, [signed.id]: true });+ });+});diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex ed02e4ef767..b5743bc87fa 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -10,7 +10,7 @@ import type {GoalSupervisionState,GoalUnderstanding,} from '@lobechat/types';-import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, isNull, ne, notInArray, or, sql } from 'drizzle-orm';import { alias } from 'drizzle-orm/pg-core';import type { GoalItem, NewGoal } from '../schemas/goal';@@ -20,6 +20,7 @@ import { tasks, taskTopics } from '../schemas/task';import { topics } from '../schemas/topic';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { GoalArchivedError, goalSignedOffSql } from './goalArchive';/** States after which a goal's loop no longer advances. */const TERMINAL_GOAL_STATUSES = new Set<GoalStatus>(['achieved', 'failed', 'canceled']);@@ -340,7 +341,15 @@ export class GoalModel {return row ? next : undefined;};- update = async (id: string, value: Partial<Omit<GoalItem, 'id' | 'userId'>>) => {+ update = async (+ id: string,+ value: Partial<Omit<GoalItem, 'id' | 'userId'>>,+ /**+ * Match an archived goal only when its status already is this one — an+ * archived goal's status is frozen until it is restored (see `updateStatus`).+ */+ options: { archivedKeepsStatus?: GoalStatus } = {},+ ) => {// Policy editors may carry a pre-claim or pre-release snapshot. Runtime// ownership always comes from the current row, never that snapshot, and// policy edits cannot replace the concurrently written incident ledger.@@ -375,7 +384,15 @@ export class GoalModel {: {}),updatedAt: new Date(),})- .where(and(eq(goals.id, id), this.ownership()))+ .where(+ and(+ eq(goals.id, id),+ this.ownership(),+ options.archivedKeepsStatus+ ? or(isNull(goals.archivedAt), eq(goals.status, options.archivedKeepsStatus))+ : undefined,+ ),+ ).returning();return row as GoalItem | undefined;};@@ -459,11 +476,24 @@ export class GoalModel {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,- });+ // Every status write — resume, pause, close, a sign-off sent back, the+ // coordinator — lands here, so this is where an archived goal is kept put:+ // its status is frozen until it is restored, which keeps the archive's own+ // rule (signed off or canceled) true while it is hidden. The check is part+ // of the UPDATE, which serializes with the guarded archive write.+ const row = await this.update(+ id,+ {+ completedAt: TERMINAL_GOAL_STATUSES.has(status)+ ? (existing.completedAt ?? new Date())+ : null,+ startedAt: existing.startedAt ?? (status === 'running' ? new Date() : null),+ status,+ },+ { archivedKeepsStatus: status },+ );+ if (!row && (await this.findById(id))?.archivedAt) throw new GoalArchivedError(id);+ return row;};/**@@ -492,6 +522,8 @@ export class GoalModel {// Only a goal parked on its questions asks them; one the user paused// or ended keeps its open questions without nagging about them.notInArray(goals.status, ['paused', 'achieved', 'failed', 'canceled']),+ // An archived goal was put away; its open questions stay with it.+ isNull(goals.archivedAt),eq(goalNodeDecisions.status, 'pending'),eq(goalNodes.title, GOAL_CLARIFICATION_TITLE),),@@ -549,6 +581,7 @@ export class GoalModel {sql`${goals.config} ->> 'pausedBy' in ('release_review', 'pattern_break')`,),),+ isNull(goals.archivedAt),eq(goalNodeDecisions.status, 'pending'),eq(goalNodeDecisions.authority, 'user'),// In a workspace every member can see the goal, but a gate is asked@@ -634,6 +667,11 @@ export class GoalModel {list = async (options: {agentId?: string;+ /**+ * Archived goals are put away by the user and left out of every list+ * unless asked for: `true` lists only them (the list page's Archived tab).+ */+ archived?: boolean;limit?: number;offset?: number;projectId?: string;@@ -642,13 +680,17 @@ export class GoalModel {topicId?: string;} = {},): Promise<{ goals: GoalListItem[]; total: number }> => {- const { agentId, limit = 50, offset = 0, projectId, statuses, topicId } = options;+ const { agentId, archived, limit = 50, offset = 0, projectId, statuses, topicId } = options;// Only goals that actually have a graph. Rows created by the earlier// task-carried flow have no `goal_nodes`, so they would render as a// zero-task goal page that can never advance; they stay out of the list// until something backfills them into graphs.- const conditions = [this.ownership(), GoalModel.hasGraphSql];+ const conditions = [+ this.ownership(),+ GoalModel.hasGraphSql,+ archived ? isNotNull(goals.archivedAt) : isNull(goals.archivedAt),+ ];if (agentId) conditions.push(eq(goals.agentId, agentId));if (projectId) conditions.push(eq(goals.projectId, projectId));if (statuses && statuses.length > 0) conditions.push(inArray(goals.status, statuses));@@ -671,7 +713,7 @@ export class GoalModel {.offset(offset);const goalIds = rows.map((goal) => goal.id);- const [nodeRows, decisionRows, runStats] = await Promise.all([+ const [nodeRows, decisionRows, runStats, signedOffRows] = await Promise.all([this.db.select({goalId: goalNodes.goalId,@@ -689,7 +731,13 @@ export class GoalModel {.where(and(inArray(goalNodes.goalId, goalIds), eq(goalNodeDecisions.status, 'pending'))).groupBy(goalNodes.goalId),this.graphTaskRunStats(goalIds),+ // Archiving needs the owner's sign-off, which the row alone cannot say.+ this.db+ .select({ id: goals.id })+ .from(goals)+ .where(and(inArray(goals.id, goalIds), eq(goals.status, 'achieved'), goalSignedOffSql)),]);+ const signedOff = new Set(signedOffRows.map((row) => row.id));const stats = new Map<string, { findingCount: number; taskDone: number; taskTotal: number }>();for (const row of nodeRows) {@@ -711,6 +759,7 @@ export class GoalModel {findingCount: counts.findingCount,goal,pendingDecisions: pendingByGoal.get(goal.id) ?? 0,+ signedOff: signedOff.has(goal.id),taskDone: counts.taskDone,taskTotal: counts.taskTotal,totalRunCost: run.totalRunCost,@@ -783,6 +832,8 @@ export interface GoalListItem {goal: GoalItem;/** Decision gates waiting on a human right now. */pendingDecisions: number;+ /** Achieved and accepted by its owner (its Goal-level acceptance is `accepted`). */+ signedOff: boolean;/** Task nodes in a terminal status (resolved / rejected / retired). */taskDone: number;taskTotal: number;diff --git a/packages/database/src/models/goalArchive.ts b/packages/database/src/models/goalArchive.tsnew file mode 100644index 00000000000..1704f0abe85--- /dev/null+++ b/packages/database/src/models/goalArchive.ts@@ -0,0 +1,89 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { and, eq, or, sql } from 'drizzle-orm';++import { goals } from '../schemas/goal';+import { goalNodes } from '../schemas/goalGraph';+import { acceptances } from '../schemas/verify';+import type { LobeChatDatabase } from '../type';+import { buildWorkspaceWhere } from '../utils/workspace';++/**+ * Thrown when a write would change an archived goal's status. Archived goals+ * are hidden from every list, so they stay put until restored.+ */+export class GoalArchivedError extends Error {+ readonly goalId: string;++ constructor(goalId: string) {+ super(`Goal is archived; restore it first with lh goal unarchive ${goalId}`);+ this.name = 'GoalArchivedError';+ this.goalId = goalId;+ }+}++/**+ * Whether the owner signed the goal off: its Goal-level acceptance Task has an+ * accepted acceptance. Correlated on `goals.id`, so it reads inside any query+ * over `goals`.+ */+export const goalSignedOffSql = sql<boolean>`EXISTS (+ SELECT 1 FROM ${goalNodes}+ JOIN ${acceptances}+ ON ${acceptances.subjectType} = 'task' AND ${acceptances.subjectId} = ${goalNodes.taskId}+ WHERE ${goalNodes.goalId} = ${goals.id}+ AND ${goalNodes.kind} = 'task'+ AND ${goalNodes.title} = ${GOAL_ACCEPTANCE_TASK_TITLE}+ AND ${acceptances.status} = 'accepted'+)`;++/**+ * Archive writes for `goals`, kept out of `GoalModel` the way `TaskArchiveModel`+ * is: the "signed off or canceled" check is part of the UPDATE that sets+ * `archived_at`, so a resume or start racing it either lands first (and the+ * archive matches no row) or sees the archive under the row lock and refuses.+ */+export class GoalArchiveModel {+ 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);++ /**+ * Archive a goal that is signed off or canceled (`isGoalArchiveBlocked`).+ * Returns null when the goal is missing or not done with yet; an already+ * archived goal keeps its original `archived_at`. Only the `goals` row:+ * `GoalArchiveRepository` archives its Tasks with it.+ */+ async archive(id: string) {+ const [goal] = await this.db+ .update(goals)+ .set({ archivedAt: sql`COALESCE(${goals.archivedAt}, now())`, updatedAt: new Date() })+ .where(+ and(+ eq(goals.id, id),+ this.ownership(),+ or(eq(goals.status, 'canceled'), and(eq(goals.status, 'achieved'), goalSignedOffSql)),+ ),+ )+ .returning();+ return goal ?? null;+ }++ /** Restore an archived goal. Always allowed: it never hides work. */+ async unarchive(id: string) {+ const [goal] = await this.db+ .update(goals)+ .set({ archivedAt: null, updatedAt: new Date() })+ .where(and(eq(goals.id, id), this.ownership()))+ .returning();+ return goal ?? null;+ }+}diff --git a/packages/database/src/models/taskArchive.ts b/packages/database/src/models/taskArchive.tsindex ebeec89b8eb..2ac9d090b2e 100644--- a/packages/database/src/models/taskArchive.ts+++ b/packages/database/src/models/taskArchive.ts@@ -1,4 +1,4 @@-import { and, inArray, ne, sql } from 'drizzle-orm';+import { and, eq, inArray, ne, type SQL, sql } from 'drizzle-orm';import { tasks } from '../schemas/task';import type { LobeChatDatabase } from '../type';@@ -51,11 +51,21 @@ export class TaskArchiveModel {* {@link archive} for many tasks in one guarded statement. Returns only the* rows that were archived; a missing or blocked task is simply absent.*/- async archiveMany(ids: string[], options: { onlyStatuses?: string[] } = {}) {+ async archiveMany(+ ids: string[],+ options: {+ /** The archive time to stamp instead of now — a goal archiving its Tasks shares its own. */+ at?: SQL;+ onlyStatuses?: string[];+ } = {},+ ) {if (ids.length === 0) return [];return this.db.update(tasks)- .set({ archivedAt: sql`COALESCE(${tasks.archivedAt}, now())`, updatedAt: new Date() })+ .set({+ archivedAt: sql`COALESCE(${tasks.archivedAt}, ${options.at ?? sql`now()`})`,+ updatedAt: new Date(),+ }).where(and(inArray(tasks.id, ids),@@ -76,13 +86,23 @@ export class TaskArchiveModel {return task ?? null;}- /** {@link unarchive} for many tasks in one statement. */- async unarchiveMany(ids: string[]) {+ /**+ * {@link unarchive} for many tasks in one statement. `onlyArchivedAt` restores+ * only the Tasks stamped with that archive time — the ones a goal archived+ * with itself — and leaves any archived on their own alone.+ */+ async unarchiveMany(ids: string[], options: { onlyArchivedAt?: SQL } = {}) {if (ids.length === 0) return [];return this.db.update(tasks).set({ archivedAt: null, updatedAt: new Date() })- .where(and(inArray(tasks.id, ids), this.ownership()))+ .where(+ and(+ inArray(tasks.id, ids),+ this.ownership(),+ options.onlyArchivedAt ? eq(tasks.archivedAt, options.onlyArchivedAt) : undefined,+ ),+ ).returning();}}diff --git a/packages/database/src/repositories/goalArchive/index.ts b/packages/database/src/repositories/goalArchive/index.tsnew file mode 100644index 00000000000..f2f6605c0ca--- /dev/null+++ b/packages/database/src/repositories/goalArchive/index.ts@@ -0,0 +1,71 @@+import { and, eq, isNotNull, sql } from 'drizzle-orm';++import { GoalModel } from '../../models/goal';+import { GoalArchiveModel } from '../../models/goalArchive';+import { TaskArchiveModel } from '../../models/taskArchive';+import { goals } from '../../schemas/goal';+import { goalNodes } from '../../schemas/goalGraph';+import type { LobeChatDatabase } from '../../type';++/**+ * A goal and the Tasks its graph dispatched are put away and brought back+ * together. Both directions run in one transaction and lock the goal row+ * before any Task, so concurrent archive / unarchive calls queue on the goal+ * instead of deadlocking on each other's rows.+ */+export class GoalArchiveRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ /** The Tasks the goal's graph dispatched. */+ private graphTaskIds = async (db: LobeChatDatabase, goalId: string) => {+ const rows = await db+ .selectDistinct({ taskId: goalNodes.taskId })+ .from(goalNodes)+ .where(+ and(eq(goalNodes.goalId, goalId), eq(goalNodes.kind, 'task'), isNotNull(goalNodes.taskId)),+ );+ return rows.flatMap((row) => (row.taskId ? [row.taskId] : []));+ };++ /** The goal's own archive time, read in SQL so its Tasks share it to the microsecond. */+ private goalArchivedAt = (goalId: string) =>+ sql`(SELECT ${goals.archivedAt} FROM ${goals} WHERE ${goals.id} = ${goalId})`;++ /**+ * Archive a signed-off or canceled goal and its Tasks. The goal's UPDATE+ * takes its row lock first. The Tasks go through the guarded task archive,+ * so one still running or with a live schedule / heartbeat stays where its+ * owner can see it, and they carry the goal's own archive time, which is how+ * {@link unarchive} tells them from Tasks archived on their own. Returns null+ * when the goal is missing or not done with yet.+ */+ archive = async (id: string) =>+ this.db.transaction(async (tx) => {+ const goal = await new GoalArchiveModel(tx, this.userId, this.workspaceId).archive(id);+ if (!goal) return null;+ await new TaskArchiveModel(tx, this.userId, this.workspaceId).archiveMany(+ await this.graphTaskIds(tx, id),+ { at: this.goalArchivedAt(id) },+ );+ return goal;+ });++ /**+ * Restore a goal and the Tasks archived with it; a Task archived on its own+ * stays archived. Locks the goal row first, the same order as {@link archive}.+ */+ unarchive = async (id: string) =>+ this.db.transaction(async (tx) => {+ if (!(await new GoalModel(tx, this.userId, this.workspaceId).lockById(id))) return null;+ // Before the goal's own stamp is cleared — it is what names its Tasks.+ await new TaskArchiveModel(tx, this.userId, this.workspaceId).unarchiveMany(+ await this.graphTaskIds(tx, id),+ { onlyArchivedAt: this.goalArchivedAt(id) },+ );+ return new GoalArchiveModel(tx, this.userId, this.workspaceId).unarchive(id);+ });+}diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 4f1c791c8b9..2717496b2f8 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2411,6 +2411,12 @@ export default {'goalEmpty.title': 'Chase goals without limits','goalList.acceptanceProgress': '{{passed}}/{{total}} passed','goalList.agentRuns': '{{count}} runs',+ 'goalList.archive': 'Archive',+ 'goalList.archiveBlocked': 'Sign off or cancel the goal before archiving it',+ 'goalList.archiveDenied': 'Only the goal creator or a workspace owner can archive it',+ 'goalList.archiveFailed': 'Failed to archive goal',+ 'goalList.archiveSuccess': 'Goal archived',+ 'goalList.archived': 'Archived','goalList.contextMenu.copyConfirm': 'Copy','goalList.contextMenu.copyDescription':'Copies the goal, its budget and acceptance criteria as a new draft. Progress, tasks and the agent are not copied; pick an agent there and start it.',@@ -2459,6 +2465,9 @@ export default {'goalTask.stage.verifying': 'Accept','goalTask.step.queued': 'Not started','goalList.title': 'Goals',+ 'goalList.unarchive': 'Unarchive',+ 'goalList.unarchiveFailed': 'Failed to unarchive goal',+ 'goalList.unarchiveSuccess': 'Goal restored','goalDetail.acceptance': 'Acceptance checks','goalDetail.agentManagedByOwner':"Only the goal's creator or a Workspace admin can change its agents",@@ -2757,6 +2766,7 @@ export default {'Fork a fresh recipe for the units that broke; the rest of the batch continues once the new gate passes.','goalProcess.decision.effect.releaseBatch':'Release the next wave on the current recipe. Each later wave goes to the main Agent, which releases it or brings it back to you.',+ 'goalProcess.signOff.archivedBlocked': 'Restore this archived goal before requesting changes','goalProcess.signOff.islandSubtitle': 'is done and waiting for your sign-off','goalProcess.signOff.islandSummary':'Goal-level acceptance passed. Read the delivery report, then sign off or request changes.',@@ -3076,6 +3086,7 @@ export default {'goalPage.filteredEmptyTitle': 'No goals in this view','goalPage.filter.achieved': 'Completed','goalPage.filter.all': 'All',+ 'goalPage.filter.archived': 'Archived','goalPage.filter.review': 'Needs you','goalPage.filter.running': 'In progress','goalPage.loadingProgress': 'Loading acceptance progress…',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 3f01ce10874..6f069e6ee9c 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -543,6 +543,8 @@ export type GoalCreateConfig = Omit<*/export interface GoalItem {agentId: string | null;+ /** Set when the user archives the goal; archived goals are hidden from lists by default. */+ archivedAt?: Date | null;completedAt: Date | null;config: GoalConfig | null;createdAt: Date;diff --git a/packages/types/src/goalArchive.test.ts b/packages/types/src/goalArchive.test.tsnew file mode 100644index 00000000000..eb2d20dd82c--- /dev/null+++ b/packages/types/src/goalArchive.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { isGoalArchiveBlocked } from './goalArchive';++describe('isGoalArchiveBlocked', () => {+ it('lets a signed-off or canceled goal be archived', () => {+ expect(isGoalArchiveBlocked({ signedOff: true, status: 'achieved' })).toBe(false);+ expect(isGoalArchiveBlocked({ status: 'canceled' })).toBe(false);+ });++ it('blocks an achieved goal still waiting on its sign-off', () => {+ expect(isGoalArchiveBlocked({ signedOff: false, status: 'achieved' })).toBe(true);+ expect(isGoalArchiveBlocked({ status: 'achieved' })).toBe(true);+ });++ it('blocks a failed, draft or open goal', () => {+ for (const status of [+ 'failed',+ 'draft',+ 'planning',+ 'running',+ 'verifying',+ 'review',+ 'paused',+ ])+ expect(isGoalArchiveBlocked({ signedOff: true, status })).toBe(true);+ });+});diff --git a/packages/types/src/goalArchive.ts b/packages/types/src/goalArchive.tsnew file mode 100644index 00000000000..e6b8b5f5d44--- /dev/null+++ b/packages/types/src/goalArchive.ts@@ -0,0 +1,20 @@+import type { GoalStatus } from './goal';++/** What decides whether a goal may be archived. */+export interface GoalArchiveGuardInput {+ /** Its Goal-level acceptance was accepted by the owner. */+ signedOff?: boolean;+ status: GoalStatus | string;+}++/**+ * A goal may be archived once it is truly done with: achieved and signed off+ * by its owner, or canceled. Anything else still has a decision left — an+ * achieved goal waits on its sign-off (and the owner may still send it back),+ * a failed one on a retry or a continuation, and an open one can move on its+ * own — so hiding it from every list would leave that decision out of sight.+ *+ * `GoalArchiveModel` applies the same rule inside its UPDATE.+ */+export const isGoalArchiveBlocked = ({ signedOff, status }: GoalArchiveGuardInput): boolean =>+ !(status === 'canceled' || (status === 'achieved' && !!signedOff));diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 6e3d7d886bd..9238e187de1 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -40,6 +40,7 @@ export * from './followUpAction';export * from './ftsSearch';export * from './generation';export * from './goal';+export * from './goalArchive';export * from './goalReport';export * from './goalRetro';export * from './goalRollout';diff --git a/src/features/AgentGoals/AgentGoalsPage.tsx b/src/features/AgentGoals/AgentGoalsPage.tsxindex 43ad887881c..5368fa7c044 100644--- a/src/features/AgentGoals/AgentGoalsPage.tsx+++ b/src/features/AgentGoals/AgentGoalsPage.tsx@@ -150,6 +150,16 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {isGlobal ? 'all' : 'review',isGlobal ? cacheScope : undefined,);+ // Archived goals are left out of `all`, so a scope whose every goal was put+ // away reads as empty. Ask the Archived tab of the same scope the empty check+ // reads, but only then: the onboarding state would otherwise hide the tab the+ // goals went to.+ const archivedProbe = {+ agentId: isGlobal ? undefined : agentId,+ filter: 'archived' as const,+ globalScope: isGlobal ? cacheScope : undefined,+ projectId,+ };const listView = useGoalStore(goalSelectors.goalListView(scopeId));const allGoalsView = useGoalStore(goalSelectors.goalListView(allGoalsScopeId));const tabView = useGoalStore(@@ -163,14 +173,45 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {goalSelectors.goalListView(goalListKey({ agentId, filter: 'review', projectId })),);const goals = useMemo(() => listView?.goals ?? [], [listView]);- const agentFilterOptions = useMemo(- () => (isGlobal ? goalAgentFilterOptions(allGoalsView?.goals ?? []) : []),- [allGoalsView, isGlobal],- );// Whether the scope has any goal at all — on the cross-agent page that is// every agent's list, so narrowing to one agent shows the filtered-empty// state rather than the first-goal onboarding.- const hasNoGoals = (isGlobal ? (allGoalsView?.goals.length ?? 0) : goals.length) === 0;+ const isScopeEmpty =+ (isGlobal ? (allGoalsView?.goals.length ?? 0) : goals.length) === 0 && !isLoading;+ // The cross-agent Archived tab also lists its agent options from the scope's+ // archived goals: `all` leaves them out, so an agent whose every goal was+ // archived would otherwise be missing from the picker of the tab holding them.+ const readsArchivedScope = isScopeEmpty || (isGlobal && filter === 'archived');+ const archivedSync = useFetchGoals(+ readsArchivedScope ? archivedProbe.agentId : undefined,+ readsArchivedScope ? archivedProbe.projectId : undefined,+ 'archived',+ readsArchivedScope ? archivedProbe.globalScope : undefined,+ );+ const archivedView = useGoalStore(goalSelectors.goalListView(goalListKey(archivedProbe)));+ const agentFilterOptions = useMemo(+ () =>+ isGlobal+ ? goalAgentFilterOptions((filter === 'archived' ? archivedView : allGoalsView)?.goals ?? [])+ : [],+ [allGoalsView, archivedView, filter, isGlobal],+ );+ // Onboarding only once the probe has answered "nothing archived either":+ // while it is in flight the page holds its skeleton, and a failed probe keeps+ // the tabs (the Archived tab then reads and reports its own failure) rather+ // than a first-goal screen that would hide them.+ // A persisted empty projection is not an answer either: the last live goal+ // may have been archived elsewhere since, so an empty hydrated row waits for+ // the revalidation in flight.+ const isArchivedProbePending =+ isScopeEmpty &&+ !archivedSync.error &&+ (archivedView === undefined || (archivedView.goals.length === 0 && archivedSync.isValidating));+ const hasNoGoals =+ isScopeEmpty &&+ !isArchivedProbePending &&+ archivedView !== undefined &&+ archivedView.goals.length === 0;const summary = useMemo(() => {const total = listView?.total ?? goals.length;// An aggregate that has not answered is unknown, not zero. Falling back to@@ -250,7 +291,7 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {paddingInline={16}wrapperStyle={{ flex: 1, overflowY: 'auto' }}>- {isLoading ? (+ {isLoading || isArchivedProbePending ? (<GoalSkeleton chrome={'body'} />) : error && listView === undefined ? (// Only a read that left nothing to show becomes the page: a failed@@ -354,6 +395,10 @@ const AgentGoalsPage = memo<AgentGoalsPageProps>(({ agentId, projectId }) => {label: t('goalPage.filter.achieved'),value: 'achieved',},+ {+ label: t('goalPage.filter.archived'),+ value: 'archived',+ },]}onChange={(value) => setFilter(value as GoalListFilter)}/>diff --git a/src/features/AgentGoals/GoalArchivedMark.tsx b/src/features/AgentGoals/GoalArchivedMark.tsxnew file mode 100644index 00000000000..5d4b1aa42e8--- /dev/null+++ b/src/features/AgentGoals/GoalArchivedMark.tsx@@ -0,0 +1,29 @@+import { cssVar, Icon, Tooltip } from '@lobehub/ui';+import { ArchiveIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++interface GoalArchivedMarkProps {+ goal: { archivedAt?: Date | string | null };+}++/** An archive box next to an archived goal's title, like an archived task row. */+const GoalArchivedMark = memo<GoalArchivedMarkProps>(({ goal }) => {+ const { t } = useTranslation('chat');+ if (!goal.archivedAt) return null;++ return (+ <Tooltip title={t('goalList.archived')}>+ <Icon+ color={cssVar.colorTextDescription}+ icon={ArchiveIcon}+ size={14}+ style={{ flex: 'none' }}+ />+ </Tooltip>+ );+});++GoalArchivedMark.displayName = 'GoalArchivedMark';++export default GoalArchivedMark;diff --git a/src/features/AgentGoals/GoalCardItem.tsx b/src/features/AgentGoals/GoalCardItem.tsxindex 94031a9df7f..90d6b987084 100644--- a/src/features/AgentGoals/GoalCardItem.tsx+++ b/src/features/AgentGoals/GoalCardItem.tsx@@ -8,6 +8,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import GoalAgentLabel from './GoalAgentLabel';+import GoalArchivedMark from './GoalArchivedMark';import GoalItemMoreButton from './GoalItemMoreButton';import { goalItemPath } from './goalItemPath';import GoalPrivateMark from './GoalPrivateMark';@@ -50,6 +51,7 @@ export const GoalCardItem = memo<GoalItemProps>(({ globalScopeId, goal: item, prgoal,projectId,routeAgentId: aid,+ signedOff: item.signedOff,});const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {if (event.key !== 'Enter' && event.key !== ' ') return;@@ -78,6 +80,7 @@ export const GoalCardItem = memo<GoalItemProps>(({ globalScopeId, goal: item, pr{goal.title}</Text><GoalPrivateMark goal={goal} />+ <GoalArchivedMark goal={goal} /></Flexbox>{goal.requirement && goal.requirement !== goal.title && (<Text ellipsis fontSize={12} type={'secondary'}>diff --git a/src/features/AgentGoals/GoalDetailActions.tsx b/src/features/AgentGoals/GoalDetailActions.tsxindex c2961652b66..88be8ec96f5 100644--- a/src/features/AgentGoals/GoalDetailActions.tsx+++ b/src/features/AgentGoals/GoalDetailActions.tsx@@ -5,11 +5,13 @@ import { useTranslation } from 'react-i18next';import { goalSelectors, useGoalStore } from '@/store/goal';+import { isGoalSnapshotSignedOff } from './goalSignedOff';import { useGoalMenuItems } from './useGoalMenuItems';interface GoalDetailActionsProps {/** Absent for a goal with no responsible agent — e.g. one created from a project. */agentId?: string;+ archivedAt?: Date | string | null;goalId: string;/** Moves to the in-place title editor instead of opening the rename dialog. */onRename?: () => void;@@ -17,17 +19,22 @@ interface GoalDetailActionsProps {}const GoalDetailActions = memo<GoalDetailActionsProps>(- ({ agentId, goalId, onRename, projectId }) => {+ ({ agentId, archivedAt, goalId, onRename, projectId }) => {const { t } = useTranslation('chat');const status = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.status);const creatorUserId = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.userId);const title = useGoalStore((s) => goalSelectors.goalGraph(goalId)(s)?.goal.title);+ const signedOff = useGoalStore((s) =>+ isGoalSnapshotSignedOff(goalSelectors.goalGraph(goalId)(s)),+ );const items = useGoalMenuItems({agentId,+ archivedAt,creatorUserId,goalId,onRename,projectId,+ signedOff,status,title,});diff --git a/src/features/AgentGoals/GoalDetailPage.tsx b/src/features/AgentGoals/GoalDetailPage.tsxindex 151f14e1abb..dfa9fdb424a 100644--- a/src/features/AgentGoals/GoalDetailPage.tsx+++ b/src/features/AgentGoals/GoalDetailPage.tsx@@ -1,7 +1,7 @@'use client';-import { Button, createStaticStyles, Flexbox, Text, toast } from '@lobehub/ui';-import { PauseIcon, PlayIcon } from 'lucide-react';+import { Button, createStaticStyles, Flexbox, Tag, Text, toast } from '@lobehub/ui';+import { ArchiveIcon, ArchiveRestoreIcon, PauseIcon, PlayIcon } from 'lucide-react';import { memo, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link } from 'react-router';@@ -82,6 +82,8 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {const pauseGoal = useGoalStore((s) => s.pauseGoal);const resumeGoal = useGoalStore((s) => s.resumeGoal);const startGoal = useGoalStore((s) => s.startGoal);+ const archiveGoal = useGoalStore((s) => s.archiveGoal);+ const [restoring, setRestoring] = useState(false);// The server lets only a draft's creator or a workspace owner launch it.const canStart = useResourceManageable(snapshot?.goal.userId);@@ -288,6 +290,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {be deletable, and this menu is the only place that can do it. */}<GoalDetailActionsagentId={agentId}+ archivedAt={goal.archivedAt ?? null}goalId={goal.id}projectId={goal.projectId}onRename={focusTitleEditor}@@ -330,7 +333,32 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {<Flexbox horizontal align={'center'} gap={10} paddingBlock={'8px 0'} wrap={'wrap'}>{/* One control at a time: a draft is started, a moving goal ispaused or resumed — the two states never overlap. */}- {goal.status === 'draft' ? (+ {goal.archivedAt ? (+ // Archived goals stay put: start / resume refuse them until+ // restored, so restoring is the one control offered.+ <>+ <Tag icon={<ArchiveIcon size={12} />}>{t('goalList.archived')}</Tag>+ {canEdit && canStart && (+ <Button+ icon={ArchiveRestoreIcon}+ loading={restoring}+ onClick={async () => {+ setRestoring(true);+ try {+ await archiveGoal(goal.id, false);+ toast.success(t('goalList.unarchiveSuccess'));+ } catch {+ toast.error(t('goalList.unarchiveFailed'));+ } finally {+ setRestoring(false);+ }+ }}+ >+ {t('goalList.unarchive')}+ </Button>+ )}+ </>+ ) : goal.status === 'draft' ? (canEdit &&canStart && (<Button@@ -372,7 +400,7 @@ const GoalDetailPage = memo<GoalDetailPageProps>(({ agentId, goalId }) => {}/><GoalVisibilitySelector goalId={goal.id} />- {goal.status === 'draft' && (+ {goal.status === 'draft' && !goal.archivedAt && (<Text fontSize={12} type={'secondary'}>{t('goalProcess.draft')}</Text>diff --git a/src/features/AgentGoals/GoalListItem.tsx b/src/features/AgentGoals/GoalListItem.tsxindex fa94c1537dd..667a4e620bb 100644--- a/src/features/AgentGoals/GoalListItem.tsx+++ b/src/features/AgentGoals/GoalListItem.tsx@@ -8,6 +8,7 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwarimport { useActiveRouteParams } from '@/hooks/useActiveRouteParams';import GoalAgentLabel from './GoalAgentLabel';+import GoalArchivedMark from './GoalArchivedMark';import GoalItemMoreButton from './GoalItemMoreButton';import { goalItemPath } from './goalItemPath';import GoalPrivateMark from './GoalPrivateMark';@@ -64,6 +65,7 @@ export const GoalListItem = memo<GoalItemProps>(({ globalScopeId, goal: item, prgoal,projectId,routeAgentId: aid,+ signedOff: item.signedOff,});const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {if (event.key !== 'Enter' && event.key !== ' ') return;@@ -95,6 +97,7 @@ export const GoalListItem = memo<GoalItemProps>(({ globalScopeId, goal: item, pr{goal.title}</Text><GoalPrivateMark goal={goal} />+ <GoalArchivedMark goal={goal} /></Flexbox>{goal.requirement && goal.requirement !== goal.title && (<Text ellipsis fontSize={12} type={'secondary'}>diff --git a/src/features/AgentGoals/SignOffReport/SignOffReport.tsx b/src/features/AgentGoals/SignOffReport/SignOffReport.tsxindex 3e1ebf682c6..5529710fa1c 100644--- a/src/features/AgentGoals/SignOffReport/SignOffReport.tsx+++ b/src/features/AgentGoals/SignOffReport/SignOffReport.tsx@@ -105,6 +105,8 @@ const GoalSignOffReport = ({useFetchGoalGraph(goalId);const snapshot = useGoalStore(goalSelectors.goalGraph(goalId));const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);+ // An archived goal stays put, so the server refuses a change request on it.+ const archived = !!snapshot?.goal.archivedAt;const { accept, pending, requestChanges } = useGoalSignOff({acceptanceId,@@ -158,8 +160,9 @@ const GoalSignOffReport = ({{t('goalProcess.signOff.description')}</Text><Button- disabled={!!pending}+ disabled={!!pending || archived}loading={pending === 'changes'}+ title={archived ? t('goalProcess.signOff.archivedBlocked') : undefined}onClick={() => openRequestChangesModal({ onConfirm: requestChanges })}>{t('goalProcess.signOff.requestChanges')}diff --git a/src/features/AgentGoals/goalSignedOff.test.ts b/src/features/AgentGoals/goalSignedOff.test.tsnew file mode 100644index 00000000000..bf7dd9419ad--- /dev/null+++ b/src/features/AgentGoals/goalSignedOff.test.ts@@ -0,0 +1,27 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { describe, expect, it } from 'vitest';++import { isGoalSnapshotSignedOff } from './goalSignedOff';++const snapshot = (status: string, acceptance?: string) =>+ ({+ acceptances: acceptance ? { node_acc: { id: 'acc_1', status: acceptance } } : {},+ goal: { status },+ nodes: [+ { id: 'node_work', kind: 'task', title: 'Draft the checklist' },+ { id: 'node_acc', kind: 'task', title: GOAL_ACCEPTANCE_TASK_TITLE },+ ],+ }) as never;++describe('isGoalSnapshotSignedOff', () => {+ it('is true once an achieved goal’s Goal-level acceptance is accepted', () => {+ expect(isGoalSnapshotSignedOff(snapshot('achieved', 'accepted'))).toBe(true);+ });++ it('is false while the sign-off is still open, or for a goal that is not achieved', () => {+ expect(isGoalSnapshotSignedOff(snapshot('achieved', 'delivered'))).toBe(false);+ expect(isGoalSnapshotSignedOff(snapshot('achieved'))).toBe(false);+ expect(isGoalSnapshotSignedOff(snapshot('running', 'accepted'))).toBe(false);+ expect(isGoalSnapshotSignedOff(undefined)).toBe(false);+ });+});diff --git a/src/features/AgentGoals/goalSignedOff.ts b/src/features/AgentGoals/goalSignedOff.tsnew file mode 100644index 00000000000..fdee9ecabbb--- /dev/null+++ b/src/features/AgentGoals/goalSignedOff.ts@@ -0,0 +1,18 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import type { GoalGraphSnapshot } from '@lobechat/types';++/**+ * Whether the owner signed the goal off: it is achieved and its Goal-level+ * acceptance was accepted. The detail page's counterpart of the list row's+ * `signedOff`, read from the graph snapshot it already holds.+ */+export const isGoalSnapshotSignedOff = (+ snapshot: Pick<GoalGraphSnapshot, 'acceptances' | 'goal' | 'nodes'> | undefined,+): boolean =>+ snapshot?.goal.status === 'achieved' &&+ snapshot.nodes.some(+ (node) =>+ node.kind === 'task' &&+ node.title === GOAL_ACCEPTANCE_TASK_TITLE &&+ snapshot.acceptances?.[node.id]?.status === 'accepted',+ );diff --git a/src/features/AgentGoals/useGoalMenuItems.test.ts b/src/features/AgentGoals/useGoalMenuItems.test.tsindex ed76e131f35..0d09d2dbc42 100644--- a/src/features/AgentGoals/useGoalMenuItems.test.ts+++ b/src/features/AgentGoals/useGoalMenuItems.test.ts@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({openRename: vi.fn(),renameGoalId: undefined as string | undefined,store: {+ archiveGoal: vi.fn(),closeGoal: vi.fn(),pauseGoal: vi.fn(),refreshGoals: vi.fn(),@@ -106,7 +107,111 @@ describe('useGoalItemMenu', () => {);const keys = result.current.map((item) => (item && 'key' in item ? item.key : item?.type));- expect(keys.slice(-4)).toEqual(['copyLink', 'copy-goal', 'divider', 'delete']);+ expect(keys.slice(-5)).toEqual(['copyLink', 'copy-goal', 'divider', 'archive', 'delete']);+ });++ describe('archive', () => {+ const archiveItem = (items: DropdownItem[]) =>+ items.find((item) => item && 'key' in item && item.key === 'archive') as any;++ it('is disabled, with the reason, until the goal is signed off or canceled', () => {+ const cases = [+ ...['draft', 'planning', 'running', 'verifying', 'review', 'paused', 'failed'].map(+ (status) => ({ signedOff: true, status }),+ ),+ // Achieved but the owner has not signed it off yet.+ { signedOff: false, status: 'achieved' },+ ];+ for (const { signedOff, status } of cases) {+ const { result } = renderHook(() =>+ useGoalItemMenu({+ agentId: 'agt_1',+ goal: { ...goal, archivedAt: null, status },+ signedOff,+ }),+ );+ expect(archiveItem(result.current)).toMatchObject({+ desc: 'goalList.archiveBlocked',+ disabled: true,+ label: 'goalList.archive',+ });+ }+ });++ it('is enabled for a canceled goal', () => {+ const { result } = renderHook(() =>+ useGoalItemMenu({+ agentId: 'agt_1',+ goal: { ...goal, archivedAt: null, status: 'canceled' },+ }),+ );++ expect(archiveItem(result.current)).toMatchObject({ disabled: false });+ });++ it('archives a signed-off goal and refreshes the list it was opened from', async () => {+ mocks.store.archiveGoal.mockResolvedValue(undefined);+ const { result } = renderHook(() =>+ useGoalItemMenu({+ agentId: 'agt_1',+ goal: { ...goal, archivedAt: null, status: 'achieved' },+ routeAgentId: 'agt_1',+ signedOff: true,+ }),+ );++ const item = archiveItem(result.current);+ expect(item).toMatchObject({ disabled: false, label: 'goalList.archive' });+ await act(async () => {+ await item.onClick();+ });++ expect(mocks.store.archiveGoal).toHaveBeenCalledWith('goal_1', true);+ expect(mocks.store.refreshGoals).toHaveBeenCalledWith('agt_1');+ });++ it('offers to restore an archived goal whatever its status', async () => {+ mocks.store.archiveGoal.mockResolvedValue(undefined);+ const { result } = renderHook(() =>+ useGoalItemMenu({+ agentId: 'agt_1',+ goal: { ...goal, archivedAt: '2026-11-03T00:00:00.000Z', status: 'canceled' },+ }),+ );++ const item = archiveItem(result.current);+ expect(item).toMatchObject({ disabled: false, label: 'goalList.unarchive' });+ await act(async () => {+ await item.onClick();+ });++ expect(mocks.store.archiveGoal).toHaveBeenCalledWith('goal_1', false);+ });++ it('locks the status submenu of an archived goal until it is restored', () => {+ const status = (items: DropdownItem[]) =>+ items.find((item) => item && 'key' in item && item.key === 'status') as any;+ const archivedGoal = renderHook(() =>+ useGoalItemMenu({+ agentId: 'agt_1',+ goal: { ...goal, archivedAt: '2026-11-03T00:00:00.000Z', status: 'achieved' },+ }),+ );+ const liveGoal = renderHook(() =>+ useGoalItemMenu({ agentId: 'agt_1', goal: { ...goal, archivedAt: null } }),+ );++ expect(status(archivedGoal.result.current).disabled).toBe(true);+ expect(status(liveGoal.result.current).disabled).toBe(false);+ });++ it('is left out when the host does not know whether the goal is archived', () => {+ const { result } = renderHook(() =>+ useGoalMenuItems({ goalId: 'goal_1', status: 'achieved' }),+ );++ expect(archiveItem(result.current)).toBeUndefined();+ });});// Same pair, copy and order as a topic's menu.diff --git a/src/features/AgentGoals/useGoalMenuItems.tsx b/src/features/AgentGoals/useGoalMenuItems.tsxindex 01abf1bb5e8..393f6109b69 100644--- a/src/features/AgentGoals/useGoalMenuItems.tsx+++ b/src/features/AgentGoals/useGoalMenuItems.tsx@@ -1,5 +1,8 @@+import { isGoalArchiveBlocked } from '@lobechat/types';import { confirmModal, copyToClipboard, type DropdownItem, Icon, toast } from '@lobehub/ui';import {+ ArchiveIcon,+ ArchiveRestoreIcon,CircleDashedIcon,CopyIcon,LinkIcon,@@ -29,6 +32,8 @@ import { useConfirmDeleteGoal, useGoalRename, useGoalShareUrl } from './useGoalAinterface UseGoalMenuItemsOptions {/** Absent for a goal with no responsible agent — e.g. one created from a project. */agentId?: string;+ /** Omitted when the host does not know it, which leaves the archive action out. */+ archivedAt?: Date | string | null;creatorUserId?: string | null;goalId: string;/** Replaces the default redirect to the goal list after a delete. */@@ -38,6 +43,8 @@ interface UseGoalMenuItemsOptions {/** Runs after a status change lands, for hosts that render the status from another read. */onStatusChanged?: () => void;projectId?: string | null;+ /** Achieved and accepted by its owner — with `canceled`, what archiving needs. */+ signedOff?: boolean;status?: string;/** The current title, prefilled by the rename dialog. */title?: string;@@ -46,12 +53,14 @@ interface UseGoalMenuItemsOptions {/** The goal's action menu, shared by the detail header's "more" button and the list rows. */export const useGoalMenuItems = ({agentId,+ archivedAt,creatorUserId,goalId,onDeleted,onRename,onStatusChanged,projectId,+ signedOff,status,title,}: UseGoalMenuItemsOptions): DropdownItem[] => {@@ -66,12 +75,27 @@ export const useGoalMenuItems = ({const resumeGoal = useGoalStore((s) => s.resumeGoal);const startGoal = useGoalStore((s) => s.startGoal);const closeGoal = useGoalStore((s) => s.closeGoal);+ const archiveGoal = useGoalStore((s) => s.archiveGoal);const transferItems = useGoalTransferMenuItem(goalId) as DropdownItem[] | null;const { autoRename, openRename } = useGoalRename(goalId);// The server lets a workspace goal be renamed only by its creator or an owner.const canRename = canEditTask && canClose;const current = toManualStatus(status);+ const isArchived = !!archivedAt;+ // Archived goals leave every list, so only a goal that is done with — signed+ // off, or canceled — may be put away. Restoring is always fine.+ const archiveBlocked = !isArchived && (!status || isGoalArchiveBlocked({ signedOff, status }));++ const toggleArchive = useCallback(async () => {+ try {+ await archiveGoal(goalId, !isArchived);+ toast.success(t(isArchived ? 'goalList.unarchiveSuccess' : 'goalList.archiveSuccess'));+ onStatusChanged?.();+ } catch {+ toast.error(t(isArchived ? 'goalList.unarchiveFailed' : 'goalList.archiveFailed'));+ }+ }, [archiveGoal, goalId, isArchived, onStatusChanged, t]);const changeStatus = useCallback((next: ManualGoalStatus) => {@@ -129,7 +153,9 @@ export const useGoalMenuItems = ({onClick: () => changeStatus(next),};}),- disabled: !canEditTask || !status,+ // An archived goal stays put until restored: the server refuses to+ // start or resume it, so its lifecycle is not offered here either.+ disabled: !canEditTask || !status || isArchived,icon: <Icon icon={CircleDashedIcon} />,key: 'status',label: t('taskList.contextMenu.status'),@@ -157,6 +183,22 @@ export const useGoalMenuItems = ({},...(transferItems ?? []),{ type: 'divider' },+ ...(archivedAt === undefined+ ? []+ : [+ {+ desc: !canClose+ ? t('goalList.archiveDenied')+ : archiveBlocked+ ? t('goalList.archiveBlocked')+ : undefined,+ disabled: !canClose || archiveBlocked,+ icon: <Icon icon={isArchived ? ArchiveRestoreIcon : ArchiveIcon} />,+ key: 'archive',+ label: t(isArchived ? 'goalList.unarchive' : 'goalList.archive'),+ onClick: toggleArchive,+ } satisfies DropdownItem,+ ]),{danger: true,disabled: !canEditTask,@@ -167,6 +209,8 @@ export const useGoalMenuItems = ({},],[+ archiveBlocked,+ archivedAt,autoRename,canClose,canEditTask,@@ -175,12 +219,14 @@ export const useGoalMenuItems = ({confirmDelete,current,goalId,+ isArchived,onRename,openRename,shareUrl,status,t,title,+ toggleArchive,transferItems,],);@@ -193,6 +239,7 @@ interface UseGoalItemMenuOptions {globalScopeId?: string;goal: {agentId?: string | null;+ archivedAt?: Date | string | null;id: string;status: string;title?: string;@@ -202,6 +249,8 @@ interface UseGoalItemMenuOptions {projectId?: string;/** The route's agent, which keys the list scope on an agent's page. */routeAgentId?: string;+ /** The list row's sign-off state (`GoalListItem.signedOff`). */+ signedOff?: boolean;}/** The action menu of a goal-list row (list or card view). */@@ -211,6 +260,7 @@ export const useGoalItemMenu = ({goal,projectId,routeAgentId,+ signedOff,}: UseGoalItemMenuOptions): DropdownItem[] => {// The row reads its status from the list, not the goal graph the store// actions refresh, so a status change refetches the list it was rendered in.@@ -222,12 +272,15 @@ export const useGoalItemMenu = ({return useGoalMenuItems({agentId: agentId ?? undefined,+ // A list row always knows it: the list read returns the whole goal row.+ archivedAt: goal.archivedAt ?? null,creatorUserId: goal.userId,goalId: goal.id,// Deleting from the list keeps the reader on the list it just pruned.onDeleted: noop,onStatusChanged: handleStatusChanged,projectId,+ signedOff,status: goal.status,title: goal.title,});diff --git a/src/services/goal.ts b/src/services/goal.tsindex 3a920d9d76b..88ccaebefa4 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -24,6 +24,8 @@ const goalModelProvider = (planningProvider?: string) =>export interface GoalListParams {agentId?: string;+ /** List only archived goals; omitted, archived goals are left out. */+ archived?: boolean;limit?: number;offset?: number;projectId?: string;@@ -187,6 +189,10 @@ class GoalService {close = async (id: string, status: 'achieved' | 'canceled') =>lambdaClient.goal.close.mutate({ id, status });+ /** Archive (or restore) a signed-off or canceled goal; archived goals leave every list. */+ archive = async (id: string, archived: boolean) =>+ lambdaClient.goal.archive.mutate({ archived, id });+/** Resolve a pending decision gate. Does not resume a paused goal by itself. */decide = async (params: {decisionId: string;diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex b41cfa080af..17bb1cb8f05 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -2,9 +2,12 @@ import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';import { act, renderHook } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import type * as ReplicaModule from '@/libs/replica';+import { revalidateReplica } from '@/libs/replica';import { mutate, useClientDataSWR } from '@/libs/swr';import { aiChatService } from '@/services/aiChat';import { goalService } from '@/services/goal';+import { taskGroupListResource, taskListResource } from '@/store/task/slices/list/projection';import { useGoalStore } from './index';import { initialState } from './initialState';@@ -20,9 +23,15 @@ vi.mock('@/libs/swr/useCacheScope', () => ({useCacheScope: () => 'user-1:personal',}));+vi.mock('@/libs/replica', async (importOriginal) => {+ const actual = await importOriginal<typeof ReplicaModule>();+ return { ...actual, revalidateReplica: vi.fn(actual.revalidateReplica) };+});+vi.mock('@/services/goal', () => ({goalService: {advance: vi.fn(),+ archive: vi.fn(),delete: vi.fn(),getGraph: vi.fn(),list: vi.fn(),@@ -297,6 +306,16 @@ describe('GoalAction', () => {);});+ it('asks the server for archived goals only under the Archived tab', () => {+ renderHook(() => useGoalStore.getState().useFetchGoals('agent-1', undefined, 'archived'));++ expect(syncKeyFor('goalList')?.[4]).toBe('agent-1:goals-page:archived');+ void syncFetcherFor('goalList')?.();+ expect(goalService.list).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: 'agent-1', archived: true }),+ );+ });+it('does not fetch without a scope', () => {const sync = renderHook(() => useGoalStore.getState().useFetchGoals());@@ -392,6 +411,37 @@ describe('GoalAction', () => {expect(list?.total).toBe(1);});+ it('archives a goal and takes it off the ordinary list it was on', async () => {+ useGoalStore.setState({+ goalListByAgentId: {+ 'agent-1': {+ goals: [{ goal: { id: 'goal-1' } }, { goal: { id: 'goal-2' } }] as never,+ total: 2,+ },+ },+ });++ await useGoalStore.getState().archiveGoal('goal-1', true);++ expect(goalService.archive).toHaveBeenCalledWith('goal-1', true);+ const list = useGoalStore.getState().goalListByAgentId['agent-1'];+ expect(list?.goals.map((item) => item.goal.id)).toEqual(['goal-2']);+ // Its Tasks move with it, so the task lists and boards re-read as well.+ expect(revalidateReplica).toHaveBeenCalledWith(taskListResource);+ expect(revalidateReplica).toHaveBeenCalledWith(taskGroupListResource);+ });++ it('reports an archive that landed as done even when the refresh after it fails', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(revalidateReplica).mockRejectedValueOnce(new Error('offline'));++ await expect(useGoalStore.getState().archiveGoal('goal-1', true)).resolves.toBeUndefined();++ expect(goalService.archive).toHaveBeenCalledWith('goal-1', true);+ expect(error).toHaveBeenCalled();+ error.mockRestore();+ });+it('relays the provider the goal actually plans on when advancing it', async () => {vi.mocked(goalService.advance).mockResolvedValue({ ticks: 1 } as never);vi.mocked(goalService.tick).mockResolvedValue({} as never);diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex d935c96ae65..f70ef13a75f 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -27,12 +27,13 @@ import { goalKeys } from '@/libs/swr/keys';import { aiChatService } from '@/services/aiChat';import { type GoalListItem, goalService } from '@/services/goal';import { type MetricSeriesWithPoints, metricService } from '@/services/metric';+import { taskGroupListResource, taskListResource } from '@/store/task/slices/list/projection';import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import { systemAgentSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';import { isTrpcErrorCode } from '@/utils/trpcError';-import { goalStatusesForFilter } from './goalListFilter';+import { goalArchivedForFilter, goalStatusesForFilter } from './goalListFilter';import { buildGoalTitleMessages } from './goalTitle';import { useGoalStore } from './index';import type { GoalListFilter, GoalState, GoalViewMode } from './initialState';@@ -213,6 +214,7 @@ export class GoalActionImpl {fetcher: ({ agentId, filter, projectId }) =>goalService.list({agentId,+ archived: goalArchivedForFilter(filter),limit: GOAL_LIST_FETCH_LIMIT,projectId,statuses: goalStatusesForFilter(filter),@@ -344,6 +346,32 @@ export class GoalActionImpl {await this.refreshGoalGraph(goalId);};+ /**+ * Archive a goal, or restore it. The row moves between every list's ordinary+ * tabs and its Archived tab, so it leaves every list it is held in at once+ * and each list — loaded tabs, the home rail — re-reads where it belongs now.+ * The goal's Tasks are archived and restored with it, so the task lists and+ * boards re-read too.+ */+ archiveGoal = async (goalId: string, archived: boolean): Promise<void> => {+ await goalService.archive(goalId, archived);+ this.#goalListRows.remove(goalId);+ // The archive has landed; a refresh that fails afterwards is a stale view,+ // not a failed archive, so it is logged rather than reported as one.+ const refreshes = await Promise.allSettled([+ this.refreshGoalGraph(goalId),+ revalidateReplica(goalListResource),+ revalidateReplica(homeGoalListResource),+ revalidateReplica(topicGoalListResource),+ revalidateReplica(taskListResource),+ revalidateReplica(taskGroupListResource),+ ]);+ for (const result of refreshes) {+ if (result.status === 'rejected')+ console.error('[goal:archive] refresh failed after archiving', result.reason);+ }+ };+closeGoal = async (goalId: string, status: 'achieved' | 'canceled'): Promise<void> => {await goalService.close(goalId, status);await this.refreshGoalGraph(goalId);diff --git a/src/store/goal/goalListFilter.test.ts b/src/store/goal/goalListFilter.test.tsindex 98592f2204c..8514d93c483 100644--- a/src/store/goal/goalListFilter.test.ts+++ b/src/store/goal/goalListFilter.test.ts@@ -1,7 +1,7 @@import { goalStatuses } from '@lobechat/const/goal';import { describe, expect, it } from 'vitest';-import { goalStatusesForFilter } from './goalListFilter';+import { goalArchivedForFilter, goalStatusesForFilter } from './goalListFilter';describe('goalStatusesForFilter', () => {it('asks the server for every status under All', () => {@@ -34,3 +34,16 @@ describe('goalStatusesForFilter', () => {expect(goalStatusesForFilter('all')).toEqual([...goalStatuses]);});});++describe('goalArchivedForFilter', () => {+ it('lists archived goals, in any status, only under the Archived tab', () => {+ expect(goalArchivedForFilter('archived')).toBe(true);+ expect(goalStatusesForFilter('archived')).toEqual([...goalStatuses]);+ });++ it('leaves archived goals out of every other tab', () => {+ for (const filter of ['all', 'review', 'running', 'achieved'] as const) {+ expect(goalArchivedForFilter(filter)).toBeUndefined();+ }+ });+});diff --git a/src/store/goal/goalListFilter.ts b/src/store/goal/goalListFilter.tsindex 159385105af..c0965f0b2a4 100644--- a/src/store/goal/goalListFilter.ts+++ b/src/store/goal/goalListFilter.ts@@ -13,6 +13,8 @@ import type { GoalListFilter } from './initialState';const goalListFilterStatuses: Record<GoalListFilter, GoalStatus[] | null> = {achieved: ['achieved'],all: null,+ // Archived goals in any status; every other tab leaves them out.+ archived: null,review: ['review'],running: ['running'],};@@ -30,3 +32,11 @@ const allGoalStatuses = (): GoalStatus[] => [...goalStatuses];*/export const goalStatusesForFilter = (filter: GoalListFilter): GoalStatus[] =>goalListFilterStatuses[filter] ?? allGoalStatuses();++/**+ * Whether the tab lists archived goals. Only the Archived tab does: the server+ * leaves archived goals out of every other read, so `all` never shows a goal+ * the user put away.+ */+export const goalArchivedForFilter = (filter: GoalListFilter): true | undefined =>+ filter === 'archived' ? true : undefined;diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.tsindex 001686277d4..47005426dc0 100644--- a/src/store/goal/initialState.ts+++ b/src/store/goal/initialState.ts@@ -13,9 +13,10 @@ export type { GoalListItem };* `running` the goal whose loop is executing right now, `achieved` the goals* that reached their terminal outcome. The other terminal states (`failed`,* `canceled`) stay reachable through `all` only — "completed" would misname- * them.+ * them. `archived` lists the goals the user put away, which every other tab+ * leaves out.*/-export type GoalListFilter = 'all' | 'review' | 'running' | 'achieved';+export type GoalListFilter = 'all' | 'review' | 'running' | 'achieved' | 'archived';export type GoalViewMode = 'card' | 'list';export interface GoalState {diff --git a/src/store/goal/projection.ts b/src/store/goal/projection.tsindex 9bfd7637b0b..c6e92f84424 100644--- a/src/store/goal/projection.ts+++ b/src/store/goal/projection.ts@@ -83,7 +83,13 @@ export const goalListKey = (params: GoalListParams): string => {};/** Every tab of one scope, for a refresh that has to cover them all. */-export const GOAL_LIST_FILTERS: GoalListFilter[] = ['all', 'review', 'running', 'achieved'];+export const GOAL_LIST_FILTERS: GoalListFilter[] = [+ 'all',+ 'review',+ 'running',+ 'achieved',+ 'archived',+];/** One scope's goal list, one entry per tab (`goalListByAgentId`). */export const goalListResource = defineReplica<GoalListParams, GoalListValue, GoalListResponse>({