Skip to content

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

♻️ refactor(database): split the 2605-line task model into cohesive modules (#21137)

Arvin Xu3e895929b9af
diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.md
index 29fdc28a52c..27ed4732fd7 100644
--- a/.agents/acceptance/references/probe-field-notes.md
+++ b/.agents/acceptance/references/probe-field-notes.md
@@ -226,7 +226,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
hand-written id like `tsk_foo`, then calling a task procedure — it 404s
("Task not found") even though the row exists and the caller is a member.
- **Doesn't work**: any id not starting with `task_`. `TaskModel.resolve()`
- (`packages/database/src/models/task.ts:220-223`) only treats the input as a row
+ (`packages/database/src/models/task/index.ts:116-119`) only treats the input as a row
id when it starts with `task_`; everything else is upper-cased and looked up as
a workspace `identifier` (e.g. `T-1`), so `tsk_foo` becomes the identifier
lookup `TSK_FOO` → null.
diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.ts
index fcc3a77cf55..0b38408575d 100644
--- a/apps/server/src/routers/lambda/task.ts
+++ b/apps/server/src/routers/lambda/task.ts
@@ -15,6 +15,7 @@ import { TaskArchiveModel } from '@/database/models/taskArchive';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
+import { TaskSubtreeRepository } from '@/database/repositories/taskSubtree';
import type { LobeChatDatabase } from '@/database/type';
import { assertAgentUsableBy } from '@/database/utils/agent-access';
import { router } from '@/libs/trpc/lambda';
@@ -64,6 +65,7 @@ const taskProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>
taskModel: new TaskModel(ctx.serverDB, ctx.userId, wsId),
taskIntentService: new TaskIntentService(ctx.serverDB, ctx.userId, wsId),
taskService: new TaskService(ctx.serverDB, ctx.userId, wsId),
+ taskSubtree: new TaskSubtreeRepository(ctx.serverDB, ctx.userId, wsId),
taskTopicModel: new TaskTopicModel(ctx.serverDB, ctx.userId, wsId),
topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),
},
@@ -1489,24 +1491,22 @@ export const taskRouter = router({
);
}
- // Promoting a task to public while a private agent is its assignee
- // breaks the visibility invariant. Reject early — the user should
- // reassign first, then promote.
+ // A private assignee agent on a public task breaks the visibility
+ // invariant. Reject early — reassign first, then promote.
if (input.visibility === 'public' && resolved.assigneeAgentId) {
const agentVisibility = await ctx.agentModel.getAgentVisibility(resolved.assigneeAgentId);
ctx.taskService.assertAgentVisibilityCompat(input.visibility, agentVisibility);
}
- // Promoting a subtask to public while its parent is still private
- // would orphan the child in the workspace view — a subtask cannot
- // be more public than its parent. The user must promote the parent
- // chain first, or keep the subtask private.
+ // A public subtask under a private parent would be orphaned in the
+ // workspace view — a subtask cannot be more public than its parent.
+ // The user must promote the parent chain first, or keep it private.
if (input.visibility === 'public' && resolved.parentTaskId) {
const parent = await ctx.taskModel.findById(resolved.parentTaskId);
ctx.taskService.assertParentVisibilityCompat(input.visibility, parent?.visibility);
}
- const updated = await ctx.taskModel.updateVisibility(resolved.id, input.visibility);
+ const updated = await ctx.taskSubtree.updateVisibility(resolved.id, input.visibility);
if (!updated) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
return { data: updated, message: 'Task visibility updated', success: true };
} catch (error) {
diff --git a/packages/database/src/models/__tests__/task.surface.test.ts b/packages/database/src/models/__tests__/task.surface.test.ts
new file mode 100644
index 00000000000..9c313cacac3
--- /dev/null
+++ b/packages/database/src/models/__tests__/task.surface.test.ts
@@ -0,0 +1,188 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { users, workspaces } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import * as taskModule from '../task';
+import { TaskModel } from '../task';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-surface-user';
+const userId2 = 'task-surface-user-2';
+const workspaceId = 'task-surface-ws';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+const createWorkspace = () =>
+ serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId })
+ .onConflictDoNothing();
+
+/**
+ * Pins the public surface of `TaskModel` so a split into helper modules keeps
+ * every caller-visible name, and keeps instance methods on the prototype
+ * (server tests `vi.spyOn(TaskModel.prototype, …)`).
+ */
+describe('TaskModel public surface', () => {
+ it('keeps the module exports', () => {
+ expect(Object.keys(taskModule).sort()).toEqual([
+ 'TaskModel',
+ 'isTaskIdentifierUniqueViolation',
+ 'taskActivityActor',
+ ]);
+ });
+
+ it('keeps every instance method on the prototype', () => {
+ const publicMethods = [
+ 'addActivities',
+ 'addActivity',
+ 'addComment',
+ 'addDependency',
+ 'areAllDependenciesCompleted',
+ 'areAllSubtasksCompleted',
+ 'batchUpdateStatus',
+ 'copyToWorkspace',
+ 'countTasksBlockingAgentDemotion',
+ 'create',
+ 'delete',
+ 'deleteAll',
+ 'deleteComment',
+ 'deleteIfStatus',
+ 'deleteByIds',
+ 'findAllDescendants',
+ 'findAssigneesByIds',
+ 'findById',
+ 'findByIdentifier',
+ 'findByIds',
+ 'findCommentById',
+ 'findSubtasks',
+ 'getActivities',
+ 'getCheckpointConfig',
+ 'getComments',
+ 'getDependencies',
+ 'getDependenciesByTaskIds',
+ 'getDependents',
+ 'getDocumentsPinnedSince',
+ 'getPinnedDocuments',
+ 'getReviewConfig',
+ 'getTaskTree',
+ 'getTreeAgentIdsForTaskIds',
+ 'getTreePinnedDocuments',
+ 'getUnlockedTasks',
+ 'getUnlockedTasksForMany',
+ 'getVerifyConfig',
+ 'groupList',
+ 'incrementTopicCount',
+ 'list',
+ 'lockForStatusChange',
+ 'lockForUpdate',
+ 'pinDocument',
+ 'removeDependency',
+ 'reorder',
+ 'resolve',
+ 'resolveMany',
+ 'resolveVerifyConfig',
+ 'shouldPauseAfterComplete',
+ 'shouldPauseBeforeStart',
+ 'setSubtreeVisibility',
+ 'shouldPauseOnTopicComplete',
+ 'subtreeHasForeignRows',
+ 'subtreeHasOtherCreators',
+ 'transferTo',
+ 'unpinDocument',
+ 'updateCheckpointConfig',
+ 'updateComment',
+ 'updateContext',
+ 'updateCurrentTopic',
+ 'updateHeartbeat',
+ 'updateReviewConfig',
+ 'updateStatus',
+ 'updateStatusForIds',
+ 'updateStatusIfCurrent',
+ 'updateTaskConfig',
+ 'updateVerifyConfig',
+ 'updateWithLog',
+ 'update',
+ ];
+ const proto = TaskModel.prototype as unknown as Record<string, unknown>;
+ const missing = publicMethods.filter(
+ (name) => !Object.hasOwn(proto, name) || typeof proto[name] !== 'function',
+ );
+
+ expect(missing).toEqual([]);
+ });
+
+ it('keeps the static methods', () => {
+ expect(
+ [
+ 'findOrphanedRunningTopics',
+ 'findStuckTasks',
+ 'getScheduledTasks',
+ 'swapDispatchedScheduleOccurrence',
+ ]
+ .map((name) => typeof (TaskModel as unknown as Record<string, unknown>)[name])
+ .every((type) => type === 'function'),
+ ).toBe(true);
+ });
+});
+
+// Methods with no other direct test before the split.
+describe('TaskModel previously uncovered reads', () => {
+ it('resolveMany matches ids and case-insensitive identifiers within scope', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const a = await model.create({ instruction: 'a' });
+ const b = await model.create({ instruction: 'b' });
+ const other = await new TaskModel(serverDB, userId2).create({ instruction: 'other' });
+
+ expect(await model.resolveMany([])).toEqual([]);
+
+ const resolved = await model.resolveMany([a.id, b.identifier.toLowerCase(), other.id]);
+ expect(resolved.map(({ id }) => id).sort()).toEqual([a.id, b.id].sort());
+ });
+
+ it('findCommentById returns only comments in scope', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'commented' });
+ const comment = await model.addComment({ content: 'hi', taskId: task.id, userId });
+
+ expect((await model.findCommentById(comment.id))?.content).toBe('hi');
+ expect(await new TaskModel(serverDB, userId2).findCommentById(comment.id)).toBeUndefined();
+ expect(await model.findCommentById('missing')).toBeUndefined();
+ });
+
+ it('lockForUpdate reports whether the task is visible', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'lock' });
+
+ expect(await model.lockForUpdate(task.id)).toBe(true);
+ expect(await new TaskModel(serverDB, userId2).lockForUpdate(task.id)).toBe(false);
+ });
+
+ it('subtreeHasForeignRows detects a teammate subtask', async () => {
+ await createWorkspace();
+ const owner = new TaskModel(serverDB, userId, workspaceId);
+ const member = new TaskModel(serverDB, userId2, workspaceId);
+ const root = await owner.create({ instruction: 'root', visibility: 'public' });
+ await owner.create({ instruction: 'own child', parentTaskId: root.id, visibility: 'public' });
+
+ expect(await owner.subtreeHasForeignRows(root.id)).toBe(false);
+
+ await member.create({
+ instruction: 'member child',
+ parentTaskId: root.id,
+ visibility: 'public',
+ });
+ expect(await owner.subtreeHasForeignRows(root.id)).toBe(true);
+ expect(await owner.subtreeHasForeignRows('missing')).toBe(false);
+ });
+});
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index 4e41b36c26f..812d06f7cae 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -9,7 +9,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
import {
- acceptances,
agents,
briefs,
documents,
@@ -946,29 +945,6 @@ describe('TaskModel', () => {
});
});
- describe('deleteSubtree', () => {
- it('should delete the root and all descendants without leaving orphan tasks', async () => {
- const model = new TaskModel(serverDB, userId);
- const root = await model.create({ instruction: 'Root goal' });
- const child = await model.create({ instruction: 'Child', parentTaskId: root.id });
- const grandchild = await model.create({ instruction: 'Grandchild', parentTaskId: child.id });
- await serverDB.insert(acceptances).values({
- subjectId: grandchild.id,
- subjectType: 'task',
- userId,
- });
-
- await expect(model.deleteSubtree(root.id)).resolves.toBe(3);
- await expect(model.findAllDescendants(root.id)).resolves.toEqual([]);
- await expect(model.findById(root.id)).resolves.toBeNull();
- const remainingAcceptances = await serverDB
- .select()
- .from(acceptances)
- .where(eq(acceptances.subjectId, grandchild.id));
- expect(remainingAcceptances).toEqual([]);
- });
- });
-
describe('findSubtasks', () => {
it('should find direct subtasks', async () => {
const model = new TaskModel(serverDB, userId);
@@ -2206,33 +2182,6 @@ describe('TaskModel', () => {
expect(activity.visibility).toBe('private');
expect(activity.workspaceId).toBe('ws_activity');
});
-
- it('pulls public-era activities back to private when the task is demoted', async () => {
- await serverDB
- .insert(workspaces)
- .values({
- id: 'ws_activity_demote',
- name: 'WS',
- primaryOwnerId: userId,
- slug: 'ws-activity-demote',
- })
- .onConflictDoNothing();
- const model = new TaskModel(serverDB, userId, 'ws_activity_demote');
- const task = await model.create({ instruction: 'Test', visibility: 'public' });
-
- await model.addActivity({
- actorUserId: userId,
- payload: { fromId: null, toId: userId2 },
- taskId: task.id,
- type: 'assignee_user',
- });
-
- await model.updateVisibility(task.id, 'private');
-
- const activities = await model.getActivities(task.id);
- expect(activities).toHaveLength(1);
- expect(activities[0].visibility).toBe('private');
- });
});
describe('review rubrics', () => {
@@ -3223,81 +3172,6 @@ describe('TaskModel', () => {
expect(await bob.findById(privateTask.id)).toBeNull();
});
- it('should cascade updateVisibility to descendants and child tables', async () => {
- const alice = new TaskModel(serverDB, userId, wsId);
- const bob = new TaskModel(serverDB, userId2, wsId);
-
- const root = await alice.create({
- instruction: 'Root',
- visibility: 'private',
- });
- const child = await alice.create({
- instruction: 'Child',
- parentTaskId: root.id,
- visibility: 'private',
- });
- await alice.addDependency(root.id, child.id, 'blocks');
-
- // Sanity check: Bob can't see the private subtree
- expect((await bob.list()).total).toBe(0);
-
- const promoted = await alice.updateVisibility(root.id, 'public');
- expect(promoted?.visibility).toBe('public');
-
- const aliceChild = await alice.findById(child.id);
- expect(aliceChild?.visibility).toBe('public');
-
- // Bob now sees both
- const bobList = await bob.list();
- expect(bobList.tasks.map((t) => t.id).sort()).toEqual([root.id, child.id].sort());
-
- // Dependency row also flipped to public
- const deps = await alice.getDependencies(root.id);
- expect(deps).toHaveLength(1);
- expect(deps[0].visibility).toBe('public');
- });
-
- it('should reject updateVisibility for tasks not visible to the caller', async () => {
- const alice = new TaskModel(serverDB, userId, wsId);
- const bob = new TaskModel(serverDB, userId2, wsId);
-
- const aliceTask = await alice.create({
- instruction: 'Alice secret',
- visibility: 'private',
- });
-
- const result = await bob.updateVisibility(aliceTask.id, 'public');
- expect(result).toBeNull();
- const reload = await alice.findById(aliceTask.id);
- expect(reload?.visibility).toBe('private');
- });
-
- it('should return the row when demoting another member’s public task to private', async () => {
- // Regression: the post-update SELECT used to filter by `ownership()`,
- // which evaluates against the new row state. Bob (acting as workspace
- // owner after the TRPC-layer override) demoting Alice's public task to
- // private would write the row but then fail to read it back (new state:
- // visibility=private, createdBy=Alice), so the model returned null and
- // the TRPC procedure surfaced a spurious NOT_FOUND while the DB row had
- // actually been mutated.
- const alice = new TaskModel(serverDB, userId, wsId);
- const bob = new TaskModel(serverDB, userId2, wsId);
-
- const aliceTask = await alice.create({
- instruction: 'Alice public',
- visibility: 'public',
- });
-
- const result = await bob.updateVisibility(aliceTask.id, 'private');
- expect(result).not.toBeNull();
- expect(result?.visibility).toBe('private');
- expect(result?.createdByUserId).toBe(userId);
-
- // DB state matches the returned row (no silent mutation drift).
- const reload = await alice.findById(aliceTask.id);
- expect(reload?.visibility).toBe('private');
- });
-
it('should keep personal-mode behavior unchanged', async () => {
const personal = new TaskModel(serverDB, userId);
const task = await personal.create({ instruction: 'Personal' });
@@ -3345,140 +3219,6 @@ describe('TaskModel', () => {
expect(await bob.getComments(publicTask.id)).toHaveLength(1);
});
- it('should NOT cascade updateVisibility into historical task_comments', async () => {
- // Comments are event-shaped historical rows whose visibility is fixed at
- // write time. Promoting the parent task to public must not retroactively
- // expose discussions that took place while the task was private — that
- // would let other workspace members read messages the commenter intended
- // for the private context. Comments written *after* promotion inherit
- // 'public' through their own create path and surface normally.
- const alice = new TaskModel(serverDB, userId, wsId);
- const bob = new TaskModel(serverDB, userId2, wsId);
-
- const task = await alice.create({
- instruction: 'will be promoted',
- visibility: 'private',
- });
- await alice.addComment({
- authorUserId: userId,
- content: 'private-era thoughts',
- taskId: task.id,
- userId,
- });
-
- // Bob can't see the private task or its comments
- expect(await bob.getComments(task.id)).toHaveLength(0);
-
- await alice.updateVisibility(task.id, 'public');
-
- // Task is public now (Bob sees it), but the historical comment stays
- // hidden — its row still has visibility='private'.
- expect((await bob.list()).tasks.map((t) => t.id)).toContain(task.id);
- expect(await bob.getComments(task.id)).toHaveLength(0);
- // Owner (Alice) of course still sees her own comment.
- expect(await alice.getComments(task.id)).toHaveLength(1);
-
- // A new comment written after promotion inherits 'public' and is
- // visible to Bob — the non-cascade only protects the past, not the
- // future.
- await alice.addComment({
- authorUserId: userId,
- content: 'post-promotion ping',
- taskId: task.id,
- userId,
- });
- expect(await bob.getComments(task.id)).toHaveLength(1);
- });
-
- it('should NOT cascade updateVisibility into historical task_topics', async () => {
- // Same rationale as comments: a task_topics row records one run of the
- // task. Its visibility is fixed at write time; promoting the task to
- // public must not retroactively expose runs (transcripts, handoffs,
- // review scores) created while the task was private.
- const alice = new TaskModel(serverDB, userId, wsId);
-
- const task = await alice.create({
- instruction: 'will be promoted',
- visibility: 'private',
- });
-
- // Seed a historical run row directly — no model API for taskTopics
- // outside the runtime path, and inserting raw is precise enough for
- // asserting the non-cascade invariant.
- const historicalTopicId = await createTopic('historical-run-topic-id');
- await serverDB.insert(taskTopics).values({
- seq: 1,
- status: 'completed',
- taskId: task.id,
- topicId: historicalTopicId,
- userId,
- visibility: 'private',
- workspaceId: wsId,
- });
-
- await alice.updateVisibility(task.id, 'public');
-
- // Task itself is public now.
- expect((await alice.findById(task.id))?.visibility).toBe('public');
-
- // But the historical run row keeps its private visibility — it was
- // recorded during the private phase and stays there.
- const [historical] = await serverDB
- .select({ visibility: taskTopics.visibility })
- .from(taskTopics)
- .where(eq(taskTopics.taskId, task.id));
- expect(historical.visibility).toBe('private');
- });
-
- it('should cascade public→private demotion into task_comments and task_topics', async () => {
- // Inverse of the two non-cascade tests above: comment/topic visibility
- // is a write-time mirror of the task used as a JOIN-free authorization
- // proxy. When the task is pulled back to private, public-era rows must
- // follow — otherwise members who saved a comment/topic id while the
- // task was public could keep reading/operating those historical rows.
- const alice = new TaskModel(serverDB, userId, wsId);
- const bob = new TaskModel(serverDB, userId2, wsId);
-
- const task = await alice.create({
- instruction: 'will be demoted',
- visibility: 'public',
- });
- await alice.addComment({
- authorUserId: userId,
- content: 'public-era comment',
- taskId: task.id,
- userId,
- });
-
- const publicTopicId = await createTopic('public-era-run-topic-id');
- await serverDB.insert(taskTopics).values({
- seq: 1,
- status: 'completed',
- taskId: task.id,
- topicId: publicTopicId,
- userId,
- visibility: 'public',
- workspaceId: wsId,
- });
-
- // Sanity: Bob sees the public-era comment while the task is public.
- expect(await bob.getComments(task.id)).toHaveLength(1);
-
- await alice.updateVisibility(task.id, 'private');
-
- // Task and both child rows are private now — gone from Bob's scope.
- expect(await bob.findById(task.id)).toBeNull();
- expect(await bob.getComments(task.id)).toHaveLength(0);
- const [demotedTopic] = await serverDB
- .select({ visibility: taskTopics.visibility })
- .from(taskTopics)
- .where(eq(taskTopics.taskId, task.id));
- expect(demotedTopic.visibility).toBe('private');
-
- // Alice (creator) keeps access to her own rows.
- expect(await alice.getComments(task.id)).toHaveLength(1);
- });
-
it('should count tasks blocking agent demotion (public + other creators, even private)', async () => {
// Backs the agent demotion guard. Blocking: public tasks by any member,
// and other members' tasks of ANY visibility (their creators lose the
diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.ts
index a4e9ccad409..683fc71804a 100644
--- a/packages/database/src/models/acceptance.ts
+++ b/packages/database/src/models/acceptance.ts
@@ -537,4 +537,29 @@ export class AcceptanceModel {
delete = async (id: string) => {
return this.db.delete(acceptances).where(and(eq(acceptances.id, id), this.ownership()));
};
+
+ /**
+ * Delete every acceptance attached to the given subjects in the caller's
+ * user/workspace scope. Used when the subjects themselves are deleted (see
+ * `TaskSubtreeRepository.deleteSubtree`).
+ */
+ deleteBySubjects = async (
+ subjectType: AcceptanceSubjectType,
+ subjectIds: string[],
+ ): Promise<void> => {
+ if (subjectIds.length === 0) return;
+
+ await this.db
+ .delete(acceptances)
+ .where(
+ and(
+ eq(acceptances.subjectType, subjectType),
+ inArray(acceptances.subjectId, subjectIds),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { userId: acceptances.userId, workspaceId: acceptances.workspaceId },
+ ),
+ ),
+ );
+ };
}
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
deleted file mode 100644
index 39d6b52b825..00000000000
--- a/packages/database/src/models/task.ts
+++ /dev/null
@@ -1,2605 +0,0 @@
-import type {
- AgentOperationStatus,
- CheckpointConfig,
- NewTask,
- TaskActivityLogPayload,
- TaskActivityLogType,
- TaskAutomationMode,
- TaskAutomationSnapshot,
- TaskItem,
- TaskRunTrigger,
- TaskSubtaskProgress,
- TaskVerifyConfig,
- WorkspaceData,
- WorkspaceDocNode,
- WorkspaceTreeNode,
-} from '@lobechat/types';
-import {
- clearTaskReposSelection,
- readTaskExecutionConfig,
- toTaskExecutionConfigPatch,
- withoutTaskExecutionSelection,
-} from '@lobechat/types';
-import {
- and,
- desc,
- eq,
- getTableColumns,
- gte,
- inArray,
- isNotNull,
- isNull,
- lt,
- ne,
- notInArray,
- or,
- type SQL,
- sql,
-} from 'drizzle-orm';
-import type { AnyPgColumn } from 'drizzle-orm/pg-core';
-
-import { merge } from '@/utils/merge';
-
-import type { AgentOperationError } from '../schemas/agentOperations';
-import { agentOperations } from '../schemas/agentOperations';
-import { documents } from '../schemas/file';
-import type {
- NewTaskActivity,
- NewTaskComment,
- TaskActivityItem,
- TaskCommentItem,
-} from '../schemas/task';
-import {
- taskActivities,
- taskComments,
- taskDependencies,
- taskDocuments,
- tasks,
- taskTopics,
-} from '../schemas/task';
-import { topics } from '../schemas/topic';
-import { acceptances } from '../schemas/verify';
-import { works } from '../schemas/work';
-import type { LobeChatDatabase } from '../type';
-import { buildWorkspaceWhere } from '../utils/workspace';
-import { ProjectModel } from './project';
-import {
- buildTaskListFilters,
- type TaskListFilterOptions,
- type TaskListOptions,
-} from './taskListFilters';
-
-const DEFAULT_TASK_IDENTIFIER_PREFIX = 'T';
-
-/** Columns whose change is worth a line in the task activity feed. */
-const TRACKED_TASK_COLUMNS = [
- 'assigneeAgentId',
- 'assigneeUserId',
- 'automationMode',
- // Only for `schedule.maxExecutions`, which lives in the JSONB pocket; the
- // rest of `config` is not diffed.
- 'config',
- 'heartbeatInterval',
- 'priority',
- 'schedulePattern',
- 'scheduleTimezone',
- 'status',
-] as const;
-
-/**
- * Operation outcomes the orphaned-run reconciliation settles.
- *
- * An allow-list on purpose. `done` needs the success path's own inputs (the
- * run's last assistant content, the creator bridge) and `interrupted` belongs
- * to the interrupt path, so converging either from a sweep would mislabel the
- * outcome; and an operation status added later is skipped rather than guessed
- * at.
- */
-const ORPHANED_RUN_OPERATION_STATUSES: AgentOperationStatus[] = ['abandoned', 'error'];
-
-/** One `running` Task run whose operation has already ended — see the finder. */
-export interface OrphanedRunningTopic {
- completionReason: string | null;
- /**
- * The failure the operation recorded, when it recorded one — the raw
- * `state.error`, so its message may be nested (`{ errorType, error: { message } }`).
- */
- operationError: AgentOperationError | null;
- operationId: string;
- operationStatus: AgentOperationStatus;
- taskId: string;
- taskIdentifier: string;
- topicId: string;
- trigger: TaskRunTrigger | null;
- userId: string;
- workspaceId: string | null;
-}
-
-/** The automation columns folded into one value — see `TaskAutomationSnapshot`. */
-/**
- * The actor columns plus the payload tombstone for one activity row. An
- * agent-driven edit is attributed to the agent, not to the session owner
- * whose credentials it borrowed. Both ids null means the system did it on
- * nobody's behalf (the runner's inbox fallback). `actorKind` repeats that in
- * the payload because the id columns are cleared when the actor is deleted,
- * and "someone who is gone" must not read as "the system".
- */
-export const taskActivityActor = (actor: {
- agentId?: string | null;
- userId?: string | null;
-}): {
- actorAgentId: string | null;
- actorKind: 'agent' | 'system' | 'user';
- actorUserId: string | null;
-} => ({
- actorAgentId: actor.agentId ?? null,
- actorKind: actor.agentId ? 'agent' : actor.userId ? 'user' : 'system',
- actorUserId: actor.agentId ? null : (actor.userId ?? null),
-});
-
-const snapshotAutomation = (row: {
- automationMode: TaskAutomationMode | null;
- config: unknown;
- heartbeatInterval: number | null;
- schedulePattern: string | null;
- scheduleTimezone: string | null;
-}): TaskAutomationSnapshot | null => {
- // No mode means automation is off; the leftover pattern / interval columns
- // are configuration in waiting, not something the user turned on.
- if (!row.automationMode) return null;
- const maxExecutions = (row.config as { schedule?: { maxExecutions?: number | null } } | null)
- ?.schedule?.maxExecutions;
- return {
- heartbeatInterval: row.heartbeatInterval,
- maxExecutions: typeof maxExecutions === 'number' ? maxExecutions : null,
- mode: row.automationMode,
- schedulePattern: row.schedulePattern,
- scheduleTimezone: row.scheduleTimezone,
- };
-};
-
-// Foreign-key id columns a caller may clear or leave unset. LLM tool calls often
-// fill optional ids with "" — that must mean "unset", never reach the FK as ''.
-const TASK_NULLABLE_REF_KEYS = ['assigneeAgentId', 'assigneeUserId', 'parentTaskId'] as const;
-
-const normalizeTaskRefs = <
- T extends Partial<Record<(typeof TASK_NULLABLE_REF_KEYS)[number], unknown>>,
->(
- data: T,
-): T => {
- const normalized = { ...data };
- for (const key of TASK_NULLABLE_REF_KEYS) {
- const value = normalized[key];
- if (typeof value === 'string' && !value.trim()) {
- (normalized as Record<string, unknown>)[key] = null;
- }
- }
- return normalized;
-};
-
-/**
- * The data to write when a task moves to another assignee, with the previous
- * assignee's cloud-repo selection dropped in the same write.
- *
- * `repos` resolve against the assignee agent's provider env, so they belong to
- * the agent they were picked for: carrying them to another agent leaves every
- * later run pointing at a repository the new assignee cannot open. The
- * machine-local axes (the device pin and a path on that machine) are the user's
- * own and stay.
- *
- * Only a change of the AGENT counts, and only when the write does not state an
- * execution of its own — a writer that moves the assignee AND names a directory
- * is describing the new assignee's run on purpose. Returns `data` untouched when
- * there is nothing to drop.
- */
-const withStaleReposCleared = (
- before: { assigneeAgentId: string | null; config: unknown },
- data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
-): Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>> => {
- // Nothing to drop for a task that had no assignee to begin with (the runner's
- // "unassigned → inbox agent" fallback), nor for a write that keeps it.
- if (!before.assigneeAgentId) return data;
- if (data.assigneeAgentId === undefined || data.assigneeAgentId === before.assigneeAgentId) {
- return data;
- }
-
- const statedExecution = (data.config as Record<string, unknown> | undefined)?.execution;
- if (statedExecution !== undefined) return data;
-
- const currentConfig = (before.config ?? {}) as Record<string, unknown>;
- const cleared = clearTaskReposSelection(readTaskExecutionConfig(currentConfig));
- if (cleared === readTaskExecutionConfig(currentConfig)) return data;
-
- return {
- ...data,
- config: {
- ...currentConfig,
- ...(data.config as Record<string, unknown> | undefined),
- execution: toTaskExecutionConfigPatch(cleared),
- },
- };
-};
-
-export const isTaskIdentifierUniqueViolation = (error: unknown): boolean => {
- const message = error instanceof Error ? error.message : String(error);
- const code =
- typeof error === 'object' && error && 'code' in error
- ? String((error as { code?: unknown }).code)
- : '';
- const cause = error instanceof Error ? error.cause : undefined;
-
- return (
- code === '23505' ||
- message.includes('23505') ||
- message.includes('duplicate') ||
- message.includes('unique') ||
- (!!cause && isTaskIdentifierUniqueViolation(cause))
- );
-};
-
-/**
- * Ownership helpers in this model come in three flavors. Choose by USE CASE,
- * not by table — picking the wrong one led to a `seq` allocation hotfix
- * (see git log).
- *
- * ┌────────────────────┬──────────────────────────────────────────────┬────────────────────────┐
- * │ Helper │ Use for │ Visibility-aware? │
- * ├────────────────────┼──────────────────────────────────────────────┼────────────────────────┤
- * │ ownership() │ list / read / per-row find on `tasks` │ YES — public OR owner │
- * │ ownershipSql() │ raw-SQL CTEs that need the same predicate │ YES — public OR owner │
- * │ childOwnership() │ task_dependencies / task_documents / │ YES when caller passes │
- * │ │ task_comments etc. (per-child-table) │ the visibility column │
- * │ seqOwnership() │ identifier / seq allocation on `tasks` │ NO — workspace-wide │
- * │ │ (the `(workspace_id, identifier)` unique │ (visibility filter │
- * │ │ constraint is workspace-wide, regardless │ would skip other │
- * │ │ of visibility) │ members' rows and │
- * │ │ │ collide on insert) │
- * └────────────────────┴──────────────────────────────────────────────┴────────────────────────┘
- *
- * Personal mode (no workspace) is always `created_by_user_id = $self AND
- * workspace_id IS NULL` for all four helpers — visibility is inert because
- * everything personal is implicitly owner-only.
- */
-interface TaskRunStats extends Record<string, unknown> {
- root_id: string;
- total_run_cost: number;
- total_run_duration: number;
-}
-
-interface TaskSubtaskProgressRow extends Record<string, unknown> {
- completed: number;
- root_id: string;
- total: number;
-}
-
-export class TaskModel {
- private readonly userId: string;
- private readonly db: LobeChatDatabase;
- private readonly workspaceId?: string;
-
- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
- this.db = db;
- this.userId = userId;
- this.workspaceId = workspaceId;
- }
-
- /**
- * Compat-mode ownership predicate for the `tasks` table — **visibility-aware**.
- * `tasks` uses `createdByUserId` instead of `userId`. Workspace mode applies
- * visibility-aware filtering: public tasks are visible to every member,
- * private tasks only to their creator. Use this for every list/read path.
- * For identifier / seq allocation, use `seqOwnership` instead.
- */
- private ownership = () =>
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- {
- isDeleted: tasks.isDeleted,
- userId: tasks.createdByUserId,
- visibility: tasks.visibility,
- workspaceId: tasks.workspaceId,
- },
- );
-
- /**
- * Ownership predicate for task child tables (deps / docs / comments) that
- * use a `userId` column instead of `createdByUserId`. Pass `visibility` for
- * tables that mirror the parent task's visibility column; leave it omitted
- * for tables that stay workspace-shared (e.g. comments).
- */
- private childOwnership = (cols: {
- userId: AnyPgColumn;
- visibility?: AnyPgColumn;
- workspaceId: AnyPgColumn;
- }) => buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, cols);
-
- /**
- * Workspace-wide ownership for `tasks.seq` / `identifier` allocation —
- * must NOT be visibility-filtered. The `(workspace_id, identifier)` unique
- * constraint is workspace-scoped regardless of visibility, so seq lookups
- * have to see every row in the workspace; otherwise creators of private
- * tasks can collide on identifiers belonging to other members' rows.
- */
- private seqOwnership = () =>
- this.workspaceId
- ? eq(tasks.workspaceId, this.workspaceId)
- : (and(eq(tasks.createdByUserId, this.userId), isNull(tasks.workspaceId)) as SQL);
-
- /**
- * Raw-SQL ownership clause for use inside `db.execute(sql...)` CTEs that
- * can't easily compose with drizzle's `and(...)` helpers. Mirrors
- * `buildWorkspaceWhere` semantics:
- * - workspace mode → `workspace_id = $ws AND (visibility = 'public' OR created_by_user_id = $userId)`
- * - personal mode → `created_by_user_id = $userId AND workspace_id IS NULL`
- */
- private ownershipSql = (alias?: string) => {
- const prefix = alias ? sql.raw(`${alias}.`) : sql.raw('');
- return this.workspaceId
- ? sql`${prefix}workspace_id = ${this.workspaceId}
- AND (${prefix}visibility = 'public' OR ${prefix}created_by_user_id = ${this.userId})
- AND ${prefix}is_deleted IS NOT TRUE`
- : sql`${prefix}created_by_user_id = ${this.userId} AND ${prefix}workspace_id IS NULL AND ${prefix}is_deleted IS NOT TRUE`;
- };
-
- private buildListConditions = (options: TaskListFilterOptions): SQL[] => [
- this.ownership(),
- ...buildTaskListFilters(options),
- ];
-
- /**
- * Look up a task's visibility so child-row inserts (deps, docs, topics) can
- * mirror it without forcing every call site to know the value. Missing or
- * trashed parents fail closed so no child can be attached after deletion or
- * through a model constructed for the wrong scope.
- */
- private async getTaskVisibility(taskId: string): Promise<'private' | 'public'> {
- const row = await this.db
- .select({ visibility: tasks.visibility })
- .from(tasks)
- .where(and(eq(tasks.id, taskId), this.ownership()))
- .limit(1);
- if (!row[0]) throw new Error(`Task not found: ${taskId}`);
- return row[0].visibility;
- }
-
- // ========== CRUD ==========
-
- async create(
- data: Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>,
- options: { maxRetries?: number } = {},
- ): Promise<TaskItem> {
- const createData = normalizeTaskRefs(data);
-
- // Keep the invariant at the write boundary, including direct model callers.
- // Parent references here are canonical database ids; the service resolves
- // display identifiers before calling the model.
- if (createData.parentTaskId) {
- const parent = await this.findById(createData.parentTaskId);
- if (!parent) throw new Error('Task not found');
- if (createData.projectId && createData.projectId !== parent.projectId) {
- throw new Error('Subtask must belong to the same project as its parent');
- }
- createData.projectId ??= parent.projectId;
- }
-
- // A prefix is derived from placement, never accepted as a creation field.
- let identifierPrefix = DEFAULT_TASK_IDENTIFIER_PREFIX;
- if (createData.projectId) {
- const project = await new ProjectModel(
- this.db,
- this.userId,
- this.workspaceId,
- ).findManageableById(createData.projectId);
- if (!project) throw new Error('Project not found');
- identifierPrefix = project.identifier;
- }
-
- // Retry loop to handle concurrent creates (parallel tool calls)
- const maxRetries = options.maxRetries ?? 5;
- for (let attempt = 0; attempt < maxRetries; attempt++) {
- try {
- // Seq is allocated per ownership scope: workspace-wide in team mode,
- // user-private in personal mode. This keeps `T-N` identifiers stable
- // within the surface the user actually sees.
- //
- // Note: this uses `seqOwnership` (visibility-blind), NOT the regular
- // `ownership()`, because the `(workspace_id, identifier)` unique
- // constraint is workspace-wide and ignores visibility. If we let the
- // seq lookup filter out private rows, a private creator would compute
- // a max seq that skips another member's existing identifier and hit
- // PG error 23505 on insert.
- const seqResult = await this.db
- .select({ maxSeq: sql<number>`COALESCE(MAX(${tasks.seq}), 0)` })
- .from(tasks)
- .where(this.seqOwnership());
-
- const nextSeq = Number(seqResult[0].maxSeq) + 1;
- const identifier = `${identifierPrefix}-${nextSeq}`;
-
- const [task] = await this.db
- .insert(tasks)
- .values({
- ...createData,
- createdByUserId: this.userId,
- identifier,
- seq: nextSeq,
- workspaceId: this.workspaceId ?? null,
- } as NewTask)
- .returning();
-
- return task;
- } catch (error: any) {
- // Retry on unique constraint violation (concurrent seq conflict)
- // Check error itself, cause, and stringified message for PG error code 23505
- if (isTaskIdentifierUniqueViolation(error) && attempt < maxRetries - 1) {
- continue;
- }
- throw error;
- }
- }
-
- throw new Error('Failed to create task after max retries');
- }
-
- async findById(id: string): Promise<TaskItem | null> {
- const result = await this.db
- .select()
- .from(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .limit(1);
-
- return result[0] || null;
- }
-
- async findByIds(ids: string[]): Promise<TaskItem[]> {
- if (ids.length === 0) return [];
- return this.db
- .select()
- .from(tasks)
- .where(and(inArray(tasks.id, ids), this.ownership()));
- }
-
- /**
- * Only the assignee of each task. For callers on a polling path (the goal
- * graph re-reads every few seconds while a goal advances) that would
- * otherwise pull full rows — instruction, editor data, context, config — for
- * up to hundreds of tasks just to read one column.
- */
- async findAssigneesByIds(
- ids: string[],
- ): Promise<{ assigneeAgentId: string | null; id: string }[]> {
- if (ids.length === 0) return [];
- return this.db
- .select({ assigneeAgentId: tasks.assigneeAgentId, id: tasks.id })
- .from(tasks)
- .where(and(inArray(tasks.id, ids), this.ownership()));
- }
-
- async resolveMany(idsOrIdentifiers: string[]): Promise<TaskItem[]> {
- if (idsOrIdentifiers.length === 0) return [];
- const identifiers = idsOrIdentifiers.map((value) => value.toUpperCase());
- return this.db
- .select()
- .from(tasks)
- .where(
- and(
- or(inArray(tasks.id, idsOrIdentifiers), inArray(tasks.identifier, identifiers)),
- this.ownership(),
- ),
- );
- }
-
- // Resolve id or identifier (e.g. 'T-1') to a task
- async resolve(idOrIdentifier: string): Promise<TaskItem | null> {
- if (idOrIdentifier.startsWith('task_')) return this.findById(idOrIdentifier);
- return this.findByIdentifier(idOrIdentifier.toUpperCase());
- }
-
- async findByIdentifier(identifier: string): Promise<TaskItem | null> {
- const result = await this.db
- .select()
- .from(tasks)
- .where(and(eq(tasks.identifier, identifier), this.ownership()))
- .limit(1);
-
- return result[0] || null;
- }
-
- async update(
- id: string,
- data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
- ): Promise<TaskItem | null> {
- if (Object.keys(data).length === 0) return this.findById(id);
-
- // A reassignment is not a plain column write: the row being moved away from
- // decides whether the previous assignee's cloud-repo selection has to go,
- // so read it under a lock — a config write landing between the read and the
- // merge below would be lost. Every writer of the assignee column comes
- // through here (`updateWithLog`, the update procedure, the coordinator's
- // handoff/restart, the runner's inbox fallback), so this is the one place
- // the invariant has to hold; `updateWithLog` locks its own read for the
- // activity log and then delegates.
- if (data.assigneeAgentId === undefined) return this.writeRow(this.db, id, data);
-
- return this.db.transaction(async (tx) => {
- const runner = tx as LobeChatDatabase;
- const [before] = await runner
- .select({ assigneeAgentId: tasks.assigneeAgentId, config: tasks.config })
- .from(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .for('update')
- .limit(1);
- if (!before) return null;
-
- return this.writeRow(runner, id, withStaleReposCleared(before, data));
- });
- }
-
- /** The column write itself — the assignee rule lives in `update`. */
- private async writeRow(
- db: LobeChatDatabase,
- id: string,
- data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
- ): Promise<TaskItem | null> {
- const updated = await db
- .update(tasks)
- .set({ ...normalizeTaskRefs(data), updatedAt: new Date() })
- .where(and(eq(tasks.id, id), this.ownership()))
- .returning();
- return updated[0] || null;
- }
-
- /**
- * Delete a task. This does NOT touch the task's Work artifact: the Work
- * lifecycle is driven by the deleteTask tool call at the tool-execution
- * dispatch layer (which calls `WorkModel.deleteTaskWork`), so non-tool deletes
- * (UI / CLI / deleteAll) deliberately leave the Work as an orphan for the UI
- * to render as "resource deleted" from its version snapshot. See.
- */
- async delete(id: string): Promise<boolean> {
- const deleted = await this.db
- .delete(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .returning({ id: tasks.id });
-
- return deleted.length > 0;
- }
-
- /**
- * Move a task and its full subtree to a new visibility (both directions —
- * added the `public → private` demotion; the router gates who
- * may call it).
- *
- * Cascades inside a single transaction:
- * - the root task and every descendant in `tasks`;
- * - `task_dependencies` and `task_documents` whose `task_id` is in the set.
- *
- * `task_topics` and `task_comments` are direction-sensitive. Their
- * `visibility` column is a write-time mirror of the parent task used as a
- * JOIN-free authorization proxy, so:
- * - `private → public` deliberately does **not** cascade them: promoting
- * the task must not retroactively expose runs and discussions that
- * happened while it was private. Rows created after promotion inherit
- * the task's then-current visibility through their own create paths.
- * - `public → private` **does** cascade them: leaving public-era rows
- * public would let workspace members keep reading/operating historical
- * topics and comments of a task they can no longer see.
- *
- * Returns `null` if the root task is not visible to the current caller
- * (either missing or owned by another workspace member). Callers should
- * gate authorization (creator-only / admin) before invoking this.
- */
- async updateVisibility(id: string, visibility: 'private' | 'public'): Promise<TaskItem | null> {
- const root = await this.findById(id);
- if (!root) return null;
- if (root.visibility === visibility) return root;
-
- const descendants = await this.findAllDescendants(root.id);
- const taskIds = [root.id, ...descendants.map((d) => d.id)];
- const stamp = new Date();
-
- return this.db.transaction(async (tx) => {
- // Update the root with RETURNING so we read the post-update row in the
- // same statement. A second SELECT filtered by `ownership()` would self-
- // cancel when a workspace owner demotes another member's task to private:
- // the UPDATE filter sees the OLD (public) row and writes, but the read-
- // back filter sees the NEW (private + other-creator) row and returns 0
- // rows, so the caller would observe a NOT_FOUND error even though the
- // write succeeded.
- const [updated] = await tx
- .update(tasks)
- .set({ updatedAt: stamp, visibility })
- .where(and(eq(tasks.id, root.id), this.ownership()))
- .returning();
-
- const descendantIds = descendants.map((d) => d.id);
- if (descendantIds.length > 0) {
- await tx
- .update(tasks)
- .set({ updatedAt: stamp, visibility })
- .where(and(inArray(tasks.id, descendantIds), this.ownership()));
- }
-
- await tx
- .update(taskDependencies)
- .set({ visibility })
- .where(and(inArray(taskDependencies.taskId, taskIds), this.depsOwnership()));
-
- await tx
- .update(taskDocuments)
- .set({ visibility })
- .where(and(inArray(taskDocuments.taskId, taskIds), this.docsOwnership()));
-
- // Work is a denormalized resource projection. Keep its indexed visibility
- // mirror in the same transaction as the task subtree so gallery/list
- // queries cannot observe a stale public row after demotion.
- await tx
- .update(works)
- .set({ visibility })
- .where(
- and(
- eq(works.resourceType, 'task'),
- inArray(works.resourceId, taskIds),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- { isDeleted: works.isDeleted, userId: works.userId, workspaceId: works.workspaceId },
- ),
- ),
- );
-
- // Demotion-only cascade for the event-shaped child rows (see docstring):
- // their visibility mirrors the task, so pulling the task back to private
- // must also pull public-era topics/comments out of workspace scope.
- if (visibility === 'private') {
- await tx
- .update(taskTopics)
- .set({ visibility })
- .where(and(inArray(taskTopics.taskId, taskIds), this.topicsOwnership()));
-
- await tx
- .update(taskComments)
- .set({ visibility })
- .where(and(inArray(taskComments.taskId, taskIds), this.commentsOwnership()));
-
- await tx
- .update(taskActivities)
- .set({ visibility })
- .where(and(inArray(taskActivities.taskId, taskIds), this.activitiesOwnership()));
- }
-
- return updated ?? null;
- });
- }
-
- /**
- * Count workspace tasks that would break if the given agent were demoted to
- * private:
- * - public tasks assigned to it — a public task must never reference a
- * private agent (`assertAgentVisibilityCompat`);
- * - tasks created by anyone other than the agent's owner (any visibility)
- * — after demotion those creators can no longer resolve the assignee,
- * so their runs and assignee updates fail.
- * Deliberately workspace-wide and visibility-blind (NOT `ownership()`):
- * other members' private tasks are invisible to the caller but still lose
- * their assignee. Backs the router-level agent demotion guard.
- */
- async countTasksBlockingAgentDemotion(
- assigneeAgentId: string,
- agentOwnerUserId: string,
- ): Promise<number> {
- if (!this.workspaceId) return 0;
- const [row] = await this.db
- .select({ count: sql<number>`count(*)` })
- .from(tasks)
- .where(
- and(
- eq(tasks.workspaceId, this.workspaceId),
- eq(tasks.assigneeAgentId, assigneeAgentId),
- or(eq(tasks.visibility, 'public'), ne(tasks.createdByUserId, agentOwnerUserId)),
- ),
- );
- return Number(row?.count ?? 0);
- }
-
- /**
- * Whether the subtree rooted at `rootTaskId` (root excluded) contains tasks
- * created by someone other than `creatorUserId`. Deliberately workspace-wide
- * and visibility-blind: other members' private subtasks are invisible to the
- * caller but would still be fractured by a public→private demotion (each row
- * stays owned by its creator, so the root creator loses those descendants
- * while their creators keep orphaned children whose parent is hidden).
- * Backs the router-level task demotion guard.
- */
- async subtreeHasOtherCreators(rootTaskId: string, creatorUserId: string): Promise<boolean> {
- if (!this.workspaceId) return false;
- const result = await this.db.execute(sql`
- WITH RECURSIVE task_tree AS (
- SELECT id, created_by_user_id FROM tasks
- WHERE id = ${rootTaskId} AND workspace_id = ${this.workspaceId}
- UNION ALL
- SELECT t.id, t.created_by_user_id FROM tasks t
- JOIN task_tree tt ON t.parent_task_id = tt.id
- )
- SELECT 1 AS hit FROM task_tree
- WHERE id <> ${rootTaskId} AND created_by_user_id <> ${creatorUserId}
- LIMIT 1
- `);
- return result.rows.length > 0;
- }
-
- /**
- * Row-lock the task for the rest of the enclosing transaction. Serializes a
- * run recording its topic against a delete deciding there is nothing left to
- * interrupt. Returns false when the task no longer exists.
- */
- async lockForUpdate(id: string): Promise<boolean> {
- const rows = await this.db
- .select({ id: tasks.id })
- .from(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .for('update');
-
- return rows.length > 0;
- }
-
- /**
- * Delete a task only while it still has `status`. Lets a delete that
- * inspected the task's runs lose cleanly to a run that started meanwhile,
- * instead of removing the row out from under it.
- */
- async deleteIfStatus(id: string, status: string): Promise<boolean> {
- const deleted = await this.db
- .delete(tasks)
- .where(and(eq(tasks.id, id), eq(tasks.status, status), this.ownership()))
- .returning({ id: tasks.id });
-
- return deleted.length > 0;
- }
-
- /** See {@link delete}: bulk task deletion likewise leaves Work artifacts intact. */
- async deleteAll(options?: { restrictToCreator?: boolean }): Promise<number> {
- // `restrictToCreator` narrows the workspace-wide sweep to rows the caller
- // created (non-owner members); owners/personal mode keep the full scope.
- const where = options?.restrictToCreator
- ? and(this.ownership(), eq(tasks.createdByUserId, this.userId))
- : this.ownership();
-
- const result = await this.db.delete(tasks).where(where).returning({ id: tasks.id });
- return result.length;
- }
-
- /** Delete a task and every descendant in one transaction. */
- async deleteSubtree(rootTaskId: string): Promise<number> {
- const descendants = await this.findAllDescendants(rootTaskId);
- const taskIds = [rootTaskId, ...descendants.map(({ id }) => id)];
-
- return this.db.transaction(async (tx) => {
- await tx
- .delete(acceptances)
- .where(
- and(
- eq(acceptances.subjectType, 'task'),
- inArray(acceptances.subjectId, taskIds),
- buildWorkspaceWhere(
- { userId: this.userId, workspaceId: this.workspaceId },
- { userId: acceptances.userId, workspaceId: acceptances.workspaceId },
- ),
- ),
- );
- const result = await tx
- .delete(tasks)
- .where(and(inArray(tasks.id, taskIds), this.ownership()))
- .returning({ id: tasks.id });
-
- return result.length;
- });
- }
-
- // ========== Query ==========
-
- async groupList(
- options: TaskListFilterOptions & {
- excludeStatuses?: string[];
- groupBy?: 'agent' | 'assignee' | 'member' | 'priority';
- groups?: Array<{
- key: string;
- limit?: number;
- offset?: number;
- statuses: string[];
- }>;
- },
- ): Promise<
- Array<{
- assigneeAgentId?: string | null;
- assigneeUserId?: string | null;
- hasMore: boolean;
- key: string;
- limit: number;
- offset: number;
- priority?: number;
- tasks: TaskItem[];
- total: number;
- }>
- > {
- const { assigneeAgentId, excludeStatuses, groupBy, groups } = options;
-
- if ((!groups || groups.length === 0) && !groupBy) {
- throw new Error('Task groups or a grouping dimension are required');
- }
-
- const baseConditions = this.buildListConditions(options);
- if (excludeStatuses?.length) {
- baseConditions.push(notInArray(tasks.status, excludeStatuses));
- }
-
- interface GroupQuery {
- assigneeAgentId?: string | null;
- assigneeUserId?: string | null;
- conditions: SQL[];
- key: string;
- limit: number;
- offset: number;
- prefetchedTasks?: TaskItem[];
- priority?: number;
- total: number;
- }
-
- let groupQueries: GroupQuery[];
-
- if (groupBy === 'assignee') {
- const limit = 50;
- const assigneeGroupKey = sql<string>`case
- when ${tasks.assigneeAgentId} is not null then 'assignee:' || ${tasks.assigneeAgentId}
- when ${tasks.assigneeUserId} is not null then 'assignee:user:' || ${tasks.assigneeUserId}
- else 'assignee:unassigned'
- end`;
- const rankedTasks = this.db
- .select({
- ...getTableColumns(tasks),
- assigneeGroupKey: assigneeGroupKey.as('assignee_group_key'),
- groupRank:
- sql<number>`row_number() over (partition by ${assigneeGroupKey} order by ${tasks.createdAt} desc, ${tasks.seq} desc)`.as(
- 'group_rank',
- ),
- })
- .from(tasks)
- .where(and(...baseConditions))
- .as('ranked_assignee_tasks');
- const [countResult, rankedTaskRows] = await Promise.all([
- this.db
- .select({
- assigneeGroupKey: assigneeGroupKey.as('assignee_group_key'),
- count: sql<number>`count(*)`,
- })
- .from(tasks)
- .where(and(...baseConditions))
- .groupBy(assigneeGroupKey),
- this.db
- .select()
- .from(rankedTasks)
- .where(sql`${rankedTasks.groupRank} <= ${limit}`)
- .orderBy(rankedTasks.assigneeGroupKey, rankedTasks.groupRank),
- ]);
- const assigneeCounts = new Map(
- countResult.map((row) => [row.assigneeGroupKey, Number(row.count)]),
- );
- const tasksByAssignee = new Map<string, TaskItem[]>();
- for (const row of rankedTaskRows) {
- const { assigneeGroupKey: groupKey, groupRank: _groupRank, ...task } = row;
- const groupTasks = tasksByAssignee.get(groupKey) ?? [];
- groupTasks.push(task);
- tasksByAssignee.set(groupKey, groupTasks);
- }
-
- // `assignee` is the released hybrid grouping contract: agents take
- // precedence, member-only tasks get their own user group, and only tasks
- // with neither assignee are unassigned. New clients use `agent` for the
- // agent-only board instead of changing this existing API in place.
- if (!assigneeAgentId && !assigneeCounts.has('assignee:unassigned')) {
- assigneeCounts.set('assignee:unassigned', 0);
- }
-
- groupQueries = [...assigneeCounts.entries()].map(([key, total]) => {
- const isUnassigned = key === 'assignee:unassigned';
- const isUser = key.startsWith('assignee:user:');
- const groupAssigneeAgentId =
- isUnassigned || isUser
- ? isUnassigned
- ? null
- : undefined
- : key.slice('assignee:'.length);
- const groupAssigneeUserId = isUser
- ? key.slice('assignee:user:'.length)
- : isUnassigned
- ? null
- : undefined;
- const conditions = isUser
- ? [and(isNull(tasks.assigneeAgentId), eq(tasks.assigneeUserId, groupAssigneeUserId!))!]
- : isUnassigned
- ? [and(isNull(tasks.assigneeAgentId), isNull(tasks.assigneeUserId))!]
- : [eq(tasks.assigneeAgentId, groupAssigneeAgentId!)];
-
- return {
- assigneeAgentId: groupAssigneeAgentId,
- assigneeUserId: groupAssigneeUserId,
- conditions,
- key,
- limit,
- offset: 0,
- prefetchedTasks: tasksByAssignee.get(key) ?? [],
- total,
- };
- });
- } else if (groupBy === 'agent' || groupBy === 'member') {
- const limit = 50;
- const groupColumn = groupBy === 'agent' ? tasks.assigneeAgentId : tasks.assigneeUserId;
- const groupPrefix = groupBy === 'agent' ? 'assignee:' : 'member:';
- const unassignedKey = `${groupPrefix}unassigned`;
- const assigneeGroupKey = sql<string>`case
- when ${groupColumn} is not null then ${groupPrefix} || ${groupColumn}
- else ${unassignedKey}
- end`;
- const rankedTasks = this.db
- .select({
- ...getTableColumns(tasks),
- assigneeGroupKey: assigneeGroupKey.as('assignee_group_key'),
- groupRank:
- sql<number>`row_number() over (partition by ${assigneeGroupKey} order by ${tasks.createdAt} desc, ${tasks.seq} desc)`.as(
- 'group_rank',
- ),
- })
- .from(tasks)
- .where(and(...baseConditions))
- .as('ranked_assignee_tasks');
- const [countResult, rankedTaskRows] = await Promise.all([
- this.db
- .select({
- assigneeId: groupColumn,
- count: sql<number>`count(*)`,
- })
- .from(tasks)
- .where(and(...baseConditions))
- .groupBy(groupColumn),
- this.db
- .select()
- .from(rankedTasks)
- .where(sql`${rankedTasks.groupRank} <= ${limit}`)
- .orderBy(rankedTasks.assigneeGroupKey, rankedTasks.groupRank),
- ]);
- const assigneeCounts = new Map(
- countResult.map((row) => [
- row.assigneeId ? `${groupPrefix}${row.assigneeId}` : unassignedKey,
- Number(row.count),
- ]),
- );
- const tasksByAssignee = new Map<string, TaskItem[]>();
- for (const row of rankedTaskRows) {
- const { assigneeGroupKey: groupKey, groupRank: _groupRank, ...task } = row;
- const groupTasks = tasksByAssignee.get(groupKey) ?? [];
- groupTasks.push(task);
- tasksByAssignee.set(groupKey, groupTasks);
- }
-
- // Keep an empty Unassigned column as a stable drop target. Agent-scoped
- // boards omit the Agent-unassigned column because their base filter
- // guarantees one assignee, while Member grouping remains independent.
- if ((groupBy === 'member' || !assigneeAgentId) && !assigneeCounts.has(unassignedKey)) {
- assigneeCounts.set(unassignedKey, 0);
- }
-
- groupQueries = [...assigneeCounts.entries()].map(([key, total]) => {
- const isUnassigned = key === unassignedKey;
- const assigneeId = isUnassigned ? null : key.slice(groupPrefix.length);
- const groupAssigneeAgentId = groupBy === 'agent' ? assigneeId : undefined;
- const groupAssigneeUserId = groupBy === 'member' ? assigneeId : undefined;
- const conditions = [isUnassigned ? isNull(groupColumn) : eq(groupColumn, assigneeId!)];
-
- return {
- assigneeAgentId: groupAssigneeAgentId,
- assigneeUserId: groupAssigneeUserId,
- conditions,
- key,
- limit,
- offset: 0,
- prefetchedTasks: tasksByAssignee.get(key) ?? [],
- total,
- };
- });
- } else if (groupBy === 'priority') {
- const priorities = [1, 2, 3, 4, 0];
- const countQuery = this.db
- .select({ count: sql<number>`count(*)`, priority: tasks.priority })
- .from(tasks)
- .where(and(...baseConditions))
- .groupBy(tasks.priority);
- const taskQueries = priorities.map(async (priority) => {
- const conditions = [
- priority === 0
- ? or(eq(tasks.priority, priority), isNull(tasks.priority))!
- : eq(tasks.priority, priority),
- ];
- const limit = 50;
- const offset = 0;
- const prefetchedTasks = await this.db
- .select()
- .from(tasks)
- .where(and(...baseConditions, ...conditions))
- .orderBy(desc(tasks.createdAt), desc(tasks.seq))
- .limit(limit)
- .offset(offset);
-
- return {
- conditions,
- key: `priority:${priority}`,
- limit,
- offset,
- prefetchedTasks,
- priority,
- total: 0,
- };
- });
- const [countResult, queriedGroups] = await Promise.all([
- countQuery,
- Promise.all(taskQueries),
- ]);
- const priorityCounts = new Map<number, number>();
- for (const row of countResult) {
- const priority = row.priority ?? 0;
- priorityCounts.set(priority, (priorityCounts.get(priority) ?? 0) + Number(row.count));
- }
-
- // Priority is a finite dimension, so include empty values as usable drop
- // targets. The order matches the task list's semantic rank.
- groupQueries = queriedGroups.map((group) => ({
- ...group,
- total: priorityCounts.get(group.priority) ?? 0,
- }));
- } else {
- const statusGroups = (groups ?? []).map((group) => ({
- ...group,
- statuses: Array.from(new Set(group.statuses)),
- }));
- const allStatuses = Array.from(new Set(statusGroups.flatMap((group) => group.statuses)));
- const countQuery = this.db
- .select({ count: sql<number>`count(*)`, status: tasks.status })
- .from(tasks)
- .where(and(...baseConditions, inArray(tasks.status, allStatuses)))
- .groupBy(tasks.status);
- const taskQueries = statusGroups.map(async (group) => {
- const conditions = [inArray(tasks.status, group.statuses)];
- const limit = group.limit ?? 50;
- const offset = group.offset ?? 0;
- const prefetchedTasks = await this.db
- .select()
- .from(tasks)
- .where(and(...baseConditions, ...conditions))
- .orderBy(desc(tasks.createdAt), desc(tasks.seq))
- .limit(limit)
- .offset(offset);
-
- return {
- conditions,
- key: group.key,
- limit,
- offset,
- prefetchedTasks,
- statuses: group.statuses,
- total: 0,
- };
- });
- const [countResult, queriedGroups] = await Promise.all([
- countQuery,
- Promise.all(taskQueries),
- ]);
- const countByStatus = new Map(countResult.map((row) => [row.status, Number(row.count)]));
-
- groupQueries = queriedGroups.map(({ statuses, ...group }) => ({
- ...group,
- total: statuses.reduce((sum, status) => sum + (countByStatus.get(status) ?? 0), 0),
- }));
- }
-
- const results = await Promise.all(
- groupQueries.map(async (group) => {
- const groupTasks =
- group.prefetchedTasks ??
- (await this.db
- .select()
- .from(tasks)
- .where(and(...baseConditions, ...group.conditions))
- .orderBy(desc(tasks.createdAt), desc(tasks.seq))
- .limit(group.limit)
- .offset(group.offset));
-
- return {
- ...(group.assigneeAgentId !== undefined
- ? { assigneeAgentId: group.assigneeAgentId }
- : {}),
- ...(group.assigneeUserId !== undefined ? { assigneeUserId: group.assigneeUserId } : {}),
- hasMore: group.offset + groupTasks.length < group.total,
- key: group.key,
- limit: group.limit,
- offset: group.offset,
- ...(group.priority !== undefined ? { priority: group.priority } : {}),
- tasks: groupTasks,
- total: group.total,
- };
- }),
- );
-
- const taskIds = Array.from(
- new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))),
- );
- const [runStats, subtaskProgressByTaskId] = await Promise.all([
- this.runStatsByTaskIds(taskIds),
- this.subtaskProgressByTaskIds(taskIds),
- ]);
- const runStatsByTaskId = new Map(
- runStats.map((stats) => [
- stats.root_id,
- {
- totalRunCost: Number(stats.total_run_cost),
- totalRunDuration: Number(stats.total_run_duration),
- },
- ]),
- );
-
- return results.map((group) => ({
- ...group,
- tasks: group.tasks.map((task) => ({
- ...task,
- subtaskProgress: subtaskProgressByTaskId.get(task.id),
- totalRunCost: runStatsByTaskId.get(task.id)?.totalRunCost ?? 0,
- totalRunDuration: runStatsByTaskId.get(task.id)?.totalRunDuration ?? 0,
- })),
- }));
- }
-
- private async runStatsByTaskIds(taskIds: string[]): Promise<TaskRunStats[]> {
- if (taskIds.length === 0) return [];
-
- const result = await this.db.execute<TaskRunStats>(sql`
- WITH RECURSIVE goal_tree AS (
- SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id
- FROM ${tasks}
- WHERE ${inArray(tasks.id, taskIds)} AND ${this.ownership()}
- UNION ALL
- SELECT goal_tree.root_id, child.id
- FROM ${tasks} child
- JOIN goal_tree ON child.parent_task_id = goal_tree.task_id
- WHERE ${this.ownershipSql('child')}
- )
- SELECT
- goal_tree.root_id,
- coalesce(sum(${topics.totalCost}), 0) AS total_run_cost,
- coalesce(
- sum(extract(epoch from (${topics.completedAt} - ${taskTopics.createdAt})) * 1000)
- filter (where ${topics.completedAt} is not null),
- 0
- ) AS total_run_duration
- FROM goal_tree
- LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = goal_tree.task_id
- LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}
- GROUP BY goal_tree.root_id
- `);
-
- return result.rows;
- }
-
- private async subtaskProgressByTaskIds(
- taskIds: string[],
- ): Promise<Map<string, TaskSubtaskProgress>> {
- if (taskIds.length === 0) return new Map();
-
- const result = await this.db.execute<TaskSubtaskProgressRow>(sql`
- WITH RECURSIVE task_tree AS (
- SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id, ${tasks.status} AS status
- FROM ${tasks}
- WHERE ${inArray(tasks.id, taskIds)} AND ${this.ownership()}
- UNION ALL
- SELECT task_tree.root_id, child.id, child.status
- FROM ${tasks} child
- JOIN task_tree ON child.parent_task_id = task_tree.task_id
- WHERE ${this.ownershipSql('child')}
- )
- SELECT
- task_tree.root_id,
- count(*) filter (
- where task_tree.task_id <> task_tree.root_id and task_tree.status = 'completed'
- ) AS completed,
- count(*) filter (where task_tree.task_id <> task_tree.root_id) AS total
- FROM task_tree
- GROUP BY task_tree.root_id
- `);
-
- return new Map(
- result.rows.map((progress) => [
- progress.root_id,
- { completed: Number(progress.completed), total: Number(progress.total) },
- ]),
- );
- }
-
- async list(options: TaskListOptions = {}): Promise<{ tasks: TaskItem[]; total: number }> {
- const { after, statuses, priorities, limit = 50, offset = 0, orderBy = 'createdAt' } = options;
- const orderColumn = orderBy === 'updatedAt' ? tasks.updatedAt : tasks.createdAt;
-
- const conditions = this.buildListConditions(options);
-
- if (statuses?.length) conditions.push(inArray(tasks.status, statuses));
- if (priorities?.length) conditions.push(inArray(tasks.priority, priorities));
- if (after) {
- conditions.push(
- or(
- lt(orderColumn, after.at),
- and(eq(orderColumn, after.at), lt(tasks.seq, after.seq)),
- ) as SQL,
- );
- }
-
- const where = and(...conditions);
-
- const countQuery = this.db
- .select({ count: sql<number>`count(*)` })
- .from(tasks)
- .where(where);
-
- const taskListQuery = this.db
- .select()
- .from(tasks)
- .where(where)
- // `seq` breaks timestamp ties so the order is total — required for the
- // keyset cursor above and for offset pages to never repeat or skip a row.
- .orderBy(desc(orderColumn), desc(tasks.seq))
- .limit(limit)
- .offset(offset);
- const [countResult, taskList] = await Promise.all([countQuery, taskListQuery]);
- const subtaskProgressByTaskId = await this.subtaskProgressByTaskIds(
- taskList.map(({ id }) => id),
- );
-
- return {
- tasks: taskList.map((task) => ({
- ...task,
- subtaskProgress: subtaskProgressByTaskId.get(task.id),
- })),
- total: Number(countResult[0].count),
- };
- }
-
- /**
- * Batch update sortOrder for multiple tasks.
- * @param order Array of { id, sortOrder } pairs
- */
- async reorder(order: Array<{ id: string; sortOrder: number }>): Promise<void> {
- for (const item of order) {
- await this.db
- .update(tasks)
- .set({ sortOrder: item.sortOrder, updatedAt: new Date() })
- .where(and(eq(tasks.id, item.id), this.ownership()));
- }
- }
-
- async findSubtasks(parentTaskId: string): Promise<TaskItem[]> {
- return this.db
- .select()
- .from(tasks)
- .where(and(eq(tasks.parentTaskId, parentTaskId), this.ownership()))
- .orderBy(tasks.sortOrder, tasks.seq);
- }
-
- /**
- * Fetch all descendants of a root task using Drizzle select() (returns camelCase fields).
- * Uses breadth-first traversal with O(depth) queries.
- */
- async findAllDescendants(rootTaskId: string): Promise<TaskItem[]> {
- const all: TaskItem[] = [];
- let parentIds = [rootTaskId];
-
- while (parentIds.length > 0) {
- const children = await this.db
- .select()
- .from(tasks)
- .where(and(inArray(tasks.parentTaskId, parentIds), this.ownership()))
- .orderBy(tasks.sortOrder, tasks.seq);
-
- if (children.length === 0) break;
-
- all.push(...children);
- parentIds = children.map((c) => c.id);
- }
-
- return all;
- }
-
- // Recursive query to get full task tree
- async getTaskTree(rootTaskId: string): Promise<TaskItem[]> {
- const ownership = this.ownershipSql();
- const result = await this.db.execute(sql`
- WITH RECURSIVE task_tree AS (
- SELECT * FROM tasks WHERE id = ${rootTaskId} AND ${ownership}
- UNION ALL
- SELECT t.* FROM tasks t
- JOIN task_tree tt ON t.parent_task_id = tt.id
- )
- SELECT * FROM task_tree
- `);
-
- return result.rows as unknown as TaskItem[];
- }
-
- /**
- * For a list of task IDs, find all agent IDs (assignee + creator) across their full task trees.
- * Walks UP to find root, then DOWN to collect all agents.
- * Returns { [inputTaskId]: agentId[] }
- */
- async getTreeAgentIdsForTaskIds(taskIds: string[]): Promise<Record<string, string[]>> {
- if (taskIds.length === 0) return {};
-
- const taskIdParams = taskIds.map((id) => sql`${id}`);
- const taskIdList = sql.join(taskIdParams, sql`, `);
-
- const ownershipBare = this.ownershipSql();
- const ownershipAliased = this.ownershipSql('t');
- const result = await this.db.execute(sql`
- WITH RECURSIVE
- ancestors AS (
- SELECT id AS origin_id, id, parent_task_id
- FROM tasks
- WHERE id IN (${taskIdList})
- AND ${ownershipBare}
- UNION ALL
- SELECT a.origin_id, t.id, t.parent_task_id
- FROM tasks t
- JOIN ancestors a ON t.id = a.parent_task_id
- WHERE ${ownershipAliased}
- ),
- roots AS (
- SELECT DISTINCT ON (origin_id) origin_id, id AS root_id
- FROM ancestors
- WHERE parent_task_id IS NULL
- ),
- descendants AS (
- SELECT r.origin_id, t.id, t.assignee_agent_id, t.created_by_agent_id
- FROM tasks t
- JOIN roots r ON t.id = r.root_id
- WHERE ${ownershipAliased}
- UNION ALL
- SELECT d.origin_id, t.id, t.assignee_agent_id, t.created_by_agent_id
- FROM tasks t
- JOIN descendants d ON t.parent_task_id = d.id
- WHERE ${ownershipAliased}
- )
- SELECT origin_id, assignee_agent_id, created_by_agent_id
- FROM descendants
- WHERE assignee_agent_id IS NOT NULL OR created_by_agent_id IS NOT NULL
- `);
-
- const map: Record<string, Set<string>> = {};
- for (const row of result.rows as any[]) {
- const originId = row.origin_id as string;
- if (!map[originId]) map[originId] = new Set();
- if (row.assignee_agent_id) map[originId].add(row.assignee_agent_id as string);
- if (row.created_by_agent_id) map[originId].add(row.created_by_agent_id as string);
- }
-
- return Object.fromEntries(Object.entries(map).map(([k, v]) => [k, Array.from(v)]));
- }
-
- // ========== Status ==========
-
- async updateStatus(
- id: string,
- status: string,
- extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },
- ): Promise<TaskItem | null> {
- return this.update(id, { status, ...extra });
- }
-
- /** Atomically transition a task only while it still has the expected status. */
- async updateStatusIfCurrent(
- id: string,
- currentStatus: string,
- status: string,
- extra?: { completedAt?: Date | null; error?: string | null; startedAt?: Date },
- ): Promise<TaskItem | null> {
- const [task] = await this.db
- .update(tasks)
- .set({ status, updatedAt: new Date(), ...extra })
- .where(and(eq(tasks.id, id), eq(tasks.status, currentStatus), this.ownership()))
- .returning();
-
- return task ?? null;
- }
-
- async batchUpdateStatus(ids: string[], status: string): Promise<number> {
- const result = await this.db
- .update(tasks)
- .set({ status, updatedAt: new Date() })
- .where(and(inArray(tasks.id, ids), this.ownership()))
- .returning();
-
- return result.length;
- }
-
- /**
- * Update a frozen set of task ids in one SQL statement so the family cannot
- * be left partially transitioned. Callers pass the exact ids they snapshotted
- * (and the user confirmed); a task that changes status concurrently is never
- * pulled into the update by a status re-query.
- */
- async updateStatusForIds(
- ids: string[],
- status: string,
- extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },
- ): Promise<TaskItem[]> {
- if (ids.length === 0) return [];
- return this.db
- .update(tasks)
- .set({ status, updatedAt: new Date(), ...extra })
- .where(and(inArray(tasks.id, ids), this.ownership()))
- .returning();
- }
-
- // ========== Config ==========
-
- /**
- * Safely merge-update the task's config object.
- * Reads the current config, deep-merges the incoming partial, and writes back.
- *
- * The read is taken under a row lock: several independent writers merge into
- * this one column (model, run location, checkpoint, review, verify), and two
- * of them reading the same snapshot would let the later whole-column write
- * silently drop the other's key.
- */
- async updateTaskConfig(id: string, partial: Record<string, unknown>): Promise<TaskItem | null> {
- return this.rewriteConfig(id, (current) => merge(current, partial));
- }
-
- /**
- * Read-modify-write of the `config` column under a row lock. Every writer that
- * derives the next config from the current one must come through here, so two
- * of them cannot read the same snapshot and drop each other's key.
- */
- private async rewriteConfig(
- id: string,
- next: (current: Record<string, any>) => Record<string, unknown>,
- ): Promise<TaskItem | null> {
- return this.db.transaction(async (tx) => {
- const runner = tx as LobeChatDatabase;
- const [task] = await runner
- .select({ config: tasks.config })
- .from(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .for('update')
- .limit(1);
- if (!task) return null;
-
- return this.writeRow(runner, id, {
- config: next((task.config as Record<string, any>) || {}),
- });
- });
- }
-
- // ========== Context (runtime state) ==========
-
- /**
- * Deep-merge into the task's context JSONB. Used by the heartbeat scheduler
- * to update `context.scheduler.{tickMessageId, consecutiveFailures, ...}`
- * without disturbing other namespaces under context.
- */
- async updateContext(id: string, partial: Record<string, unknown>): Promise<TaskItem | null> {
- const task = await this.findById(id);
- if (!task) return null;
-
- const current = (task.context as Record<string, unknown>) || {};
- const context = merge(current, partial);
- return this.update(id, { context });
- }
-
- // ========== Checkpoint ==========
-
- getCheckpointConfig(task: TaskItem): CheckpointConfig {
- return (task.config as Record<string, any>)?.checkpoint || {};
- }
-
- async updateCheckpointConfig(id: string, checkpoint: CheckpointConfig): Promise<TaskItem | null> {
- return this.updateTaskConfig(id, { checkpoint });
- }
-
- // ========== Review Config ==========
-
- getReviewConfig(task: TaskItem): Record<string, any> | undefined {
- return (task.config as Record<string, any>)?.review;
- }
-
- async updateReviewConfig(id: string, review: Record<string, any>): Promise<TaskItem | null> {
- return this.updateTaskConfig(id, { review });
- }
-
- // ========== Verify Config ==========
-
- /**
- * Read this task's own verify config from `config.verify`. During the
- * migration window it falls back to the legacy `config.review` key so tasks
- * configured before the verify cutover still surface their gate settings —
- * only the shared `enabled` / `maxIterations` fields carry over (review's
- * inline rubrics are dropped, no data was using them).
- */
- getVerifyConfig(task: TaskItem): TaskVerifyConfig | undefined {
- const config = task.config as Record<string, any> | undefined;
- if (config?.verify) return config.verify as TaskVerifyConfig;
-
- const review = config?.review as Record<string, any> | undefined;
- if (review && (review.enabled !== undefined || review.maxIterations !== undefined)) {
- return { enabled: review.enabled, maxIterations: review.maxIterations };
- }
- return undefined;
- }
-
- /**
- * Resolve the effective verify config for a task, honoring subtask
- * inheritance. Whole-config override semantics: the task uses its own config
- * when it has one, otherwise it walks up `parentTaskId` and adopts the
- * nearest ancestor's config in full (never a field-level merge of the two).
- * Returns `undefined` when no task in the chain has a verify config.
- */
- async resolveVerifyConfig(taskId: string): Promise<TaskVerifyConfig | undefined> {
- const seen = new Set<string>();
- let currentId: string | null = taskId;
-
- while (currentId && !seen.has(currentId)) {
- seen.add(currentId);
- const task = await this.findById(currentId);
- if (!task) break;
-
- const config = this.getVerifyConfig(task);
- if (config) return config;
-
- currentId = task.parentTaskId;
- }
- return undefined;
- }
-
- /**
- * Patch the task's own `config.verify`. Per-key semantics (a plain deep-merge
- * can't express "remove", and JSON can't transmit `undefined`):
- * - `null` → clear the key (e.g. switch a rubric/verifier back to default)
- * - omitted → leave the existing value untouched
- * - any value → set it (arrays replace wholesale, not index-merged)
- *
- * The merge is scoped to the `verify` sub-object so sibling config keys
- * (model, checkpoint, schedule, …) are preserved.
- */
- async updateVerifyConfig(
- id: string,
- patch: { [K in keyof TaskVerifyConfig]?: TaskVerifyConfig[K] | null },
- ): Promise<TaskItem | null> {
- return this.rewriteConfig(id, (config) => {
- const next: Record<string, any> = { ...(config.verify as TaskVerifyConfig | undefined) };
-
- for (const [key, value] of Object.entries(patch)) {
- if (value === null) delete next[key];
- else if (value !== undefined) next[key] = value;
- }
-
- return { ...config, verify: next };
- });
- }
-
- // Check if a task should pause after a topic completes
- // Default: pause (when no checkpoint config is set)
- // Explicit: pause only if topic.after is true
- shouldPauseOnTopicComplete(task: TaskItem): boolean {
- const checkpoint = this.getCheckpointConfig(task);
- const hasAnyConfig = Object.keys(checkpoint).length > 0;
- return hasAnyConfig ? !!checkpoint.topic?.after : true;
- }
-
- // Check if a task should be paused before starting (parent's tasks.beforeIds)
- shouldPauseBeforeStart(parentTask: TaskItem, childIdentifier: string): boolean {
- const checkpoint = this.getCheckpointConfig(parentTask);
- return checkpoint.tasks?.beforeIds?.includes(childIdentifier) ?? false;
- }
-
- // Check if a task should be paused after completing (parent's tasks.afterIds)
- shouldPauseAfterComplete(parentTask: TaskItem, childIdentifier: string): boolean {
- const checkpoint = this.getCheckpointConfig(parentTask);
- return checkpoint.tasks?.afterIds?.includes(childIdentifier) ?? false;
- }
-
- // ========== Heartbeat ==========
-
- async updateHeartbeat(id: string): Promise<void> {
- await this.db
- .update(tasks)
- .set({ lastHeartbeatAt: new Date(), updatedAt: new Date() })
- .where(and(eq(tasks.id, id), this.ownership()));
- }
-
- // Tasks eligible for cron-based dispatch.
- // Excludes terminal/paused/running — `paused` requires user attention,
- // `running` is already in flight (and `runTask` would CONFLICT anyway).
- static async getScheduledTasks(db: LobeChatDatabase): Promise<TaskItem[]> {
- return db
- .select()
- .from(tasks)
- .where(
- and(
- eq(tasks.automationMode, 'schedule'),
- isNotNull(tasks.schedulePattern),
- notInArray(tasks.status, ['canceled', 'completed', 'failed', 'paused', 'running']),
- ),
- );
- }
-
- /**
- * Atomically move `context.scheduler.lastDispatchedOccurrenceAt` from
- * `expected` to `next`. Returns false when another writer changed it first.
- *
- * The schedule dispatcher reserves a cron occurrence this way before
- * publishing its execution, so a later tick inside the grace window (or an
- * overlapping dispatcher run) cannot publish the same occurrence again while
- * the first delivery is still queued.
- */
- static async swapDispatchedScheduleOccurrence(
- db: LobeChatDatabase,
- taskId: string,
- expected: string | null,
- next: string | null,
- ): Promise<boolean> {
- const current = sql`coalesce(${tasks.context}, '{}'::jsonb)`;
- const rows = await db
- .update(tasks)
- .set({
- context: sql`${current} || jsonb_build_object('scheduler', coalesce(${current} -> 'scheduler', '{}'::jsonb) || jsonb_build_object('lastDispatchedOccurrenceAt', ${next}::text))`,
- })
- .where(
- and(
- eq(tasks.id, taskId),
- sql`coalesce(${current} -> 'scheduler' ->> 'lastDispatchedOccurrenceAt', '') = ${expected ?? ''}`,
- ),
- )
- .returning({ id: tasks.id });
- return rows.length > 0;
- }
-
- // Find stuck tasks (running but heartbeat timed out)
- // Only checks tasks that have both lastHeartbeatAt and heartbeatTimeout set
- static async findStuckTasks(db: LobeChatDatabase): Promise<TaskItem[]> {
- return db
- .select()
- .from(tasks)
- .where(
- and(
- eq(tasks.status, 'running'),
- isNotNull(tasks.lastHeartbeatAt),
- isNotNull(tasks.heartbeatTimeout),
- sql`${tasks.lastHeartbeatAt} < now() - make_interval(secs => ${tasks.heartbeatTimeout})`,
- ),
- );
- }
-
- /**
- * Running Task runs whose operation has already ended.
- *
- * The terminal state of a run reaches `task_topics` / `tasks` through the
- * run's `onComplete` webhook, and that delivery is fire-and-forget: when it is
- * lost, the Task keeps a `running` run forever. Everything downstream then
- * believes a dead run is live — the Goal view reads its frozen heartbeat as
- * activity, and the coordinator parks on `waiting_external` instead of
- * recovering it. This finder is what lets a sweep settle those
- * rows without depending on the lost delivery.
- *
- * The grace window is what keeps the sweep from racing the normal path: the
- * operation is settled before its hook is dispatched, so only a run that has
- * been over for longer than any delivery lag is treated as orphaned.
- */
- static async findOrphanedRunningTopics(
- db: LobeChatDatabase,
- options: { limit?: number; staleBefore: Date },
- ): Promise<OrphanedRunningTopic[]> {
- const { limit = 200, staleBefore } = options;
-
- return (
- db
- .select({
- completionReason: agentOperations.completionReason,
- operationError: agentOperations.error,
- operationId: agentOperations.id,
- operationStatus: agentOperations.status,
- taskId: tasks.id,
- taskIdentifier: tasks.identifier,
- // Non-null by the guard below; the column is only nullable because a
- // legacy row could have been written without one.
- topicId: sql<string>`${taskTopics.topicId}`,
- trigger: taskTopics.trigger,
- userId: tasks.createdByUserId,
- workspaceId: tasks.workspaceId,
- })
- .from(taskTopics)
- // The run row names the operation it belongs to; a row without one cannot
- // be judged against an operation at all and is left alone.
- .innerJoin(agentOperations, eq(taskTopics.operationId, agentOperations.id))
- .innerJoin(tasks, eq(taskTopics.taskId, tasks.id))
- .where(
- and(
- eq(taskTopics.status, 'running'),
- // Only a Task that still believes it is running is repaired here.
- // One that left `running` was settled deliberately — by the user, or
- // by a cascade that already cancelled its run — and must not be
- // dragged back into a failure.
- eq(tasks.status, 'running'),
- isNotNull(taskTopics.operationId),
- // A run row with no topic cannot be driven through the lifecycle.
- isNotNull(taskTopics.topicId),
- // Sub-agent children extend their parent's turn and never own the
- // Task's run row, so only a top-level operation may settle it.
- isNull(agentOperations.parentOperationId),
- inArray(agentOperations.status, ORPHANED_RUN_OPERATION_STATUSES),
- sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt}) < ${staleBefore}`,
- ),
- )
- .orderBy(sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt})`)
- .limit(limit)
- );
- }
-
- // ========== Dependencies ==========
-
- private depsOwnership = () =>
- this.childOwnership({
- userId: taskDependencies.userId,
- visibility: taskDependencies.visibility,
- workspaceId: taskDependencies.workspaceId,
- });
-
- /** Only used by the demotion cascade in {@link updateVisibility} — regular
- * taskTopics reads/writes live in `TaskTopicModel`. */
- private topicsOwnership = () =>
- this.childOwnership({
- userId: taskTopics.userId,
- visibility: taskTopics.visibility,
- workspaceId: taskTopics.workspaceId,
- });
-
- async addDependency(taskId: string, dependsOnId: string, type: string = 'blocks'): Promise<void> {
- const dependencyTasks = await this.findByIds([taskId, dependsOnId]);
- const task = dependencyTasks.find(({ id }) => id === taskId);
- const dependsOn = dependencyTasks.find(({ id }) => id === dependsOnId);
- if (!task || !dependsOn) throw new Error('Task not found');
- if (task.projectId !== dependsOn.projectId && (task.projectId || dependsOn.projectId)) {
- throw new Error('Task dependencies cannot cross project boundaries');
- }
-
- const visibility = await this.getTaskVisibility(taskId);
- await this.db
- .insert(taskDependencies)
- .values({
- dependsOnId,
- taskId,
- type,
- userId: this.userId,
- visibility,
- workspaceId: this.workspaceId ?? null,
- })
- .onConflictDoNothing();
- }
-
- async removeDependency(taskId: string, dependsOnId: string): Promise<void> {
- await this.db
- .delete(taskDependencies)
- .where(
- and(
- eq(taskDependencies.taskId, taskId),
- eq(taskDependencies.dependsOnId, dependsOnId),
- this.depsOwnership(),
- ),
- );
- }
-
- async getDependencies(taskId: string) {
- return this.db
- .select()
- .from(taskDependencies)
- .where(and(eq(taskDependencies.taskId, taskId), this.depsOwnership()));
- }
-
- async getDependenciesByTaskIds(taskIds: string[]) {
- if (taskIds.length === 0) return [];
- return this.db
- .select()
- .from(taskDependencies)
- .where(and(inArray(taskDependencies.taskId, taskIds), this.depsOwnership()));
- }
-
- async getDependents(taskId: string) {
- return this.db
- .select()
- .from(taskDependencies)
- .where(and(eq(taskDependencies.dependsOnId, taskId), this.depsOwnership()));
- }
-
- // Check if all dependencies of a task are completed
- async areAllDependenciesCompleted(taskId: string): Promise<boolean> {
- const result = await this.db
- .select({ count: sql<number>`count(*)` })
- .from(taskDependencies)
- .innerJoin(tasks, eq(taskDependencies.dependsOnId, tasks.id))
- .where(
- and(
- eq(taskDependencies.taskId, taskId),
- eq(taskDependencies.type, 'blocks'),
- ne(tasks.status, 'completed'),
- this.depsOwnership(),
- ),
- );
-
- return Number(result[0].count) === 0;
- }
-
- // Find tasks that are now unblocked after a dependency completes
- async getUnlockedTasks(completedTaskId: string): Promise<TaskItem[]> {
- return this.getUnlockedTasksForMany([completedTaskId]);
- }
-
- /**
- * Batched variant of {@link getUnlockedTasks}: discover every task unblocked
- * by any of `completedTaskIds` with a constant number of queries instead of
- * one dependency walk per completed task.
- */
- async getUnlockedTasksForMany(completedTaskIds: string[]): Promise<TaskItem[]> {
- if (completedTaskIds.length === 0) return [];
-
- // All tasks that depend on any of the completed tasks
- const dependents = await this.db
- .select({ taskId: taskDependencies.taskId })
- .from(taskDependencies)
- .where(
- and(
- inArray(taskDependencies.dependsOnId, completedTaskIds),
- eq(taskDependencies.type, 'blocks'),
- this.depsOwnership(),
- ),
- );
- const dependentIds = [...new Set(dependents.map(({ taskId }) => taskId))];
- if (dependentIds.length === 0) return [];
-
- // Of those, which still have at least one incomplete blocking dependency
- const blocked = await this.db
- .selectDistinct({ taskId: taskDependencies.taskId })
- .from(taskDependencies)
- .innerJoin(tasks, eq(taskDependencies.dependsOnId, tasks.id))
- .where(
- and(
- inArray(taskDependencies.taskId, dependentIds),
- eq(taskDependencies.type, 'blocks'),
- ne(tasks.status, 'completed'),
- this.depsOwnership(),
- ),
- );
- const blockedIds = new Set(blocked.map(({ taskId }) => taskId));
- const unlockedIds = dependentIds.filter((id) => !blockedIds.has(id));
- if (unlockedIds.length === 0) return [];
-
- // Only unlock tasks still waiting in backlog
- return this.db
- .select()
- .from(tasks)
- .where(and(inArray(tasks.id, unlockedIds), eq(tasks.status, 'backlog'), this.ownership()));
- }
-
- // Check if all subtasks of a parent task are completed
- async areAllSubtasksCompleted(parentTaskId: string): Promise<boolean> {
- const result = await this.db
- .select({ count: sql<number>`count(*)` })
- .from(tasks)
- .where(
- and(eq(tasks.parentTaskId, parentTaskId), ne(tasks.status, 'completed'), this.ownership()),
- );
-
- return Number(result[0].count) === 0;
- }
-
- // ========== Documents (MVP Workspace) ==========
-
- private docsOwnership = () =>
- this.childOwnership({
- userId: taskDocuments.userId,
- visibility: taskDocuments.visibility,
- workspaceId: taskDocuments.workspaceId,
- });
-
- async pinDocument(taskId: string, documentId: string, pinnedBy: string = 'agent'): Promise<void> {
- const visibility = await this.getTaskVisibility(taskId);
- await this.db
- .insert(taskDocuments)
- .values({
- documentId,
- pinnedBy,
- taskId,
- userId: this.userId,
- visibility,
- workspaceId: this.workspaceId ?? null,
- })
- .onConflictDoNothing();
- }
-
- async unpinDocument(taskId: string, documentId: string): Promise<void> {
- await this.db
- .delete(taskDocuments)
- .where(
- and(
- eq(taskDocuments.taskId, taskId),
- eq(taskDocuments.documentId, documentId),
- this.docsOwnership(),
- ),
- );
- }
-
- async getPinnedDocuments(taskId: string) {
- return this.db
- .select()
- .from(taskDocuments)
- .where(and(eq(taskDocuments.taskId, taskId), this.docsOwnership()))
- .orderBy(taskDocuments.createdAt);
- }
-
- /**
- * Documents pinned to a task at or after a given timestamp, joined with the
- * `documents` table so callers receive `{ id, kind, title }` directly.
- *
- * Used by topic-brief synthesis to attribute artifacts to the topic that
- * just completed: pass the topic's start time as `since`.
- */
- async getDocumentsPinnedSince(
- taskId: string,
- since: Date,
- ): Promise<{ id: string; kind: string | null; title: string | null }[]> {
- const rows = await this.db
- .select({
- fileType: documents.fileType,
- id: documents.id,
- title: documents.title,
- })
- .from(taskDocuments)
- // Guard the referenced document too: the junction's visibility column is
- // a write-time mirror of the TASK, so a document independently switched
- // back to private would otherwise still leak its title here.
- .innerJoin(
- documents,
- and(
- eq(taskDocuments.documentId, documents.id),
- buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, documents),
- ),
- )
- .where(
- and(
- eq(taskDocuments.taskId, taskId),
- this.docsOwnership(),
- gte(taskDocuments.createdAt, since),
- ),
- );
-
- return rows.map((row) => ({
- id: row.id,
- kind: row.fileType ?? null,
- title: row.title ?? null,
- }));
- }
-
- // Get all pinned docs from a task tree (recursive), returns nodeMap + tree structure
- async getTreePinnedDocuments(rootTaskId: string): Promise<WorkspaceData> {
- const rootOwnership = this.ownershipSql();
- const recursiveOwnership = this.ownershipSql('t');
- const docsOwnership = this.workspaceId
- ? sql`td.workspace_id = ${this.workspaceId}
- AND (td.visibility = 'public' OR td.user_id = ${this.userId})`
- : sql`td.user_id = ${this.userId} AND td.workspace_id IS NULL`;
- // Guard the referenced document row itself: `td.visibility` is a
- // write-time mirror of the TASK's visibility, so a document independently
- // switched back to private would otherwise still leak its title/metadata
- // through this join. A guarded-out document keeps its junction row but
- // joins as NULL → surfaced as an inaccessible tombstone node.
- const documentVisibility = this.workspaceId
- ? sql`d.workspace_id = ${this.workspaceId}
- AND (d.visibility IS NULL OR d.visibility = 'public' OR d.user_id = ${this.userId})`
- : sql`d.user_id = ${this.userId} AND d.workspace_id IS NULL`;
- const result = await this.db.execute(sql`
- WITH RECURSIVE task_tree AS (
- SELECT id, identifier FROM tasks WHERE id = ${rootTaskId} AND ${rootOwnership}
- UNION ALL
- SELECT t.id, t.identifier FROM tasks t
- JOIN task_tree tt ON t.parent_task_id = tt.id
- WHERE ${recursiveOwnership}
- )
- SELECT td.*, tt.id as source_task_id, tt.identifier as source_task_identifier,
- d.id as document_ref_id,
- d.title as document_title, d.file_type as document_file_type, d.parent_id as document_parent_id,
- d.total_char_count as document_char_count, d.updated_at as document_updated_at
- FROM task_documents td
- JOIN task_tree tt ON td.task_id = tt.id
- LEFT JOIN documents d ON td.document_id = d.id AND ${documentVisibility}
- WHERE ${docsOwnership}
- ORDER BY td.created_at
- `);
-
- // Build nodeMap
- const nodeMap: Record<string, WorkspaceDocNode> = {};
-
- const docIds = new Set<string>();
-
- for (const row of result.rows as any[]) {
- const docId = row.document_id;
- // Join miss = the viewer lost access to the document (switched back to
- // private) or it was deleted. Emit a titleless tombstone so the UI can
- // render a no-access placeholder instead of leaking the title.
- const inaccessible = row.document_ref_id === null;
- docIds.add(docId);
- nodeMap[docId] = {
- charCount: inaccessible ? null : row.document_char_count,
- createdAt: row.created_at,
- fileType: inaccessible ? '' : row.document_file_type,
- inaccessible: inaccessible || undefined,
- parentId: inaccessible ? null : row.document_parent_id,
- pinnedBy: row.pinned_by,
- sourceTaskId: row.source_task_id,
- sourceTaskIdentifier: row.source_task_id !== rootTaskId ? row.source_task_identifier : null,
- title: inaccessible ? '' : row.document_title || 'Untitled',
- updatedAt: inaccessible ? null : row.document_updated_at,
- };
- }
-
- // Build tree (children as id references)
- type TreeNode = WorkspaceTreeNode;
-
- const childrenMap = new Map<string | null, TreeNode[]>();
- for (const docId of docIds) {
- const node = nodeMap[docId];
- const parentId = node.parentId && docIds.has(node.parentId) ? node.parentId : null;
- const list = childrenMap.get(parentId) || [];
- list.push({ children: [], id: docId });
- childrenMap.set(parentId, list);
- }
-
- const buildTree = (parentId: string | null): TreeNode[] => {
- const nodes = childrenMap.get(parentId) || [];
- for (const node of nodes) {
- node.children = buildTree(node.id);
- }
- return nodes;
- };
-
- return { nodeMap, tree: buildTree(null) };
- }
-
- // ========== Topic Management ==========
-
- async incrementTopicCount(id: string): Promise<void> {
- await this.db
- .update(tasks)
- .set({
- totalTopics: sql`${tasks.totalTopics} + 1`,
- updatedAt: new Date(),
- })
- .where(and(eq(tasks.id, id), this.ownership()));
- }
-
- async updateCurrentTopic(id: string, topicId: string): Promise<void> {
- await this.db
- .update(tasks)
- .set({ currentTopicId: topicId, updatedAt: new Date() })
- .where(and(eq(tasks.id, id), this.ownership()));
- }
-
- // ========== Comments ==========
-
- private commentsOwnership = () =>
- this.childOwnership({
- userId: taskComments.userId,
- visibility: taskComments.visibility,
- workspaceId: taskComments.workspaceId,
- });
-
- async addComment(data: Omit<NewTaskComment, 'id'>): Promise<TaskCommentItem> {
- // Mirror the parent task's visibility onto the comment so subsequent
- // reads/writes can be filtered without a JOIN. `getTaskVisibility` also
- // provides the final live-parent write fence.
- const visibility = await this.getTaskVisibility(data.taskId);
- const [comment] = await this.db
- .insert(taskComments)
- .values({ ...data, visibility, workspaceId: this.workspaceId ?? null })
- .returning();
- return comment;
- }
-
- async findCommentById(id: string): Promise<TaskCommentItem | undefined> {
- const [comment] = await this.db
- .select()
- .from(taskComments)
- .where(and(eq(taskComments.id, id), this.commentsOwnership()))
- .limit(1);
- return comment;
- }
-
- async getComments(taskId: string): Promise<TaskCommentItem[]> {
- return this.db
- .select()
- .from(taskComments)
- .where(and(eq(taskComments.taskId, taskId), this.commentsOwnership()))
- .orderBy(taskComments.createdAt);
- }
-
- async deleteComment(id: string): Promise<boolean> {
- const result = await this.db
- .delete(taskComments)
- .where(and(eq(taskComments.id, id), this.commentsOwnership()))
- .returning();
- return result.length > 0;
- }
-
- async updateComment(
- id: string,
- content: string,
- opts?: { editorData?: unknown },
- ): Promise<TaskCommentItem | undefined> {
- const [comment] = await this.db
- .update(taskComments)
- .set({
- content,
- ...(opts?.editorData !== undefined ? { editorData: opts.editorData as never } : {}),
- updatedAt: new Date(),
- })
- .where(and(eq(taskComments.id, id), this.commentsOwnership()))
- .returning();
- return comment;
- }
-
- // ========== Activities ==========
-
- private activitiesOwnership = () =>
- this.childOwnership({
- userId: taskActivities.userId,
- visibility: taskActivities.visibility,
- workspaceId: taskActivities.workspaceId,
- });
-
- /**
- * Append one event row. Mirrors the parent task's visibility onto the row so
- * subsequent reads can be filtered without a JOIN — same contract as
- * `addComment`.
- */
- async addActivity(
- data: Omit<NewTaskActivity, 'id' | 'userId' | 'workspaceId' | 'visibility'>,
- ): Promise<TaskActivityItem> {
- const visibility = await this.getTaskVisibility(data.taskId);
- const [activity] = await this.db
- .insert(taskActivities)
- .values({
- ...data,
- userId: this.userId,
- visibility,
- workspaceId: this.workspaceId ?? null,
- })
- .returning();
- return activity;
- }
-
- /**
- * Append several event rows in one INSERT. Unlike `addActivity`, the caller
- * supplies each row's visibility — meant for a bulk write that has already
- * read (and locked) the tasks it describes.
- */
- async addActivities(
- rows: Omit<NewTaskActivity, 'id' | 'userId' | 'workspaceId'>[],
- ): Promise<TaskActivityItem[]> {
- if (rows.length === 0) return [];
- return this.db
- .insert(taskActivities)
- .values(
- rows.map((row) => ({ ...row, userId: this.userId, workspaceId: this.workspaceId ?? null })),
- )
- .returning();
- }
-
- /**
- * Lock a set of tasks for the rest of the transaction and return what a
- * bulk status write needs to describe them afterwards: the status each one
- * is leaving and the visibility its activity row inherits. Reading these
- * before the lock would let a concurrent edit slip in between and the log
- * would name a transition that never happened.
- */
- async lockForStatusChange(
- ids: string[],
- ): Promise<{ id: string; status: string; visibility: 'private' | 'public' }[]> {
- if (ids.length === 0) return [];
- return this.db
- .select({ id: tasks.id, status: tasks.status, visibility: tasks.visibility })
- .from(tasks)
- .where(and(inArray(tasks.id, ids), this.ownership()))
- .for('update');
- }
-
- /**
- * Update a task and append one event per tracked field that actually
- * changed, in ONE transaction, with the previous values taken from a
- * **locked** read of the row.
- *
- * The lock is the point. Reading the "before" value outside the write lets
- * two concurrent edits both observe the same origin — an A→B and an A→C
- * racing on one task persist A→B then B→C while a lock-free recorder logs
- * A→B and A→C, losing the middle state. Rows are inserted next to the write
- * they describe, so their order cannot disagree with the order the updates
- * landed in.
- *
- * Which edits reach the feed is decided by the caller, not here: anything
- * that goes through this method is logged. Person-made changes (the update
- * procedure, the agent `editTask` tool, the status picker) and the runner's
- * inbox fallback come here; the runner / lifecycle / watchdog status
- * transitions use the plain writers, because the run row already tells that
- * story.
- */
- async updateWithLog(
- id: string,
- data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
- actor: { agentId?: string | null; userId?: string | null },
- options: {
- /**
- * Deep-merged into the `config` column under this update's row lock,
- * instead of replacing it. A client that edits one key (the schedule
- * cap) must not send back a whole-config snapshot that can predate
- * another tab's or member's write of a different key.
- */
- configPatch?: Record<string, unknown>;
- } = {},
- ): Promise<TaskItem | null> {
- const { configPatch } = options;
- const touched = !!configPatch || TRACKED_TASK_COLUMNS.some((col) => data[col] !== undefined);
- // Nothing to diff against: an ordinary rename should not pay for a lock.
- if (!touched) return this.update(id, data);
-
- return this.db.transaction(async (tx) => {
- const runner = tx as LobeChatDatabase;
- const [before] = await runner
- .select({
- assigneeAgentId: tasks.assigneeAgentId,
- assigneeUserId: tasks.assigneeUserId,
- automationMode: tasks.automationMode,
- config: tasks.config,
- heartbeatInterval: tasks.heartbeatInterval,
- priority: tasks.priority,
- schedulePattern: tasks.schedulePattern,
- scheduleTimezone: tasks.scheduleTimezone,
- status: tasks.status,
- })
- .from(tasks)
- .where(and(eq(tasks.id, id), this.ownership()))
- .for('update')
- .limit(1);
- if (!before) return null;
-
- const scoped = new TaskModel(runner, this.userId, this.workspaceId);
-
- // The reassignment rule — dropping the previous assignee's cloud-repo
- // selection — lives in `update`, which is the only writer of the assignee
- // column, so this locked read is kept for the activity-log diff only and
- // the write below re-checks the rule in the same transaction.
- const writeData = configPatch
- ? {
- ...data,
- config: merge(
- ((data.config ?? before.config) as Record<string, unknown> | null) ?? {},
- configPatch,
- ),
- }
- : data;
- const updated = await scoped.update(id, writeData);
- if (!updated) return null;
-
- const events: { payload: TaskActivityLogPayload; type: TaskActivityLogType }[] = [];
-
- // The two assignee slots are independent — one edit can move both, and
- // each gets its own row so the feed reads one change per line.
- if (before.assigneeAgentId !== updated.assigneeAgentId) {
- events.push({
- payload: { fromId: before.assigneeAgentId, toId: updated.assigneeAgentId },
- type: 'assignee_agent',
- });
- }
- if (before.assigneeUserId !== updated.assigneeUserId) {
- events.push({
- payload: { fromId: before.assigneeUserId, toId: updated.assigneeUserId },
- type: 'assignee_user',
- });
- }
- if (before.status !== updated.status) {
- events.push({ payload: { from: before.status, to: updated.status }, type: 'status' });
- }
- if ((before.priority ?? null) !== (updated.priority ?? null)) {
- events.push({
- payload: { from: before.priority ?? null, to: updated.priority ?? null },
- type: 'priority',
- });
- }
- const automationBefore = snapshotAutomation(before);
- const automationAfter = snapshotAutomation(updated);
- if (JSON.stringify(automationBefore) !== JSON.stringify(automationAfter)) {
- events.push({
- payload: { from: automationBefore, to: automationAfter },
- type: 'automation',
- });
- }
-
- const { actorKind, ...actorColumns } = taskActivityActor(actor);
- for (const event of events) {
- await scoped.addActivity({
- ...actorColumns,
- payload: { ...event.payload, actorKind },
- taskId: id,
- type: event.type,
- });
- }
-
- return updated;
- });
- }
-
- /**
- * Oldest-first. `limit` keeps the newest N rows (still returned
- * oldest-first) so a long-lived task does not ship its whole history on
- * every detail poll; the table itself is the full audit trail.
- */
- async getActivities(taskId: string, limit?: number): Promise<TaskActivityItem[]> {
- const where = and(eq(taskActivities.taskId, taskId), this.activitiesOwnership());
- if (limit === undefined) {
- return this.db.select().from(taskActivities).where(where).orderBy(taskActivities.createdAt);
- }
- const newest = await this.db
- .select()
- .from(taskActivities)
- .where(where)
- .orderBy(desc(taskActivities.createdAt), desc(taskActivities.id))
- .limit(limit);
- return newest.reverse();
- }
-
- // ========== Transfer / Copy ==========
-
- /**
- * Collect a task and all its descendants (parentTaskId-linked) via BFS.
- * Honors the current ownership scope.
- */
- private async collectTaskSubtree(rootId: string, runner: LobeChatDatabase): Promise<TaskItem[]> {
- const [root] = await runner
- .select()
- .from(tasks)
- .where(and(eq(tasks.id, rootId), this.ownership()))
- .limit(1);
- if (!root) return [];
-
- const collected: TaskItem[] = [root];
- let frontier: string[] = [root.id];
-
- while (frontier.length > 0) {
- const children = await runner
- .select()
- .from(tasks)
- .where(and(inArray(tasks.parentTaskId, frontier), this.ownership()));
- if (children.length === 0) break;
- collected.push(...children);
- frontier = children.map((c) => c.id);
- }
-
- return collected;
- }
-
- /**
- * Allocate a contiguous block of seq numbers + identifiers in the target
- * scope. Returns the next available seq baseline.
- */
- private async nextSeqIn(
- runner: LobeChatDatabase,
- targetWorkspaceId: string | null,
- targetUserId: string,
- ): Promise<number> {
- const where = targetWorkspaceId
- ? eq(tasks.workspaceId, targetWorkspaceId)
- : and(eq(tasks.createdByUserId, targetUserId), isNull(tasks.workspaceId));
- const [{ maxSeq }] = await runner
- .select({ maxSeq: sql<number>`COALESCE(MAX(${tasks.seq}), 0)` })
- .from(tasks)
- .where(where!);
- return Number(maxSeq) + 1;
- }
-
- /**
- * Transfer a task subtree to another workspace / personal scope. Reallocates
- * `identifier`/`seq` in the target scope and rewrites the child tables that
- * mirror the parent's ownership (`task_dependencies`, `task_documents`,
- * `task_comments`, `task_activities`) so the ownership predicates keep
- * resolving after the move — those mirrored columns are what authorizes
- * reads, so a child left behind goes invisible in the destination scope.
- *
- * NOTE: `task_topics` and `briefs` carry the same mirrored columns but are
- * not rewritten here. Pre-existing gap, called out rather than widened.
- *
- * Cross-scope references that may no longer be valid are cleared:
- * - `assigneeAgentId` (workspace move: agent likely doesn't exist there)
- * - `currentTopicId` (topic ownership is also moving but the link is
- * reset to avoid surfacing a stale active topic in the new scope)
- */
- /**
- * Whether the task subtree contains rows created by someone else. Transfers
- * rehome every cascaded row, so non-owner members must not move a task tree
- * that carries teammates' subtasks.
- */
- async subtreeHasForeignRows(taskId: string): Promise<boolean> {
- const subtree = await this.collectTaskSubtree(taskId, this.db);
- return subtree.some((task) => task.createdByUserId !== this.userId);
- }
-
- async transferTo(
- taskId: string,
- targetWorkspaceId: string | null,
- targetUserId: string,
- targetVisibility?: 'private' | 'public',
- ): Promise<{ taskIds: string[] }> {
- return this.db.transaction(async (trx) => {
- const scoped = new TaskModel(trx as LobeChatDatabase, this.userId, this.workspaceId);
- const subtree = await scoped.collectTaskSubtree(taskId, trx as LobeChatDatabase);
- if (subtree.length === 0) throw new Error('Task not found');
-
- const ids = subtree.map((t) => t.id);
-
- // Visibility only applies when landing in a workspace. In personal scope
- // every row is implicitly private and the field is ignored.
- const visibilityUpdate =
- targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
-
- // Reallocate identifier + seq in target scope to avoid collisions.
- const baseSeq = await this.nextSeqIn(
- trx as LobeChatDatabase,
- targetWorkspaceId,
- targetUserId,
- );
- // Update each task individually because identifier/seq are per-row.
- for (const [idx, task] of subtree.entries()) {
- const seq = baseSeq + idx;
- const identifier = `T-${seq}`;
- await (trx as LobeChatDatabase)
- .update(tasks)
- .set({
- // Clear cross-scope refs: agent / topic may be invalid in new scope.
- assigneeAgentId: targetWorkspaceId === this.workspaceId ? task.assigneeAgentId : null,
- createdByUserId: targetUserId,
- currentTopicId: null,
- identifier,
- seq,
- updatedAt: new Date(),
- workspaceId: targetWorkspaceId,
- ...visibilityUpdate,
- })
- .where(eq(tasks.id, task.id));
- }
-
- // Update child tables that key off taskId. Child rows mirror the parent
- // task's visibility (see schema comments on task_deps / task_docs /
- // task_comments) so cascade the new visibility here too.
- const ownershipUpdate = { userId: targetUserId, workspaceId: targetWorkspaceId };
- await (trx as LobeChatDatabase)
- .update(taskDependencies)
- .set({ ...ownershipUpdate, ...visibilityUpdate })
- .where(inArray(taskDependencies.taskId, ids));
- await (trx as LobeChatDatabase)
- .update(taskDocuments)
- .set({ ...ownershipUpdate, ...visibilityUpdate })
- .where(inArray(taskDocuments.taskId, ids));
- await (trx as LobeChatDatabase)
- .update(taskComments)
- .set({ ...ownershipUpdate, ...visibilityUpdate })
- .where(inArray(taskComments.taskId, ids));
- await (trx as LobeChatDatabase)
- .update(taskActivities)
- .set({ ...ownershipUpdate, ...visibilityUpdate })
- .where(inArray(taskActivities.taskId, ids));
-
- return { taskIds: ids };
- });
- }
-
- /**
- * Deep clone a task subtree into another workspace / personal scope. Fresh
- * ids, fresh identifiers, preserved parent/child topology. Cross-scope refs
- * (agent / topic / brief / current topic) are cleared on the clones so the
- * copies start clean in the new scope.
- */
- async copyToWorkspace(
- taskId: string,
- targetWorkspaceId: string | null,
- targetUserId: string,
- targetVisibility?: 'private' | 'public',
- ): Promise<{ rootId: string }> {
- return this.db.transaction(async (trx) => {
- const scoped = new TaskModel(trx as LobeChatDatabase, this.userId, this.workspaceId);
- const subtree = await scoped.collectTaskSubtree(taskId, trx as LobeChatDatabase);
- if (subtree.length === 0) throw new Error('Task not found');
-
- // Visibility only applies when landing in a workspace.
- const visibilityOverride =
- targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
-
- // BFS clone — parent inserted before children, so we always know the
- // new parentTaskId by the time we reach the child.
- const idMap = new Map<string, string>();
- const byId = new Map(subtree.map((t) => [t.id, t]));
- const queue: string[] = [taskId];
- const seen = new Set<string>();
-
- let seq = await this.nextSeqIn(trx as LobeChatDatabase, targetWorkspaceId, targetUserId);
-
- while (queue.length > 0) {
- const currentId = queue.shift()!;
- if (seen.has(currentId)) continue;
- seen.add(currentId);
- const original = byId.get(currentId);
- if (!original) continue;
-
- const newParentId =
- currentId === taskId ? null : (idMap.get(original.parentTaskId!) ?? null);
-
- const identifier = `${DEFAULT_TASK_IDENTIFIER_PREFIX}-${seq}`;
- const inserted = (await (trx as LobeChatDatabase)
- .insert(tasks)
- .values({
- assigneeAgentId: null,
- assigneeUserId: null,
- automationMode: original.automationMode,
- // The run location is dropped the way the other cross-scope refs
- // are: a pinned machine, a path on it and a repo set all name
- // something in the scope this task came from, and the clone's first
- // assignment cannot clean them up later (it has no previous assignee
- // to diff against — see `updateWithLog`).
- config: withoutTaskExecutionSelection(
- original.config as null | Record<string, unknown>,
- ),
- context: {
- ...(original.context as Record<string, unknown>),
- duplicatedFrom: original.id,
- },
- createdByAgentId: null,
- createdByUserId: targetUserId,
- currentTopicId: null,
- description: original.description,
- error: null,
- heartbeatInterval: original.heartbeatInterval,
- heartbeatTimeout: original.heartbeatTimeout,
- identifier,
- instruction: original.instruction,
- maxTopics: original.maxTopics,
- name: original.name,
- parentTaskId: newParentId,
- priority: original.priority,
- schedulePattern: original.schedulePattern,
- scheduleTimezone: original.scheduleTimezone,
- seq,
- sortOrder: original.sortOrder,
- // Reset lifecycle: copy starts fresh, not mid-run.
- status: 'backlog',
- totalTopics: 0,
- workspaceId: targetWorkspaceId,
- ...visibilityOverride,
- } as NewTask)
- .returning({ id: tasks.id })) as { id: string }[];
-
- idMap.set(original.id, inserted[0]!.id);
- seq++;
-
- for (const c of subtree) {
- if (c.parentTaskId === original.id) queue.push(c.id);
- }
- }
-
- return { rootId: idMap.get(taskId)! };
- });
- }
-}
diff --git a/packages/database/src/models/task/activities.ts b/packages/database/src/models/task/activities.ts
new file mode 100644
index 00000000000..0d8a01ad08a
--- /dev/null
+++ b/packages/database/src/models/task/activities.ts
@@ -0,0 +1,92 @@
+import { and, desc, eq, inArray } from 'drizzle-orm';
+
+import type { NewTaskActivity, TaskActivityItem } from '../../schemas/task';
+import { taskActivities, tasks } from '../../schemas/task';
+import {
+ activitiesOwnership,
+ getTaskVisibility,
+ type TaskModelContext,
+ taskOwnership,
+} from './context';
+
+/**
+ * Append one event row. Mirrors the parent task's visibility onto the row so
+ * subsequent reads can be filtered without a JOIN — same contract as
+ * `addComment`.
+ */
+export const addActivity = async (
+ ctx: TaskModelContext,
+ data: Omit<NewTaskActivity, 'id' | 'userId' | 'workspaceId' | 'visibility'>,
+): Promise<TaskActivityItem> => {
+ const visibility = await getTaskVisibility(ctx, data.taskId);
+ const [activity] = await ctx.db
+ .insert(taskActivities)
+ .values({
+ ...data,
+ userId: ctx.userId,
+ visibility,
+ workspaceId: ctx.workspaceId ?? null,
+ })
+ .returning();
+ return activity;
+};
+
+/**
+ * Append several event rows in one INSERT. Unlike `addActivity`, the caller
+ * supplies each row's visibility — meant for a bulk write that has already
+ * read (and locked) the tasks it describes.
+ */
+export const addActivities = async (
+ ctx: TaskModelContext,
+ rows: Omit<NewTaskActivity, 'id' | 'userId' | 'workspaceId'>[],
+): Promise<TaskActivityItem[]> => {
+ if (rows.length === 0) return [];
+ return ctx.db
+ .insert(taskActivities)
+ .values(
+ rows.map((row) => ({ ...row, userId: ctx.userId, workspaceId: ctx.workspaceId ?? null })),
+ )
+ .returning();
+};
+
+/**
+ * Lock a set of tasks for the rest of the transaction and return what a
+ * bulk status write needs to describe them afterwards: the status each one
+ * is leaving and the visibility its activity row inherits. Reading these
+ * before the lock would let a concurrent edit slip in between and the log
+ * would name a transition that never happened.
+ */
+export const lockForStatusChange = async (
+ ctx: TaskModelContext,
+ ids: string[],
+): Promise<{ id: string; status: string; visibility: 'private' | 'public' }[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .select({ id: tasks.id, status: tasks.status, visibility: tasks.visibility })
+ .from(tasks)
+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)))
+ .for('update');
+};
+
+/**
+ * Oldest-first. `limit` keeps the newest N rows (still returned
+ * oldest-first) so a long-lived task does not ship its whole history on
+ * every detail poll; the table itself is the full audit trail.
+ */
+export const getActivities = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ limit?: number,
+): Promise<TaskActivityItem[]> => {
+ const where = and(eq(taskActivities.taskId, taskId), activitiesOwnership(ctx));
+ if (limit === undefined) {
+ return ctx.db.select().from(taskActivities).where(where).orderBy(taskActivities.createdAt);
+ }
+ const newest = await ctx.db
+ .select()
+ .from(taskActivities)
+ .where(where)
+ .orderBy(desc(taskActivities.createdAt), desc(taskActivities.id))
+ .limit(limit);
+ return newest.reverse();
+};
diff --git a/packages/database/src/models/task/comments.ts b/packages/database/src/models/task/comments.ts
new file mode 100644
index 00000000000..2d4edb93b26
--- /dev/null
+++ b/packages/database/src/models/task/comments.ts
@@ -0,0 +1,69 @@
+import { and, eq } from 'drizzle-orm';
+
+import type { NewTaskComment, TaskCommentItem } from '../../schemas/task';
+import { taskComments } from '../../schemas/task';
+import { commentsOwnership, getTaskVisibility, type TaskModelContext } from './context';
+
+export const addComment = async (
+ ctx: TaskModelContext,
+ data: Omit<NewTaskComment, 'id'>,
+): Promise<TaskCommentItem> => {
+ // Mirror the parent task's visibility onto the comment so subsequent
+ // reads/writes can be filtered without a JOIN. `getTaskVisibility` also
+ // provides the final live-parent write fence.
+ const visibility = await getTaskVisibility(ctx, data.taskId);
+ const [comment] = await ctx.db
+ .insert(taskComments)
+ .values({ ...data, visibility, workspaceId: ctx.workspaceId ?? null })
+ .returning();
+ return comment;
+};
+
+export const findCommentById = async (
+ ctx: TaskModelContext,
+ id: string,
+): Promise<TaskCommentItem | undefined> => {
+ const [comment] = await ctx.db
+ .select()
+ .from(taskComments)
+ .where(and(eq(taskComments.id, id), commentsOwnership(ctx)))
+ .limit(1);
+ return comment;
+};
+
+export const getComments = async (
+ ctx: TaskModelContext,
+ taskId: string,
+): Promise<TaskCommentItem[]> => {
+ return ctx.db
+ .select()
+ .from(taskComments)
+ .where(and(eq(taskComments.taskId, taskId), commentsOwnership(ctx)))
+ .orderBy(taskComments.createdAt);
+};
+
+export const deleteComment = async (ctx: TaskModelContext, id: string): Promise<boolean> => {
+ const result = await ctx.db
+ .delete(taskComments)
+ .where(and(eq(taskComments.id, id), commentsOwnership(ctx)))
+ .returning();
+ return result.length > 0;
+};
+
+export const updateComment = async (
+ ctx: TaskModelContext,
+ id: string,
+ content: string,
+ opts?: { editorData?: unknown },
+): Promise<TaskCommentItem | undefined> => {
+ const [comment] = await ctx.db
+ .update(taskComments)
+ .set({
+ content,
+ ...(opts?.editorData !== undefined ? { editorData: opts.editorData as never } : {}),
+ updatedAt: new Date(),
+ })
+ .where(and(eq(taskComments.id, id), commentsOwnership(ctx)))
+ .returning();
+ return comment;
+};
diff --git a/packages/database/src/models/task/config.ts b/packages/database/src/models/task/config.ts
new file mode 100644
index 00000000000..adc31b7a29e
--- /dev/null
+++ b/packages/database/src/models/task/config.ts
@@ -0,0 +1,86 @@
+import type { CheckpointConfig, TaskItem, TaskVerifyConfig } from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import { tasks } from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+import { type TaskModelContext, taskOwnership } from './context';
+import { writeRow } from './rows';
+
+/**
+ * Read-modify-write of the `config` column under a row lock. Every writer that
+ * derives the next config from the current one must come through here, so two
+ * of them cannot read the same snapshot and drop each other's key.
+ */
+export const rewriteConfig = async (
+ ctx: TaskModelContext,
+ id: string,
+ next: (current: Record<string, any>) => Record<string, unknown>,
+): Promise<TaskItem | null> => {
+ return ctx.db.transaction(async (tx) => {
+ const runner = tx as LobeChatDatabase;
+ const [task] = await runner
+ .select({ config: tasks.config })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)))
+ .for('update')
+ .limit(1);
+ if (!task) return null;
+
+ return writeRow(ctx, runner, id, {
+ config: next((task.config as Record<string, any>) || {}),
+ });
+ });
+};
+
+/**
+ * Patch the task's own `config.verify`. Per-key semantics (a plain deep-merge
+ * can't express "remove", and JSON can't transmit `undefined`):
+ * - `null` → clear the key (e.g. switch a rubric/verifier back to default)
+ * - omitted → leave the existing value untouched
+ * - any value → set it (arrays replace wholesale, not index-merged)
+ *
+ * The merge is scoped to the `verify` sub-object so sibling config keys
+ * (model, checkpoint, schedule, …) are preserved.
+ */
+export const updateVerifyConfig = async (
+ ctx: TaskModelContext,
+ id: string,
+ patch: { [K in keyof TaskVerifyConfig]?: TaskVerifyConfig[K] | null },
+): Promise<TaskItem | null> => {
+ return rewriteConfig(ctx, id, (config) => {
+ const next: Record<string, any> = { ...(config.verify as TaskVerifyConfig | undefined) };
+
+ for (const [key, value] of Object.entries(patch)) {
+ if (value === null) delete next[key];
+ else if (value !== undefined) next[key] = value;
+ }
+
+ return { ...config, verify: next };
+ });
+};
+
+export const getCheckpointConfig = (task: TaskItem): CheckpointConfig => {
+ return (task.config as Record<string, any>)?.checkpoint || {};
+};
+
+export const getReviewConfig = (task: TaskItem): Record<string, any> | undefined => {
+ return (task.config as Record<string, any>)?.review;
+};
+
+/**
+ * Read this task's own verify config from `config.verify`. During the
+ * migration window it falls back to the legacy `config.review` key so tasks
+ * configured before the verify cutover still surface their gate settings —
+ * only the shared `enabled` / `maxIterations` fields carry over (review's
+ * inline rubrics are dropped, no data was using them).
+ */
+export const getVerifyConfig = (task: TaskItem): TaskVerifyConfig | undefined => {
+ const config = task.config as Record<string, any> | undefined;
+ if (config?.verify) return config.verify as TaskVerifyConfig;
+
+ const review = config?.review as Record<string, any> | undefined;
+ if (review && (review.enabled !== undefined || review.maxIterations !== undefined)) {
+ return { enabled: review.enabled, maxIterations: review.maxIterations };
+ }
+ return undefined;
+};
diff --git a/packages/database/src/models/task/context.ts b/packages/database/src/models/task/context.ts
new file mode 100644
index 00000000000..8e4299d8a30
--- /dev/null
+++ b/packages/database/src/models/task/context.ts
@@ -0,0 +1,165 @@
+import { and, eq, isNull, type SQL, sql } from 'drizzle-orm';
+import type { AnyPgColumn } from 'drizzle-orm/pg-core';
+
+import {
+ taskActivities,
+ taskComments,
+ taskDependencies,
+ taskDocuments,
+ tasks,
+ taskTopics,
+} from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+
+/**
+ * The scope every `TaskModel` helper runs in. Passed as the first argument to
+ * the free functions in this directory instead of `this`, so the helper
+ * modules never import the `TaskModel` class.
+ */
+export interface TaskModelContext {
+ db: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Ownership helpers in this model come in three flavors. Choose by USE CASE,
+ * not by table — picking the wrong one led to a `seq` allocation hotfix
+ * (see git log).
+ *
+ * ┌────────────────────┬──────────────────────────────────────────────┬────────────────────────┐
+ * │ Helper │ Use for │ Visibility-aware? │
+ * ├────────────────────┼──────────────────────────────────────────────┼────────────────────────┤
+ * │ taskOwnership() │ list / read / per-row find on `tasks` │ YES — public OR owner │
+ * │ taskOwnershipSql() │ raw-SQL CTEs that need the same predicate │ YES — public OR owner │
+ * │ childOwnership() │ task_dependencies / task_documents / │ YES when caller passes │
+ * │ │ task_comments etc. (per-child-table) │ the visibility column │
+ * │ seqOwnership() │ identifier / seq allocation on `tasks` │ NO — workspace-wide │
+ * │ │ (the `(workspace_id, identifier)` unique │ (visibility filter │
+ * │ │ constraint is workspace-wide, regardless │ would skip other │
+ * │ │ of visibility) │ members' rows and │
+ * │ │ │ collide on insert) │
+ * └────────────────────┴──────────────────────────────────────────────┴────────────────────────┘
+ *
+ * Personal mode (no workspace) is always `created_by_user_id = $self AND
+ * workspace_id IS NULL` for all four helpers — visibility is inert because
+ * everything personal is implicitly owner-only.
+ */
+
+/**
+ * Compat-mode ownership predicate for the `tasks` table — **visibility-aware**.
+ * `tasks` uses `createdByUserId` instead of `userId`. Workspace mode applies
+ * visibility-aware filtering: public tasks are visible to every member,
+ * private tasks only to their creator. Use this for every list/read path.
+ * For identifier / seq allocation, use `seqOwnership` instead.
+ */
+export const taskOwnership = (ctx: TaskModelContext) =>
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: tasks.isDeleted,
+ userId: tasks.createdByUserId,
+ visibility: tasks.visibility,
+ workspaceId: tasks.workspaceId,
+ },
+ );
+
+/**
+ * Ownership predicate for task child tables (deps / docs / comments) that
+ * use a `userId` column instead of `createdByUserId`. Pass `visibility` for
+ * tables that mirror the parent task's visibility column; leave it omitted
+ * for tables that stay workspace-shared (e.g. comments).
+ */
+export const childOwnership = (
+ ctx: TaskModelContext,
+ cols: {
+ userId: AnyPgColumn;
+ visibility?: AnyPgColumn;
+ workspaceId: AnyPgColumn;
+ },
+) => buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, cols);
+
+/**
+ * Workspace-wide ownership for `tasks.seq` / `identifier` allocation —
+ * must NOT be visibility-filtered. The `(workspace_id, identifier)` unique
+ * constraint is workspace-scoped regardless of visibility, so seq lookups
+ * have to see every row in the workspace; otherwise creators of private
+ * tasks can collide on identifiers belonging to other members' rows.
+ */
+export const seqOwnership = (ctx: TaskModelContext) =>
+ ctx.workspaceId
+ ? eq(tasks.workspaceId, ctx.workspaceId)
+ : (and(eq(tasks.createdByUserId, ctx.userId), isNull(tasks.workspaceId)) as SQL);
+
+/**
+ * Raw-SQL ownership clause for use inside `db.execute(sql...)` CTEs that
+ * can't easily compose with drizzle's `and(...)` helpers. Mirrors
+ * `buildWorkspaceWhere` semantics:
+ * - workspace mode → `workspace_id = $ws AND (visibility = 'public' OR created_by_user_id = $userId)`
+ * - personal mode → `created_by_user_id = $userId AND workspace_id IS NULL`
+ */
+export const taskOwnershipSql = (ctx: TaskModelContext, alias?: string) => {
+ const prefix = alias ? sql.raw(`${alias}.`) : sql.raw('');
+ return ctx.workspaceId
+ ? sql`${prefix}workspace_id = ${ctx.workspaceId}
+ AND (${prefix}visibility = 'public' OR ${prefix}created_by_user_id = ${ctx.userId})
+ AND ${prefix}is_deleted IS NOT TRUE`
+ : sql`${prefix}created_by_user_id = ${ctx.userId} AND ${prefix}workspace_id IS NULL AND ${prefix}is_deleted IS NOT TRUE`;
+};
+
+export const depsOwnership = (ctx: TaskModelContext) =>
+ childOwnership(ctx, {
+ userId: taskDependencies.userId,
+ visibility: taskDependencies.visibility,
+ workspaceId: taskDependencies.workspaceId,
+ });
+
+/** Only used by the demotion cascade in `TaskModel.updateVisibility` — regular
+ * taskTopics reads/writes live in `TaskTopicModel`. */
+export const topicsOwnership = (ctx: TaskModelContext) =>
+ childOwnership(ctx, {
+ userId: taskTopics.userId,
+ visibility: taskTopics.visibility,
+ workspaceId: taskTopics.workspaceId,
+ });
+
+export const docsOwnership = (ctx: TaskModelContext) =>
+ childOwnership(ctx, {
+ userId: taskDocuments.userId,
+ visibility: taskDocuments.visibility,
+ workspaceId: taskDocuments.workspaceId,
+ });
+
+export const commentsOwnership = (ctx: TaskModelContext) =>
+ childOwnership(ctx, {
+ userId: taskComments.userId,
+ visibility: taskComments.visibility,
+ workspaceId: taskComments.workspaceId,
+ });
+
+export const activitiesOwnership = (ctx: TaskModelContext) =>
+ childOwnership(ctx, {
+ userId: taskActivities.userId,
+ visibility: taskActivities.visibility,
+ workspaceId: taskActivities.workspaceId,
+ });
+
+/**
+ * Look up a task's visibility so child-row inserts (deps, docs, topics) can
+ * mirror it without forcing every call site to know the value. Missing or
+ * trashed parents fail closed so no child can be attached after deletion or
+ * through a model constructed for the wrong scope.
+ */
+export const getTaskVisibility = async (
+ ctx: TaskModelContext,
+ taskId: string,
+): Promise<'private' | 'public'> => {
+ const row = await ctx.db
+ .select({ visibility: tasks.visibility })
+ .from(tasks)
+ .where(and(eq(tasks.id, taskId), taskOwnership(ctx)))
+ .limit(1);
+ if (!row[0]) throw new Error(`Task not found: ${taskId}`);
+ return row[0].visibility;
+};
diff --git a/packages/database/src/models/task/dependencies.ts b/packages/database/src/models/task/dependencies.ts
new file mode 100644
index 00000000000..6479b089fa6
--- /dev/null
+++ b/packages/database/src/models/task/dependencies.ts
@@ -0,0 +1,128 @@
+import type { TaskItem } from '@lobechat/types';
+import { and, eq, inArray, ne, sql } from 'drizzle-orm';
+
+import { taskDependencies, tasks } from '../../schemas/task';
+import { depsOwnership, type TaskModelContext, taskOwnership } from './context';
+
+export const removeDependency = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ dependsOnId: string,
+): Promise<void> => {
+ await ctx.db
+ .delete(taskDependencies)
+ .where(
+ and(
+ eq(taskDependencies.taskId, taskId),
+ eq(taskDependencies.dependsOnId, dependsOnId),
+ depsOwnership(ctx),
+ ),
+ );
+};
+
+export const getDependencies = async (ctx: TaskModelContext, taskId: string) => {
+ return ctx.db
+ .select()
+ .from(taskDependencies)
+ .where(and(eq(taskDependencies.taskId, taskId), depsOwnership(ctx)));
+};
+
+export const getDependenciesByTaskIds = async (ctx: TaskModelContext, taskIds: string[]) => {
+ if (taskIds.length === 0) return [];
+ return ctx.db
+ .select()
+ .from(taskDependencies)
+ .where(and(inArray(taskDependencies.taskId, taskIds), depsOwnership(ctx)));
+};
+
+export const getDependents = async (ctx: TaskModelContext, taskId: string) => {
+ return ctx.db
+ .select()
+ .from(taskDependencies)
+ .where(and(eq(taskDependencies.dependsOnId, taskId), depsOwnership(ctx)));
+};
+
+// Check if all dependencies of a task are completed
+export const areAllDependenciesCompleted = async (
+ ctx: TaskModelContext,
+ taskId: string,
+): Promise<boolean> => {
+ const result = await ctx.db
+ .select({ count: sql<number>`count(*)` })
+ .from(taskDependencies)
+ .innerJoin(tasks, eq(taskDependencies.dependsOnId, tasks.id))
+ .where(
+ and(
+ eq(taskDependencies.taskId, taskId),
+ eq(taskDependencies.type, 'blocks'),
+ ne(tasks.status, 'completed'),
+ depsOwnership(ctx),
+ ),
+ );
+
+ return Number(result[0].count) === 0;
+};
+
+/**
+ * Batched variant of {@link getUnlockedTasks}: discover every task unblocked
+ * by any of `completedTaskIds` with a constant number of queries instead of
+ * one dependency walk per completed task.
+ */
+export const getUnlockedTasksForMany = async (
+ ctx: TaskModelContext,
+ completedTaskIds: string[],
+): Promise<TaskItem[]> => {
+ if (completedTaskIds.length === 0) return [];
+
+ // All tasks that depend on any of the completed tasks
+ const dependents = await ctx.db
+ .select({ taskId: taskDependencies.taskId })
+ .from(taskDependencies)
+ .where(
+ and(
+ inArray(taskDependencies.dependsOnId, completedTaskIds),
+ eq(taskDependencies.type, 'blocks'),
+ depsOwnership(ctx),
+ ),
+ );
+ const dependentIds = [...new Set(dependents.map(({ taskId }) => taskId))];
+ if (dependentIds.length === 0) return [];
+
+ // Of those, which still have at least one incomplete blocking dependency
+ const blocked = await ctx.db
+ .selectDistinct({ taskId: taskDependencies.taskId })
+ .from(taskDependencies)
+ .innerJoin(tasks, eq(taskDependencies.dependsOnId, tasks.id))
+ .where(
+ and(
+ inArray(taskDependencies.taskId, dependentIds),
+ eq(taskDependencies.type, 'blocks'),
+ ne(tasks.status, 'completed'),
+ depsOwnership(ctx),
+ ),
+ );
+ const blockedIds = new Set(blocked.map(({ taskId }) => taskId));
+ const unlockedIds = dependentIds.filter((id) => !blockedIds.has(id));
+ if (unlockedIds.length === 0) return [];
+
+ // Only unlock tasks still waiting in backlog
+ return ctx.db
+ .select()
+ .from(tasks)
+ .where(and(inArray(tasks.id, unlockedIds), eq(tasks.status, 'backlog'), taskOwnership(ctx)));
+};
+
+// Check if all subtasks of a parent task are completed
+export const areAllSubtasksCompleted = async (
+ ctx: TaskModelContext,
+ parentTaskId: string,
+): Promise<boolean> => {
+ const result = await ctx.db
+ .select({ count: sql<number>`count(*)` })
+ .from(tasks)
+ .where(
+ and(eq(tasks.parentTaskId, parentTaskId), ne(tasks.status, 'completed'), taskOwnership(ctx)),
+ );
+
+ return Number(result[0].count) === 0;
+};
diff --git a/packages/database/src/models/task/documents.ts b/packages/database/src/models/task/documents.ts
new file mode 100644
index 00000000000..15faa675697
--- /dev/null
+++ b/packages/database/src/models/task/documents.ts
@@ -0,0 +1,188 @@
+import type { WorkspaceData, WorkspaceDocNode, WorkspaceTreeNode } from '@lobechat/types';
+import { and, eq, gte, sql } from 'drizzle-orm';
+
+import { documents } from '../../schemas/file';
+import { taskDocuments } from '../../schemas/task';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import {
+ docsOwnership,
+ getTaskVisibility,
+ type TaskModelContext,
+ taskOwnershipSql,
+} from './context';
+
+export const pinDocument = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ documentId: string,
+ pinnedBy: string = 'agent',
+): Promise<void> => {
+ const visibility = await getTaskVisibility(ctx, taskId);
+ await ctx.db
+ .insert(taskDocuments)
+ .values({
+ documentId,
+ pinnedBy,
+ taskId,
+ userId: ctx.userId,
+ visibility,
+ workspaceId: ctx.workspaceId ?? null,
+ })
+ .onConflictDoNothing();
+};
+
+export const unpinDocument = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ documentId: string,
+): Promise<void> => {
+ await ctx.db
+ .delete(taskDocuments)
+ .where(
+ and(
+ eq(taskDocuments.taskId, taskId),
+ eq(taskDocuments.documentId, documentId),
+ docsOwnership(ctx),
+ ),
+ );
+};
+
+export const getPinnedDocuments = async (ctx: TaskModelContext, taskId: string) => {
+ return ctx.db
+ .select()
+ .from(taskDocuments)
+ .where(and(eq(taskDocuments.taskId, taskId), docsOwnership(ctx)))
+ .orderBy(taskDocuments.createdAt);
+};
+
+/**
+ * Documents pinned to a task at or after a given timestamp, joined with the
+ * `documents` table so callers receive `{ id, kind, title }` directly.
+ *
+ * Used by topic-brief synthesis to attribute artifacts to the topic that
+ * just completed: pass the topic's start time as `since`.
+ */
+export const getDocumentsPinnedSince = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ since: Date,
+): Promise<{ id: string; kind: string | null; title: string | null }[]> => {
+ const rows = await ctx.db
+ .select({
+ fileType: documents.fileType,
+ id: documents.id,
+ title: documents.title,
+ })
+ .from(taskDocuments)
+ // Guard the referenced document too: the junction's visibility column is
+ // a write-time mirror of the TASK, so a document independently switched
+ // back to private would otherwise still leak its title here.
+ .innerJoin(
+ documents,
+ and(
+ eq(taskDocuments.documentId, documents.id),
+ buildWorkspaceWhere({ userId: ctx.userId, workspaceId: ctx.workspaceId }, documents),
+ ),
+ )
+ .where(
+ and(
+ eq(taskDocuments.taskId, taskId),
+ docsOwnership(ctx),
+ gte(taskDocuments.createdAt, since),
+ ),
+ );
+
+ return rows.map((row) => ({
+ id: row.id,
+ kind: row.fileType ?? null,
+ title: row.title ?? null,
+ }));
+};
+
+// Get all pinned docs from a task tree (recursive), returns nodeMap + tree structure
+export const getTreePinnedDocuments = async (
+ ctx: TaskModelContext,
+ rootTaskId: string,
+): Promise<WorkspaceData> => {
+ const rootOwnership = taskOwnershipSql(ctx);
+ const recursiveOwnership = taskOwnershipSql(ctx, 't');
+ const docsOwnership = ctx.workspaceId
+ ? sql`td.workspace_id = ${ctx.workspaceId}
+ AND (td.visibility = 'public' OR td.user_id = ${ctx.userId})`
+ : sql`td.user_id = ${ctx.userId} AND td.workspace_id IS NULL`;
+ // Guard the referenced document row itself: `td.visibility` is a
+ // write-time mirror of the TASK's visibility, so a document independently
+ // switched back to private would otherwise still leak its title/metadata
+ // through this join. A guarded-out document keeps its junction row but
+ // joins as NULL → surfaced as an inaccessible tombstone node.
+ const documentVisibility = ctx.workspaceId
+ ? sql`d.workspace_id = ${ctx.workspaceId}
+ AND (d.visibility IS NULL OR d.visibility = 'public' OR d.user_id = ${ctx.userId})`
+ : sql`d.user_id = ${ctx.userId} AND d.workspace_id IS NULL`;
+ const result = await ctx.db.execute(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT id, identifier FROM tasks WHERE id = ${rootTaskId} AND ${rootOwnership}
+ UNION ALL
+ SELECT t.id, t.identifier FROM tasks t
+ JOIN task_tree tt ON t.parent_task_id = tt.id
+ WHERE ${recursiveOwnership}
+ )
+ SELECT td.*, tt.id as source_task_id, tt.identifier as source_task_identifier,
+ d.id as document_ref_id,
+ d.title as document_title, d.file_type as document_file_type, d.parent_id as document_parent_id,
+ d.total_char_count as document_char_count, d.updated_at as document_updated_at
+ FROM task_documents td
+ JOIN task_tree tt ON td.task_id = tt.id
+ LEFT JOIN documents d ON td.document_id = d.id AND ${documentVisibility}
+ WHERE ${docsOwnership}
+ ORDER BY td.created_at
+ `);
+
+ // Build nodeMap
+ const nodeMap: Record<string, WorkspaceDocNode> = {};
+
+ const docIds = new Set<string>();
+
+ for (const row of result.rows as any[]) {
+ const docId = row.document_id;
+ // Join miss = the viewer lost access to the document (switched back to
+ // private) or it was deleted. Emit a titleless tombstone so the UI can
+ // render a no-access placeholder instead of leaking the title.
+ const inaccessible = row.document_ref_id === null;
+ docIds.add(docId);
+ nodeMap[docId] = {
+ charCount: inaccessible ? null : row.document_char_count,
+ createdAt: row.created_at,
+ fileType: inaccessible ? '' : row.document_file_type,
+ inaccessible: inaccessible || undefined,
+ parentId: inaccessible ? null : row.document_parent_id,
+ pinnedBy: row.pinned_by,
+ sourceTaskId: row.source_task_id,
+ sourceTaskIdentifier: row.source_task_id !== rootTaskId ? row.source_task_identifier : null,
+ title: inaccessible ? '' : row.document_title || 'Untitled',
+ updatedAt: inaccessible ? null : row.document_updated_at,
+ };
+ }
+
+ // Build tree (children as id references)
+ type TreeNode = WorkspaceTreeNode;
+
+ const childrenMap = new Map<string | null, TreeNode[]>();
+ for (const docId of docIds) {
+ const node = nodeMap[docId];
+ const parentId = node.parentId && docIds.has(node.parentId) ? node.parentId : null;
+ const list = childrenMap.get(parentId) || [];
+ list.push({ children: [], id: docId });
+ childrenMap.set(parentId, list);
+ }
+
+ const buildTree = (parentId: string | null): TreeNode[] => {
+ const nodes = childrenMap.get(parentId) || [];
+ for (const node of nodes) {
+ node.children = buildTree(node.id);
+ }
+ return nodes;
+ };
+
+ return { nodeMap, tree: buildTree(null) };
+};
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
new file mode 100644
index 00000000000..121d69aa2e4
--- /dev/null
+++ b/packages/database/src/models/task/index.ts
@@ -0,0 +1,745 @@
+import type {
+ CheckpointConfig,
+ NewTask,
+ TaskActivityLogPayload,
+ TaskActivityLogType,
+ TaskItem,
+ TaskVerifyConfig,
+ WorkspaceData,
+} from '@lobechat/types';
+import { and, eq } from 'drizzle-orm';
+
+import { merge } from '@/utils/merge';
+
+import type {
+ NewTaskActivity,
+ NewTaskComment,
+ TaskActivityItem,
+ TaskCommentItem,
+} from '../../schemas/task';
+import { taskDependencies, tasks } from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+import { ProjectModel } from '../project';
+import type { TaskListFilterOptions, TaskListOptions } from '../taskListFilters';
+import * as activities from './activities';
+import * as comments from './comments';
+import * as config from './config';
+import { getTaskVisibility, type TaskModelContext, taskOwnership } from './context';
+import * as dependencies from './dependencies';
+import * as documents from './documents';
+import * as queries from './queries';
+import * as rows from './rows';
+import type { OrphanedRunningTopic } from './scheduling';
+import * as scheduling from './scheduling';
+import * as transfer from './transfer';
+import * as tree from './tree';
+import {
+ DEFAULT_TASK_IDENTIFIER_PREFIX,
+ normalizeTaskRefs,
+ snapshotAutomation,
+ taskActivityActor,
+ TRACKED_TASK_COLUMNS,
+ withStaleReposCleared,
+} from './utils';
+
+export type { OrphanedRunningTopic } from './scheduling';
+export { isTaskIdentifierUniqueViolation, taskActivityActor } from './utils';
+
+export class TaskModel {
+ private readonly userId: string;
+ private readonly db: LobeChatDatabase;
+ private readonly workspaceId?: string;
+ /** The scope handed to the helper modules in this directory. */
+ private readonly ctx: TaskModelContext;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ this.ctx = { db, userId, workspaceId };
+ }
+
+ // ========== CRUD ==========
+
+ async create(
+ data: Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>,
+ options: { maxRetries?: number } = {},
+ ): Promise<TaskItem> {
+ const createData = normalizeTaskRefs(data);
+
+ // Keep the invariant at the write boundary, including direct model callers.
+ // Parent references here are canonical database ids; the service resolves
+ // display identifiers before calling the model.
+ if (createData.parentTaskId) {
+ const parent = await this.findById(createData.parentTaskId);
+ if (!parent) throw new Error('Task not found');
+ if (createData.projectId && createData.projectId !== parent.projectId) {
+ throw new Error('Subtask must belong to the same project as its parent');
+ }
+ createData.projectId ??= parent.projectId;
+ }
+
+ // A prefix is derived from placement, never accepted as a creation field.
+ let identifierPrefix = DEFAULT_TASK_IDENTIFIER_PREFIX;
+ if (createData.projectId) {
+ const project = await new ProjectModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findManageableById(createData.projectId);
+ if (!project) throw new Error('Project not found');
+ identifierPrefix = project.identifier;
+ }
+
+ return rows.insertWithNextSeq(this.ctx, createData, identifierPrefix, options.maxRetries ?? 5);
+ }
+
+ async findById(id: string): Promise<TaskItem | null> {
+ return rows.findById(this.ctx, id);
+ }
+
+ async findByIds(ids: string[]): Promise<TaskItem[]> {
+ return rows.findByIds(this.ctx, ids);
+ }
+
+ async findAssigneesByIds(
+ ids: string[],
+ ): Promise<{ assigneeAgentId: string | null; id: string }[]> {
+ return rows.findAssigneesByIds(this.ctx, ids);
+ }
+
+ async resolveMany(idsOrIdentifiers: string[]): Promise<TaskItem[]> {
+ return rows.resolveMany(this.ctx, idsOrIdentifiers);
+ }
+
+ // Resolve id or identifier (e.g. 'T-1') to a task
+ async resolve(idOrIdentifier: string): Promise<TaskItem | null> {
+ if (idOrIdentifier.startsWith('task_')) return this.findById(idOrIdentifier);
+ return this.findByIdentifier(idOrIdentifier.toUpperCase());
+ }
+
+ async findByIdentifier(identifier: string): Promise<TaskItem | null> {
+ return rows.findByIdentifier(this.ctx, identifier);
+ }
+
+ async update(
+ id: string,
+ data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
+ ): Promise<TaskItem | null> {
+ if (Object.keys(data).length === 0) return this.findById(id);
+
+ // A reassignment is not a plain column write: the row being moved away from
+ // decides whether the previous assignee's cloud-repo selection has to go,
+ // so read it under a lock — a config write landing between the read and the
+ // merge below would be lost. Every writer of the assignee column comes
+ // through here (`updateWithLog`, the update procedure, the coordinator's
+ // handoff/restart, the runner's inbox fallback), so this is the one place
+ // the invariant has to hold; `updateWithLog` locks its own read for the
+ // activity log and then delegates.
+ if (data.assigneeAgentId === undefined) return rows.writeRow(this.ctx, this.db, id, data);
+
+ return this.db.transaction(async (tx) => {
+ const runner = tx as LobeChatDatabase;
+ const [before] = await runner
+ .select({ assigneeAgentId: tasks.assigneeAgentId, config: tasks.config })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), taskOwnership(this.ctx)))
+ .for('update')
+ .limit(1);
+ if (!before) return null;
+
+ return rows.writeRow(this.ctx, runner, id, withStaleReposCleared(before, data));
+ });
+ }
+
+ async delete(id: string): Promise<boolean> {
+ return rows.deleteTask(this.ctx, id);
+ }
+
+ /**
+ * Write `visibility` onto a task subtree and its task-owned child rows.
+ * Task aggregate only — callers changing a task's visibility go through
+ * `TaskSubtreeRepository.updateVisibility`, which also mirrors it onto
+ * the task's Work row in the same transaction.
+ */
+ async setSubtreeVisibility(
+ rootId: string,
+ descendantIds: string[],
+ visibility: 'private' | 'public',
+ ): Promise<TaskItem | null> {
+ return tree.setSubtreeVisibility(this.ctx, rootId, descendantIds, visibility);
+ }
+
+ async countTasksBlockingAgentDemotion(
+ assigneeAgentId: string,
+ agentOwnerUserId: string,
+ ): Promise<number> {
+ return rows.countTasksBlockingAgentDemotion(this.ctx, assigneeAgentId, agentOwnerUserId);
+ }
+
+ async subtreeHasOtherCreators(rootTaskId: string, creatorUserId: string): Promise<boolean> {
+ return rows.subtreeHasOtherCreators(this.ctx, rootTaskId, creatorUserId);
+ }
+
+ async lockForUpdate(id: string): Promise<boolean> {
+ return rows.lockForUpdate(this.ctx, id);
+ }
+
+ async deleteIfStatus(id: string, status: string): Promise<boolean> {
+ return rows.deleteIfStatus(this.ctx, id, status);
+ }
+
+ async deleteAll(options?: { restrictToCreator?: boolean }): Promise<number> {
+ return rows.deleteAll(this.ctx, options);
+ }
+
+ /**
+ * Delete the given tasks (task aggregate only). Use
+ * `TaskSubtreeRepository.deleteSubtree` to also drop their acceptances.
+ */
+ async deleteByIds(taskIds: string[]): Promise<number> {
+ return tree.deleteTasksByIds(this.ctx, taskIds);
+ }
+
+ // ========== Query ==========
+
+ async groupList(
+ options: TaskListFilterOptions & {
+ excludeStatuses?: string[];
+ groupBy?: 'agent' | 'assignee' | 'member' | 'priority';
+ groups?: Array<{
+ key: string;
+ limit?: number;
+ offset?: number;
+ statuses: string[];
+ }>;
+ },
+ ): Promise<
+ Array<{
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ hasMore: boolean;
+ key: string;
+ limit: number;
+ offset: number;
+ priority?: number;
+ tasks: TaskItem[];
+ total: number;
+ }>
+ > {
+ return queries.groupList(this.ctx, options);
+ }
+
+ async list(options: TaskListOptions = {}): Promise<{ tasks: TaskItem[]; total: number }> {
+ return queries.list(this.ctx, options);
+ }
+
+ async reorder(order: Array<{ id: string; sortOrder: number }>): Promise<void> {
+ return rows.reorder(this.ctx, order);
+ }
+
+ async findSubtasks(parentTaskId: string): Promise<TaskItem[]> {
+ return tree.findSubtasks(this.ctx, parentTaskId);
+ }
+
+ async findAllDescendants(rootTaskId: string): Promise<TaskItem[]> {
+ return tree.findAllDescendants(this.ctx, rootTaskId);
+ }
+
+ async getTaskTree(rootTaskId: string): Promise<TaskItem[]> {
+ return tree.getTaskTree(this.ctx, rootTaskId);
+ }
+
+ async getTreeAgentIdsForTaskIds(taskIds: string[]): Promise<Record<string, string[]>> {
+ return tree.getTreeAgentIdsForTaskIds(this.ctx, taskIds);
+ }
+
+ // ========== Status ==========
+
+ async updateStatus(
+ id: string,
+ status: string,
+ extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },
+ ): Promise<TaskItem | null> {
+ return this.update(id, { status, ...extra });
+ }
+
+ async updateStatusIfCurrent(
+ id: string,
+ currentStatus: string,
+ status: string,
+ extra?: { completedAt?: Date | null; error?: string | null; startedAt?: Date },
+ ): Promise<TaskItem | null> {
+ return rows.updateStatusIfCurrent(this.ctx, id, currentStatus, status, extra);
+ }
+
+ async batchUpdateStatus(ids: string[], status: string): Promise<number> {
+ return rows.batchUpdateStatus(this.ctx, ids, status);
+ }
+
+ async updateStatusForIds(
+ ids: string[],
+ status: string,
+ extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },
+ ): Promise<TaskItem[]> {
+ return rows.updateStatusForIds(this.ctx, ids, status, extra);
+ }
+
+ // ========== Config ==========
+
+ /**
+ * Safely merge-update the task's config object.
+ * Reads the current config, deep-merges the incoming partial, and writes back.
+ *
+ * The read is taken under a row lock: several independent writers merge into
+ * this one column (model, run location, checkpoint, review, verify), and two
+ * of them reading the same snapshot would let the later whole-column write
+ * silently drop the other's key.
+ */
+ async updateTaskConfig(id: string, partial: Record<string, unknown>): Promise<TaskItem | null> {
+ return config.rewriteConfig(this.ctx, id, (current) => merge(current, partial));
+ }
+
+ // ========== Context (runtime state) ==========
+
+ /**
+ * Deep-merge into the task's context JSONB. Used by the heartbeat scheduler
+ * to update `context.scheduler.{tickMessageId, consecutiveFailures, ...}`
+ * without disturbing other namespaces under context.
+ */
+ async updateContext(id: string, partial: Record<string, unknown>): Promise<TaskItem | null> {
+ const task = await this.findById(id);
+ if (!task) return null;
+
+ const current = (task.context as Record<string, unknown>) || {};
+ const context = merge(current, partial);
+ return this.update(id, { context });
+ }
+
+ // ========== Checkpoint ==========
+
+ getCheckpointConfig(task: TaskItem): CheckpointConfig {
+ return config.getCheckpointConfig(task);
+ }
+
+ async updateCheckpointConfig(id: string, checkpoint: CheckpointConfig): Promise<TaskItem | null> {
+ return this.updateTaskConfig(id, { checkpoint });
+ }
+
+ // ========== Review Config ==========
+
+ getReviewConfig(task: TaskItem): Record<string, any> | undefined {
+ return config.getReviewConfig(task);
+ }
+
+ async updateReviewConfig(id: string, review: Record<string, any>): Promise<TaskItem | null> {
+ return this.updateTaskConfig(id, { review });
+ }
+
+ // ========== Verify Config ==========
+
+ getVerifyConfig(task: TaskItem): TaskVerifyConfig | undefined {
+ return config.getVerifyConfig(task);
+ }
+
+ /**
+ * Resolve the effective verify config for a task, honoring subtask
+ * inheritance. Whole-config override semantics: the task uses its own config
+ * when it has one, otherwise it walks up `parentTaskId` and adopts the
+ * nearest ancestor's config in full (never a field-level merge of the two).
+ * Returns `undefined` when no task in the chain has a verify config.
+ */
+ async resolveVerifyConfig(taskId: string): Promise<TaskVerifyConfig | undefined> {
+ const seen = new Set<string>();
+ let currentId: string | null = taskId;
+
+ while (currentId && !seen.has(currentId)) {
+ seen.add(currentId);
+ const task = await this.findById(currentId);
+ if (!task) break;
+
+ const config = this.getVerifyConfig(task);
+ if (config) return config;
+
+ currentId = task.parentTaskId;
+ }
+ return undefined;
+ }
+
+ async updateVerifyConfig(
+ id: string,
+ patch: { [K in keyof TaskVerifyConfig]?: TaskVerifyConfig[K] | null },
+ ): Promise<TaskItem | null> {
+ return config.updateVerifyConfig(this.ctx, id, patch);
+ }
+
+ // Check if a task should pause after a topic completes
+ // Default: pause (when no checkpoint config is set)
+ // Explicit: pause only if topic.after is true
+ shouldPauseOnTopicComplete(task: TaskItem): boolean {
+ const checkpoint = this.getCheckpointConfig(task);
+ const hasAnyConfig = Object.keys(checkpoint).length > 0;
+ return hasAnyConfig ? !!checkpoint.topic?.after : true;
+ }
+
+ // Check if a task should be paused before starting (parent's tasks.beforeIds)
+ shouldPauseBeforeStart(parentTask: TaskItem, childIdentifier: string): boolean {
+ const checkpoint = this.getCheckpointConfig(parentTask);
+ return checkpoint.tasks?.beforeIds?.includes(childIdentifier) ?? false;
+ }
+
+ // Check if a task should be paused after completing (parent's tasks.afterIds)
+ shouldPauseAfterComplete(parentTask: TaskItem, childIdentifier: string): boolean {
+ const checkpoint = this.getCheckpointConfig(parentTask);
+ return checkpoint.tasks?.afterIds?.includes(childIdentifier) ?? false;
+ }
+
+ // ========== Heartbeat ==========
+
+ async updateHeartbeat(id: string): Promise<void> {
+ return rows.updateHeartbeat(this.ctx, id);
+ }
+
+ static async getScheduledTasks(db: LobeChatDatabase): Promise<TaskItem[]> {
+ return scheduling.getScheduledTasks(db);
+ }
+
+ static async swapDispatchedScheduleOccurrence(
+ db: LobeChatDatabase,
+ taskId: string,
+ expected: string | null,
+ next: string | null,
+ ): Promise<boolean> {
+ return scheduling.swapDispatchedScheduleOccurrence(db, taskId, expected, next);
+ }
+
+ static async findStuckTasks(db: LobeChatDatabase): Promise<TaskItem[]> {
+ return scheduling.findStuckTasks(db);
+ }
+
+ static async findOrphanedRunningTopics(
+ db: LobeChatDatabase,
+ options: { limit?: number; staleBefore: Date },
+ ): Promise<OrphanedRunningTopic[]> {
+ return scheduling.findOrphanedRunningTopics(db, options);
+ }
+
+ // ========== Dependencies ==========
+
+ async addDependency(taskId: string, dependsOnId: string, type: string = 'blocks'): Promise<void> {
+ const dependencyTasks = await this.findByIds([taskId, dependsOnId]);
+ const task = dependencyTasks.find(({ id }) => id === taskId);
+ const dependsOn = dependencyTasks.find(({ id }) => id === dependsOnId);
+ if (!task || !dependsOn) throw new Error('Task not found');
+ if (task.projectId !== dependsOn.projectId && (task.projectId || dependsOn.projectId)) {
+ throw new Error('Task dependencies cannot cross project boundaries');
+ }
+
+ const visibility = await getTaskVisibility(this.ctx, taskId);
+ await this.db
+ .insert(taskDependencies)
+ .values({
+ dependsOnId,
+ taskId,
+ type,
+ userId: this.userId,
+ visibility,
+ workspaceId: this.workspaceId ?? null,
+ })
+ .onConflictDoNothing();
+ }
+
+ async removeDependency(taskId: string, dependsOnId: string): Promise<void> {
+ return dependencies.removeDependency(this.ctx, taskId, dependsOnId);
+ }
+
+ async getDependencies(taskId: string) {
+ return dependencies.getDependencies(this.ctx, taskId);
+ }
+
+ async getDependenciesByTaskIds(taskIds: string[]) {
+ return dependencies.getDependenciesByTaskIds(this.ctx, taskIds);
+ }
+
+ async getDependents(taskId: string) {
+ return dependencies.getDependents(this.ctx, taskId);
+ }
+
+ async areAllDependenciesCompleted(taskId: string): Promise<boolean> {
+ return dependencies.areAllDependenciesCompleted(this.ctx, taskId);
+ }
+
+ // Find tasks that are now unblocked after a dependency completes
+ async getUnlockedTasks(completedTaskId: string): Promise<TaskItem[]> {
+ return this.getUnlockedTasksForMany([completedTaskId]);
+ }
+
+ async getUnlockedTasksForMany(completedTaskIds: string[]): Promise<TaskItem[]> {
+ return dependencies.getUnlockedTasksForMany(this.ctx, completedTaskIds);
+ }
+
+ async areAllSubtasksCompleted(parentTaskId: string): Promise<boolean> {
+ return dependencies.areAllSubtasksCompleted(this.ctx, parentTaskId);
+ }
+
+ // ========== Documents (MVP Workspace) ==========
+
+ async pinDocument(taskId: string, documentId: string, pinnedBy: string = 'agent'): Promise<void> {
+ return documents.pinDocument(this.ctx, taskId, documentId, pinnedBy);
+ }
+
+ async unpinDocument(taskId: string, documentId: string): Promise<void> {
+ return documents.unpinDocument(this.ctx, taskId, documentId);
+ }
+
+ async getPinnedDocuments(taskId: string) {
+ return documents.getPinnedDocuments(this.ctx, taskId);
+ }
+
+ async getDocumentsPinnedSince(
+ taskId: string,
+ since: Date,
+ ): Promise<{ id: string; kind: string | null; title: string | null }[]> {
+ return documents.getDocumentsPinnedSince(this.ctx, taskId, since);
+ }
+
+ async getTreePinnedDocuments(rootTaskId: string): Promise<WorkspaceData> {
+ return documents.getTreePinnedDocuments(this.ctx, rootTaskId);
+ }
+
+ // ========== Topic Management ==========
+
+ async incrementTopicCount(id: string): Promise<void> {
+ return rows.incrementTopicCount(this.ctx, id);
+ }
+
+ async updateCurrentTopic(id: string, topicId: string): Promise<void> {
+ return rows.updateCurrentTopic(this.ctx, id, topicId);
+ }
+
+ // ========== Comments ==========
+
+ async addComment(data: Omit<NewTaskComment, 'id'>): Promise<TaskCommentItem> {
+ return comments.addComment(this.ctx, data);
+ }
+
+ async findCommentById(id: string): Promise<TaskCommentItem | undefined> {
+ return comments.findCommentById(this.ctx, id);
+ }
+
+ async getComments(taskId: string): Promise<TaskCommentItem[]> {
+ return comments.getComments(this.ctx, taskId);
+ }
+
+ async deleteComment(id: string): Promise<boolean> {
+ return comments.deleteComment(this.ctx, id);
+ }
+
+ async updateComment(
+ id: string,
+ content: string,
+ opts?: { editorData?: unknown },
+ ): Promise<TaskCommentItem | undefined> {
+ return comments.updateComment(this.ctx, id, content, opts);
+ }
+
+ // ========== Activities ==========
+
+ async addActivity(
+ data: Omit<NewTaskActivity, 'id' | 'userId' | 'workspaceId' | 'visibility'>,
+ ): Promise<TaskActivityItem> {
+ return activities.addActivity(this.ctx, data);
+ }
+
+ async addActivities(
+ rows: Omit<NewTaskActivity, 'id' | 'userId' | 'workspaceId'>[],
+ ): Promise<TaskActivityItem[]> {
+ return activities.addActivities(this.ctx, rows);
+ }
+
+ async lockForStatusChange(
+ ids: string[],
+ ): Promise<{ id: string; status: string; visibility: 'private' | 'public' }[]> {
+ return activities.lockForStatusChange(this.ctx, ids);
+ }
+
+ /**
+ * Update a task and append one event per tracked field that actually
+ * changed, in ONE transaction, with the previous values taken from a
+ * **locked** read of the row.
+ *
+ * The lock is the point. Reading the "before" value outside the write lets
+ * two concurrent edits both observe the same origin — an A→B and an A→C
+ * racing on one task persist A→B then B→C while a lock-free recorder logs
+ * A→B and A→C, losing the middle state. Rows are inserted next to the write
+ * they describe, so their order cannot disagree with the order the updates
+ * landed in.
+ *
+ * Which edits reach the feed is decided by the caller, not here: anything
+ * that goes through this method is logged. Person-made changes (the update
+ * procedure, the agent `editTask` tool, the status picker) and the runner's
+ * inbox fallback come here; the runner / lifecycle / watchdog status
+ * transitions use the plain writers, because the run row already tells that
+ * story.
+ */
+ async updateWithLog(
+ id: string,
+ data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
+ actor: { agentId?: string | null; userId?: string | null },
+ options: {
+ /**
+ * Deep-merged into the `config` column under this update's row lock,
+ * instead of replacing it. A client that edits one key (the schedule
+ * cap) must not send back a whole-config snapshot that can predate
+ * another tab's or member's write of a different key.
+ */
+ configPatch?: Record<string, unknown>;
+ } = {},
+ ): Promise<TaskItem | null> {
+ const { configPatch } = options;
+ const touched = !!configPatch || TRACKED_TASK_COLUMNS.some((col) => data[col] !== undefined);
+ // Nothing to diff against: an ordinary rename should not pay for a lock.
+ if (!touched) return this.update(id, data);
+
+ return this.db.transaction(async (tx) => {
+ const runner = tx as LobeChatDatabase;
+ const [before] = await runner
+ .select({
+ assigneeAgentId: tasks.assigneeAgentId,
+ assigneeUserId: tasks.assigneeUserId,
+ automationMode: tasks.automationMode,
+ config: tasks.config,
+ heartbeatInterval: tasks.heartbeatInterval,
+ priority: tasks.priority,
+ schedulePattern: tasks.schedulePattern,
+ scheduleTimezone: tasks.scheduleTimezone,
+ status: tasks.status,
+ })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), taskOwnership(this.ctx)))
+ .for('update')
+ .limit(1);
+ if (!before) return null;
+
+ const scoped = new TaskModel(runner, this.userId, this.workspaceId);
+
+ // The reassignment rule — dropping the previous assignee's cloud-repo
+ // selection — lives in `update`, which is the only writer of the assignee
+ // column, so this locked read is kept for the activity-log diff only and
+ // the write below re-checks the rule in the same transaction.
+ const writeData = configPatch
+ ? {
+ ...data,
+ config: merge(
+ ((data.config ?? before.config) as Record<string, unknown> | null) ?? {},
+ configPatch,
+ ),
+ }
+ : data;
+ const updated = await scoped.update(id, writeData);
+ if (!updated) return null;
+
+ const events: { payload: TaskActivityLogPayload; type: TaskActivityLogType }[] = [];
+
+ // The two assignee slots are independent — one edit can move both, and
+ // each gets its own row so the feed reads one change per line.
+ if (before.assigneeAgentId !== updated.assigneeAgentId) {
+ events.push({
+ payload: { fromId: before.assigneeAgentId, toId: updated.assigneeAgentId },
+ type: 'assignee_agent',
+ });
+ }
+ if (before.assigneeUserId !== updated.assigneeUserId) {
+ events.push({
+ payload: { fromId: before.assigneeUserId, toId: updated.assigneeUserId },
+ type: 'assignee_user',
+ });
+ }
+ if (before.status !== updated.status) {
+ events.push({ payload: { from: before.status, to: updated.status }, type: 'status' });
+ }
+ if ((before.priority ?? null) !== (updated.priority ?? null)) {
+ events.push({
+ payload: { from: before.priority ?? null, to: updated.priority ?? null },
+ type: 'priority',
+ });
+ }
+ const automationBefore = snapshotAutomation(before);
+ const automationAfter = snapshotAutomation(updated);
+ if (JSON.stringify(automationBefore) !== JSON.stringify(automationAfter)) {
+ events.push({
+ payload: { from: automationBefore, to: automationAfter },
+ type: 'automation',
+ });
+ }
+
+ const { actorKind, ...actorColumns } = taskActivityActor(actor);
+ for (const event of events) {
+ await scoped.addActivity({
+ ...actorColumns,
+ payload: { ...event.payload, actorKind },
+ taskId: id,
+ type: event.type,
+ });
+ }
+
+ return updated;
+ });
+ }
+
+ async getActivities(taskId: string, limit?: number): Promise<TaskActivityItem[]> {
+ return activities.getActivities(this.ctx, taskId, limit);
+ }
+
+ // ========== Transfer / Copy ==========
+
+ /**
+ * Transfer a task subtree to another workspace / personal scope. Reallocates
+ * `identifier`/`seq` in the target scope and rewrites the child tables that
+ * mirror the parent's ownership (`task_dependencies`, `task_documents`,
+ * `task_comments`, `task_activities`) so the ownership predicates keep
+ * resolving after the move — those mirrored columns are what authorizes
+ * reads, so a child left behind goes invisible in the destination scope.
+ *
+ * NOTE: `task_topics` and `briefs` carry the same mirrored columns but are
+ * not rewritten here. Pre-existing gap, called out rather than widened.
+ *
+ * Cross-scope references that may no longer be valid are cleared:
+ * - `assigneeAgentId` (workspace move: agent likely doesn't exist there)
+ * - `currentTopicId` (topic ownership is also moving but the link is
+ * reset to avoid surfacing a stale active topic in the new scope)
+ */
+ /**
+ * Whether the task subtree contains rows created by someone else. Transfers
+ * rehome every cascaded row, so non-owner members must not move a task tree
+ * that carries teammates' subtasks.
+ */
+ async subtreeHasForeignRows(taskId: string): Promise<boolean> {
+ const subtree = await tree.collectTaskSubtree(this.ctx, taskId, this.db);
+ return subtree.some((task) => task.createdByUserId !== this.userId);
+ }
+
+ async transferTo(
+ taskId: string,
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+ ): Promise<{ taskIds: string[] }> {
+ return transfer.transferTo(this.ctx, taskId, targetWorkspaceId, targetUserId, targetVisibility);
+ }
+
+ async copyToWorkspace(
+ taskId: string,
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+ ): Promise<{ rootId: string }> {
+ return transfer.copyToWorkspace(
+ this.ctx,
+ taskId,
+ targetWorkspaceId,
+ targetUserId,
+ targetVisibility,
+ );
+ }
+}
diff --git a/packages/database/src/models/task/queries.ts b/packages/database/src/models/task/queries.ts
new file mode 100644
index 00000000000..ce7832f370b
--- /dev/null
+++ b/packages/database/src/models/task/queries.ts
@@ -0,0 +1,505 @@
+import type { TaskItem, TaskSubtaskProgress } from '@lobechat/types';
+import {
+ and,
+ desc,
+ eq,
+ getTableColumns,
+ inArray,
+ isNull,
+ lt,
+ notInArray,
+ or,
+ type SQL,
+ sql,
+} from 'drizzle-orm';
+
+import { tasks, taskTopics } from '../../schemas/task';
+import { topics } from '../../schemas/topic';
+import {
+ buildTaskListFilters,
+ type TaskListFilterOptions,
+ type TaskListOptions,
+} from '../taskListFilters';
+import { type TaskModelContext, taskOwnership, taskOwnershipSql } from './context';
+
+interface TaskRunStats extends Record<string, unknown> {
+ root_id: string;
+ total_run_cost: number;
+ total_run_duration: number;
+}
+
+interface TaskSubtaskProgressRow extends Record<string, unknown> {
+ completed: number;
+ root_id: string;
+ total: number;
+}
+
+const buildListConditions = (ctx: TaskModelContext, options: TaskListFilterOptions): SQL[] => [
+ taskOwnership(ctx),
+ ...buildTaskListFilters(options),
+];
+
+export const groupList = async (
+ ctx: TaskModelContext,
+ options: TaskListFilterOptions & {
+ excludeStatuses?: string[];
+ groupBy?: 'agent' | 'assignee' | 'member' | 'priority';
+ groups?: Array<{
+ key: string;
+ limit?: number;
+ offset?: number;
+ statuses: string[];
+ }>;
+ },
+): Promise<
+ Array<{
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ hasMore: boolean;
+ key: string;
+ limit: number;
+ offset: number;
+ priority?: number;
+ tasks: TaskItem[];
+ total: number;
+ }>
+> => {
+ const { assigneeAgentId, excludeStatuses, groupBy, groups } = options;
+
+ if ((!groups || groups.length === 0) && !groupBy) {
+ throw new Error('Task groups or a grouping dimension are required');
+ }
+
+ const baseConditions = buildListConditions(ctx, options);
+ if (excludeStatuses?.length) {
+ baseConditions.push(notInArray(tasks.status, excludeStatuses));
+ }
+
+ interface GroupQuery {
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ conditions: SQL[];
+ key: string;
+ limit: number;
+ offset: number;
+ prefetchedTasks?: TaskItem[];
+ priority?: number;
+ total: number;
+ }
+
+ let groupQueries: GroupQuery[];
+
+ if (groupBy === 'assignee') {
+ const limit = 50;
+ const assigneeGroupKey = sql<string>`case
+ when ${tasks.assigneeAgentId} is not null then 'assignee:' || ${tasks.assigneeAgentId}
+ when ${tasks.assigneeUserId} is not null then 'assignee:user:' || ${tasks.assigneeUserId}
+ else 'assignee:unassigned'
+ end`;
+ const rankedTasks = ctx.db
+ .select({
+ ...getTableColumns(tasks),
+ assigneeGroupKey: assigneeGroupKey.as('assignee_group_key'),
+ groupRank:
+ sql<number>`row_number() over (partition by ${assigneeGroupKey} order by ${tasks.createdAt} desc, ${tasks.seq} desc)`.as(
+ 'group_rank',
+ ),
+ })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .as('ranked_assignee_tasks');
+ const [countResult, rankedTaskRows] = await Promise.all([
+ ctx.db
+ .select({
+ assigneeGroupKey: assigneeGroupKey.as('assignee_group_key'),
+ count: sql<number>`count(*)`,
+ })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .groupBy(assigneeGroupKey),
+ ctx.db
+ .select()
+ .from(rankedTasks)
+ .where(sql`${rankedTasks.groupRank} <= ${limit}`)
+ .orderBy(rankedTasks.assigneeGroupKey, rankedTasks.groupRank),
+ ]);
+ const assigneeCounts = new Map(
+ countResult.map((row) => [row.assigneeGroupKey, Number(row.count)]),
+ );
+ const tasksByAssignee = new Map<string, TaskItem[]>();
+ for (const row of rankedTaskRows) {
+ const { assigneeGroupKey: groupKey, groupRank: _groupRank, ...task } = row;
+ const groupTasks = tasksByAssignee.get(groupKey) ?? [];
+ groupTasks.push(task);
+ tasksByAssignee.set(groupKey, groupTasks);
+ }
+
+ // `assignee` is the released hybrid grouping contract: agents take
+ // precedence, member-only tasks get their own user group, and only tasks
+ // with neither assignee are unassigned. New clients use `agent` for the
+ // agent-only board instead of changing this existing API in place.
+ if (!assigneeAgentId && !assigneeCounts.has('assignee:unassigned')) {
+ assigneeCounts.set('assignee:unassigned', 0);
+ }
+
+ groupQueries = [...assigneeCounts.entries()].map(([key, total]) => {
+ const isUnassigned = key === 'assignee:unassigned';
+ const isUser = key.startsWith('assignee:user:');
+ const groupAssigneeAgentId =
+ isUnassigned || isUser ? (isUnassigned ? null : undefined) : key.slice('assignee:'.length);
+ const groupAssigneeUserId = isUser
+ ? key.slice('assignee:user:'.length)
+ : isUnassigned
+ ? null
+ : undefined;
+ const conditions = isUser
+ ? [and(isNull(tasks.assigneeAgentId), eq(tasks.assigneeUserId, groupAssigneeUserId!))!]
+ : isUnassigned
+ ? [and(isNull(tasks.assigneeAgentId), isNull(tasks.assigneeUserId))!]
+ : [eq(tasks.assigneeAgentId, groupAssigneeAgentId!)];
+
+ return {
+ assigneeAgentId: groupAssigneeAgentId,
+ assigneeUserId: groupAssigneeUserId,
+ conditions,
+ key,
+ limit,
+ offset: 0,
+ prefetchedTasks: tasksByAssignee.get(key) ?? [],
+ total,
+ };
+ });
+ } else if (groupBy === 'agent' || groupBy === 'member') {
+ const limit = 50;
+ const groupColumn = groupBy === 'agent' ? tasks.assigneeAgentId : tasks.assigneeUserId;
+ const groupPrefix = groupBy === 'agent' ? 'assignee:' : 'member:';
+ const unassignedKey = `${groupPrefix}unassigned`;
+ const assigneeGroupKey = sql<string>`case
+ when ${groupColumn} is not null then ${groupPrefix} || ${groupColumn}
+ else ${unassignedKey}
+ end`;
+ const rankedTasks = ctx.db
+ .select({
+ ...getTableColumns(tasks),
+ assigneeGroupKey: assigneeGroupKey.as('assignee_group_key'),
+ groupRank:
+ sql<number>`row_number() over (partition by ${assigneeGroupKey} order by ${tasks.createdAt} desc, ${tasks.seq} desc)`.as(
+ 'group_rank',
+ ),
+ })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .as('ranked_assignee_tasks');
+ const [countResult, rankedTaskRows] = await Promise.all([
+ ctx.db
+ .select({
+ assigneeId: groupColumn,
+ count: sql<number>`count(*)`,
+ })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .groupBy(groupColumn),
+ ctx.db
+ .select()
+ .from(rankedTasks)
+ .where(sql`${rankedTasks.groupRank} <= ${limit}`)
+ .orderBy(rankedTasks.assigneeGroupKey, rankedTasks.groupRank),
+ ]);
+ const assigneeCounts = new Map(
+ countResult.map((row) => [
+ row.assigneeId ? `${groupPrefix}${row.assigneeId}` : unassignedKey,
+ Number(row.count),
+ ]),
+ );
+ const tasksByAssignee = new Map<string, TaskItem[]>();
+ for (const row of rankedTaskRows) {
+ const { assigneeGroupKey: groupKey, groupRank: _groupRank, ...task } = row;
+ const groupTasks = tasksByAssignee.get(groupKey) ?? [];
+ groupTasks.push(task);
+ tasksByAssignee.set(groupKey, groupTasks);
+ }
+
+ // Keep an empty Unassigned column as a stable drop target. Agent-scoped
+ // boards omit the Agent-unassigned column because their base filter
+ // guarantees one assignee, while Member grouping remains independent.
+ if ((groupBy === 'member' || !assigneeAgentId) && !assigneeCounts.has(unassignedKey)) {
+ assigneeCounts.set(unassignedKey, 0);
+ }
+
+ groupQueries = [...assigneeCounts.entries()].map(([key, total]) => {
+ const isUnassigned = key === unassignedKey;
+ const assigneeId = isUnassigned ? null : key.slice(groupPrefix.length);
+ const groupAssigneeAgentId = groupBy === 'agent' ? assigneeId : undefined;
+ const groupAssigneeUserId = groupBy === 'member' ? assigneeId : undefined;
+ const conditions = [isUnassigned ? isNull(groupColumn) : eq(groupColumn, assigneeId!)];
+
+ return {
+ assigneeAgentId: groupAssigneeAgentId,
+ assigneeUserId: groupAssigneeUserId,
+ conditions,
+ key,
+ limit,
+ offset: 0,
+ prefetchedTasks: tasksByAssignee.get(key) ?? [],
+ total,
+ };
+ });
+ } else if (groupBy === 'priority') {
+ const priorities = [1, 2, 3, 4, 0];
+ const countQuery = ctx.db
+ .select({ count: sql<number>`count(*)`, priority: tasks.priority })
+ .from(tasks)
+ .where(and(...baseConditions))
+ .groupBy(tasks.priority);
+ const taskQueries = priorities.map(async (priority) => {
+ const conditions = [
+ priority === 0
+ ? or(eq(tasks.priority, priority), isNull(tasks.priority))!
+ : eq(tasks.priority, priority),
+ ];
+ const limit = 50;
+ const offset = 0;
+ const prefetchedTasks = await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(...baseConditions, ...conditions))
+ .orderBy(desc(tasks.createdAt), desc(tasks.seq))
+ .limit(limit)
+ .offset(offset);
+
+ return {
+ conditions,
+ key: `priority:${priority}`,
+ limit,
+ offset,
+ prefetchedTasks,
+ priority,
+ total: 0,
+ };
+ });
+ const [countResult, queriedGroups] = await Promise.all([countQuery, Promise.all(taskQueries)]);
+ const priorityCounts = new Map<number, number>();
+ for (const row of countResult) {
+ const priority = row.priority ?? 0;
+ priorityCounts.set(priority, (priorityCounts.get(priority) ?? 0) + Number(row.count));
+ }
+
+ // Priority is a finite dimension, so include empty values as usable drop
+ // targets. The order matches the task list's semantic rank.
+ groupQueries = queriedGroups.map((group) => ({
+ ...group,
+ total: priorityCounts.get(group.priority) ?? 0,
+ }));
+ } else {
+ const statusGroups = (groups ?? []).map((group) => ({
+ ...group,
+ statuses: Array.from(new Set(group.statuses)),
+ }));
+ const allStatuses = Array.from(new Set(statusGroups.flatMap((group) => group.statuses)));
+ const countQuery = ctx.db
+ .select({ count: sql<number>`count(*)`, status: tasks.status })
+ .from(tasks)
+ .where(and(...baseConditions, inArray(tasks.status, allStatuses)))
+ .groupBy(tasks.status);
+ const taskQueries = statusGroups.map(async (group) => {
+ const conditions = [inArray(tasks.status, group.statuses)];
+ const limit = group.limit ?? 50;
+ const offset = group.offset ?? 0;
+ const prefetchedTasks = await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(...baseConditions, ...conditions))
+ .orderBy(desc(tasks.createdAt), desc(tasks.seq))
+ .limit(limit)
+ .offset(offset);
+
+ return {
+ conditions,
+ key: group.key,
+ limit,
+ offset,
+ prefetchedTasks,
+ statuses: group.statuses,
+ total: 0,
+ };
+ });
+ const [countResult, queriedGroups] = await Promise.all([countQuery, Promise.all(taskQueries)]);
+ const countByStatus = new Map(countResult.map((row) => [row.status, Number(row.count)]));
+
+ groupQueries = queriedGroups.map(({ statuses, ...group }) => ({
+ ...group,
+ total: statuses.reduce((sum, status) => sum + (countByStatus.get(status) ?? 0), 0),
+ }));
+ }
+
+ const results = await Promise.all(
+ groupQueries.map(async (group) => {
+ const groupTasks =
+ group.prefetchedTasks ??
+ (await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(...baseConditions, ...group.conditions))
+ .orderBy(desc(tasks.createdAt), desc(tasks.seq))
+ .limit(group.limit)
+ .offset(group.offset));
+
+ return {
+ ...(group.assigneeAgentId !== undefined ? { assigneeAgentId: group.assigneeAgentId } : {}),
+ ...(group.assigneeUserId !== undefined ? { assigneeUserId: group.assigneeUserId } : {}),
+ hasMore: group.offset + groupTasks.length < group.total,
+ key: group.key,
+ limit: group.limit,
+ offset: group.offset,
+ ...(group.priority !== undefined ? { priority: group.priority } : {}),
+ tasks: groupTasks,
+ total: group.total,
+ };
+ }),
+ );
+
+ const taskIds = Array.from(new Set(results.flatMap((group) => group.tasks.map(({ id }) => id))));
+ const [runStats, subtaskProgressByTaskId] = await Promise.all([
+ runStatsByTaskIds(ctx, taskIds),
+ subtaskProgressByTaskIds(ctx, taskIds),
+ ]);
+ const runStatsByTaskId = new Map(
+ runStats.map((stats) => [
+ stats.root_id,
+ {
+ totalRunCost: Number(stats.total_run_cost),
+ totalRunDuration: Number(stats.total_run_duration),
+ },
+ ]),
+ );
+
+ return results.map((group) => ({
+ ...group,
+ tasks: group.tasks.map((task) => ({
+ ...task,
+ subtaskProgress: subtaskProgressByTaskId.get(task.id),
+ totalRunCost: runStatsByTaskId.get(task.id)?.totalRunCost ?? 0,
+ totalRunDuration: runStatsByTaskId.get(task.id)?.totalRunDuration ?? 0,
+ })),
+ }));
+};
+
+export const runStatsByTaskIds = async (
+ ctx: TaskModelContext,
+ taskIds: string[],
+): Promise<TaskRunStats[]> => {
+ if (taskIds.length === 0) return [];
+
+ const result = await ctx.db.execute<TaskRunStats>(sql`
+ WITH RECURSIVE goal_tree AS (
+ SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id
+ FROM ${tasks}
+ WHERE ${inArray(tasks.id, taskIds)} AND ${taskOwnership(ctx)}
+ UNION ALL
+ SELECT goal_tree.root_id, child.id
+ FROM ${tasks} child
+ JOIN goal_tree ON child.parent_task_id = goal_tree.task_id
+ WHERE ${taskOwnershipSql(ctx, 'child')}
+ )
+ SELECT
+ goal_tree.root_id,
+ coalesce(sum(${topics.totalCost}), 0) AS total_run_cost,
+ coalesce(
+ sum(extract(epoch from (${topics.completedAt} - ${taskTopics.createdAt})) * 1000)
+ filter (where ${topics.completedAt} is not null),
+ 0
+ ) AS total_run_duration
+ FROM goal_tree
+ LEFT JOIN ${taskTopics} ON ${taskTopics.taskId} = goal_tree.task_id
+ LEFT JOIN ${topics} ON ${topics.id} = ${taskTopics.topicId}
+ GROUP BY goal_tree.root_id
+ `);
+
+ return result.rows;
+};
+
+export const subtaskProgressByTaskIds = async (
+ ctx: TaskModelContext,
+ taskIds: string[],
+): Promise<Map<string, TaskSubtaskProgress>> => {
+ if (taskIds.length === 0) return new Map();
+
+ const result = await ctx.db.execute<TaskSubtaskProgressRow>(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT ${tasks.id} AS root_id, ${tasks.id} AS task_id, ${tasks.status} AS status
+ FROM ${tasks}
+ WHERE ${inArray(tasks.id, taskIds)} AND ${taskOwnership(ctx)}
+ UNION ALL
+ SELECT task_tree.root_id, child.id, child.status
+ FROM ${tasks} child
+ JOIN task_tree ON child.parent_task_id = task_tree.task_id
+ WHERE ${taskOwnershipSql(ctx, 'child')}
+ )
+ SELECT
+ task_tree.root_id,
+ count(*) filter (
+ where task_tree.task_id <> task_tree.root_id and task_tree.status = 'completed'
+ ) AS completed,
+ count(*) filter (where task_tree.task_id <> task_tree.root_id) AS total
+ FROM task_tree
+ GROUP BY task_tree.root_id
+ `);
+
+ return new Map(
+ result.rows.map((progress) => [
+ progress.root_id,
+ { completed: Number(progress.completed), total: Number(progress.total) },
+ ]),
+ );
+};
+
+export const list = async (
+ ctx: TaskModelContext,
+ options: TaskListOptions = {},
+): Promise<{ tasks: TaskItem[]; total: number }> => {
+ const { after, statuses, priorities, limit = 50, offset = 0, orderBy = 'createdAt' } = options;
+ const orderColumn = orderBy === 'updatedAt' ? tasks.updatedAt : tasks.createdAt;
+
+ const conditions = buildListConditions(ctx, options);
+
+ if (statuses?.length) conditions.push(inArray(tasks.status, statuses));
+ if (priorities?.length) conditions.push(inArray(tasks.priority, priorities));
+ if (after) {
+ conditions.push(
+ or(
+ lt(orderColumn, after.at),
+ and(eq(orderColumn, after.at), lt(tasks.seq, after.seq)),
+ ) as SQL,
+ );
+ }
+
+ const where = and(...conditions);
+
+ const countQuery = ctx.db
+ .select({ count: sql<number>`count(*)` })
+ .from(tasks)
+ .where(where);
+
+ const taskListQuery = ctx.db
+ .select()
+ .from(tasks)
+ .where(where)
+ // `seq` breaks timestamp ties so the order is total — required for the
+ // keyset cursor above and for offset pages to never repeat or skip a row.
+ .orderBy(desc(orderColumn), desc(tasks.seq))
+ .limit(limit)
+ .offset(offset);
+ const [countResult, taskList] = await Promise.all([countQuery, taskListQuery]);
+ const subtaskProgressByTaskId = await subtaskProgressByTaskIds(
+ ctx,
+ taskList.map(({ id }) => id),
+ );
+
+ return {
+ tasks: taskList.map((task) => ({
+ ...task,
+ subtaskProgress: subtaskProgressByTaskId.get(task.id),
+ })),
+ total: Number(countResult[0].count),
+ };
+};
diff --git a/packages/database/src/models/task/rows.ts b/packages/database/src/models/task/rows.ts
new file mode 100644
index 00000000000..64b27854023
--- /dev/null
+++ b/packages/database/src/models/task/rows.ts
@@ -0,0 +1,363 @@
+import type { NewTask, TaskItem } from '@lobechat/types';
+import { and, eq, inArray, ne, or, sql } from 'drizzle-orm';
+
+import { tasks } from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+import { seqOwnership, type TaskModelContext, taskOwnership } from './context';
+import { isTaskIdentifierUniqueViolation, normalizeTaskRefs } from './utils';
+
+/**
+ * Insert a task under the next free `seq` in scope, retrying when a concurrent
+ * create took the same identifier first.
+ */
+export const insertWithNextSeq = async (
+ ctx: TaskModelContext,
+ createData: Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>,
+ identifierPrefix: string,
+ maxRetries: number,
+): Promise<TaskItem> => {
+ // Retry loop to handle concurrent creates (parallel tool calls)
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
+ try {
+ // Seq is allocated per ownership scope: workspace-wide in team mode,
+ // user-private in personal mode. This keeps `T-N` identifiers stable
+ // within the surface the user actually sees.
+ //
+ // Note: this uses `seqOwnership` (visibility-blind), NOT the regular
+ // `ownership()`, because the `(workspace_id, identifier)` unique
+ // constraint is workspace-wide and ignores visibility. If we let the
+ // seq lookup filter out private rows, a private creator would compute
+ // a max seq that skips another member's existing identifier and hit
+ // PG error 23505 on insert.
+ const seqResult = await ctx.db
+ .select({ maxSeq: sql<number>`COALESCE(MAX(${tasks.seq}), 0)` })
+ .from(tasks)
+ .where(seqOwnership(ctx));
+
+ const nextSeq = Number(seqResult[0].maxSeq) + 1;
+ const identifier = `${identifierPrefix}-${nextSeq}`;
+
+ const [task] = await ctx.db
+ .insert(tasks)
+ .values({
+ ...createData,
+ createdByUserId: ctx.userId,
+ identifier,
+ seq: nextSeq,
+ workspaceId: ctx.workspaceId ?? null,
+ } as NewTask)
+ .returning();
+
+ return task;
+ } catch (error: any) {
+ // Retry on unique constraint violation (concurrent seq conflict)
+ // Check error itself, cause, and stringified message for PG error code 23505
+ if (isTaskIdentifierUniqueViolation(error) && attempt < maxRetries - 1) {
+ continue;
+ }
+ throw error;
+ }
+ }
+
+ throw new Error('Failed to create task after max retries');
+};
+
+export const findById = async (ctx: TaskModelContext, id: string): Promise<TaskItem | null> => {
+ const result = await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)))
+ .limit(1);
+
+ return result[0] || null;
+};
+
+export const findByIds = async (ctx: TaskModelContext, ids: string[]): Promise<TaskItem[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .select()
+ .from(tasks)
+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)));
+};
+
+/**
+ * Only the assignee of each task. For callers on a polling path (the goal
+ * graph re-reads every few seconds while a goal advances) that would
+ * otherwise pull full rows — instruction, editor data, context, config — for
+ * up to hundreds of tasks just to read one column.
+ */
+export const findAssigneesByIds = async (
+ ctx: TaskModelContext,
+ ids: string[],
+): Promise<{ assigneeAgentId: string | null; id: string }[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .select({ assigneeAgentId: tasks.assigneeAgentId, id: tasks.id })
+ .from(tasks)
+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)));
+};
+
+export const resolveMany = async (
+ ctx: TaskModelContext,
+ idsOrIdentifiers: string[],
+): Promise<TaskItem[]> => {
+ if (idsOrIdentifiers.length === 0) return [];
+ const identifiers = idsOrIdentifiers.map((value) => value.toUpperCase());
+ return ctx.db
+ .select()
+ .from(tasks)
+ .where(
+ and(
+ or(inArray(tasks.id, idsOrIdentifiers), inArray(tasks.identifier, identifiers)),
+ taskOwnership(ctx),
+ ),
+ );
+};
+
+export const findByIdentifier = async (
+ ctx: TaskModelContext,
+ identifier: string,
+): Promise<TaskItem | null> => {
+ const result = await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(eq(tasks.identifier, identifier), taskOwnership(ctx)))
+ .limit(1);
+
+ return result[0] || null;
+};
+
+/** The column write itself — the assignee rule lives in `update`. */
+export const writeRow = async (
+ ctx: TaskModelContext,
+ db: LobeChatDatabase,
+ id: string,
+ data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
+): Promise<TaskItem | null> => {
+ const updated = await db
+ .update(tasks)
+ .set({ ...normalizeTaskRefs(data), updatedAt: new Date() })
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)))
+ .returning();
+ return updated[0] || null;
+};
+
+/**
+ * Delete a task. This does NOT touch the task's Work artifact: the Work
+ * lifecycle is driven by the deleteTask tool call at the tool-execution
+ * dispatch layer (which calls `WorkModel.deleteTaskWork`), so non-tool deletes
+ * (UI / CLI / deleteAll) deliberately leave the Work as an orphan for the UI
+ * to render as "resource deleted" from its version snapshot. See.
+ */
+export const deleteTask = async (ctx: TaskModelContext, id: string): Promise<boolean> => {
+ const deleted = await ctx.db
+ .delete(tasks)
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)))
+ .returning({ id: tasks.id });
+
+ return deleted.length > 0;
+};
+
+/**
+ * Count workspace tasks that would break if the given agent were demoted to
+ * private:
+ * - public tasks assigned to it — a public task must never reference a
+ * private agent (`assertAgentVisibilityCompat`);
+ * - tasks created by anyone other than the agent's owner (any visibility)
+ * — after demotion those creators can no longer resolve the assignee,
+ * so their runs and assignee updates fail.
+ * Deliberately workspace-wide and visibility-blind (NOT `ownership()`):
+ * other members' private tasks are invisible to the caller but still lose
+ * their assignee. Backs the router-level agent demotion guard.
+ */
+export const countTasksBlockingAgentDemotion = async (
+ ctx: TaskModelContext,
+ assigneeAgentId: string,
+ agentOwnerUserId: string,
+): Promise<number> => {
+ if (!ctx.workspaceId) return 0;
+ const [row] = await ctx.db
+ .select({ count: sql<number>`count(*)` })
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.workspaceId, ctx.workspaceId),
+ eq(tasks.assigneeAgentId, assigneeAgentId),
+ or(eq(tasks.visibility, 'public'), ne(tasks.createdByUserId, agentOwnerUserId)),
+ ),
+ );
+ return Number(row?.count ?? 0);
+};
+
+/**
+ * Whether the subtree rooted at `rootTaskId` (root excluded) contains tasks
+ * created by someone other than `creatorUserId`. Deliberately workspace-wide
+ * and visibility-blind: other members' private subtasks are invisible to the
+ * caller but would still be fractured by a public→private demotion (each row
+ * stays owned by its creator, so the root creator loses those descendants
+ * while their creators keep orphaned children whose parent is hidden).
+ * Backs the router-level task demotion guard.
+ */
+export const subtreeHasOtherCreators = async (
+ ctx: TaskModelContext,
+ rootTaskId: string,
+ creatorUserId: string,
+): Promise<boolean> => {
+ if (!ctx.workspaceId) return false;
+ const result = await ctx.db.execute(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT id, created_by_user_id FROM tasks
+ WHERE id = ${rootTaskId} AND workspace_id = ${ctx.workspaceId}
+ UNION ALL
+ SELECT t.id, t.created_by_user_id FROM tasks t
+ JOIN task_tree tt ON t.parent_task_id = tt.id
+ )
+ SELECT 1 AS hit FROM task_tree
+ WHERE id <> ${rootTaskId} AND created_by_user_id <> ${creatorUserId}
+ LIMIT 1
+ `);
+ return result.rows.length > 0;
+};
+
+/**
+ * Row-lock the task for the rest of the enclosing transaction. Serializes a
+ * run recording its topic against a delete deciding there is nothing left to
+ * interrupt. Returns false when the task no longer exists.
+ */
+export const lockForUpdate = async (ctx: TaskModelContext, id: string): Promise<boolean> => {
+ const rows = await ctx.db
+ .select({ id: tasks.id })
+ .from(tasks)
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)))
+ .for('update');
+
+ return rows.length > 0;
+};
+
+/**
+ * Delete a task only while it still has `status`. Lets a delete that
+ * inspected the task's runs lose cleanly to a run that started meanwhile,
+ * instead of removing the row out from under it.
+ */
+export const deleteIfStatus = async (
+ ctx: TaskModelContext,
+ id: string,
+ status: string,
+): Promise<boolean> => {
+ const deleted = await ctx.db
+ .delete(tasks)
+ .where(and(eq(tasks.id, id), eq(tasks.status, status), taskOwnership(ctx)))
+ .returning({ id: tasks.id });
+
+ return deleted.length > 0;
+};
+
+/** See {@link delete}: bulk task deletion likewise leaves Work artifacts intact. */
+export const deleteAll = async (
+ ctx: TaskModelContext,
+ options?: { restrictToCreator?: boolean },
+): Promise<number> => {
+ // `restrictToCreator` narrows the workspace-wide sweep to rows the caller
+ // created (non-owner members); owners/personal mode keep the full scope.
+ const where = options?.restrictToCreator
+ ? and(taskOwnership(ctx), eq(tasks.createdByUserId, ctx.userId))
+ : taskOwnership(ctx);
+
+ const result = await ctx.db.delete(tasks).where(where).returning({ id: tasks.id });
+ return result.length;
+};
+
+/**
+ * Batch update sortOrder for multiple tasks.
+ * @param order Array of { id, sortOrder } pairs
+ */
+export const reorder = async (
+ ctx: TaskModelContext,
+ order: Array<{ id: string; sortOrder: number }>,
+): Promise<void> => {
+ for (const item of order) {
+ await ctx.db
+ .update(tasks)
+ .set({ sortOrder: item.sortOrder, updatedAt: new Date() })
+ .where(and(eq(tasks.id, item.id), taskOwnership(ctx)));
+ }
+};
+
+/** Atomically transition a task only while it still has the expected status. */
+export const updateStatusIfCurrent = async (
+ ctx: TaskModelContext,
+ id: string,
+ currentStatus: string,
+ status: string,
+ extra?: { completedAt?: Date | null; error?: string | null; startedAt?: Date },
+): Promise<TaskItem | null> => {
+ const [task] = await ctx.db
+ .update(tasks)
+ .set({ status, updatedAt: new Date(), ...extra })
+ .where(and(eq(tasks.id, id), eq(tasks.status, currentStatus), taskOwnership(ctx)))
+ .returning();
+
+ return task ?? null;
+};
+
+export const batchUpdateStatus = async (
+ ctx: TaskModelContext,
+ ids: string[],
+ status: string,
+): Promise<number> => {
+ const result = await ctx.db
+ .update(tasks)
+ .set({ status, updatedAt: new Date() })
+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)))
+ .returning();
+
+ return result.length;
+};
+
+/**
+ * Update a frozen set of task ids in one SQL statement so the family cannot
+ * be left partially transitioned. Callers pass the exact ids they snapshotted
+ * (and the user confirmed); a task that changes status concurrently is never
+ * pulled into the update by a status re-query.
+ */
+export const updateStatusForIds = async (
+ ctx: TaskModelContext,
+ ids: string[],
+ status: string,
+ extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },
+): Promise<TaskItem[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .update(tasks)
+ .set({ status, updatedAt: new Date(), ...extra })
+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)))
+ .returning();
+};
+
+export const updateHeartbeat = async (ctx: TaskModelContext, id: string): Promise<void> => {
+ await ctx.db
+ .update(tasks)
+ .set({ lastHeartbeatAt: new Date(), updatedAt: new Date() })
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)));
+};
+
+export const incrementTopicCount = async (ctx: TaskModelContext, id: string): Promise<void> => {
+ await ctx.db
+ .update(tasks)
+ .set({
+ totalTopics: sql`${tasks.totalTopics} + 1`,
+ updatedAt: new Date(),
+ })
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)));
+};
+
+export const updateCurrentTopic = async (
+ ctx: TaskModelContext,
+ id: string,
+ topicId: string,
+): Promise<void> => {
+ await ctx.db
+ .update(tasks)
+ .set({ currentTopicId: topicId, updatedAt: new Date() })
+ .where(and(eq(tasks.id, id), taskOwnership(ctx)));
+};
diff --git a/packages/database/src/models/task/scheduling.ts b/packages/database/src/models/task/scheduling.ts
new file mode 100644
index 00000000000..f43a9c82786
--- /dev/null
+++ b/packages/database/src/models/task/scheduling.ts
@@ -0,0 +1,164 @@
+import type { AgentOperationStatus, TaskItem, TaskRunTrigger } from '@lobechat/types';
+import { and, eq, inArray, isNotNull, isNull, notInArray, sql } from 'drizzle-orm';
+
+import type { AgentOperationError } from '../../schemas/agentOperations';
+import { agentOperations } from '../../schemas/agentOperations';
+import { tasks, taskTopics } from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+
+/**
+ * Operation outcomes the orphaned-run reconciliation settles.
+ *
+ * An allow-list on purpose. `done` needs the success path's own inputs (the
+ * run's last assistant content, the creator bridge) and `interrupted` belongs
+ * to the interrupt path, so converging either from a sweep would mislabel the
+ * outcome; and an operation status added later is skipped rather than guessed
+ * at.
+ */
+const ORPHANED_RUN_OPERATION_STATUSES: AgentOperationStatus[] = ['abandoned', 'error'];
+
+/** One `running` Task run whose operation has already ended — see the finder. */
+export interface OrphanedRunningTopic {
+ completionReason: string | null;
+ /**
+ * The failure the operation recorded, when it recorded one — the raw
+ * `state.error`, so its message may be nested (`{ errorType, error: { message } }`).
+ */
+ operationError: AgentOperationError | null;
+ operationId: string;
+ operationStatus: AgentOperationStatus;
+ taskId: string;
+ taskIdentifier: string;
+ topicId: string;
+ trigger: TaskRunTrigger | null;
+ userId: string;
+ workspaceId: string | null;
+}
+
+// Tasks eligible for cron-based dispatch.
+// Excludes terminal/paused/running — `paused` requires user attention,
+// `running` is already in flight (and `runTask` would CONFLICT anyway).
+export const getScheduledTasks = async (db: LobeChatDatabase): Promise<TaskItem[]> => {
+ return db
+ .select()
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.automationMode, 'schedule'),
+ isNotNull(tasks.schedulePattern),
+ notInArray(tasks.status, ['canceled', 'completed', 'failed', 'paused', 'running']),
+ ),
+ );
+};
+
+/**
+ * Atomically move `context.scheduler.lastDispatchedOccurrenceAt` from
+ * `expected` to `next`. Returns false when another writer changed it first.
+ *
+ * The schedule dispatcher reserves a cron occurrence this way before
+ * publishing its execution, so a later tick inside the grace window (or an
+ * overlapping dispatcher run) cannot publish the same occurrence again while
+ * the first delivery is still queued.
+ */
+export const swapDispatchedScheduleOccurrence = async (
+ db: LobeChatDatabase,
+ taskId: string,
+ expected: string | null,
+ next: string | null,
+): Promise<boolean> => {
+ const current = sql`coalesce(${tasks.context}, '{}'::jsonb)`;
+ const rows = await db
+ .update(tasks)
+ .set({
+ context: sql`${current} || jsonb_build_object('scheduler', coalesce(${current} -> 'scheduler', '{}'::jsonb) || jsonb_build_object('lastDispatchedOccurrenceAt', ${next}::text))`,
+ })
+ .where(
+ and(
+ eq(tasks.id, taskId),
+ sql`coalesce(${current} -> 'scheduler' ->> 'lastDispatchedOccurrenceAt', '') = ${expected ?? ''}`,
+ ),
+ )
+ .returning({ id: tasks.id });
+ return rows.length > 0;
+};
+
+// Find stuck tasks (running but heartbeat timed out)
+// Only checks tasks that have both lastHeartbeatAt and heartbeatTimeout set
+export const findStuckTasks = async (db: LobeChatDatabase): Promise<TaskItem[]> => {
+ return db
+ .select()
+ .from(tasks)
+ .where(
+ and(
+ eq(tasks.status, 'running'),
+ isNotNull(tasks.lastHeartbeatAt),
+ isNotNull(tasks.heartbeatTimeout),
+ sql`${tasks.lastHeartbeatAt} < now() - make_interval(secs => ${tasks.heartbeatTimeout})`,
+ ),
+ );
+};
+
+/**
+ * Running Task runs whose operation has already ended.
+ *
+ * The terminal state of a run reaches `task_topics` / `tasks` through the
+ * run's `onComplete` webhook, and that delivery is fire-and-forget: when it is
+ * lost, the Task keeps a `running` run forever. Everything downstream then
+ * believes a dead run is live — the Goal view reads its frozen heartbeat as
+ * activity, and the coordinator parks on `waiting_external` instead of
+ * recovering it. This finder is what lets a sweep settle those
+ * rows without depending on the lost delivery.
+ *
+ * The grace window is what keeps the sweep from racing the normal path: the
+ * operation is settled before its hook is dispatched, so only a run that has
+ * been over for longer than any delivery lag is treated as orphaned.
+ */
+export const findOrphanedRunningTopics = async (
+ db: LobeChatDatabase,
+ options: { limit?: number; staleBefore: Date },
+): Promise<OrphanedRunningTopic[]> => {
+ const { limit = 200, staleBefore } = options;
+
+ return (
+ db
+ .select({
+ completionReason: agentOperations.completionReason,
+ operationError: agentOperations.error,
+ operationId: agentOperations.id,
+ operationStatus: agentOperations.status,
+ taskId: tasks.id,
+ taskIdentifier: tasks.identifier,
+ // Non-null by the guard below; the column is only nullable because a
+ // legacy row could have been written without one.
+ topicId: sql<string>`${taskTopics.topicId}`,
+ trigger: taskTopics.trigger,
+ userId: tasks.createdByUserId,
+ workspaceId: tasks.workspaceId,
+ })
+ .from(taskTopics)
+ // The run row names the operation it belongs to; a row without one cannot
+ // be judged against an operation at all and is left alone.
+ .innerJoin(agentOperations, eq(taskTopics.operationId, agentOperations.id))
+ .innerJoin(tasks, eq(taskTopics.taskId, tasks.id))
+ .where(
+ and(
+ eq(taskTopics.status, 'running'),
+ // Only a Task that still believes it is running is repaired here.
+ // One that left `running` was settled deliberately — by the user, or
+ // by a cascade that already cancelled its run — and must not be
+ // dragged back into a failure.
+ eq(tasks.status, 'running'),
+ isNotNull(taskTopics.operationId),
+ // A run row with no topic cannot be driven through the lifecycle.
+ isNotNull(taskTopics.topicId),
+ // Sub-agent children extend their parent's turn and never own the
+ // Task's run row, so only a top-level operation may settle it.
+ isNull(agentOperations.parentOperationId),
+ inArray(agentOperations.status, ORPHANED_RUN_OPERATION_STATUSES),
+ sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt}) < ${staleBefore}`,
+ ),
+ )
+ .orderBy(sql`coalesce(${agentOperations.completedAt}, ${agentOperations.updatedAt})`)
+ .limit(limit)
+ );
+};
diff --git a/packages/database/src/models/task/transfer.ts b/packages/database/src/models/task/transfer.ts
new file mode 100644
index 00000000000..db4daf364e9
--- /dev/null
+++ b/packages/database/src/models/task/transfer.ts
@@ -0,0 +1,208 @@
+import type { NewTask } from '@lobechat/types';
+import { withoutTaskExecutionSelection } from '@lobechat/types';
+import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
+
+import {
+ taskActivities,
+ taskComments,
+ taskDependencies,
+ taskDocuments,
+ tasks,
+} from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+import type { TaskModelContext } from './context';
+import { collectTaskSubtree } from './tree';
+import { DEFAULT_TASK_IDENTIFIER_PREFIX } from './utils';
+
+/**
+ * Allocate a contiguous block of seq numbers + identifiers in the target
+ * scope. Returns the next available seq baseline.
+ */
+export const nextSeqIn = async (
+ runner: LobeChatDatabase,
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+): Promise<number> => {
+ const where = targetWorkspaceId
+ ? eq(tasks.workspaceId, targetWorkspaceId)
+ : and(eq(tasks.createdByUserId, targetUserId), isNull(tasks.workspaceId));
+ const [{ maxSeq }] = await runner
+ .select({ maxSeq: sql<number>`COALESCE(MAX(${tasks.seq}), 0)` })
+ .from(tasks)
+ .where(where!);
+ return Number(maxSeq) + 1;
+};
+
+/**
+ * Transfer a task subtree to another workspace / personal scope. Reallocates
+ * `identifier`/`seq` in the target scope and rewrites the child tables that
+ * mirror the parent's ownership (`task_dependencies`, `task_documents`,
+ * `task_comments`, `task_activities`) so the ownership predicates keep
+ * resolving after the move — those mirrored columns are what authorizes
+ * reads, so a child left behind goes invisible in the destination scope.
+ *
+ * NOTE: `task_topics` and `briefs` carry the same mirrored columns but are
+ * not rewritten here. Pre-existing gap, called out rather than widened.
+ *
+ * Cross-scope references that may no longer be valid are cleared:
+ * - `assigneeAgentId` (workspace move: agent likely doesn't exist there)
+ * - `currentTopicId` (topic ownership is also moving but the link is
+ * reset to avoid surfacing a stale active topic in the new scope)
+ */
+export const transferTo = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+): Promise<{ taskIds: string[] }> => {
+ return ctx.db.transaction(async (trx) => {
+ const subtree = await collectTaskSubtree(ctx, taskId, trx as LobeChatDatabase);
+ if (subtree.length === 0) throw new Error('Task not found');
+
+ const ids = subtree.map((t) => t.id);
+
+ // Visibility only applies when landing in a workspace. In personal scope
+ // every row is implicitly private and the field is ignored.
+ const visibilityUpdate =
+ targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
+
+ // Reallocate identifier + seq in target scope to avoid collisions.
+ const baseSeq = await nextSeqIn(trx as LobeChatDatabase, targetWorkspaceId, targetUserId);
+ // Update each task individually because identifier/seq are per-row.
+ for (const [idx, task] of subtree.entries()) {
+ const seq = baseSeq + idx;
+ const identifier = `T-${seq}`;
+ await (trx as LobeChatDatabase)
+ .update(tasks)
+ .set({
+ // Clear cross-scope refs: agent / topic may be invalid in new scope.
+ assigneeAgentId: targetWorkspaceId === ctx.workspaceId ? task.assigneeAgentId : null,
+ createdByUserId: targetUserId,
+ currentTopicId: null,
+ identifier,
+ seq,
+ updatedAt: new Date(),
+ workspaceId: targetWorkspaceId,
+ ...visibilityUpdate,
+ })
+ .where(eq(tasks.id, task.id));
+ }
+
+ // Update child tables that key off taskId. Child rows mirror the parent
+ // task's visibility (see schema comments on task_deps / task_docs /
+ // task_comments) so cascade the new visibility here too.
+ const ownershipUpdate = { userId: targetUserId, workspaceId: targetWorkspaceId };
+ await (trx as LobeChatDatabase)
+ .update(taskDependencies)
+ .set({ ...ownershipUpdate, ...visibilityUpdate })
+ .where(inArray(taskDependencies.taskId, ids));
+ await (trx as LobeChatDatabase)
+ .update(taskDocuments)
+ .set({ ...ownershipUpdate, ...visibilityUpdate })
+ .where(inArray(taskDocuments.taskId, ids));
+ await (trx as LobeChatDatabase)
+ .update(taskComments)
+ .set({ ...ownershipUpdate, ...visibilityUpdate })
+ .where(inArray(taskComments.taskId, ids));
+ await (trx as LobeChatDatabase)
+ .update(taskActivities)
+ .set({ ...ownershipUpdate, ...visibilityUpdate })
+ .where(inArray(taskActivities.taskId, ids));
+
+ return { taskIds: ids };
+ });
+};
+
+/**
+ * Deep clone a task subtree into another workspace / personal scope. Fresh
+ * ids, fresh identifiers, preserved parent/child topology. Cross-scope refs
+ * (agent / topic / brief / current topic) are cleared on the clones so the
+ * copies start clean in the new scope.
+ */
+export const copyToWorkspace = async (
+ ctx: TaskModelContext,
+ taskId: string,
+ targetWorkspaceId: string | null,
+ targetUserId: string,
+ targetVisibility?: 'private' | 'public',
+): Promise<{ rootId: string }> => {
+ return ctx.db.transaction(async (trx) => {
+ const subtree = await collectTaskSubtree(ctx, taskId, trx as LobeChatDatabase);
+ if (subtree.length === 0) throw new Error('Task not found');
+
+ // Visibility only applies when landing in a workspace.
+ const visibilityOverride =
+ targetWorkspaceId && targetVisibility ? { visibility: targetVisibility } : {};
+
+ // BFS clone — parent inserted before children, so we always know the
+ // new parentTaskId by the time we reach the child.
+ const idMap = new Map<string, string>();
+ const byId = new Map(subtree.map((t) => [t.id, t]));
+ const queue: string[] = [taskId];
+ const seen = new Set<string>();
+
+ let seq = await nextSeqIn(trx as LobeChatDatabase, targetWorkspaceId, targetUserId);
+
+ while (queue.length > 0) {
+ const currentId = queue.shift()!;
+ if (seen.has(currentId)) continue;
+ seen.add(currentId);
+ const original = byId.get(currentId);
+ if (!original) continue;
+
+ const newParentId = currentId === taskId ? null : (idMap.get(original.parentTaskId!) ?? null);
+
+ const identifier = `${DEFAULT_TASK_IDENTIFIER_PREFIX}-${seq}`;
+ const inserted = (await (trx as LobeChatDatabase)
+ .insert(tasks)
+ .values({
+ assigneeAgentId: null,
+ assigneeUserId: null,
+ automationMode: original.automationMode,
+ // The run location is dropped the way the other cross-scope refs
+ // are: a pinned machine, a path on it and a repo set all name
+ // something in the scope this task came from, and the clone's first
+ // assignment cannot clean them up later (it has no previous assignee
+ // to diff against — see `updateWithLog`).
+ config: withoutTaskExecutionSelection(original.config as null | Record<string, unknown>),
+ context: {
+ ...(original.context as Record<string, unknown>),
+ duplicatedFrom: original.id,
+ },
+ createdByAgentId: null,
+ createdByUserId: targetUserId,
+ currentTopicId: null,
+ description: original.description,
+ error: null,
+ heartbeatInterval: original.heartbeatInterval,
+ heartbeatTimeout: original.heartbeatTimeout,
+ identifier,
+ instruction: original.instruction,
+ maxTopics: original.maxTopics,
+ name: original.name,
+ parentTaskId: newParentId,
+ priority: original.priority,
+ schedulePattern: original.schedulePattern,
+ scheduleTimezone: original.scheduleTimezone,
+ seq,
+ sortOrder: original.sortOrder,
+ // Reset lifecycle: copy starts fresh, not mid-run.
+ status: 'backlog',
+ totalTopics: 0,
+ workspaceId: targetWorkspaceId,
+ ...visibilityOverride,
+ } as NewTask)
+ .returning({ id: tasks.id })) as { id: string }[];
+
+ idMap.set(original.id, inserted[0]!.id);
+ seq++;
+
+ for (const c of subtree) {
+ if (c.parentTaskId === original.id) queue.push(c.id);
+ }
+ }
+
+ return { rootId: idMap.get(taskId)! };
+ });
+};
diff --git a/packages/database/src/models/task/tree.ts b/packages/database/src/models/task/tree.ts
new file mode 100644
index 00000000000..e26eb36b93f
--- /dev/null
+++ b/packages/database/src/models/task/tree.ts
@@ -0,0 +1,264 @@
+import type { TaskItem } from '@lobechat/types';
+import { and, eq, inArray, sql } from 'drizzle-orm';
+
+import {
+ taskActivities,
+ taskComments,
+ taskDependencies,
+ taskDocuments,
+ tasks,
+ taskTopics,
+} from '../../schemas/task';
+import type { LobeChatDatabase } from '../../type';
+import {
+ activitiesOwnership,
+ commentsOwnership,
+ depsOwnership,
+ docsOwnership,
+ type TaskModelContext,
+ taskOwnership,
+ taskOwnershipSql,
+ topicsOwnership,
+} from './context';
+
+export const findSubtasks = async (
+ ctx: TaskModelContext,
+ parentTaskId: string,
+): Promise<TaskItem[]> => {
+ return ctx.db
+ .select()
+ .from(tasks)
+ .where(and(eq(tasks.parentTaskId, parentTaskId), taskOwnership(ctx)))
+ .orderBy(tasks.sortOrder, tasks.seq);
+};
+
+/**
+ * Fetch all descendants of a root task using Drizzle select() (returns camelCase fields).
+ * Uses breadth-first traversal with O(depth) queries.
+ */
+export const findAllDescendants = async (
+ ctx: TaskModelContext,
+ rootTaskId: string,
+): Promise<TaskItem[]> => {
+ const all: TaskItem[] = [];
+ let parentIds = [rootTaskId];
+
+ while (parentIds.length > 0) {
+ const children = await ctx.db
+ .select()
+ .from(tasks)
+ .where(and(inArray(tasks.parentTaskId, parentIds), taskOwnership(ctx)))
+ .orderBy(tasks.sortOrder, tasks.seq);
+
+ if (children.length === 0) break;
+
+ all.push(...children);
+ parentIds = children.map((c) => c.id);
+ }
+
+ return all;
+};
+
+// Recursive query to get full task tree
+export const getTaskTree = async (
+ ctx: TaskModelContext,
+ rootTaskId: string,
+): Promise<TaskItem[]> => {
+ const ownership = taskOwnershipSql(ctx);
+ const result = await ctx.db.execute(sql`
+ WITH RECURSIVE task_tree AS (
+ SELECT * FROM tasks WHERE id = ${rootTaskId} AND ${ownership}
+ UNION ALL
+ SELECT t.* FROM tasks t
+ JOIN task_tree tt ON t.parent_task_id = tt.id
+ )
+ SELECT * FROM task_tree
+ `);
+
+ return result.rows as unknown as TaskItem[];
+};
+
+/**
+ * For a list of task IDs, find all agent IDs (assignee + creator) across their full task trees.
+ * Walks UP to find root, then DOWN to collect all agents.
+ * Returns { [inputTaskId]: agentId[] }
+ */
+export const getTreeAgentIdsForTaskIds = async (
+ ctx: TaskModelContext,
+ taskIds: string[],
+): Promise<Record<string, string[]>> => {
+ if (taskIds.length === 0) return {};
+
+ const taskIdParams = taskIds.map((id) => sql`${id}`);
+ const taskIdList = sql.join(taskIdParams, sql`, `);
+
+ const ownershipBare = taskOwnershipSql(ctx);
+ const ownershipAliased = taskOwnershipSql(ctx, 't');
+ const result = await ctx.db.execute(sql`
+ WITH RECURSIVE
+ ancestors AS (
+ SELECT id AS origin_id, id, parent_task_id
+ FROM tasks
+ WHERE id IN (${taskIdList})
+ AND ${ownershipBare}
+ UNION ALL
+ SELECT a.origin_id, t.id, t.parent_task_id
+ FROM tasks t
+ JOIN ancestors a ON t.id = a.parent_task_id
+ WHERE ${ownershipAliased}
+ ),
+ roots AS (
+ SELECT DISTINCT ON (origin_id) origin_id, id AS root_id
+ FROM ancestors
+ WHERE parent_task_id IS NULL
+ ),
+ descendants AS (
+ SELECT r.origin_id, t.id, t.assignee_agent_id, t.created_by_agent_id
+ FROM tasks t
+ JOIN roots r ON t.id = r.root_id
+ WHERE ${ownershipAliased}
+ UNION ALL
+ SELECT d.origin_id, t.id, t.assignee_agent_id, t.created_by_agent_id
+ FROM tasks t
+ JOIN descendants d ON t.parent_task_id = d.id
+ WHERE ${ownershipAliased}
+ )
+ SELECT origin_id, assignee_agent_id, created_by_agent_id
+ FROM descendants
+ WHERE assignee_agent_id IS NOT NULL OR created_by_agent_id IS NOT NULL
+ `);
+
+ const map: Record<string, Set<string>> = {};
+ for (const row of result.rows as any[]) {
+ const originId = row.origin_id as string;
+ if (!map[originId]) map[originId] = new Set();
+ if (row.assignee_agent_id) map[originId].add(row.assignee_agent_id as string);
+ if (row.created_by_agent_id) map[originId].add(row.created_by_agent_id as string);
+ }
+
+ return Object.fromEntries(Object.entries(map).map(([k, v]) => [k, Array.from(v)]));
+};
+
+/**
+ * Collect a task and all its descendants (parentTaskId-linked) via BFS.
+ * Honors the current ownership scope.
+ */
+export const collectTaskSubtree = async (
+ ctx: TaskModelContext,
+ rootId: string,
+ runner: LobeChatDatabase,
+): Promise<TaskItem[]> => {
+ const [root] = await runner
+ .select()
+ .from(tasks)
+ .where(and(eq(tasks.id, rootId), taskOwnership(ctx)))
+ .limit(1);
+ if (!root) return [];
+
+ const collected: TaskItem[] = [root];
+ let frontier: string[] = [root.id];
+
+ while (frontier.length > 0) {
+ const children = await runner
+ .select()
+ .from(tasks)
+ .where(and(inArray(tasks.parentTaskId, frontier), taskOwnership(ctx)));
+ if (children.length === 0) break;
+ collected.push(...children);
+ frontier = children.map((c) => c.id);
+ }
+
+ return collected;
+};
+
+/**
+ * Write one visibility onto a task subtree and the task-owned child rows that
+ * mirror it, in one transaction. Only the task aggregate is written here; the
+ * cross-aggregate flow (Work visibility mirror) lives in
+ * `TaskSubtreeRepository.updateVisibility`, which runs this inside its own
+ * transaction. `TaskSubtreeRepository.updateVisibility` documents the
+ * cascade rules.
+ */
+export const setSubtreeVisibility = async (
+ ctx: TaskModelContext,
+ rootId: string,
+ descendantIds: string[],
+ visibility: 'private' | 'public',
+): Promise<TaskItem | null> => {
+ const taskIds = [rootId, ...descendantIds];
+ const stamp = new Date();
+
+ return ctx.db.transaction(async (tx) => {
+ // Update the root with RETURNING so we read the post-update row in the
+ // same statement. A second SELECT filtered by `ownership()` would self-
+ // cancel when a workspace owner demotes another member's task to private:
+ // the UPDATE filter sees the OLD (public) row and writes, but the read-
+ // back filter sees the NEW (private + other-creator) row and returns 0
+ // rows, so the caller would observe a NOT_FOUND error even though the
+ // write succeeded.
+ const [updated] = await tx
+ .update(tasks)
+ .set({ updatedAt: stamp, visibility })
+ .where(and(eq(tasks.id, rootId), taskOwnership(ctx)))
+ .returning();
+
+ if (descendantIds.length > 0) {
+ await tx
+ .update(tasks)
+ .set({ updatedAt: stamp, visibility })
+ .where(and(inArray(tasks.id, descendantIds), taskOwnership(ctx)));
+ }
+
+ await tx
+ .update(taskDependencies)
+ .set({ visibility })
+ .where(and(inArray(taskDependencies.taskId, taskIds), depsOwnership(ctx)));
+
+ await tx
+ .update(taskDocuments)
+ .set({ visibility })
+ .where(and(inArray(taskDocuments.taskId, taskIds), docsOwnership(ctx)));
+
+ // Demotion-only cascade for the event-shaped child rows (see the
+ // `TaskSubtreeRepository.updateVisibility` docstring): their visibility
+ // mirrors the task, so pulling the task back to private must also pull
+ // public-era topics/comments out of workspace scope.
+ if (visibility === 'private') {
+ await tx
+ .update(taskTopics)
+ .set({ visibility })
+ .where(and(inArray(taskTopics.taskId, taskIds), topicsOwnership(ctx)));
+
+ await tx
+ .update(taskComments)
+ .set({ visibility })
+ .where(and(inArray(taskComments.taskId, taskIds), commentsOwnership(ctx)));
+
+ await tx
+ .update(taskActivities)
+ .set({ visibility })
+ .where(and(inArray(taskActivities.taskId, taskIds), activitiesOwnership(ctx)));
+ }
+
+ return updated ?? null;
+ });
+};
+
+/**
+ * Delete the given tasks (owned child rows cascade through their FKs).
+ * Acceptances belong to the verify aggregate; `TaskSubtreeRepository`
+ * removes them in the same transaction.
+ */
+export const deleteTasksByIds = async (
+ ctx: TaskModelContext,
+ taskIds: string[],
+): Promise<number> => {
+ if (taskIds.length === 0) return 0;
+
+ const result = await ctx.db
+ .delete(tasks)
+ .where(and(inArray(tasks.id, taskIds), taskOwnership(ctx)))
+ .returning({ id: tasks.id });
+
+ return result.length;
+};
diff --git a/packages/database/src/models/task/utils.ts b/packages/database/src/models/task/utils.ts
new file mode 100644
index 00000000000..98713a3afb3
--- /dev/null
+++ b/packages/database/src/models/task/utils.ts
@@ -0,0 +1,145 @@
+import type { NewTask, TaskAutomationMode, TaskAutomationSnapshot } from '@lobechat/types';
+import {
+ clearTaskReposSelection,
+ readTaskExecutionConfig,
+ toTaskExecutionConfigPatch,
+} from '@lobechat/types';
+
+export const DEFAULT_TASK_IDENTIFIER_PREFIX = 'T';
+
+/** Columns whose change is worth a line in the task activity feed. */
+export const TRACKED_TASK_COLUMNS = [
+ 'assigneeAgentId',
+ 'assigneeUserId',
+ 'automationMode',
+ // Only for `schedule.maxExecutions`, which lives in the JSONB pocket; the
+ // rest of `config` is not diffed.
+ 'config',
+ 'heartbeatInterval',
+ 'priority',
+ 'schedulePattern',
+ 'scheduleTimezone',
+ 'status',
+] as const;
+
+/** The automation columns folded into one value — see `TaskAutomationSnapshot`. */
+/**
+ * The actor columns plus the payload tombstone for one activity row. An
+ * agent-driven edit is attributed to the agent, not to the session owner
+ * whose credentials it borrowed. Both ids null means the system did it on
+ * nobody's behalf (the runner's inbox fallback). `actorKind` repeats that in
+ * the payload because the id columns are cleared when the actor is deleted,
+ * and "someone who is gone" must not read as "the system".
+ */
+export const taskActivityActor = (actor: {
+ agentId?: string | null;
+ userId?: string | null;
+}): {
+ actorAgentId: string | null;
+ actorKind: 'agent' | 'system' | 'user';
+ actorUserId: string | null;
+} => ({
+ actorAgentId: actor.agentId ?? null,
+ actorKind: actor.agentId ? 'agent' : actor.userId ? 'user' : 'system',
+ actorUserId: actor.agentId ? null : (actor.userId ?? null),
+});
+
+export const snapshotAutomation = (row: {
+ automationMode: TaskAutomationMode | null;
+ config: unknown;
+ heartbeatInterval: number | null;
+ schedulePattern: string | null;
+ scheduleTimezone: string | null;
+}): TaskAutomationSnapshot | null => {
+ // No mode means automation is off; the leftover pattern / interval columns
+ // are configuration in waiting, not something the user turned on.
+ if (!row.automationMode) return null;
+ const maxExecutions = (row.config as { schedule?: { maxExecutions?: number | null } } | null)
+ ?.schedule?.maxExecutions;
+ return {
+ heartbeatInterval: row.heartbeatInterval,
+ maxExecutions: typeof maxExecutions === 'number' ? maxExecutions : null,
+ mode: row.automationMode,
+ schedulePattern: row.schedulePattern,
+ scheduleTimezone: row.scheduleTimezone,
+ };
+};
+
+// Foreign-key id columns a caller may clear or leave unset. LLM tool calls often
+// fill optional ids with "" — that must mean "unset", never reach the FK as ''.
+const TASK_NULLABLE_REF_KEYS = ['assigneeAgentId', 'assigneeUserId', 'parentTaskId'] as const;
+
+export const normalizeTaskRefs = <
+ T extends Partial<Record<(typeof TASK_NULLABLE_REF_KEYS)[number], unknown>>,
+>(
+ data: T,
+): T => {
+ const normalized = { ...data };
+ for (const key of TASK_NULLABLE_REF_KEYS) {
+ const value = normalized[key];
+ if (typeof value === 'string' && !value.trim()) {
+ (normalized as Record<string, unknown>)[key] = null;
+ }
+ }
+ return normalized;
+};
+
+/**
+ * The data to write when a task moves to another assignee, with the previous
+ * assignee's cloud-repo selection dropped in the same write.
+ *
+ * `repos` resolve against the assignee agent's provider env, so they belong to
+ * the agent they were picked for: carrying them to another agent leaves every
+ * later run pointing at a repository the new assignee cannot open. The
+ * machine-local axes (the device pin and a path on that machine) are the user's
+ * own and stay.
+ *
+ * Only a change of the AGENT counts, and only when the write does not state an
+ * execution of its own — a writer that moves the assignee AND names a directory
+ * is describing the new assignee's run on purpose. Returns `data` untouched when
+ * there is nothing to drop.
+ */
+export const withStaleReposCleared = (
+ before: { assigneeAgentId: string | null; config: unknown },
+ data: Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>>,
+): Partial<Omit<NewTask, 'id' | 'identifier' | 'seq' | 'createdByUserId'>> => {
+ // Nothing to drop for a task that had no assignee to begin with (the runner's
+ // "unassigned → inbox agent" fallback), nor for a write that keeps it.
+ if (!before.assigneeAgentId) return data;
+ if (data.assigneeAgentId === undefined || data.assigneeAgentId === before.assigneeAgentId) {
+ return data;
+ }
+
+ const statedExecution = (data.config as Record<string, unknown> | undefined)?.execution;
+ if (statedExecution !== undefined) return data;
+
+ const currentConfig = (before.config ?? {}) as Record<string, unknown>;
+ const cleared = clearTaskReposSelection(readTaskExecutionConfig(currentConfig));
+ if (cleared === readTaskExecutionConfig(currentConfig)) return data;
+
+ return {
+ ...data,
+ config: {
+ ...currentConfig,
+ ...(data.config as Record<string, unknown> | undefined),
+ execution: toTaskExecutionConfigPatch(cleared),
+ },
+ };
+};
+
+export const isTaskIdentifierUniqueViolation = (error: unknown): boolean => {
+ const message = error instanceof Error ? error.message : String(error);
+ const code =
+ typeof error === 'object' && error && 'code' in error
+ ? String((error as { code?: unknown }).code)
+ : '';
+ const cause = error instanceof Error ? error.cause : undefined;
+
+ return (
+ code === '23505' ||
+ message.includes('23505') ||
+ message.includes('duplicate') ||
+ message.includes('unique') ||
+ (!!cause && isTaskIdentifierUniqueViolation(cause))
+ );
+};
diff --git a/packages/database/src/models/work/__tests__/task.test.ts b/packages/database/src/models/work/__tests__/task.test.ts
index 61645163a3a..00b414f1680 100644
--- a/packages/database/src/models/work/__tests__/task.test.ts
+++ b/packages/database/src/models/work/__tests__/task.test.ts
@@ -2,6 +2,7 @@
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { TaskSubtreeRepository } from '../../../repositories/taskSubtree';
import { messages, topics, works, workspaces, workVersions } from '../../../schemas';
import { TaskModel } from '../../task';
import { WorkModel } from '..';
@@ -905,7 +906,10 @@ describe('WorkModel · workspace task visibility', () => {
expect(expectTaskListItem(memberView[0]).task.name).toBe('Shared task');
// The task transition mirrors visibility onto Work in the same transaction.
- await ownerTasks.updateVisibility(task.id, 'private');
+ await new TaskSubtreeRepository(serverDB, userId, workspaceId).updateVisibility(
+ task.id,
+ 'private',
+ );
const [mirrored] = await serverDB
.select({ visibility: works.visibility })
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index 7e834ea11ca..9ae580cfcfc 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -12,6 +12,7 @@ import {
type WorkAccessScope,
type WorkItem,
type WorkSkillProvider,
+ type WorkVisibility,
} from '@lobechat/types';
import type { LobeChatDatabase } from '../../type';
@@ -140,6 +141,10 @@ export class WorkModel {
deleteWork = (params: DeleteWorkParams): Promise<void> => writes.deleteWork(this.ctx, params);
+ /** See {@link writes.setTaskWorksVisibility}. */
+ setTaskWorksVisibility = (taskIds: string[], visibility: WorkVisibility): Promise<void> =>
+ writes.setTaskWorksVisibility(this.ctx, taskIds, visibility);
+
listByRootOperation = (params: {
includeFileWorks?: boolean;
limit?: number;
diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.ts
index 279d9277b37..1c543d04b0f 100644
--- a/packages/database/src/models/work/writes.ts
+++ b/packages/database/src/models/work/writes.ts
@@ -9,12 +9,13 @@ import type {
WorkType,
WorkVisibility,
} from '@lobechat/types';
-import { and, eq, sql } from 'drizzle-orm';
+import { and, eq, inArray, sql } from 'drizzle-orm';
import { documents } from '../../schemas/file';
import { tasks } from '../../schemas/task';
import { works, workVersions } from '../../schemas/work';
import type { LobeChatDatabase } from '../../type';
+import { buildWorkspaceWhere } from '../../utils/workspace';
import {
documentOwnership,
resolveWorkAccessScope,
@@ -342,6 +343,37 @@ export const deleteTaskWork = async (
);
};
+/**
+ * Mirror a task subtree's visibility onto its Work rows. Works keep an indexed
+ * copy of the resource visibility so gallery/list queries can filter without a
+ * join; `TaskSubtreeRepository.updateVisibility` calls this in the same
+ * transaction as the task write so lists never observe a stale public row.
+ *
+ * Scoped by user/workspace only (not visibility): a workspace owner demoting
+ * another member's public task must still reach that member's Work row.
+ */
+export const setTaskWorksVisibility = async (
+ ctx: WorkContext,
+ taskIds: string[],
+ visibility: WorkVisibility,
+): Promise<void> => {
+ if (taskIds.length === 0) return;
+
+ await ctx.db
+ .update(works)
+ .set({ visibility })
+ .where(
+ and(
+ eq(works.resourceType, 'task'),
+ inArray(works.resourceId, taskIds),
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ { isDeleted: works.isDeleted, userId: works.userId, workspaceId: works.workspaceId },
+ ),
+ ),
+ );
+};
+
/**
* User-initiated removal of one Work card by its own id. Meant for orphaned
* Works (the backing task / document is gone — see `resourceDeleted`), where
diff --git a/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts b/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts
new file mode 100644
index 00000000000..8d90c75472d
--- /dev/null
+++ b/packages/database/src/repositories/taskSubtree/__tests__/index.test.ts
@@ -0,0 +1,309 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { TaskModel } from '../../../models/task';
+import { acceptances, topics, users, workspaces } from '../../../schemas';
+import { taskTopics } from '../../../schemas/task';
+import type { LobeChatDatabase } from '../../../type';
+import { TaskSubtreeRepository } from '../index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'task-subtree-repo-user';
+const userId2 = 'task-subtree-repo-user-2';
+
+const subtreeRepo = (uid: string, workspaceId?: string) =>
+ new TaskSubtreeRepository(serverDB, uid, workspaceId);
+
+const createTopic = async (id: string, uid = userId) => {
+ await serverDB.insert(topics).values({ id, userId: uid }).onConflictDoNothing();
+ return id;
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: userId2 }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+describe('TaskSubtreeRepository', () => {
+ describe('deleteSubtree', () => {
+ it('should delete the root and all descendants without leaving orphan tasks', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const root = await model.create({ instruction: 'Root goal' });
+ const child = await model.create({ instruction: 'Child', parentTaskId: root.id });
+ const grandchild = await model.create({ instruction: 'Grandchild', parentTaskId: child.id });
+ await serverDB.insert(acceptances).values({
+ subjectId: grandchild.id,
+ subjectType: 'task',
+ userId,
+ });
+
+ await expect(subtreeRepo(userId).deleteSubtree(root.id)).resolves.toBe(3);
+ await expect(model.findAllDescendants(root.id)).resolves.toEqual([]);
+ await expect(model.findById(root.id)).resolves.toBeNull();
+ const remainingAcceptances = await serverDB
+ .select()
+ .from(acceptances)
+ .where(eq(acceptances.subjectId, grandchild.id));
+ expect(remainingAcceptances).toEqual([]);
+ });
+ });
+
+ describe('updateVisibility', () => {
+ const wsId = 'task-subtree-visibility-ws';
+
+ beforeEach(async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({
+ id: wsId,
+ name: 'Visibility WS',
+ primaryOwnerId: userId,
+ slug: wsId,
+ })
+ .onConflictDoNothing();
+ });
+
+ it('should cascade updateVisibility to descendants and child tables', async () => {
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = new TaskModel(serverDB, userId2, wsId);
+
+ const root = await alice.create({
+ instruction: 'Root',
+ visibility: 'private',
+ });
+ const child = await alice.create({
+ instruction: 'Child',
+ parentTaskId: root.id,
+ visibility: 'private',
+ });
+ await alice.addDependency(root.id, child.id, 'blocks');
+
+ // Sanity check: Bob can't see the private subtree
+ expect((await bob.list()).total).toBe(0);
+
+ const promoted = await subtreeRepo(userId, wsId).updateVisibility(root.id, 'public');
+ expect(promoted?.visibility).toBe('public');
+
+ const aliceChild = await alice.findById(child.id);
+ expect(aliceChild?.visibility).toBe('public');
+
+ // Bob now sees both
+ const bobList = await bob.list();
+ expect(bobList.tasks.map((t) => t.id).sort()).toEqual([root.id, child.id].sort());
+
+ // Dependency row also flipped to public
+ const deps = await alice.getDependencies(root.id);
+ expect(deps).toHaveLength(1);
+ expect(deps[0].visibility).toBe('public');
+ });
+
+ it('should reject updateVisibility for tasks not visible to the caller', async () => {
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = subtreeRepo(userId2, wsId);
+
+ const aliceTask = await alice.create({
+ instruction: 'Alice secret',
+ visibility: 'private',
+ });
+
+ const result = await bob.updateVisibility(aliceTask.id, 'public');
+ expect(result).toBeNull();
+ const reload = await alice.findById(aliceTask.id);
+ expect(reload?.visibility).toBe('private');
+ });
+
+ it('should return the row when demoting another member’s public task to private', async () => {
+ // Regression: the post-update SELECT used to filter by `ownership()`,
+ // which evaluates against the new row state. Bob (acting as workspace
+ // owner after the TRPC-layer override) demoting Alice's public task to
+ // private would write the row but then fail to read it back (new state:
+ // visibility=private, createdBy=Alice), so the model returned null and
+ // the TRPC procedure surfaced a spurious NOT_FOUND while the DB row had
+ // actually been mutated.
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = subtreeRepo(userId2, wsId);
+
+ const aliceTask = await alice.create({
+ instruction: 'Alice public',
+ visibility: 'public',
+ });
+
+ const result = await bob.updateVisibility(aliceTask.id, 'private');
+ expect(result).not.toBeNull();
+ expect(result?.visibility).toBe('private');
+ expect(result?.createdByUserId).toBe(userId);
+
+ // DB state matches the returned row (no silent mutation drift).
+ const reload = await alice.findById(aliceTask.id);
+ expect(reload?.visibility).toBe('private');
+ });
+
+ it('should NOT cascade updateVisibility into historical task_comments', async () => {
+ // Comments are event-shaped historical rows whose visibility is fixed at
+ // write time. Promoting the parent task to public must not retroactively
+ // expose discussions that took place while the task was private — that
+ // would let other workspace members read messages the commenter intended
+ // for the private context. Comments written *after* promotion inherit
+ // 'public' through their own create path and surface normally.
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = new TaskModel(serverDB, userId2, wsId);
+
+ const task = await alice.create({
+ instruction: 'will be promoted',
+ visibility: 'private',
+ });
+ await alice.addComment({
+ authorUserId: userId,
+ content: 'private-era thoughts',
+ taskId: task.id,
+ userId,
+ });
+
+ // Bob can't see the private task or its comments
+ expect(await bob.getComments(task.id)).toHaveLength(0);
+
+ await subtreeRepo(userId, wsId).updateVisibility(task.id, 'public');
+
+ // Task is public now (Bob sees it), but the historical comment stays
+ // hidden — its row still has visibility='private'.
+ expect((await bob.list()).tasks.map((t) => t.id)).toContain(task.id);
+ expect(await bob.getComments(task.id)).toHaveLength(0);
+ // Owner (Alice) of course still sees her own comment.
+ expect(await alice.getComments(task.id)).toHaveLength(1);
+
+ // A new comment written after promotion inherits 'public' and is
+ // visible to Bob — the non-cascade only protects the past, not the
+ // future.
+ await alice.addComment({
+ authorUserId: userId,
+ content: 'post-promotion ping',
+ taskId: task.id,
+ userId,
+ });
+ expect(await bob.getComments(task.id)).toHaveLength(1);
+ });
+
+ it('should NOT cascade updateVisibility into historical task_topics', async () => {
+ // Same rationale as comments: a task_topics row records one run of the
+ // task. Its visibility is fixed at write time; promoting the task to
+ // public must not retroactively expose runs (transcripts, handoffs,
+ // review scores) created while the task was private.
+ const alice = new TaskModel(serverDB, userId, wsId);
+
+ const task = await alice.create({
+ instruction: 'will be promoted',
+ visibility: 'private',
+ });
+
+ // Seed a historical run row directly — no model API for taskTopics
+ // outside the runtime path, and inserting raw is precise enough for
+ // asserting the non-cascade invariant.
+ const historicalTopicId = await createTopic('historical-run-topic-id');
+ await serverDB.insert(taskTopics).values({
+ seq: 1,
+ status: 'completed',
+ taskId: task.id,
+ topicId: historicalTopicId,
+ userId,
+ visibility: 'private',
+ workspaceId: wsId,
+ });
+
+ await subtreeRepo(userId, wsId).updateVisibility(task.id, 'public');
+
+ // Task itself is public now.
+ expect((await alice.findById(task.id))?.visibility).toBe('public');
+
+ // But the historical run row keeps its private visibility — it was
+ // recorded during the private phase and stays there.
+ const [historical] = await serverDB
+ .select({ visibility: taskTopics.visibility })
+ .from(taskTopics)
+ .where(eq(taskTopics.taskId, task.id));
+ expect(historical.visibility).toBe('private');
+ });
+
+ it('should cascade public→private demotion into task_comments and task_topics', async () => {
+ // Inverse of the two non-cascade tests above: comment/topic visibility
+ // is a write-time mirror of the task used as a JOIN-free authorization
+ // proxy. When the task is pulled back to private, public-era rows must
+ // follow — otherwise members who saved a comment/topic id while the
+ // task was public could keep reading/operating those historical rows.
+ const alice = new TaskModel(serverDB, userId, wsId);
+ const bob = new TaskModel(serverDB, userId2, wsId);
+
+ const task = await alice.create({
+ instruction: 'will be demoted',
+ visibility: 'public',
+ });
+ await alice.addComment({
+ authorUserId: userId,
+ content: 'public-era comment',
+ taskId: task.id,
+ userId,
+ });
+
+ const publicTopicId = await createTopic('public-era-run-topic-id');
+ await serverDB.insert(taskTopics).values({
+ seq: 1,
+ status: 'completed',
+ taskId: task.id,
+ topicId: publicTopicId,
+ userId,
+ visibility: 'public',
+ workspaceId: wsId,
+ });
+
+ // Sanity: Bob sees the public-era comment while the task is public.
+ expect(await bob.getComments(task.id)).toHaveLength(1);
+
+ await subtreeRepo(userId, wsId).updateVisibility(task.id, 'private');
+
+ // Task and both child rows are private now — gone from Bob's scope.
+ expect(await bob.findById(task.id)).toBeNull();
+ expect(await bob.getComments(task.id)).toHaveLength(0);
+ const [demotedTopic] = await serverDB
+ .select({ visibility: taskTopics.visibility })
+ .from(taskTopics)
+ .where(eq(taskTopics.taskId, task.id));
+ expect(demotedTopic.visibility).toBe('private');
+
+ // Alice (creator) keeps access to her own rows.
+ expect(await alice.getComments(task.id)).toHaveLength(1);
+ });
+
+ it('pulls public-era activities back to private when the task is demoted', async () => {
+ await serverDB
+ .insert(workspaces)
+ .values({
+ id: 'ws_activity_demote',
+ name: 'WS',
+ primaryOwnerId: userId,
+ slug: 'ws-activity-demote',
+ })
+ .onConflictDoNothing();
+ const model = new TaskModel(serverDB, userId, 'ws_activity_demote');
+ const task = await model.create({ instruction: 'Test', visibility: 'public' });
+
+ await model.addActivity({
+ actorUserId: userId,
+ payload: { fromId: null, toId: userId2 },
+ taskId: task.id,
+ type: 'assignee_user',
+ });
+
+ await subtreeRepo(userId, 'ws_activity_demote').updateVisibility(task.id, 'private');
+
+ const activities = await model.getActivities(task.id);
+ expect(activities).toHaveLength(1);
+ expect(activities[0].visibility).toBe('private');
+ });
+ });
+});
diff --git a/packages/database/src/repositories/taskSubtree/index.ts b/packages/database/src/repositories/taskSubtree/index.ts
new file mode 100644
index 00000000000..ca17d871866
--- /dev/null
+++ b/packages/database/src/repositories/taskSubtree/index.ts
@@ -0,0 +1,87 @@
+import type { TaskItem } from '@lobechat/types';
+
+import { AcceptanceModel } from '../../models/acceptance';
+import { TaskModel } from '../../models/task';
+import { WorkModel } from '../../models/work';
+import type { LobeChatDatabase } from '../../type';
+
+/**
+ * Cross-aggregate write flows over a task subtree. A task's visibility is
+ * mirrored onto its Work rows, and its acceptances (verify aggregate) are keyed
+ * by the task id without an FK, so changing visibility or deleting a subtree
+ * writes several aggregates in one transaction. Each piece stays a
+ * single-aggregate Model method; this repository owns the unit of work.
+ */
+export class TaskSubtreeRepository {
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {}
+
+ private taskModel = (db: LobeChatDatabase = this.db) =>
+ new TaskModel(db, this.userId, this.workspaceId);
+
+ /**
+ * Move a task and its full subtree to a new visibility (both directions —
+ * the router gates who may call it).
+ *
+ * Cascades inside a single transaction:
+ * - the root task and every descendant in `tasks`;
+ * - `task_dependencies` and `task_documents` whose `task_id` is in the set;
+ * - the indexed visibility mirror on the tasks' Work rows, so gallery/list
+ * queries cannot observe a stale public row after demotion.
+ *
+ * `task_topics` and `task_comments` are direction-sensitive. Their
+ * `visibility` column is a write-time mirror of the parent task used as a
+ * JOIN-free authorization proxy, so:
+ * - `private → public` deliberately does **not** cascade them: promoting
+ * the task must not retroactively expose runs and discussions that
+ * happened while it was private. Rows created after promotion inherit
+ * the task's then-current visibility through their own create paths.
+ * - `public → private` **does** cascade them: leaving public-era rows
+ * public would let workspace members keep reading/operating historical
+ * topics and comments of a task they can no longer see.
+ *
+ * Returns `null` if the root task is not visible to the current caller
+ * (either missing or owned by another workspace member). Callers should
+ * gate authorization (creator-only / admin) before invoking this.
+ */
+ async updateVisibility(id: string, visibility: 'private' | 'public'): Promise<TaskItem | null> {
+ const taskModel = this.taskModel();
+ const root = await taskModel.findById(id);
+ if (!root) return null;
+ if (root.visibility === visibility) return root;
+
+ const descendantIds = (await taskModel.findAllDescendants(root.id)).map((d) => d.id);
+
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ const updated = await this.taskModel(db).setSubtreeVisibility(
+ root.id,
+ descendantIds,
+ visibility,
+ );
+ await new WorkModel(db, this.userId, this.workspaceId).setTaskWorksVisibility(
+ [root.id, ...descendantIds],
+ visibility,
+ );
+ return updated;
+ });
+ }
+
+ /** Delete a task, every descendant and their acceptances in one transaction. */
+ async deleteSubtree(rootTaskId: string): Promise<number> {
+ const descendants = await this.taskModel().findAllDescendants(rootTaskId);
+ const taskIds = [rootTaskId, ...descendants.map(({ id }) => id)];
+
+ return this.db.transaction(async (tx) => {
+ const db = tx as LobeChatDatabase;
+ await new AcceptanceModel(db, this.userId, this.workspaceId).deleteBySubjects(
+ 'task',
+ taskIds,
+ );
+ return this.taskModel(db).deleteByIds(taskIds);
+ });
+ }
+}