Skip to content

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

✨ feat(goal): archive a Goal's finished Tasks when it is signed off (#22052)

Rdmclin2a22a8b1f2aa4
diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.signOffArchive.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.signOffArchive.test.ts
new file mode 100644
index 00000000000..dc99a7cb88a
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/acceptance.signOffArchive.test.ts
@@ -0,0 +1,95 @@
+// @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.ts
index 38cbd2538de..5657aebf809 100644
--- a/apps/server/src/routers/lambda/_helpers/acceptanceStatus.ts
+++ b/apps/server/src/routers/lambda/_helpers/acceptanceStatus.ts
@@ -5,10 +5,13 @@ 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',
@@ -54,6 +57,7 @@ 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.ts
new file mode 100644
index 00000000000..bd482326f29
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/goalBriefAction.test.ts
@@ -0,0 +1,61 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { BriefItem } from '@/database/schemas';
+
+import { applyGoalBriefAction } from './goalBriefAction';
+
+const mocks = vi.hoisted(() => ({
+ accept: vi.fn(),
+ archiveSignedOffGoalTasks: vi.fn(),
+ dispatchAcceptanceRepair: vi.fn(),
+ reject: vi.fn(),
+ settleSignOff: vi.fn(),
+}));
+
+const acceptance = { id: 'acc_1', subjectId: 'task_1', subjectType: 'task', userId: 'user-1' };
+
+vi.mock('../acceptance', () => ({
+ resolveAcceptanceForWrite: vi.fn(async () => ({
+ acceptance,
+ service: { accept: mocks.accept, reject: mocks.reject },
+ })),
+}));
+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 };
+ }),
+}));
+vi.mock('@/server/services/goal', () => ({ GoalService: vi.fn() }));
+vi.mock('@/server/services/goal/scheduler', () => ({ scheduleGoalAdvance: vi.fn() }));
+
+const ctx = { serverDB: {} as any, userId: 'user-1', workspaceId: null } as any;
+const signOffBrief = {
+ metadata: { goal: { goalId: 'goal_1', kind: 'signOff', signOffAcceptanceId: 'acc_1' } },
+} as unknown as BriefItem;
+
+describe('applyGoalBriefAction sign-off', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('archives the goal Tasks after signing off from the inbox', async () => {
+ expect(await applyGoalBriefAction(ctx, signOffBrief, 'signOff')).toBe(true);
+
+ expect(mocks.accept).toHaveBeenCalledWith('acc_1', undefined);
+ expect(mocks.archiveSignedOffGoalTasks).toHaveBeenCalledWith(ctx.serverDB, acceptance);
+ });
+
+ it('archives nothing when the delivery is sent back', async () => {
+ expect(await applyGoalBriefAction(ctx, signOffBrief, 'requestChanges', 'Redo it')).toBe(true);
+
+ expect(mocks.reject).toHaveBeenCalled();
+ expect(mocks.archiveSignedOffGoalTasks).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts b/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts
index 7de2bce914b..8c399f9e00a 100644
--- a/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts
+++ b/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts
@@ -6,6 +6,7 @@ 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;
@@ -65,6 +66,7 @@ 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.ts
index bd064555296..bf485869c90 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 { settleGoalSignOff } from '../_helpers/acceptanceStatus';
+import { archiveSignedOffGoalTasks, settleGoalSignOff } from '../_helpers/acceptanceStatus';
import * as goalGate from '../_helpers/goalGateAcceptance';
import {
acceptanceWriteProcedure,
@@ -77,6 +77,7 @@ 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/services/goal/GoalService/__tests__/lifecycle.test.ts b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts
index 64dce7230cd..2a102abe6e8 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/lifecycle.test.ts
@@ -3,10 +3,12 @@ import { eq } from 'drizzle-orm';
import { describe, expect, it, vi } from 'vitest';
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 { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
+import { TaskArchiveModel } from '@/database/models/taskArchive';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { agents, goalEvents, goals, tasks, topics, users, workspaces } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
@@ -576,3 +578,141 @@ describe('GoalService', () => {
expect(await service.graph(graph.goal.id)).toBeDefined();
});
});
+
+describe('GoalService.archiveSignedOffTasks', () => {
+ /** The owner accepts the Goal-level acceptance for `taskId`. */
+ const signOff = async (taskId: string) => {
+ const model = new AcceptanceModel(serverDB, userId);
+ const acceptance = await model.ensureForSubject('task', taskId);
+ await model.updateStatus(acceptance.id, 'accepted');
+ };
+
+ /**
+ * Tick a goal with one work Task up to its last step: the work is done and
+ * the Goal-level acceptance Task has passed, so the next tick achieves it.
+ */
+ const readyToAchieve = async () => {
+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);
+ const service = new GoalService(serverDB, userId);
+ const taskModel = new TaskModel(serverDB, userId);
+ const graph = await service.create({
+ requirement: 'A one-page onboarding checklist',
+ title: 'Signed off',
+ tasks: ['Draft the checklist'],
+ });
+ const work = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(work.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+ await service.tick(graph.goal.id);
+ const acceptance = await service.tick(graph.goal.id);
+ await taskModel.updateStatus(acceptance.taskId!, 'completed');
+ await service.tick(graph.goal.id);
+ return {
+ acceptanceTaskId: acceptance.taskId!,
+ goalId: graph.goal.id,
+ service,
+ taskModel,
+ workTaskId: work.taskId!,
+ };
+ };
+
+ /** An achieved goal with one work Task and its Goal-level acceptance Task. */
+ const achieveGoal = async () => {
+ const ready = await readyToAchieve();
+ expect((await ready.service.tick(ready.goalId)).outcome).toBe('achieved');
+ 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();
+ 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([]);
+ });
+
+ 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.
+ await signOff(acceptanceTaskId);
+ expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);
+
+ expect((await service.tick(goalId)).outcome).toBe('achieved');
+
+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeInstanceOf(Date);
+ expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeInstanceOf(Date);
+ });
+
+ it('archives nothing on the achieved transition until the owner signs off', async () => {
+ const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();
+
+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();
+ expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);
+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();
+ });
+
+ it('leaves unfinished Tasks of a signed-off goal alone', async () => {
+ const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();
+ await signOff(acceptanceTaskId);
+ await taskModel.updateStatus(workTaskId, 'paused');
+
+ expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([acceptanceTaskId]);
+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();
+ });
+
+ it('archives nothing for an acceptance that is not the Goal-level one', async () => {
+ const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();
+ await signOff(acceptanceTaskId);
+ await signOff(workTaskId);
+
+ expect(await service.archiveSignedOffTasks(workTaskId)).toEqual([]);
+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();
+ expect(await service.archiveSignedOffTasks('task_not_in_any_goal')).toEqual([]);
+ });
+
+ it('restores the reworked Task when a signed-off goal is sent back for changes', async () => {
+ const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();
+ await signOff(acceptanceTaskId);
+ await service.archiveSignedOffTasks(acceptanceTaskId);
+
+ 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();
+ 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 TaskArchiveModel(serverDB, userId).archive(acceptanceTaskId, {
+ onlyStatuses: ['canceled', 'completed'],
+ }),
+ ).toBeNull();
+ expect((await taskModel.findById(acceptanceTaskId))?.archivedAt).toBeNull();
+ });
+
+ it('archives nothing while the goal is not achieved', async () => {
+ const { acceptanceTaskId, service, taskModel, workTaskId } = await achieveGoal();
+ await signOff(acceptanceTaskId);
+ const goal = await new GoalModel(serverDB, userId).findByGraphTask(acceptanceTaskId);
+ await new GoalModel(serverDB, userId).update(goal!.id, { status: 'running' });
+
+ expect(await service.archiveSignedOffTasks(acceptanceTaskId)).toEqual([]);
+ expect((await taskModel.findById(workTaskId))?.archivedAt).toBeNull();
+ });
+});
diff --git a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts
index 1ba48785b4a..a6a978a67c3 100644
--- a/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts
+++ b/apps/server/src/services/goal/GoalService/__tests__/surface.test.ts
@@ -40,6 +40,7 @@ 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.ts
index 5e21f032234..79ea42ca0eb 100644
--- a/apps/server/src/services/goal/GoalService/completion.ts
+++ b/apps/server/src/services/goal/GoalService/completion.ts
@@ -89,6 +89,17 @@ 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.ts
index b6c020e0b52..e80c74d93a5 100644
--- a/apps/server/src/services/goal/GoalService/decisions.ts
+++ b/apps/server/src/services/goal/GoalService/decisions.ts
@@ -18,6 +18,7 @@ import { TRPCError } from '@trpc/server';
import { GoalGraphModel } from '@/database/models/goalGraph';
import { TaskModel } from '@/database/models/task';
+import { TaskArchiveModel } from '@/database/models/taskArchive';
import { GoalRepository } from '@/database/repositories/goal';
import { collectStrandedDependents, GOAL_ACCEPTANCE_TASK_TITLE } from '../decideNextMove';
@@ -312,7 +313,12 @@ 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: {
diff --git a/apps/server/src/services/goal/GoalService/index.ts b/apps/server/src/services/goal/GoalService/index.ts
index d41921e996c..e1d57259ae3 100644
--- a/apps/server/src/services/goal/GoalService/index.ts
+++ b/apps/server/src/services/goal/GoalService/index.ts
@@ -55,6 +55,7 @@ import {
updateTitle,
} from './editing';
import {
+ archiveSignedOffTasks,
close,
deleteGoal,
pause,
@@ -190,6 +191,7 @@ 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() {
@@ -373,6 +375,9 @@ 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.ts
index 6ab1f267f46..902b4d6ad79 100644
--- a/apps/server/src/services/goal/GoalService/lifecycle.ts
+++ b/apps/server/src/services/goal/GoalService/lifecycle.ts
@@ -3,6 +3,7 @@ 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';
@@ -38,6 +39,59 @@ export const requestSignOff = async (ctx: GoalServiceContext, graph: GoalGraphSn
await 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.
*
diff --git a/apps/server/src/services/goal/GoalService/types.ts b/apps/server/src/services/goal/GoalService/types.ts
index bf51d3d9555..78ce71a5657 100644
--- a/apps/server/src/services/goal/GoalService/types.ts
+++ b/apps/server/src/services/goal/GoalService/types.ts
@@ -59,6 +59,7 @@ import type {
updateTitle,
} from './editing';
import type {
+ archiveSignedOffTasks,
close,
deleteGoal,
pause,
@@ -197,6 +198,7 @@ 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/signOffArchive.ts b/apps/server/src/services/goal/signOffArchive.ts
new file mode 100644
index 00000000000..2c48136e57e
--- /dev/null
+++ b/apps/server/src/services/goal/signOffArchive.ts
@@ -0,0 +1,26 @@
+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/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.ts
index b21506726ab..334980245e1 100644
--- a/apps/server/src/services/scm/ScmControlService.ts
+++ b/apps/server/src/services/scm/ScmControlService.ts
@@ -12,6 +12,7 @@ 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';
@@ -425,6 +426,8 @@ 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.ts
index 0a743dc00e1..38db082c0ef 100644
--- a/apps/server/src/services/scm/__tests__/ScmControlService.test.ts
+++ b/apps/server/src/services/scm/__tests__/ScmControlService.test.ts
@@ -25,6 +25,7 @@ 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(),
@@ -38,6 +39,9 @@ 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 }),
}));
@@ -153,6 +157,11 @@ 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/packages/database/src/models/__tests__/taskArchive.test.ts b/packages/database/src/models/__tests__/taskArchive.test.ts
index 490488ab8a1..74812ba3a69 100644
--- a/packages/database/src/models/__tests__/taskArchive.test.ts
+++ b/packages/database/src/models/__tests__/taskArchive.test.ts
@@ -35,6 +35,23 @@ describe('TaskArchiveModel', () => {
expect(again?.status).toBe('backlog');
});
+ it('archives only a task still in one of the given statuses', async () => {
+ const tasks = new TaskModel(serverDB, userId);
+ const model = new TaskArchiveModel(serverDB, userId);
+ const task = await tasks.create({ instruction: 'Reopened task' });
+ await tasks.updateStatus(task.id, 'completed', { completedAt: new Date() });
+ // Reopened between the caller's read and its archive write.
+ await tasks.updateStatus(task.id, 'backlog');
+
+ expect(await model.archive(task.id, { onlyStatuses: ['completed', 'canceled'] })).toBeNull();
+ expect((await tasks.findById(task.id))?.archivedAt).toBeNull();
+
+ await tasks.updateStatus(task.id, 'canceled');
+ expect(
+ (await model.archive(task.id, { onlyStatuses: ['completed', 'canceled'] }))?.archivedAt,
+ ).toBeInstanceOf(Date);
+ });
+
it('refuses a running task in the same statement', async () => {
const tasks = new TaskModel(serverDB, userId);
const model = new TaskArchiveModel(serverDB, userId);
diff --git a/packages/database/src/models/taskArchive.ts b/packages/database/src/models/taskArchive.ts
index fac564c2e64..4686b44643e 100644
--- a/packages/database/src/models/taskArchive.ts
+++ b/packages/database/src/models/taskArchive.ts
@@ -1,4 +1,4 @@
-import { and, eq, ne, sql } from 'drizzle-orm';
+import { and, eq, inArray, ne, sql } from 'drizzle-orm';
import { tasks } from '../schemas/task';
import type { LobeChatDatabase } from '../type';
@@ -37,8 +37,12 @@ export class TaskArchiveModel {
* Archive a task unless it is running or its schedule / heartbeat can still
* fire (mirrors `isTaskArchiveBlocked` in `@lobechat/types`). Returns null when the task is missing or blocked; an already archived
* task keeps its original `archived_at`.
+ *
+ * `onlyStatuses` narrows it to tasks still in one of those statuses, checked
+ * in the same UPDATE: a caller archiving from an earlier read (e.g. "this
+ * task is finished") can't archive a task that was reopened since.
*/
- async archive(id: string) {
+ async archive(id: string, options: { onlyStatuses?: string[] } = {}) {
const [task] = await this.db
.update(tasks)
.set({ archivedAt: sql`COALESCE(${tasks.archivedAt}, now())`, updatedAt: new Date() })
@@ -47,6 +51,7 @@ export class TaskArchiveModel {
eq(tasks.id, id),
this.ownership(),
ne(tasks.status, 'running'),
+ options.onlyStatuses ? inArray(tasks.status, options.onlyStatuses) : undefined,
// A paused schedule can't fire (dispatcher and tick skip paused);
// a paused heartbeat still ticks, so it stays blocked.
sql`(${RUNNABLE_AUTOMATION} AND NOT (${tasks.automationMode} = 'schedule' AND ${tasks.status} = 'paused')) IS NOT TRUE`,