π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
import type {
BriefArtifacts,
BriefMetadata,
TaskActivityLogPayload,
TaskActivityLogType,
} from '@lobechat/types';
import { isNotNull, isNull } from 'drizzle-orm';
import {
foreignKey,
index,
integer,
jsonb,
pgTable,
text,
uniqueIndex,
uuid,
} from 'drizzle-orm/pg-core';
import { idGenerator } from '../utils/idGenerator';
import { createdAt, softDeleteColumns, timestamps, timestamptz, varchar255 } from './_helpers';
import { agents } from './agent';
import { agentCronJobs } from './agentCronJob';
import { documents } from './file';
import { projects } from './project';
import { topics } from './topic';
import { users } from './user';
import { workspaces } from './workspace';
// ββ Tasks ββββββββββββββββββββββββββββββββββββββββββββββββ
export const tasks = pgTable(
'tasks',
{
id: text('id')
.primaryKey()
.$defaultFn(() => idGenerator('tasks'))
.notNull(),
// Workspace-level identifier (e.g. 'T-1', 'PROJ-42')
identifier: text('identifier').notNull(),
seq: integer('seq').notNull(),
// Creator (user or agent)
createdByUserId: text('created_by_user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
projectId: text('project_id').references(() => projects.id, { onDelete: 'set null' }),
createdByAgentId: text('created_by_agent_id').references(() => agents.id, {
onDelete: 'set null',
}),
// Assignee (user and agent can coexist, both nullable)
assigneeUserId: text('assignee_user_id').references(() => users.id, { onDelete: 'set null' }),
assigneeAgentId: text('assignee_agent_id').references(() => agents.id, {
onDelete: 'set null',
}),
// Tree structure (self-referencing, no depth limit)
parentTaskId: text('parent_task_id'),
// Task definition
name: text('name'),
description: varchar255('description'),
instruction: text('instruction').notNull(),
// Rich editor JSON state (Lexical). Mirrors the markdown `instruction`
// but preserves details that markdown drops β image sizes, custom nodes, etc.
// Optional: when null, callers fall back to parsing `instruction` markdown.
editorData: jsonb('editor_data'),
// Lifecycle (same state machine for user and agent)
// 'backlog' | 'running' | 'paused' | 'completed' | 'failed' | 'canceled'
status: text('status').notNull().default('backlog'),
priority: integer('priority').default(0), // 'no' | 'urgent' | 'high' | 'normal' | 'low'
sortOrder: integer('sort_order').default(0), // manual sort within parent, lower = higher
// Automation mode (mutually exclusive with each other; null = no automation)
automationMode: text('automation_mode').$type<'heartbeat' | 'schedule'>(),
// Heartbeat
heartbeatInterval: integer('heartbeat_interval'), // seconds, null = no heartbeat configured
heartbeatTimeout: integer('heartbeat_timeout'), // seconds, null = disabled (default off)
lastHeartbeatAt: timestamptz('last_heartbeat_at'),
// Schedule (optional)
schedulePattern: text('schedule_pattern'),
scheduleTimezone: text('schedule_timezone').default('UTC'),
// Topic management
totalTopics: integer('total_topics').default(0),
maxTopics: integer('max_topics'), // null = unlimited
currentTopicId: text('current_topic_id').references(() => topics.id, { onDelete: 'set null' }),
// Context & config (each task independent, no inheritance from parent)
context: jsonb('context').default({}),
config: jsonb('config').default({}), // CheckpointConfig, ReviewConfig, TaskExecutionConfig, etc.
error: text('error'),
// Visibility (mirrors agent.visibility semantics). Workspace-mode rows can be
// 'public' (visible to every workspace member) or 'private' (only the
// creator sees them). Personal-mode rows are implicitly private to their
// owner and the column is ignored.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
// Timestamps
startedAt: timestamptz('started_at'),
completedAt: timestamptz('completed_at'),
// Set when the user archives the task ("truly done"); orthogonal to
// `status`, null = not archived.
archivedAt: timestamptz('archived_at'),
/** Recycle bin β see `schemas/trash.ts`. */
...softDeleteColumns(),
...timestamps,
},
(t) => [
// Self-referential FK (defined here to avoid TS circular inference)
foreignKey({
columns: [t.parentTaskId],
foreignColumns: [t.id],
name: 'tasks_parent_task_id_tasks_id_fk',
}).onDelete('set null'),
uniqueIndex('tasks_identifier_idx')
.on(t.identifier, t.createdByUserId)
.where(isNull(t.workspaceId)),
index('tasks_created_by_user_id_idx').on(t.createdByUserId),
index('tasks_created_by_agent_id_idx').on(t.createdByAgentId),
index('tasks_assignee_user_id_idx').on(t.assigneeUserId),
index('tasks_assignee_agent_id_idx').on(t.assigneeAgentId),
index('tasks_parent_task_id_idx').on(t.parentTaskId),
index('tasks_status_idx').on(t.status),
index('tasks_priority_idx').on(t.priority),
index('tasks_automation_mode_idx').on(t.automationMode),
index('tasks_heartbeat_idx').on(t.status, t.lastHeartbeatAt),
index('tasks_workspace_id_idx').on(t.workspaceId),
index('tasks_project_id_status_idx').on(t.projectId, t.status),
index('tasks_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.createdByUserId),
uniqueIndex('tasks_identifier_workspace_id_unique')
.on(t.workspaceId, t.identifier)
.where(isNotNull(t.workspaceId)),
],
);
// ββ Task Dependencies ββββββββββββββββββββββββββββββββββββ
export const taskDependencies = pgTable(
'task_dependencies',
{
id: uuid('id').defaultRandom().primaryKey().notNull(),
taskId: text('task_id')
.references(() => tasks.id, { onDelete: 'cascade' })
.notNull(),
dependsOnId: text('depends_on_id')
.references(() => tasks.id, { onDelete: 'cascade' })
.notNull(),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
// 'blocks' | 'relates'
type: text('type').notNull().default('blocks'),
// Mirror of parent task's visibility. Kept in lockstep with `tasks.visibility`
// by `TaskModel.updateVisibility` cascade so this row can be filtered without
// joining back to `tasks`.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
// Reserved for conditional dependencies: {"on": "success"} / {"on": "failure"}
condition: jsonb('condition'),
createdAt: createdAt(),
},
(t) => [
uniqueIndex('task_deps_unique_idx').on(t.taskId, t.dependsOnId),
index('task_deps_task_id_idx').on(t.taskId),
index('task_deps_depends_on_id_idx').on(t.dependsOnId),
index('task_deps_user_id_idx').on(t.userId),
index('task_dependencies_workspace_id_idx').on(t.workspaceId),
index('task_deps_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.userId),
],
);
export type NewTaskDependency = typeof taskDependencies.$inferInsert;
export type TaskDependencyItem = typeof taskDependencies.$inferSelect;
// ββ Task Documents (MVP Workspace) βββββββββββββββββββββββ
export const taskDocuments = pgTable(
'task_documents',
{
id: uuid('id').defaultRandom().primaryKey().notNull(),
taskId: text('task_id')
.references(() => tasks.id, { onDelete: 'cascade' })
.notNull(),
documentId: text('document_id')
.references(() => documents.id, { onDelete: 'cascade' })
.notNull(),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
// 'agent' | 'user' | 'system'
pinnedBy: text('pinned_by').notNull().default('agent'),
// Mirror of parent task's visibility. Same cascade contract as
// `task_dependencies.visibility`.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
createdAt: createdAt(),
},
(t) => [
uniqueIndex('task_docs_unique_idx').on(t.taskId, t.documentId),
index('task_docs_task_id_idx').on(t.taskId),
index('task_docs_document_id_idx').on(t.documentId),
index('task_docs_user_id_idx').on(t.userId),
index('task_documents_workspace_id_idx').on(t.workspaceId),
index('task_docs_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.userId),
],
);
export type NewTaskDocument = typeof taskDocuments.$inferInsert;
export type TaskDocumentItem = typeof taskDocuments.$inferSelect;
// ββ Task Topics βββββββββββββββββββββββββββββββββββββββββ
export const taskTopics = pgTable(
'task_topics',
{
id: uuid('id').defaultRandom().primaryKey().notNull(),
taskId: text('task_id')
.references(() => tasks.id, { onDelete: 'cascade' })
.notNull(),
topicId: text('topic_id').references(() => topics.id, { onDelete: 'cascade' }),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
seq: integer('seq').notNull(), // topic sequence within task (1, 2, 3...)
operationId: text('operation_id'), // agent execution operation ID
// 'running' | 'completed' | 'failed' | 'timeout' | 'canceled'
status: text('status').notNull().default('running'),
// What triggered this run: 'manual' (ad-hoc run-now / agent tool call),
// 'schedule' (cron tick) or 'heartbeat' (interval tick). Null for legacy
// rows created before this column existed. Used so the maxExecutions quota
// counts only automation ticks, not manual runs.
trigger: text('trigger').$type<'manual' | 'schedule' | 'heartbeat' | 'goal'>(),
// Handoff (populated after topic completes via LLM summarization)
// { title, summary, keyFindings: string[], nextAction }
handoff: jsonb('handoff'),
// Review results (populated after topic completes + review runs)
reviewPassed: integer('review_passed'), // 1 = passed, 0 = failed, null = not reviewed
reviewScore: integer('review_score'), // overall score 0-100
reviewScores: jsonb('review_scores'), // [{rubricId, score, passed, reason}]
reviewIteration: integer('review_iteration'), // which iteration (1, 2, 3...)
reviewedAt: timestamptz('reviewed_at'),
// Snapshot of the task's visibility at the time this run was created.
// Topics inherit `tasks.visibility` on insert but are **not** cascaded by
// `TaskModel.updateVisibility`: promoting a task to public must not
// retroactively expose runs that happened while it was private.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
...timestamps,
},
(t) => [
uniqueIndex('task_topics_unique_idx').on(t.taskId, t.topicId),
index('task_topics_task_id_idx').on(t.taskId),
index('task_topics_topic_id_idx').on(t.topicId),
index('task_topics_user_id_idx').on(t.userId),
index('task_topics_status_idx').on(t.taskId, t.status),
index('task_topics_workspace_id_idx').on(t.workspaceId),
index('task_topics_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.userId),
],
);
export type NewTaskTopic = typeof taskTopics.$inferInsert;
export type TaskTopicItem = typeof taskTopics.$inferSelect;
// ββ Briefs βββββββββββββββββββββββββββββββββββββββββββββ
export const briefs = pgTable(
'briefs',
{
id: text('id')
.primaryKey()
.$defaultFn(() => idGenerator('briefs'))
.notNull(),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
// Source (polymorphic, fill as needed)
taskId: text('task_id').references(() => tasks.id, { onDelete: 'cascade' }),
cronJobId: text('cron_job_id').references(() => agentCronJobs.id, { onDelete: 'cascade' }),
topicId: text('topic_id'),
agentId: text('agent_id'),
// Content
type: text('type').notNull(), // 'decision' | 'result' | 'insight' | 'error'
priority: text('priority').default('info'), // 'urgent' | 'normal' | 'info'
title: text('title').notNull(),
summary: text('summary').notNull(),
artifacts: jsonb('artifacts').$type<BriefArtifacts>(), // programmatically collected at synthesis
actions: jsonb('actions'), // BriefAction[]
// Resolution
resolvedAction: text('resolved_action'),
resolvedComment: text('resolved_comment'),
readAt: timestamptz('read_at'),
resolvedAt: timestamptz('resolved_at'),
trigger: varchar255('trigger'), // field for which module triggered the brief, e.g. task, agent, signal, etc.
metadata: jsonb('metadata').$type<BriefMetadata>(), // freeform field for business and states.
createdAt: createdAt(),
},
(t) => [
index('briefs_user_id_idx').on(t.userId),
index('briefs_task_id_idx').on(t.taskId),
index('briefs_cron_job_id_idx').on(t.cronJobId),
index('briefs_agent_id_idx').on(t.agentId),
index('briefs_type_idx').on(t.type),
index('briefs_priority_idx').on(t.priority),
index('briefs_unresolved_idx').on(t.userId, t.resolvedAt),
index('briefs_trigger_idx').on(t.trigger),
index('briefs_workspace_id_idx').on(t.workspaceId),
],
);
export type NewBrief = typeof briefs.$inferInsert;
export type BriefItem = typeof briefs.$inferSelect;
// ββ Task Comments βββββββββββββββββββββββββββββββββββββββ
export const taskComments = pgTable(
'task_comments',
{
id: text('id')
.primaryKey()
.$defaultFn(() => idGenerator('taskComments'))
.notNull(),
taskId: text('task_id')
.references(() => tasks.id, { onDelete: 'cascade' })
.notNull(),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
// Author (user or agent, both nullable)
authorUserId: text('author_user_id').references(() => users.id, { onDelete: 'set null' }),
authorAgentId: text('author_agent_id').references(() => agents.id, { onDelete: 'set null' }),
// Content
content: text('content').notNull(),
editorData: jsonb('editor_data'),
// Optional references
briefId: text('brief_id').references(() => briefs.id, { onDelete: 'set null' }),
topicId: text('topic_id').references(() => topics.id, { onDelete: 'set null' }),
// Mirror of parent task's visibility. Same cascade contract as the other
// task-child tables (`task_dependencies` / `task_documents` / `task_topics`).
// Lets `commentsOwnership` filter without joining back to `tasks`, and
// closes the leak where a workspace member who somehow obtained a
// commentId could touch a comment on a task they cannot see.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
...timestamps,
},
(t) => [
index('task_comments_task_id_idx').on(t.taskId),
index('task_comments_user_id_idx').on(t.userId),
index('task_comments_author_user_id_idx').on(t.authorUserId),
index('task_comments_agent_id_idx').on(t.authorAgentId),
index('task_comments_brief_id_idx').on(t.briefId),
index('task_comments_topic_id_idx').on(t.topicId),
index('task_comments_workspace_id_idx').on(t.workspaceId),
index('task_comments_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.userId),
],
);
export type NewTaskComment = typeof taskComments.$inferInsert;
export type TaskCommentItem = typeof taskComments.$inferSelect;
// ββ Task Activities βββββββββββββββββββββββββββββββββββββ
/**
* Append-only event log for a task's non-content changes.
*
* The task detail feed used to be assembled purely from rows that happen to
* exist (`tasks.created_at`, `task_topics`, `task_comments`), so a mutation
* that only rewrites a column on `tasks` β reassigning the task β left no
* trace at all. This table is the missing side: one row per change, carrying
* who made it and what the value moved between.
*
* `type` is deliberately plain `text` (see the db-migrations skill): adding a
* new event kind is a type-only change, not a migration.
*/
export const taskActivities = pgTable(
'task_activities',
{
// Rows are only ever read in bulk for one task β never addressed by id in a
// URL or an API β so they take a plain uuid like the other task child
// tables (`task_dependencies` / `task_documents` / `task_topics`) rather
// than a prefixed id.
id: uuid('id').defaultRandom().primaryKey().notNull(),
taskId: text('task_id')
.references(() => tasks.id, { onDelete: 'cascade' })
.notNull(),
userId: text('user_id')
.references(() => users.id, { onDelete: 'cascade' })
.notNull(),
workspaceId: text('workspace_id').references(() => workspaces.id, { onDelete: 'cascade' }),
// Actor (user or agent, both nullable β an agent tool call has no user).
actorUserId: text('actor_user_id').references(() => users.id, { onDelete: 'set null' }),
actorAgentId: text('actor_agent_id').references(() => agents.id, { onDelete: 'set null' }),
// 'assignee_agent' | 'assignee_user'
type: text('type').$type<TaskActivityLogType>().notNull(),
// { fromId, toId } β null on either side means "unassigned".
payload: jsonb('payload').$type<TaskActivityLogPayload>(),
// Mirror of the parent task's visibility, same contract as the other
// task-child tables: lets ownership filter without joining back to `tasks`.
visibility: text('visibility', { enum: ['private', 'public'] })
.default('public')
.notNull(),
createdAt: createdAt(),
},
(t) => [
index('task_activities_task_id_idx').on(t.taskId),
index('task_activities_user_id_idx').on(t.userId),
index('task_activities_workspace_id_idx').on(t.workspaceId),
index('task_activities_workspace_visibility_idx').on(t.workspaceId, t.visibility, t.userId),
],
);
export type NewTaskActivity = typeof taskActivities.$inferInsert;
export type TaskActivityItem = typeof taskActivities.$inferSelect;