⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat: mention people and agents in documents and their comments (#710)
Croff2d1c60b90691
diff --git a/README.md b/README.mdindex fd3c217d..2db3e2f1 100644--- a/README.md+++ b/README.md@@ -65,7 +65,8 @@ release.completion date, breakdown, pulse- Quick actions that run on an issue, and auto-assignment when an issue moves into a state- Docs: shared Markdown pages in a tree, with revision history, private and locked pages,- favorites, embedded files, and links to the issues they describe+ favorites, embedded files, comment threads, @username mentions of people and agents,+ and links to the issues they describe- Freeform notes boards: sticky notes on a canvas, with colors, checklists, and connections- Share a view or an issue by public link, read-only and without sign-in- Initiatives that group and track related work inside a project@@ -83,7 +84,8 @@ release.[`@itsaplan/runner`](packages/runner) and it gives every task to Claude Code, Codex,Antigravity CLI, GitHub Copilot CLI, opencode, or any command that reads stdin- Or control the run queue through the API and do the work in your own implementation-- A run starts on an @mention in a comment, on an assignment, or on a schedule+- A run starts on an @mention in a comment on an issue or a document, on an assignment, or+ on a schedule- Tools for the services outside the tracker: Notion, Telegram, Threads, Instagram, Jina,Firecrawl, Gitea, and GitHub- Built-in chat with each agent, with its own conversation historydiff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 09d44a80..8b174a19 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -184,6 +184,7 @@ export const app = new Elysia(){ name: 'Dashboards', description: 'Saved analytics dashboards' },{ name: 'Documents', description: 'Shared project Docs pages' },{ name: 'Link previews', description: 'Public web link metadata' },+ { name: 'Mentions', description: 'Who an @username reaches where it is written' },{ name: 'Note boards', description: 'Freeform canvases of sticky notes' },{ name: 'Notifications', description: "The session user's inbox notifications" },{ name: 'Sync', description: 'Change markers a client polls for live refresh' },diff --git a/apps/api/src/mcp/instructions.ts b/apps/api/src/mcp/instructions.tsindex e972f06a..5137a687 100644--- a/apps/api/src/mcp/instructions.ts+++ b/apps/api/src/mcp/instructions.ts@@ -96,11 +96,12 @@ the same url, so view it again rather than reusing what you saw earlier.## Mentions-A comment or an issue description tags someone by writing @handle inline, which-notifies them. The handle is the username of a person in get_project.assignees, which-lists members and AI agents alike; a handle nobody in the project answers to tags-nobody. An AI agent tagged in a comment starts a run on that issue, so tag one only-when you want it to act.+A comment, an issue description, a document or a comment on a document tags someone+by writing @handle inline, which notifies them. The handle is the username of a person+in get_project.assignees, which lists members and AI agents alike; a handle nobody in+the project answers to tags nobody. An AI agent tagged in a comment starts a run on+that issue or document, so tag one only when you want it to act. An agent tagged in+the text of an issue or a document is not run.## Restraintdiff --git a/apps/api/src/modules/agents/core/__tests__/unit/framing.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/framing.test.tsindex ca63b461..f1b120fc 100644--- a/apps/api/src/modules/agents/core/__tests__/unit/framing.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/unit/framing.test.ts@@ -36,9 +36,53 @@ const run: RunForPrompt = {agentUsername: 'bot',threadContext: null,sourceActivityId: null,+ documentId: null,+ documentTitle: null,+ documentQuote: null,+ threadRootId: null,};describe('framePrompt', () => {+ it('frames a document mention as a reply in its thread, with the thread for context', () => {+ const text = framePrompt({+ ...run,+ trigger: 'mention',+ prompt: '@bot can you check this?',+ issueId: null,+ issueIdentifier: null,+ issueTitle: null,+ documentId: 12,+ documentTitle: 'Onboarding',+ documentQuote: 'Ship on Friday',+ threadRootId: 'root-id',+ threadContext: 'Ann: Is Friday realistic?',+ });+ expect(text).toContain('"Onboarding" (documentId 12)');+ expect(text).toContain('add_document_comment tool (documentId 12, parentId root-id)');+ expect(text).toContain('Ship on Friday');+ expect(text).toContain('Ann: Is Friday realistic?');+ expect(text.endsWith('@bot can you check this?')).toBe(true);+ expect(text).not.toContain('issueId');+ });++ it('frames an answer to the agent in a document thread as one, not as a mention', () => {+ const text = framePrompt({+ ...run,+ trigger: 'mention',+ prompt: 'Thanks, now the summary',+ issueId: null,+ issueIdentifier: null,+ issueTitle: null,+ documentId: 12,+ documentTitle: 'Onboarding',+ threadRootId: 'root-id',+ });+ expect(text.startsWith('Someone answered your comment on the document "Onboarding"')).toBe(+ true,+ );+ expect(text).toContain('The answer to your comment:');+ });+it('frames a field run as work on the issue, not as an answer to a comment', () => {const text = framePrompt(run);expect(text.startsWith(run.prompt)).toBe(true);diff --git a/apps/api/src/modules/agents/core/__tests__/unit/thread-ids.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/thread-ids.test.tsindex 214afda0..076f5b5d 100644--- a/apps/api/src/modules/agents/core/__tests__/unit/thread-ids.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/unit/thread-ids.test.ts@@ -7,12 +7,16 @@ import {} from '../../runtime/thread-ids';describe('runThreadId', () => {- const base = { id: 7, agentId: 3, issueId: null, scheduleId: null };+ const base = { id: 7, agentId: 3, issueId: null, documentId: null, scheduleId: null };it('scopes an issue run to the (issue, agent) pair', () => {expect(runThreadId({ ...base, issueId: 42 })).toBe('issue:42:3');});+ it('scopes a document run to the (document, agent) pair', () => {+ expect(runThreadId({ ...base, documentId: 12 })).toBe('document:12:3');+ });+it('keeps two agents on the same issue apart', () => {expect(runThreadId({ ...base, issueId: 42, agentId: 4 })).not.toBe(runThreadId({ ...base, issueId: 42 }),diff --git a/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.tsindex 4a944793..87fc667d 100644--- a/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/unit/tools.test.ts@@ -84,6 +84,7 @@ describe('normalizeToolKeys', () => {'create_document','update_document','delete_document',+ 'add_document_comment',];expect(normalizeToolKeys(keys)).toEqual(keys);});diff --git a/apps/api/src/modules/agents/core/model.ts b/apps/api/src/modules/agents/core/model.tsindex f61402aa..3b6a14ff 100644--- a/apps/api/src/modules/agents/core/model.ts+++ b/apps/api/src/modules/agents/core/model.ts@@ -207,6 +207,8 @@ export const AgentRunResponse = t.Object({issueId: t.Nullable(t.Number()),issueIdentifier: t.Nullable(t.String()),issueTitle: t.Nullable(t.String()),+ documentId: t.Nullable(t.Number()),+ documentTitle: t.Nullable(t.String()),prompt: t.String(),attempts: t.Number(),lastError: t.Nullable(t.String()),diff --git a/apps/api/src/modules/agents/core/prompt/framing.ts b/apps/api/src/modules/agents/core/prompt/framing.tsindex e512668d..0b670d3b 100644--- a/apps/api/src/modules/agents/core/prompt/framing.ts+++ b/apps/api/src/modules/agents/core/prompt/framing.ts@@ -30,6 +30,12 @@ export interface RunForPrompt {threadContext: string | null;// The comment that mentioned the agent, so it can answer in the same thread.sourceActivityId: number | null;+ // Set on a mention in a document comment, which has no issue: the document, the text+ // its thread is about, and the thread's first comment, which the answer goes under.+ documentId: number | null;+ documentTitle: string | null;+ documentQuote: string | null;+ threadRootId: string | null;}// System-instruction block describing how this run was started, so the agent knows@@ -37,17 +43,18 @@ export interface RunForPrompt {// a clarifying question, so the agent acts on reasonable assumptions instead of asking.// Kept in the system prompt (not the framed user message) so it outweighs the task// text and applies even when a schedule's task prompt is vague.-export function runModePreamble(trigger: RunForPrompt['trigger']): string {+export function runModePreamble(run: Pick<RunForPrompt, 'trigger' | 'documentId'>): string {const lines = ['## Run mode'];- if (trigger === 'schedule' || trigger === 'manual') {+ if (run.trigger === 'schedule' || run.trigger === 'manual') {lines.push('This run was started automatically on a schedule, not by a person. No human is','watching it and no one will answer questions. Complete the task with your tools,','making reasonable assumptions; never ask for clarification or wait for input.',);} else {+ const subject = run.documentId != null ? 'a document' : 'an issue';lines.push(- 'You are running autonomously in response to activity on an issue. No human is',+ `You are running autonomously in response to activity on ${subject}. No human is`,'waiting to answer you, so do not ask clarifying questions or wait for confirmation;','make the most reasonable assumption and carry the work out with your tools.',);@@ -59,6 +66,7 @@ export function framePrompt(run: RunForPrompt): string {if (run.trigger === 'schedule' || run.trigger === 'manual') {return `Carry out the following task:\n\n${run.prompt}`;}+ if (run.documentId != null) return frameDocumentMention(run);if (run.trigger === 'status' || run.trigger === 'event' || run.trigger === 'field') {return frameIssueTask(run);}@@ -146,6 +154,41 @@ function frameMention(run: RunForPrompt, titled: string): string {return lines.join('\n');}+// Only a comment in a document starts a run, never its text: one that tags the agent,+// or a reply right after the agent's own comment.+function frameDocumentMention(run: RunForPrompt): string {+ const titled = `"${run.documentTitle?.trim() || 'Untitled'}" (documentId ${run.documentId})`;+ const args = run.threadRootId+ ? `documentId ${run.documentId}, parentId ${run.threadRootId}`+ : `documentId ${run.documentId}`;+ const mentionsAgent =+ !!run.agentUsername &&+ parseMentionHandles(run.prompt).includes(run.agentUsername.toLowerCase());+ const lines = [+ mentionsAgent+ ? `You were mentioned in a comment on the document ${titled} of your project.`+ : `Someone answered your comment on the document ${titled} of your project.`,+ 'Work out what the comment is asking for and do it with your tools, then reply by',+ `adding one comment to its thread with the add_document_comment tool (${args})`,+ 'with the result or answer. Keep it short. Read the document with the get_document',+ 'tool when the answer depends on its text.',+ 'Do not mention yourself.',+ ];+ if (run.documentQuote) {+ lines.push('', 'The thread is about this text of the document:', '', run.documentQuote);+ }+ if (run.threadContext) {+ lines.push('', 'The comments above it in the thread, oldest first:', '', run.threadContext);+ }+ lines.push(+ '',+ mentionsAgent ? 'The comment that mentioned you:' : 'The answer to your comment:',+ '',+ run.prompt,+ );+ return lines.join('\n');+}+// A leading system-instruction block naming the project the agent works in. Grounds// every run — the test chat, the issue-triggered runs, and the ones a runner executes// — so the agent knows which project its tools act on and how issue keys are formed.diff --git a/apps/api/src/modules/agents/core/run-poller.ts b/apps/api/src/modules/agents/core/run-poller.tsindex 8d5657dc..4cb518d0 100644--- a/apps/api/src/modules/agents/core/run-poller.ts+++ b/apps/api/src/modules/agents/core/run-poller.ts@@ -86,7 +86,7 @@ async function processRun(run: ClaimedRun): Promise<void> {scheduleId: run.scheduleId,runId: run.id,trigger: run.trigger,- contextPreamble: runModePreamble(run.trigger) + peopleContext(run),+ contextPreamble: runModePreamble(run) + peopleContext(run),abortSignal: AbortSignal.timeout(timeoutMs),});if (result.aborted) {diff --git a/apps/api/src/modules/agents/core/run-queue.ts b/apps/api/src/modules/agents/core/run-queue.tsindex 3fc69b52..2e7dee88 100644--- a/apps/api/src/modules/agents/core/run-queue.ts+++ b/apps/api/src/modules/agents/core/run-queue.ts@@ -1,5 +1,28 @@-import { db, agentRun, issue, project, team } from '@repo/db';-import { and, desc, eq, gt, inArray, isNotNull, lt, sql } from 'drizzle-orm';+import {+ db,+ agentRun,+ aiAgent,+ documentComment,+ issue,+ project,+ projectDocument,+ team,+ user,+} from '@repo/db';+import {+ and,+ asc,+ desc,+ eq,+ exists,+ gt,+ inArray,+ isNotNull,+ isNull,+ lt,+ or,+ sql,+} from 'drizzle-orm';import { getAgentSettings } from '#modules/settings/service';import { intEnv, iso } from '#shared/lib';import type { AgentRunTrigger } from '../model';@@ -30,18 +53,38 @@ export function runRetryDelayMs(attempts: number): number {}// The condition a candidate run `q` of a claim meets when it is its turn. The runs of-// one agent on one issue share the agent's conversation thread and act on the same-// issue, so they go one at a time, oldest first: a run waits while another of them-// holds a slot (claimed and inside its lease, or waiting out a retry), and while an-// older one is due, which the same claim takes instead.-export const issueRunTurn = sql`NOT EXISTS (+// one agent on one issue, or on one document, share the agent's conversation thread and+// act on the same issue or document, so they go one at a time, oldest first: a run waits+// while another of them holds a slot (claimed and inside its lease, or waiting out a+// retry), and while an older one is due, which the same claim takes instead.+export const runTurn = sql`NOT EXISTS (SELECT 1 FROM agent_run o- WHERE o.agent_id = q.agent_id AND o.issue_id = q.issue_id AND o.id <> q.id+ WHERE o.agent_id = q.agent_id AND o.id <> q.id+ AND (o.issue_id = q.issue_id OR o.document_id = q.document_id)AND o.status = 'pending'AND ((o.started_at IS NOT NULL AND o.next_attempt_at > now())OR (o.next_attempt_at <= now() AND o.id < q.id)))`;+// A run started in a document reads as missing to a viewer the document is now private+// from, as the run of an issue that moved to another project does.+export function runDocumentVisibleTo(viewerId: string) {+ return or(+ isNull(agentRun.documentId),+ exists(+ db+ .select({ id: projectDocument.id })+ .from(projectDocument)+ .where(+ and(+ eq(projectDocument.id, agentRun.documentId),+ or(eq(projectDocument.isPrivate, false), eq(projectDocument.ownerUserId, viewerId)),+ ),+ ),+ ),+ );+}+// Runs of this workspace's agents that hold a slot and were queued before this one. A claim// stamps started_at and pushes next_attempt_at forward, so a pending run that is// stamped and still inside that window is one of them — as is a run waiting out its@@ -68,11 +111,14 @@ export async function countRunsAhead(workspaceId: number, runId: number): Promisexport async function enqueueAgentRun(input: {agentId: number;- // The project the run works in, which is the issue's. An agent works in several- // projects, so the run carries its own rather than reading the agent's.+ // The project the run works in, which is the issue's or the document's. An agent works+ // in several projects, so the run carries its own rather than reading the agent's.projectId: number;- issueId: number;+ issueId: number | null;sourceActivityId: number | null;+ // A mention in a document comment: the document and the comment, with no issue.+ documentId?: number;+ sourceDocumentCommentId?: string;prompt: string;trigger?: 'mention' | 'delegation' | 'field';// Seconds the run stays unclaimable after it is queued, so the issue can still be@@ -85,6 +131,8 @@ export async function enqueueAgentRun(input: {projectId: input.projectId,issueId: input.issueId,sourceActivityId: input.sourceActivityId,+ documentId: input.documentId,+ sourceDocumentCommentId: input.sourceDocumentCommentId,prompt: input.prompt,trigger: input.trigger ?? (input.sourceActivityId == null ? 'delegation' : 'mention'),nextAttemptAt: delay > 0 ? sql`now() + make_interval(secs => ${delay})` : undefined,@@ -129,6 +177,15 @@ export interface ClaimedRun {// The comments the source comment replies to, oldest first, when it is a reply.// Null for a top-level mention or a delegation.threadContext: string | null;+ // A mention in a document comment: the document, the comment, and the thread it is in.+ // All null for any other run.+ documentId: number | null;+ sourceDocumentCommentId: string | null;+ documentTitle: string | null;+ // The text of the document the thread is about.+ documentQuote: string | null;+ // The first comment of the thread, which a reply is posted under.+ threadRootId: string | null;}// Atomically claims up to batchSize due runs of internal agents. FOR UPDATE SKIP@@ -155,7 +212,7 @@ export async function claimDueRuns(): Promise<ClaimedRun[]> {SELECT id FROM agent_run qWHERE q.status = 'pending' AND q.next_attempt_at <= now()AND (SELECT kind FROM ai_agent a WHERE a.id = q.agent_id) = 'internal'- AND ${issueRunTurn}+ AND ${runTurn}ORDER BY q.next_attempt_at, q.idFOR UPDATE SKIP LOCKEDLIMIT ${batchSize}@@ -169,6 +226,8 @@ export async function claimDueRuns(): Promise<ClaimedRun[]> {r.prompt,r.attempts,r.source_activity_id AS "sourceActivityId",+ r.document_id AS "documentId",+ r.source_document_comment_id AS "sourceDocumentCommentId",r.project_id AS "projectId",(SELECT user_id FROM ai_agent a WHERE a.id = r.agent_id) AS "agentUserId",(SELECT username FROM ai_agent a WHERE a.id = r.agent_id) AS "agentUsername",@@ -190,13 +249,9 @@ export async function claimDueRuns(): Promise<ClaimedRun[]> {WHERE a.id = r.source_activity_id) AS "requesterUsername",(SELECT actor_user_id FROM issue_activity a WHERE a.id = r.source_activity_id) AS "requesterUserId"`);- const runs = rows as unknown as ClaimedRun[];+ const runs = rows as unknown as Omit<ClaimedRun, ThreadField | 'executionDeadline'>[];return Promise.all(- runs.map(async (run) => ({- ...run,- executionDeadline,- threadContext: await loadThreadContext(run.sourceActivityId),- })),+ runs.map(async (run) => ({ ...run, executionDeadline, ...(await loadRunThread(run)) })),);}@@ -204,10 +259,90 @@ export async function claimDueRuns(): Promise<ClaimedRun[]> {// the question to pay for the tokens it costs.const THREAD_CONTEXT_DEPTH = 5;+type ThreadField = 'threadContext' | 'documentTitle' | 'documentQuote' | 'threadRootId';++// What a run is told about the conversation it answers, read once it is claimed. A+// document run also names its requester here.+type RunThread = Pick<ClaimedRun, ThreadField> &+ Partial<Pick<ClaimedRun, 'requesterName' | 'requesterUsername' | 'requesterUserId'>>;++export async function loadRunThread(run: {+ sourceActivityId: number | null;+ documentId: number | null;+ sourceDocumentCommentId: string | null;+}): Promise<RunThread> {+ if (run.documentId != null)+ return loadDocumentThread(run.documentId, run.sourceDocumentCommentId);+ return {+ threadContext: await loadThreadContext(run.sourceActivityId),+ documentTitle: null,+ documentQuote: null,+ threadRootId: null,+ };+}++// A document comment's thread: the document's title, the text the thread is about, its+// first comment, and the comments before the given one, oldest first and at most+// THREAD_CONTEXT_DEPTH of them. The comment's author is the requester, read here because+// a document comment keeps no name of its own.+async function loadDocumentThread(+ documentId: number,+ commentId: string | null,+): Promise<RunThread> {+ const [document] = await db+ .select({ title: projectDocument.title })+ .from(projectDocument)+ .where(eq(projectDocument.id, documentId));+ const thread: RunThread = {+ threadContext: null,+ documentTitle: document?.title ?? null,+ documentQuote: null,+ threadRootId: null,+ };+ if (commentId == null) return thread;+ const [source] = await db+ .select({+ parentId: documentComment.parentId,+ authorId: documentComment.authorId,+ authorName: user.name,+ authorUsername: sql<string | null>`coalesce(${user.username}, ${aiAgent.username})`,+ })+ .from(documentComment)+ .leftJoin(user, eq(user.id, documentComment.authorId))+ .leftJoin(aiAgent, eq(aiAgent.userId, documentComment.authorId))+ .where(eq(documentComment.id, commentId));+ if (!source) return thread;+ const rootId = source.parentId ?? commentId;+ const comments = await db+ .select({+ id: documentComment.id,+ quote: documentComment.quote,+ body: documentComment.body,+ authorName: user.name,+ })+ .from(documentComment)+ .leftJoin(user, eq(user.id, documentComment.authorId))+ .where(or(eq(documentComment.id, rootId), eq(documentComment.parentId, rootId)))+ .orderBy(asc(documentComment.createdAt), asc(documentComment.id));+ const at = comments.findIndex((comment) => comment.id === commentId);+ const before = comments.slice(Math.max(0, at - THREAD_CONTEXT_DEPTH), Math.max(0, at));+ return {+ ...thread,+ threadContext: before.length+ ? before.map((c) => `${c.authorName ?? 'Unknown'}: ${c.body}`).join('\n\n')+ : null,+ documentQuote: comments.find((comment) => comment.id === rootId)?.quote || null,+ threadRootId: rootId,+ requesterName: source.authorName,+ requesterUsername: source.authorUsername,+ requesterUserId: source.authorId,+ };+}+// The comments the given one replies to, oldest first and at most// THREAD_CONTEXT_DEPTH of them, as the text a prompt carries. Null when the comment// is not a reply.-export async function loadThreadContext(sourceActivityId: number | null): Promise<string | null> {+async function loadThreadContext(sourceActivityId: number | null): Promise<string | null> {if (sourceActivityId == null) return null;const rows = await db.execute(sql`WITH RECURSIVE chain AS (@@ -324,6 +459,9 @@ export interface AgentRunRow {issueId: number | null;issueIdentifier: string | null;issueTitle: string | null;+ documentId: number | null;+ // Null for a document that is private now, whose title is its owner's alone.+ documentTitle: string | null;prompt: string;attempts: number;lastError: string | null;@@ -371,6 +509,8 @@ export async function listAgentRuns(executionState,trigger: agentRun.trigger,issueId: agentRun.issueId,+ documentId: agentRun.documentId,+ documentTitle: projectDocument.title,prompt: agentRun.prompt,attempts: agentRun.attempts,lastError: agentRun.lastError,@@ -386,6 +526,10 @@ export async function listAgentRuns(.from(agentRun).leftJoin(issue, eq(issue.id, agentRun.issueId)).leftJoin(project, eq(project.id, issue.projectId))+ .leftJoin(+ projectDocument,+ and(eq(projectDocument.id, agentRun.documentId), eq(projectDocument.isPrivate, false)),+ ).where(and(eq(agentRun.agentId, agentId),@@ -406,6 +550,8 @@ export async function listAgentRuns(issueId: r.issueId,issueIdentifier: r.projectKey && r.issueSeq != null ? `${r.projectKey}-${r.issueSeq}` : null,issueTitle: r.issueTitle ?? null,+ documentId: r.documentId,+ documentTitle: r.documentTitle,prompt: r.prompt,attempts: r.attempts,lastError: r.lastError,diff --git a/apps/api/src/modules/agents/core/runtime/thread-ids.ts b/apps/api/src/modules/agents/core/runtime/thread-ids.tsindex 7acb7425..894be47f 100644--- a/apps/api/src/modules/agents/core/runtime/thread-ids.ts+++ b/apps/api/src/modules/agents/core/runtime/thread-ids.ts@@ -20,17 +20,20 @@ export function isOwnChatThread(threadId: string, agentId: number, userId: strin}// The thread an autonomous run continues: one per (agent, issue) for an issue run, one-// per schedule for a scheduled run (a schedule belongs to a single agent, so its id-// already names the agent). Repeated runs then build on what the agent did before, and-// a retry sees how the failed attempt ended. The run-scoped id is the fallback for a-// run with neither, which nothing enqueues today — both columns are nullable.+// per (agent, document) for a mention in a document comment, one per schedule for a+// scheduled run (a schedule belongs to a single agent, so its id already names the+// agent). Repeated runs then build on what the agent did before, and a retry sees how+// the failed attempt ended. The run-scoped id is the fallback for a run with none of+// them, which nothing enqueues today — the columns are nullable.export function runThreadId(run: {id: number;agentId: number;issueId: number | null;+ documentId: number | null;scheduleId: number | null;}): string {if (run.issueId != null) return `issue:${run.issueId}:${run.agentId}`;+ if (run.documentId != null) return `document:${run.documentId}:${run.agentId}`;if (run.scheduleId != null) return `schedule:${run.scheduleId}`;return `run:${run.id}`;}diff --git a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts b/apps/api/src/modules/agents/core/runtime/tools/catalog.tsindex 8ce9a179..b83f126f 100644--- a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts+++ b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts@@ -243,6 +243,19 @@ export const AGENT_ACTIONS: ToolMeta[] = [description: 'Permanently delete shared project documents.',always: false,},+ // A new thread is anchored to text the agent cannot select, so its copy only replies.+ {+ key: 'add_document_comment',+ group: 'documents',+ label: 'Comment on documents',+ description: 'Reply in the comment threads of documents as this agent.',+ always: false,+ overrides: {+ hide: ['quote', 'from', 'to', 'version'],+ description:+ 'Reply in a comment thread of a document. `parentId` is the id of the first comment of the thread.',+ },+ },{key: 'list_note_boards',group: 'notes',diff --git a/apps/api/src/modules/agents/queue/__tests__/integration/runner-queue.test.ts b/apps/api/src/modules/agents/queue/__tests__/integration/runner-queue.test.tsindex 690c8396..e9a1936d 100644--- a/apps/api/src/modules/agents/queue/__tests__/integration/runner-queue.test.ts+++ b/apps/api/src/modules/agents/queue/__tests__/integration/runner-queue.test.ts@@ -253,4 +253,62 @@ describe('runner queue', () => {expect(moved.status).toBe(200);expect((await api['agent-runs'].queue.get()).data!.total).toBe(0);});++ it('shows a run started in a document only to whoever may read the document', async () => {+ const { api } = await setup();+ const documents = api.projects({ projectKey: 'RUN' }).documents;+ const created = (+ await documents.post({+ title: 'Plan',+ content: 'Hello world',+ contentJson: {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello world' }] }],+ },+ })+ ).data!;+ const doc = documents({ documentId: created.id });+ const root = (+ await doc.comments.post({+ body: 'Why?',+ quote: 'Hello',+ from: 1,+ to: 6,+ version: created.version,+ })+ ).data!;+ await doc.comments.post({ parentId: root.id, body: '@runner summarise' });+ const documentRuns = async (viewer: typeof api) =>+ (await viewer['agent-runs'].queue.get()).data!.items.filter(+ (item) => item.prompt === '@runner summarise',+ );+ const [run] = await documentRuns(api);+ expect(run).toBeDefined();++ const blindRole = await createRole(api, 'RUN', {+ name: 'No documents',+ permissions: { work_items: { read: true }, ai_agents: { read: true } },+ });+ const readerRole = await createRole(api, 'RUN', {+ name: 'Documents too',+ permissions: {+ work_items: { read: true },+ ai_agents: { read: true },+ documents: { read: true },+ },+ });+ const blind = await addProjectMember(api, 'RUN', blindRole.data!.id);+ const reader = await addProjectMember(api, 'RUN', readerRole.data!.id);++ expect(await documentRuns(blind)).toHaveLength(0);+ expect((await blind['agent-runs']({ runId: run.id }).trace.get()).status).toBe(403);+ expect(await documentRuns(reader)).toHaveLength(1);+ expect((await reader['agent-runs']({ runId: run.id }).trace.get()).status).toBe(200);++ const { version } = (await doc.get()).data!;+ expect((await doc.access.post({ version, isPrivate: true })).status).toBe(200);+ expect(await documentRuns(reader)).toHaveLength(0);+ expect((await reader['agent-runs']({ runId: run.id }).trace.get()).status).toBe(404);+ expect(await documentRuns(api)).toHaveLength(1);+ });});diff --git a/apps/api/src/modules/agents/queue/index.ts b/apps/api/src/modules/agents/queue/index.tsindex 77c9b8a4..34ea5858 100644--- a/apps/api/src/modules/agents/queue/index.ts+++ b/apps/api/src/modules/agents/queue/index.ts@@ -1,7 +1,7 @@import { assertMcpAllowed, requiresPermission } from '#shared/guards';import { HttpError } from '#shared/lib';import { externalTraceQuery, ExternalTraceResponse, runParams } from '../runner/model';-import { runProjectId, readRunTrace } from '../runner/run-events';+import { visibleRun, readRunTrace } from '../runner/run-events';import { Elysia, type DocumentDecoration } from 'elysia';import { authContext } from '#shared/auth-context';import { assertPermission, requireUser } from '#shared/access';@@ -21,10 +21,15 @@ export const runnerQueueRoutes = new Elysia({return {detail: requiresPermission(['ai_agents', 'read']) as DocumentDecoration,async resolve({ params, user, request }) {- const projectId = await runProjectId(Number((params as { runId: string }).runId));- if (projectId == null) throw new HttpError(404, 'Run not found');+ const run = await visibleRun(+ Number((params as { runId: string }).runId),+ requireUser(user).id,+ );+ if (!run) throw new HttpError(404, 'Run not found');+ const { projectId } = run;await assertPermission(projectId, user, 'work_items', 'read');await assertPermission(projectId, user, 'ai_agents', 'read');+ if (run.documentId != null) await assertPermission(projectId, user, 'documents', 'read');await assertMcpAllowed(projectId, request.headers);return { projectId };},@@ -46,7 +51,7 @@ export const runnerQueueRoutes = new Elysia({detail: {summary: 'Read an external run transcript',description:- 'Recorded events and local Codex session of the selected or latest attempt. Requires both agent and work item read permission in the original project.',+ 'Recorded events and local Codex session of the selected or latest attempt. Requires both agent and work item read permission in the original project, and document read permission for a run started in a document.',},},)@@ -73,7 +78,8 @@ export const runnerQueueRoutes = new Elysia({summary: 'Read the runner queue',description:'Active and past external runs across projects where the caller may read both ' +- 'work items and agents. Running leases first, waiting runs by due time, then newest past runs.',+ 'work items and agents. A run started in a document also takes document read permission. ' ++ 'Running leases first, waiting runs by due time, then newest past runs.',},},);diff --git a/apps/api/src/modules/agents/queue/service.ts b/apps/api/src/modules/agents/queue/service.tsindex d4abe6d1..d1228360 100644--- a/apps/api/src/modules/agents/queue/service.ts+++ b/apps/api/src/modules/agents/queue/service.ts@@ -2,7 +2,7 @@ import { db, agentRun, agentSchedule, aiAgent, project, team, issue, revision }import { and, desc, eq, inArray, isNotNull, isNull, or, sql } from 'drizzle-orm';import { readableProjectIds } from '#shared/access';import { iso } from '#shared/lib';-import { executionState, contextTokensOf } from '../core/run-queue';+import { executionState, contextTokensOf, runDocumentVisibleTo } from '../core/run-queue';// An agent with an invocation URL is sent its work and only calls back while it has// some, so its last contact says nothing about whether the endpoint is up.@@ -31,11 +31,18 @@ export async function listRunnerQueue() {const ids = await queueProjectIds(userId, mcpOnly);if (!ids.length) return { items: [], total: 0, queued: 0, running: 0 };+ // A run started in a document carries its comment, so it also takes reading documents.+ const documentIds = await readableProjectIds(userId, [['documents', 'read']], {+ mcpOnly,+ includeArchived: true,+ });const where = and(inArray(agentRun.projectId, ids),runId == null ? undefined : eq(agentRun.id, runId),eq(aiAgent.kind, 'external'),or(isNull(agentRun.issueId), eq(issue.projectId, agentRun.projectId)),+ or(isNull(agentRun.documentId), inArray(agentRun.projectId, documentIds)),+ runDocumentVisibleTo(userId),);const [rows, counted] = await Promise.all([dbdiff --git a/apps/api/src/modules/agents/runner/run-events.ts b/apps/api/src/modules/agents/runner/run-events.tsindex 0c7fef3e..d7c80520 100644--- a/apps/api/src/modules/agents/runner/run-events.ts+++ b/apps/api/src/modules/agents/runner/run-events.ts@@ -1,6 +1,7 @@import { db, agentRun, agentRunTrace, issue } from '@repo/db';import { and, desc, eq, isNull, lt, or, sql } from 'drizzle-orm';import { HttpError } from '#shared/lib';+import { runDocumentVisibleTo } from '../core/run-queue';import type { AgUiEventBody } from '../model';const MAX_EVENTS = 2000;@@ -70,18 +71,21 @@ export async function appendRunEvents(});}-export async function runProjectId(runId: number) {+// The project of a run whose transcript the viewer asks for, and the document it was+// started in, if any.+export async function visibleRun(runId: number, viewerId: string) {const [row] = await db- .select({ projectId: agentRun.projectId })+ .select({ projectId: agentRun.projectId, documentId: agentRun.documentId }).from(agentRun).leftJoin(issue, eq(issue.id, agentRun.issueId)).where(and(eq(agentRun.id, runId),or(isNull(agentRun.issueId), eq(issue.projectId, agentRun.projectId)),+ runDocumentVisibleTo(viewerId),),);- return row?.projectId;+ return row;}export async function readRunTrace(projectId: number, runId: number, attempt?: number) {diff --git a/apps/api/src/modules/agents/runner/service.ts b/apps/api/src/modules/agents/runner/service.tsindex 80a31ede..01c8892b 100644--- a/apps/api/src/modules/agents/runner/service.ts+++ b/apps/api/src/modules/agents/runner/service.ts@@ -5,8 +5,8 @@ import { type ContextUsage } from '../chat-usage';import {agentRunConfig,deferRun,- issueRunTurn,- loadThreadContext,+ runTurn,+ loadRunThread,markRunExecuting,runRetryDelayMs,scheduleRunRetry,@@ -114,6 +114,8 @@ type ClaimedRow = Omit<RunnerRun, 'systemPrompt' | 'traceEvents'> & {requesterName: string | null;requesterUsername: string | null;sourceActivityId: number | null;+ documentId: number | null;+ sourceDocumentCommentId: string | null;scheduleId: number | null;};@@ -178,7 +180,7 @@ export async function takeNextRun(agent: RunnerAgent): Promise<RunnerRun | null>WHERE r.id = (SELECT id FROM agent_run qWHERE q.agent_id = ${agentId} AND q.status = 'pending' AND q.next_attempt_at <= now()- AND ${issueRunTurn}+ AND ${runTurn}ORDER BY q.next_attempt_at, q.idFOR UPDATE SKIP LOCKEDLIMIT 1@@ -205,6 +207,8 @@ export async function takeNextRun(agent: RunnerAgent): Promise<RunnerRun | null>LEFT JOIN ai_agent ag ON ag.user_id = u.idWHERE i.id = r.issue_id) AS "assigneeUsername",r.source_activity_id AS "sourceActivityId",+ r.document_id AS "documentId",+ r.source_document_comment_id AS "sourceDocumentCommentId",(SELECT actor_name FROM issue_activity a WHERE a.id = r.source_activity_id) AS "requesterName",(SELECT COALESCE(u.username, ag.username)FROM issue_activity a JOIN "user" u ON u.id = a.actor_user_id@@ -218,12 +222,11 @@ export async function takeNextRun(agent: RunnerAgent): Promise<RunnerRun | null>await deferRun(row.id, wait);return null;}- const threadContext = await loadThreadContext(row.sourceActivityId);const forPrompt = {...row,agentUserId: agent.userId,agentUsername: agent.username,- threadContext,+ ...(await loadRunThread(row)),};// A start that fails is a failed attempt: the run comes back after the retry delay,// with the error on it, rather than being handed out half started.@@ -260,7 +263,7 @@ function buildSystemPrompt(agent: RunnerAgent, project: RunnerProject, run: RunFconst instructions = agent.instructions?.trim();return (projectPreamble(project) +- runModePreamble(run.trigger) ++ runModePreamble(run) +peopleContext(run) +(instructions ? `## Instructions\n${instructions}\n` : ''));diff --git a/apps/api/src/modules/documents/__tests__/integration/mentions.test.ts b/apps/api/src/modules/documents/__tests__/integration/mentions.test.tsnew file mode 100644index 00000000..03efeecb--- /dev/null+++ b/apps/api/src/modules/documents/__tests__/integration/mentions.test.ts@@ -0,0 +1,345 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { db, agentRun } from '@repo/db';+import { eq } from 'drizzle-orm';+import { authedApi, createProject, type Api } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { createAgent, projectIdOf, setAgentProjectRole, teamOf } from '#tests/helpers/agents';+import { createRole } from '#tests/helpers/roles';+import { claimDueRuns } from '#modules/agents/core/run-queue';+import { addDocumentComment } from '../../comments';++// A document's text notifies the members it names and runs no agent. A comment on it+// notifies the members it names and queues a run for the agents it names, which the+// claim hands the document and the thread. agent_run is read through the db, as the+// issue mention tests do: a queued run has no route of its own.++interface Member {+ api: Api;+ userId: string;+ username: string;+}++const paragraph = (...content: Record<string, unknown>[]) => ({+ type: 'doc',+ content: [{ type: 'paragraph', content }],+});+const text = (value: string) => ({ type: 'text', text: value });+const mention = (username: string) => ({ type: 'mention', attrs: { username } });++async function setup() {+ const u = await signUpTestUser({ name: 'Owner' });+ const owner: Member = { api: authedApi(u.cookie), userId: u.userId, username: u.username };+ await createProject(owner.api, { key: 'DOC', name: 'Documents' });+ return { owner, documents: owner.api.projects({ projectKey: 'DOC' }).documents };+}++async function addMember(owner: Member, roleId?: number): Promise<Member> {+ const u = await signUpTestUser({ name: 'Member' });+ const invite = await owner.api+ .projects({ projectKey: 'DOC' })+ .invites.post({ email: u.email, role: 'member', roleId });+ const api = authedApi(u.cookie);+ await api.invites({ token: invite.data!.token }).accept.post();+ return { api, userId: u.userId, username: u.username };+}++async function createInternalAgent(owner: Member) {+ return (+ await createAgent(owner.api, 'DOC', { name: 'Doc Bot', username: 'docbot', kind: 'internal' })+ ).data!.agent;+}++// A shared document holding "Hello world", and the first thread on "Hello".+async function documentWithThread(owner: Member) {+ const documents = owner.api.projects({ projectKey: 'DOC' }).documents;+ const created = (+ await documents.post({+ title: 'Plan',+ content: 'Hello world',+ contentJson: paragraph(text('Hello world')),+ })+ ).data!;+ const doc = documents({ documentId: created.id });+ const root = (+ await doc.comments.post({+ body: 'Is this right?',+ quote: 'Hello',+ from: 1,+ to: 6,+ version: created.version,+ })+ ).data!;+ return { id: created.id, doc, rootId: root.id };+}++const mentions = async (member: Member) =>+ (await member.api.notifications.get({ query: { types: 'mentioned' } })).data!.items;++const runsFor = (documentId: number) =>+ db.select().from(agentRun).where(eq(agentRun.documentId, documentId));++describe('document mentions', () => {+ beforeEach(resetDb);++ it('notifies a member mentioned in a comment, pointing at the document and the comment', async () => {+ const { owner } = await setup();+ const member = await addMember(owner);+ const { id, doc, rootId } = await documentWithThread(owner);++ const reply = await doc.comments.post({+ parentId: rootId,+ body: `@${member.username} please check`,+ });+ expect(reply.status).toBe(201);++ const items = await mentions(member);+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({+ type: 'mentioned',+ actorUserId: owner.userId,+ issueId: null,+ documentId: id,+ documentTitle: 'Plan',+ documentCommentId: reply.data!.id,+ projectKey: 'DOC',+ });+ expect(await mentions(owner)).toHaveLength(0);+ });++ it('notifies only the handles an edit of a comment adds', async () => {+ const { owner } = await setup();+ const first = await addMember(owner);+ const second = await addMember(owner);+ const { doc, rootId } = await documentWithThread(owner);+ const reply = (await doc.comments.post({ parentId: rootId, body: `@${first.username} look` }))+ .data!;++ const edited = await doc.comments({ commentId: reply.id }).patch({+ body: `@${first.username} @${second.username} look`,+ });+ expect(edited.status).toBe(200);++ expect(await mentions(first)).toHaveLength(1);+ expect(await mentions(second)).toHaveLength(1);+ });++ it('does not notify a member whose role cannot read documents', async () => {+ const { owner } = await setup();+ const role = await createRole(owner.api, 'DOC', {+ name: 'Board only',+ permissions: { work_items: { read: true } },+ });+ const member = await addMember(owner, role.data!.id);+ const { doc, rootId } = await documentWithThread(owner);++ await doc.comments.post({ parentId: rootId, body: `@${member.username} see this` });++ expect(await mentions(member)).toHaveLength(0);+ });++ it('queues a run for a mentioned agent, claimed with the document and the thread', async () => {+ const { owner } = await setup();+ const agent = await createInternalAgent(owner);+ const { id, doc, rootId } = await documentWithThread(owner);+ for (let i = 1; i <= 6; i++) await doc.comments.post({ parentId: rootId, body: `note ${i}` });++ const asked = (+ await doc.comments.post({ parentId: rootId, body: `@${agent.username} summarize` })+ ).data!;++ const queued = await runsFor(id);+ expect(queued).toHaveLength(1);+ expect(queued[0]).toMatchObject({+ agentId: agent.id,+ issueId: null,+ sourceDocumentCommentId: asked.id,+ trigger: 'mention',+ status: 'pending',+ });++ const run = (await claimDueRuns()).find((claimed) => claimed.documentId === id)!;+ expect(run).toMatchObject({+ documentTitle: 'Plan',+ documentQuote: 'Hello',+ threadRootId: rootId,+ requesterName: 'Owner',+ requesterUsername: owner.username,+ requesterUserId: owner.userId,+ });+ expect(run.threadContext).toContain('Owner: note 6');+ expect(run.threadContext).toContain('Owner: note 2');+ expect(run.threadContext).not.toContain('note 1');+ expect(run.threadContext).not.toContain('summarize');+ });++ it("names the document in the agent's run history, without the title once it is private", async () => {+ const { owner } = await setup();+ const agent = await createInternalAgent(owner);+ const { id, doc, rootId } = await documentWithThread(owner);+ await doc.comments.post({ parentId: rootId, body: `@${agent.username} summarize` });+ const teamId = await teamOf(owner.api, 'DOC');+ const history = () =>+ owner.api.teams({ teamId })['ai-agents']({ agentId: agent.id }).runs.get();++ const listed = await history();+ expect(listed.status).toBe(200);+ expect(listed.data!.items[0]).toMatchObject({+ issueId: null,+ documentId: id,+ documentTitle: 'Plan',+ });++ const { version } = (await doc.get()).data!;+ expect((await doc.access.post({ version, isPrivate: true })).status).toBe(200);+ expect((await history()).data!.items[0]).toMatchObject({ documentId: id, documentTitle: null });+ });++ it('starts no run for an agent whose role cannot comment on documents', async () => {+ const { owner } = await setup();+ const agent = await createInternalAgent(owner);+ const role = await createRole(owner.api, 'DOC', {+ name: 'Docs reader',+ permissions: { documents: { read: true } },+ });+ await setAgentProjectRole(owner.api, 'DOC', agent.userId, role.data!.id);+ const { id, doc, rootId } = await documentWithThread(owner);++ await doc.comments.post({ parentId: rootId, body: `@${agent.username} summarize` });++ expect(await runsFor(id)).toHaveLength(0);+ });++ it('queues a run for the agent a reply answers, without a tag', async () => {+ const { owner } = await setup();+ const agent = await createInternalAgent(owner);+ const { id, doc, rootId } = await documentWithThread(owner);+ const projectId = await projectIdOf(owner.api, 'DOC');+ await addDocumentComment(projectId, id, agent.userId, { parentId: rootId, body: 'Done.' });++ const answer = (await doc.comments.post({ parentId: rootId, body: 'Thanks, now the summary' }))+ .data!;+ const later = await doc.comments.post({ parentId: rootId, body: 'And one more note' });+ expect(later.status).toBe(201);++ const queued = await runsFor(id);+ expect(queued).toHaveLength(1);+ expect(queued[0]).toMatchObject({ agentId: agent.id, sourceDocumentCommentId: answer.id });+ });++ it('starts no run for a comment an agent wrote', async () => {+ const { owner } = await setup();+ const agent = await createInternalAgent(owner);+ const { id, rootId } = await documentWithThread(owner);+ const projectId = await projectIdOf(owner.api, 'DOC');++ await addDocumentComment(projectId, id, agent.userId, {+ parentId: rootId,+ body: `@${agent.username} again`,+ });++ expect(await runsFor(id)).toHaveLength(0);+ });++ it('notifies a member named in the text and runs no agent named there', async () => {+ const { owner, documents } = await setup();+ const member = await addMember(owner);+ const agent = await createInternalAgent(owner);++ const created = await documents.post({+ title: 'Spec',+ content: `Owned by @${member.username} and @${agent.username}`,+ contentJson: paragraph(+ text('Owned by '),+ mention(member.username),+ text(' and '),+ mention(agent.username),+ ),+ });+ expect(created.status).toBe(201);++ const items = await mentions(member);+ expect(items).toHaveLength(1);+ expect(items[0]).toMatchObject({ documentId: created.data!.id, documentCommentId: null });+ expect(await runsFor(created.data!.id)).toHaveLength(0);+ });++ it('reads the text mentions from the mention nodes, and notifies each one once', async () => {+ const { owner, documents } = await setup();+ const member = await addMember(owner);+ const created = (+ await documents.post({+ title: 'Spec',+ content: `typed @${member.username}`,+ contentJson: paragraph(text(`typed @${member.username}`)),+ })+ ).data!;+ expect(await mentions(member)).toHaveLength(0);++ const doc = documents({ documentId: created.id });+ const withMention = paragraph(text('picked '), mention(member.username));+ const updated = (+ await doc.patch({+ version: created.version,+ content: `picked @${member.username}`,+ contentJson: withMention,+ })+ ).data!;+ await doc.patch({+ version: updated.version,+ content: `picked @${member.username} again`,+ contentJson: paragraph(text('picked '), mention(member.username), text(' again')),+ });++ expect(await mentions(member)).toHaveLength(1);+ });++ it('reads a page written as markdown alone from the markdown', async () => {+ const { owner, documents } = await setup();+ const member = await addMember(owner);+ const created = (await documents.post({ title: 'Notes', content: 'Draft' })).data!;++ await documents({ documentId: created.id }).patch({+ version: created.version,+ content: `@${member.username} review`,+ });++ expect(await mentions(member)).toHaveLength(1);+ });++ it('reaches nobody from a private document', async () => {+ const { owner, documents } = await setup();+ const member = await addMember(owner);+ const agent = await createInternalAgent(owner);+ const created = (+ await documents.post({+ title: 'Mine',+ content: 'Hello world',+ contentJson: paragraph(text('Hello world')),+ isPrivate: true,+ })+ ).data!;+ const doc = documents({ documentId: created.id });++ await doc.comments.post({+ body: `@${member.username} @${agent.username}`,+ quote: 'Hello',+ from: 1,+ to: 6,+ version: created.version,+ });++ expect(await mentions(member)).toHaveLength(0);+ expect(await runsFor(created.id)).toHaveLength(0);+ });++ it('takes a reply without a version and refuses a new thread without one', async () => {+ const { owner } = await setup();+ const { doc, rootId } = await documentWithThread(owner);++ expect((await doc.comments.post({ parentId: rootId, body: 'Agreed' })).status).toBe(201);+ expect((await doc.comments.post({ body: 'New', quote: 'Hello', from: 1, to: 6 })).status).toBe(+ 400,+ );+ });+});diff --git a/apps/api/src/modules/documents/collaboration-routes.ts b/apps/api/src/modules/documents/collaboration-routes.tsindex 336010fe..5b61ffe7 100644--- a/apps/api/src/modules/documents/collaboration-routes.ts+++ b/apps/api/src/modules/documents/collaboration-routes.ts@@ -3,6 +3,7 @@ import { authContext } from '#shared/auth-context';import { guards } from '#shared/guards';import { requireUser } from '#shared/access';import { commonErrors, errors } from '#shared/responses';+import { mcpTool } from '#mcp/generate';import { openDocumentSession, getDocumentSteps, saveDocumentSteps } from './collaboration';import { addDocumentComment, listDocumentComments, updateDocumentComment } from './comments';import {@@ -89,7 +90,12 @@ export const documentCollaborationRoutes = new Elysia({params: documentParams,body: documentCommentBody,response: { 201: t.Object({ id: t.String() }), ...commonErrors, ...errors(409) },- detail: { summary: 'Comment on selected document text or reply' },+ detail: {+ summary: 'Comment on selected document text or reply',+ description:+ 'Reply in a comment thread of a document with parentId. Starting a thread takes the selected text: quote, from, to and the document version.',+ ...mcpTool('add_document_comment'),+ },},).patch(diff --git a/apps/api/src/modules/documents/collaboration-schema.ts b/apps/api/src/modules/documents/collaboration-schema.tsindex 7ab371eb..08f0ea76 100644--- a/apps/api/src/modules/documents/collaboration-schema.ts+++ b/apps/api/src/modules/documents/collaboration-schema.ts@@ -35,6 +35,13 @@ const nodes: Record<string, NodeSpec> = {taskItem: { content: 'paragraph block*', defining: true, attrs: { checked: { default: false } } },horizontalRule: { group: 'block', attrs: block },hardBreak: { group: 'inline', inline: true, selectable: false },+ mention: {+ group: 'inline',+ inline: true,+ atom: true,+ selectable: false,+ attrs: { username: { default: '' } },+ },codeBlock: {group: 'block',content: 'text*',diff --git a/apps/api/src/modules/documents/collaboration.ts b/apps/api/src/modules/documents/collaboration.tsindex f5f0a74c..a384db40 100644--- a/apps/api/src/modules/documents/collaboration.ts+++ b/apps/api/src/modules/documents/collaboration.ts@@ -10,6 +10,7 @@ import { Step, Mapping } from '@tiptap/pm/transform';import { HttpError } from '#shared/lib';import { assertValidDocumentContentJson, getDocument } from './service';import { collaborationSchema } from './collaboration-schema';+import { documentMentionHandles, fanOutTextMentions } from './mentions';type Transaction = Parameters<Parameters<typeof db.transaction>[0]>[0];export async function lockVisibleDocument(@@ -165,7 +166,7 @@ export async function saveDocumentSteps(content: string;},) {- await db.transaction(async (tx) => {+ const { document, contentJson } = await db.transaction(async (tx) => {const document = await lockVisibleDocument(tx, projectId, documentId, userId, true);const [session] = await tx.select()@@ -240,6 +241,14 @@ export async function saveDocumentSteps(.set({ from: Math.min(from, to), to: Math.max(from, to), orphaned: from >= to }).where(eq(documentComment.id, comment.id));}+ return { document, contentJson };+ });+ await fanOutTextMentions({+ projectId,+ documentId,+ before: documentMentionHandles(document),+ after: documentMentionHandles({ content: input.content, contentJson }),+ actorUserId: userId,});return getDocument(projectId, documentId, userId);}diff --git a/apps/api/src/modules/documents/comments.ts b/apps/api/src/modules/documents/comments.tsindex ba293579..7d7af840 100644--- a/apps/api/src/modules/documents/comments.ts+++ b/apps/api/src/modules/documents/comments.ts@@ -1,9 +1,11 @@import { db, documentComment } from '@repo/db';import { user } from '@repo/db/schema';-import { and, asc, eq } from 'drizzle-orm';+import { and, asc, desc, eq, or } from 'drizzle-orm';import { HttpError } from '#shared/lib';+import { addedMentionHandles, parseMentionHandles } from '#shared/mentions';import { collaborationSchema } from './collaboration-schema';import { lockVisibleDocument } from './collaboration';+import { fanOutCommentMentions } from './mentions';export async function listDocumentComments(projectId: number, documentId: number, userId: string) {return db.transaction(async (tx) => {@@ -34,13 +36,15 @@ export async function addDocumentComment(quote?: string;from?: number;to?: number;- version: number;+ version?: number;},) {- return db.transaction(async (tx) => {+ const { comment, answeredUserId } = await db.transaction(async (tx) => {const document = await lockVisibleDocument(tx, projectId, documentId, userId);if (document.archivedAt) throw new HttpError(409, 'Archived documents cannot be commented on');if (!input.body.trim()) throw new HttpError(400, 'A comment cannot be empty');+ // A reply answers the comment just before it in the thread.+ let answeredUserId: string | null = null;if (input.parentId) {const [parent] = await tx.select()@@ -49,7 +53,16 @@ export async function addDocumentComment(and(eq(documentComment.id, input.parentId), eq(documentComment.documentId, documentId)),);if (!parent || parent.parentId) throw new HttpError(404, 'Comment thread not found');+ const [previous] = await tx+ .select({ authorId: documentComment.authorId })+ .from(documentComment)+ .where(or(eq(documentComment.id, parent.id), eq(documentComment.parentId, parent.id)))+ .orderBy(desc(documentComment.createdAt), desc(documentComment.id))+ .limit(1);+ answeredUserId = previous?.authorId ?? null;} else {+ if (input.version === undefined)+ throw new HttpError(400, 'A new thread needs the document version');if (document.version !== input.version)throw new HttpError(409, 'The selection changed. Select the text again.');if (@@ -78,9 +91,17 @@ export async function addDocumentComment(from: input.parentId ? null : input.from,to: input.parentId ? null : input.to,})- .returning({ id: documentComment.id });- return comment!;+ .returning({ id: documentComment.id, body: documentComment.body });+ return { comment: comment!, answeredUserId };+ });+ await fanOutCommentMentions({+ projectId,+ documentId,+ comment: { ...comment, authorId: userId },+ handles: parseMentionHandles(comment.body),+ answeredUserId,});+ return { id: comment.id };}export async function updateDocumentComment(projectId: number,@@ -89,27 +110,36 @@ export async function updateDocumentComment(commentId: string,input: { body?: string; resolved?: boolean },) {- await db.transaction(async (tx) => {+ const body = input.body?.trim();+ const comment = await db.transaction(async (tx) => {await lockVisibleDocument(tx, projectId, documentId, userId);const [comment] = await tx.select().from(documentComment).where(and(eq(documentComment.id, commentId), eq(documentComment.documentId, documentId)));if (!comment) throw new HttpError(404, 'Comment not found');- if (input.body !== undefined && comment.authorId !== userId)+ if (body !== undefined && comment.authorId !== userId)throw new HttpError(403, 'Only the author can edit a comment');- if (input.body !== undefined && !input.body.trim())- throw new HttpError(400, 'A comment cannot be empty');+ if (body === '') throw new HttpError(400, 'A comment cannot be empty');if (input.resolved !== undefined && comment.parentId)throw new HttpError(400, 'Resolve the thread, not a reply');await tx.update(documentComment).set({- ...(input.body !== undefined ? { body: input.body.trim() } : {}),+ ...(body !== undefined ? { body } : {}),...(input.resolved !== undefined ? { resolvedAt: input.resolved ? new Date() : null } : {}),updatedAt: new Date(),}).where(eq(documentComment.id, commentId));+ return comment;});+ if (body !== undefined) {+ await fanOutCommentMentions({+ projectId,+ documentId,+ comment: { id: commentId, body, authorId: userId },+ handles: addedMentionHandles(comment.body, body),+ });+ }return { ok: true };}diff --git a/apps/api/src/modules/documents/mentions.ts b/apps/api/src/modules/documents/mentions.tsnew file mode 100644index 00000000..9f397fc9--- /dev/null+++ b/apps/api/src/modules/documents/mentions.ts@@ -0,0 +1,99 @@+import { parseMentionHandles, resolveMentionHandles } from '#shared/mentions';+import { mentionReach, queueMentionRuns } from '#modules/mentions/service';+import { notifyDocumentMentions } from '#modules/notifications/service';++// Mentions in a document. Who a mention reaches is decided by mentionReach; here the+// handles are read from the document and its comments, and the reach is notified or+// given a run.++// The handles the text of a document mentions, lowercased, in first-seen order. The+// editor writes a mention as a node of its own, so the stored tree is read where there+// is one: a handle typed without picking it from the menu stays text, and an autosave+// made while it is typed reaches nobody. A page written as markdown alone, over the+// API, is read from the markdown.+export function documentMentionHandles(document: {+ content: string;+ contentJson: Record<string, unknown> | null;+}): string[] {+ if (!document.contentJson) return parseMentionHandles(document.content);+ const handles = new Set<string>();+ const visit = (node: unknown) => {+ if (!node || typeof node !== 'object') return;+ const { type, attrs, content } = node as {+ type?: unknown;+ attrs?: { username?: unknown };+ content?: unknown;+ };+ if (type === 'mention' && typeof attrs?.username === 'string')+ handles.add(attrs.username.toLowerCase());+ if (Array.isArray(content)) content.forEach(visit);+ };+ visit(document.contentJson);+ return [...handles];+}++// Notifies the members a write of the document's text newly named.+export async function fanOutTextMentions(input: {+ projectId: number;+ documentId: number;+ before: string[];+ after: string[];+ actorUserId: string;+}): Promise<void> {+ const had = new Set(input.before);+ const added = input.after.filter((handle) => !had.has(handle));+ if (added.length === 0) return;+ const { memberIds } = await mentionReach(+ input.projectId,+ input.actorUserId,+ { on: 'document', documentId: input.documentId, place: 'text' },+ await resolveMentionHandles(input.projectId, added),+ );+ await notifyDocumentMentions({+ projectId: input.projectId,+ documentId: input.documentId,+ documentCommentId: null,+ actorUserId: input.actorUserId,+ memberIds,+ });+}++// Fans out the handles of a comment: all of a new comment's, and only the ones an edit+// added to an existing one. A reply also reaches the author of the comment it answers,+// so answering an agent does not have to tag it again.+export async function fanOutCommentMentions(input: {+ projectId: number;+ documentId: number;+ comment: { id: string; body: string; authorId: string };+ handles: string[];+ answeredUserId?: string | null;+}): Promise<void> {+ const { projectId, documentId, comment } = input;+ if (input.handles.length === 0 && !input.answeredUserId) return;+ const mentioned = await resolveMentionHandles(projectId, input.handles);+ const reach = await mentionReach(+ projectId,+ comment.authorId,+ { on: 'document', documentId, place: 'comment' },+ {+ memberIds: mentioned.memberIds,+ agentUserIds: input.answeredUserId+ ? [...mentioned.agentUserIds, input.answeredUserId]+ : mentioned.agentUserIds,+ },+ );+ await notifyDocumentMentions({+ projectId,+ documentId,+ documentCommentId: comment.id,+ actorUserId: comment.authorId,+ memberIds: reach.memberIds,+ });+ await queueMentionRuns({+ projectId,+ actorUserId: comment.authorId,+ agents: reach.agents,+ prompt: comment.body,+ source: { documentId, sourceDocumentCommentId: comment.id },+ });+}diff --git a/apps/api/src/modules/documents/model.ts b/apps/api/src/modules/documents/model.tsindex 4ae8c753..959be0b9 100644--- a/apps/api/src/modules/documents/model.ts+++ b/apps/api/src/modules/documents/model.ts@@ -246,12 +246,26 @@ export const documentCommentParams = t.Object({commentId: t.String({ format: 'uuid' }),});export const documentCommentBody = t.Object({- body: t.String({ minLength: 1, maxLength: 10_000 }),- parentId: t.Optional(t.String({ format: 'uuid' })),+ body: t.String({+ minLength: 1,+ maxLength: 10_000,+ description: 'The comment. Tag a project member or an AI agent with @username.',+ }),+ parentId: t.Optional(+ t.String({+ format: 'uuid',+ description: 'The first comment of the thread to reply in. Omit to start a thread.',+ }),+ ),quote: t.Optional(t.String({ maxLength: 2000 })),from: t.Optional(t.Integer({ minimum: 0 })),to: t.Optional(t.Integer({ minimum: 1 })),- version: t.Integer({ minimum: 1 }),+ version: t.Optional(+ t.Integer({+ minimum: 1,+ description: 'The document version the text was selected in. Required to start a thread.',+ }),+ ),});export const documentCommentUpdateBody = t.Object({body: t.Optional(t.String({ minLength: 1, maxLength: 10_000 })),diff --git a/apps/api/src/modules/documents/service.ts b/apps/api/src/modules/documents/service.tsindex 9f368441..da692966 100644--- a/apps/api/src/modules/documents/service.ts+++ b/apps/api/src/modules/documents/service.ts@@ -23,6 +23,8 @@ import {sql,} from 'drizzle-orm';import { HttpError, iso } from '#shared/lib';+import { MENTION_HANDLE_RE } from '#shared/mentions';+import { documentMentionHandles, fanOutTextMentions } from './mentions';import {assertAttachmentStorageCapacity,assertAttachmentFileAllowed,@@ -594,7 +596,7 @@ export async function createDocument(input: {assertValidDocumentContentJson(input.contentJson);assertValidMetadata(input.metadata);const parentId = input.parentId ?? null;- return db.transaction(async (tx) => {+ const document = await db.transaction(async (tx) => {await lockDocumentActor(tx, input.userId);await tx.execute(sql`select pg_advisory_xact_lock(${DOCUMENT_TREE_LOCK_NAMESPACE}, ${input.projectId})`,@@ -620,6 +622,14 @@ export async function createDocument(input: {.returning();return mapDocumentForUser(tx, row, input.userId);});+ await fanOutTextMentions({+ projectId: input.projectId,+ documentId: document.id,+ before: [],+ after: documentMentionHandles(document),+ actorUserId: input.userId,+ });+ return document;}function assertExpectedVersion(row: { version: number }, expected: number): void {@@ -655,6 +665,7 @@ const DOCUMENT_NODE_TYPES = new Set(['heading','horizontalRule','hardBreak',+ 'mention','codeBlock','image','table',@@ -891,6 +902,16 @@ function assertDocumentNodeAttributes(node: Record<string, unknown>): void {assertAllowedAttributes(attrs, ['language'], 'A code block');assertOptionalBoundedString(attrs.language, 100, 'Code-block language');return;+ case 'mention':+ assertAllowedAttributes(attrs, ['username'], 'A mention');+ if (+ typeof attrs.username !== 'string' ||+ attrs.username.length > 100 ||+ !MENTION_HANDLE_RE.test(attrs.username)+ ) {+ throw new HttpError(400, 'A mention must name a handle.');+ }+ return;default:assertAllowedAttributes(attrs, [], `A ${String(node.type)} node`);}@@ -991,7 +1012,8 @@ export async function updateDocument(): Promise<DocumentRow | null> {assertValidDocumentContentJson(input.contentJson);assertValidMetadata(input.metadata);- return db.transaction(async (tx) => {+ let mentionedBefore: string[] = [];+ const document = await db.transaction(async (tx) => {const anchoredMove = input.previousSiblingId !== undefined || input.nextSiblingId !== undefined;if (anchoredMove && (input.parentId === undefined || input.position === undefined)) {throw new HttpError(400, 'An anchored move requires parentId and position.');@@ -1001,6 +1023,7 @@ export async function updateDocument(}const current = await selectDocument(tx, projectId, documentId, userId);if (!current) return null;+ mentionedBefore = documentMentionHandles(current);await lockDocumentActors(tx, [userId, current.ownerUserId]);if (input.parentId !== undefined || input.position !== undefined) {await tx.execute(@@ -1093,6 +1116,16 @@ export async function updateDocument(}return mapDocumentForUser(tx, row, userId);});+ if (document && (input.content !== undefined || input.contentJson !== undefined)) {+ await fanOutTextMentions({+ projectId,+ documentId,+ before: mentionedBefore,+ after: documentMentionHandles(document),+ actorUserId: userId,+ });+ }+ return document;}async function ownedDocument(diff --git a/apps/api/src/modules/issues/activity.ts b/apps/api/src/modules/issues/activity.tsindex b7b907eb..6afef5cc 100644--- a/apps/api/src/modules/issues/activity.ts+++ b/apps/api/src/modules/issues/activity.ts@@ -15,8 +15,7 @@ import { and, asc, desc, eq, gte, inArray, isNull, lt, ne, sql } from 'drizzle-oimport { HttpError, iso } from '#shared/lib';import { emitCommentEvent } from './webhook-payload';import { addedMentionHandles, parseMentionHandles, resolveMentionHandles } from '#shared/mentions';-import { isAgentUser, listMentionTriggerAgents } from '#modules/agents/core/service';-import { enqueueAgentRun } from '#modules/agents/core/run-queue';+import { mentionReach, queueMentionRuns } from '#modules/mentions/service';import {notifyComment,notifyEditedCommentMentions,@@ -456,17 +455,13 @@ export async function deleteComment(// so answering an agent in its own thread does not have to tag it again. Only quick// queries run here; the work happens later — in the poller for an internal agent, on// the operator's runner for an external one — so creating a comment is never blocked-// on it. Comments authored by an agent's bot user never trigger runs, which stops-// agents from setting each other (or themselves) off.+// on it.async function enqueueMentionRuns(projectId: number,comment: FeedItemRow,mentionedAgentUserIds: string[],): Promise<void> {if (mentionedAgentUserIds.length === 0 && comment.replyToId == null) return;- // A comment an agent wrote starts no run of its own, which stops agent-to-agent- // mention loops.- if (comment.actorUserId && (await isAgentUser(comment.actorUserId))) return;const reachedUserIds = new Set(mentionedAgentUserIds);if (comment.replyToId != null) {const [parent] = await db@@ -475,20 +470,19 @@ async function enqueueMentionRuns(.where(eq(issueActivity.id, comment.replyToId));if (parent?.actorUserId) reachedUserIds.add(parent.actorUserId);}- const agents = await listMentionTriggerAgents(+ const { agents } = await mentionReach(projectId,- [...reachedUserIds],comment.actorUserId,+ { on: 'issue', place: 'comment' },+ { memberIds: [], agentUserIds: [...reachedUserIds] },);- for (const agent of agents) {- await enqueueAgentRun({- agentId: agent.id,- projectId,- issueId: comment.issueId,- sourceActivityId: comment.id,- prompt: comment.body ?? '',- });- }+ await queueMentionRuns({+ projectId,+ actorUserId: comment.actorUserId,+ agents,+ prompt: comment.body ?? '',+ source: { issueId: comment.issueId, sourceActivityId: comment.id },+ });}// --- Activity log ----------------------------------------------------------------diff --git a/apps/api/src/modules/mentions/__tests__/integration/mention-candidates.test.ts b/apps/api/src/modules/mentions/__tests__/integration/mention-candidates.test.tsnew file mode 100644index 00000000..bd265a4e--- /dev/null+++ b/apps/api/src/modules/mentions/__tests__/integration/mention-candidates.test.ts@@ -0,0 +1,153 @@+import { beforeEach, describe, expect, it } from 'bun:test';+import { authedApi, createProject, type Api } from '#tests/helpers/app';+import { signUpTestUser } from '#tests/helpers/auth';+import { resetDb } from '#tests/helpers/db';+import { createAgent, setAgentProjectRole } from '#tests/helpers/agents';+import { createRole } from '#tests/helpers/roles';++// The "@" menu offers whoever a mention written at that place would reach, which the+// mention fan-out reads from the same rule.++interface Member {+ api: Api;+ userId: string;+ username: string;+}++async function setup() {+ const u = await signUpTestUser({ name: 'Owner' });+ const owner: Member = { api: authedApi(u.cookie), userId: u.userId, username: u.username };+ await createProject(owner.api, { key: 'MEN', name: 'Mentions' });+ return owner;+}++async function addMember(owner: Member, roleId?: number): Promise<Member> {+ const u = await signUpTestUser({ name: 'Member' });+ const invite = await owner.api+ .projects({ projectKey: 'MEN' })+ .invites.post({ email: u.email, role: 'member', roleId });+ const api = authedApi(u.cookie);+ await api.invites({ token: invite.data!.token }).accept.post();+ return { api, userId: u.userId, username: u.username };+}++async function addAgent(owner: Member, username: string, triggerOnMention = true) {+ return (+ await createAgent(owner.api, 'MEN', {+ name: username,+ username,+ kind: 'internal',+ triggerOnMention,+ })+ ).data!.agent;+}++const handles = (items: { username: string }[] | null) =>+ (items ?? []).map((item) => item.username).sort();++const onIssue = (member: Member, place: 'comment' | 'text') =>+ member.api.projects({ projectKey: 'MEN' })['mention-candidates'].get({ query: { place } });++const onDocument = (member: Member, documentId: number, place: 'comment' | 'text') =>+ member.api+ .projects({ projectKey: 'MEN' })+ .documents({ documentId })+ ['mention-candidates'].get({ query: { place } });++async function createDocument(member: Member, isPrivate = false) {+ return (+ await member.api+ .projects({ projectKey: 'MEN' })+ .documents.post({ title: 'Plan', content: 'Hello', isPrivate })+ ).data!.id;+}++describe('mention candidates', () => {+ beforeEach(resetDb);++ it('offers members and the agents that answer mentions in an issue comment', async () => {+ const owner = await setup();+ const member = await addMember(owner);+ await addAgent(owner, 'helper');+ await addAgent(owner, 'silent', false);++ const offered = await onIssue(owner, 'comment');+ expect(offered.status).toBe(200);+ expect(handles(offered.data)).toEqual(['helper', member.username].sort());+ expect(offered.data!.find((c) => c.username === 'helper')).toMatchObject({ kind: 'agent' });+ });++ it('offers an owner-scoped external agent only to the member it works for', async () => {+ const owner = await setup();+ const member = await addMember(owner);+ await createAgent(owner.api, 'MEN', {+ name: 'Mine',+ username: 'mine',+ kind: 'external',+ triggerOnMention: true,+ runnerScope: 'owner',+ });++ expect(handles((await onIssue(owner, 'comment')).data)).toEqual(+ ['mine', member.username].sort(),+ );+ expect(handles((await onIssue(member, 'comment')).data)).toEqual([owner.username]);+ });++ it('offers no agent in the text of an issue', async () => {+ const owner = await setup();+ const member = await addMember(owner);+ await addAgent(owner, 'helper');++ expect(handles((await onIssue(owner, 'text')).data)).toEqual([member.username]);+ });++ it('offers in a document comment only who may read documents, and agents that may comment', async () => {+ const owner = await setup();+ const reader = await addMember(owner);+ const boardOnly = await createRole(owner.api, 'MEN', {+ name: 'Board only',+ permissions: { work_items: { read: true } },+ });+ await addMember(owner, boardOnly.data!.id);+ await addAgent(owner, 'writer');+ const readOnly = await addAgent(owner, 'reader');+ const docsReader = await createRole(owner.api, 'MEN', {+ name: 'Docs reader',+ permissions: { documents: { read: true } },+ });+ await setAgentProjectRole(owner.api, 'MEN', readOnly.userId, docsReader.data!.id);+ const documentId = await createDocument(owner);++ const offered = await onDocument(owner, documentId, 'comment');+ expect(offered.status).toBe(200);+ expect(handles(offered.data)).toEqual([reader.username, 'writer'].sort());+ expect(handles((await onDocument(owner, documentId, 'text')).data)).toEqual([reader.username]);+ });++ it('offers nobody in a private document and hides it from everyone else', async () => {+ const owner = await setup();+ const member = await addMember(owner);+ await addAgent(owner, 'helper');+ const documentId = await createDocument(owner, true);++ const offered = await onDocument(owner, documentId, 'comment');+ expect(offered.status).toBe(200);+ expect(offered.data).toEqual([]);+ expect((await onDocument(member, documentId, 'comment')).status).toBe(404);+ });++ it('refuses a caller outside the project', async () => {+ const owner = await setup();+ const documentId = await createDocument(owner);+ const stranger = await signUpTestUser();+ const outsider: Member = {+ api: authedApi(stranger.cookie),+ userId: stranger.userId,+ username: stranger.username,+ };++ expect((await onIssue(outsider, 'comment')).status).toBe(403);+ expect((await onDocument(outsider, documentId, 'comment')).status).toBe(403);+ });+});diff --git a/apps/api/src/modules/mentions/index.ts b/apps/api/src/modules/mentions/index.tsnew file mode 100644index 00000000..c273577c--- /dev/null+++ b/apps/api/src/modules/mentions/index.ts@@ -0,0 +1,52 @@+import { Elysia, t } from 'elysia';+import { authContext } from '#shared/auth-context';+import { guards } from '#shared/guards';+import { requireUser } from '#shared/access';+import { commonErrors } from '#shared/responses';+import {+ MentionCandidateResponse,+ documentMentionParams,+ issueMentionParams,+ mentionCandidatesQuery,+} from './model';+import { listMentionCandidates } from './service';++export const mentionRoutes = new Elysia({ name: 'mentions', detail: { tags: ['Mentions'] } })+ .use(authContext)+ .use(guards)+ .get(+ '/projects/:projectKey/mention-candidates',+ ({ project, user, query }) =>+ listMentionCandidates(project.id, requireUser(user).id, { on: 'issue', place: query.place }),+ {+ permission: ['work_items', 'read'],+ params: issueMentionParams,+ query: mentionCandidatesQuery,+ response: { 200: t.Array(MentionCandidateResponse), ...commonErrors },+ detail: {+ summary: 'List who a mention on an issue reaches',+ description:+ 'The members and agents an @username in a comment or in the text of an issue would reach, the caller left out.',+ },+ },+ )+ .get(+ '/projects/:projectKey/documents/:documentId/mention-candidates',+ ({ project, user, params, query }) =>+ listMentionCandidates(project.id, requireUser(user).id, {+ on: 'document',+ documentId: params.documentId,+ place: query.place,+ }),+ {+ permission: ['documents', 'read'],+ params: documentMentionParams,+ query: mentionCandidatesQuery,+ response: { 200: t.Array(MentionCandidateResponse), ...commonErrors },+ detail: {+ summary: 'List who a mention in a document reaches',+ description:+ 'The members and agents an @username in a comment on a document or in its text would reach, the caller left out.',+ },+ },+ );diff --git a/apps/api/src/modules/mentions/model.ts b/apps/api/src/modules/mentions/model.tsnew file mode 100644index 00000000..d831bf3b--- /dev/null+++ b/apps/api/src/modules/mentions/model.ts@@ -0,0 +1,21 @@+import { t } from 'elysia';++export const mentionCandidatesQuery = t.Object({+ place: t.Union([t.Literal('comment'), t.Literal('text')], {+ description: 'Where the mention is written: a comment, or the text itself.',+ }),+});++export const issueMentionParams = t.Object({ projectKey: t.String() });++export const documentMentionParams = t.Object({+ projectKey: t.String(),+ documentId: t.Numeric(),+});++export const MentionCandidateResponse = t.Object({+ userId: t.String(),+ name: t.String(),+ username: t.String(),+ kind: t.Union([t.Literal('member'), t.Literal('agent')]),+});diff --git a/apps/api/src/modules/mentions/service.ts b/apps/api/src/modules/mentions/service.tsnew file mode 100644index 00000000..11817016--- /dev/null+++ b/apps/api/src/modules/mentions/service.ts@@ -0,0 +1,125 @@+import { db, projectDocument } from '@repo/db';+import { and, eq, or } from 'drizzle-orm';+import { HttpError } from '#shared/lib';+import { hasPermission } from '#shared/permissions';+import type { MentionedUsers } from '#shared/mentions';+import { listAssigneeCandidates, listMemberContexts } from '#modules/members/service';+import { isAgentUser, listMentionTriggerAgents } from '#modules/agents/core/service';+import { enqueueAgentRun } from '#modules/agents/core/run-queue';++// Who a mention reaches, for every text that takes one. The fan-out of a comment or a+// text and the "@" menu both read mentionReach, so the menu offers exactly the people+// and agents a mention would reach.+//+// A comment addresses someone: a member is notified, and an agent that answers mentions+// is given a run. The text of an issue or a document names members for them to read+// it, so it reaches no agent. In a document a member must be able to read documents,+// and an agent also to comment on them, which its answer takes. A private document,+// which only its owner can open, reaches nobody.++export type MentionPlace = 'comment' | 'text';++export type MentionTarget =+ | { on: 'issue'; place: MentionPlace }+ | { on: 'document'; documentId: number; place: MentionPlace };++export interface MentionReach {+ memberIds: string[];+ agents: { id: number; userId: string }[];+}++// `users` are the project's members and agents a text names, or, for a reply, the+// author it answers among the agents.+export async function mentionReach(+ projectId: number,+ actorUserId: string | null,+ target: MentionTarget,+ users: MentionedUsers,+): Promise<MentionReach> {+ let { memberIds } = users;+ let agentUserIds = target.place === 'comment' ? users.agentUserIds : [];+ if (target.on === 'document') {+ const [document] = await db+ .select({ isPrivate: projectDocument.isPrivate })+ .from(projectDocument)+ .where(+ and(eq(projectDocument.id, target.documentId), eq(projectDocument.projectId, projectId)),+ );+ if (!document || document.isPrivate) return { memberIds: [], agents: [] };+ const contexts = await listMemberContexts(projectId);+ const may = (action: 'read' | 'edit') => (userId: string) => {+ const context = contexts.get(userId);+ return !!context && hasPermission(context.permissions, 'documents', action);+ };+ memberIds = memberIds.filter(may('read'));+ agentUserIds = agentUserIds.filter(may('edit'));+ }+ const agents = await listMentionTriggerAgents(projectId, agentUserIds, actorUserId);+ return { memberIds, agents };+}++export interface MentionCandidate {+ userId: string;+ name: string;+ username: string;+ kind: 'member' | 'agent';+}++// What the "@" menu offers the viewer at the target: everyone a mention written there+// would reach, the viewer left out. 404 for a document the viewer cannot open.+export async function listMentionCandidates(+ projectId: number,+ viewerId: string,+ target: MentionTarget,+): Promise<MentionCandidate[]> {+ if (target.on === 'document') {+ const [visible] = await db+ .select({ id: projectDocument.id })+ .from(projectDocument)+ .where(+ and(+ eq(projectDocument.id, target.documentId),+ eq(projectDocument.projectId, projectId),+ or(eq(projectDocument.isPrivate, false), eq(projectDocument.ownerUserId, viewerId)),+ ),+ );+ if (!visible) throw new HttpError(404, 'Document not found');+ }+ const named = (await listAssigneeCandidates(projectId)).filter(+ (candidate) => candidate.username && candidate.userId !== viewerId,+ );+ const reach = await mentionReach(projectId, viewerId, target, {+ memberIds: named.filter((c) => c.kind === 'member').map((c) => c.userId),+ agentUserIds: named.filter((c) => c.kind === 'agent').map((c) => c.userId),+ });+ const reached = new Set([...reach.memberIds, ...reach.agents.map((agent) => agent.userId)]);+ return named+ .filter((candidate) => reached.has(candidate.userId))+ .map(({ userId, name, username, kind }) => ({ userId, name, username: username!, kind }));+}++// Queues a run for each agent a comment reached. A comment an agent wrote starts no+// run, which stops agents from setting each other, or themselves, off.+export async function queueMentionRuns(input: {+ projectId: number;+ actorUserId: string | null;+ agents: MentionReach['agents'];+ prompt: string;+ source:+ | { issueId: number; sourceActivityId: number }+ | { documentId: number; sourceDocumentCommentId: string };+}): Promise<void> {+ if (input.agents.length === 0) return;+ if (input.actorUserId && (await isAgentUser(input.actorUserId))) return;+ for (const agent of input.agents) {+ await enqueueAgentRun({+ agentId: agent.id,+ projectId: input.projectId,+ issueId: null,+ sourceActivityId: null,+ ...input.source,+ prompt: input.prompt,+ trigger: 'mention',+ });+ }+}diff --git a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.tsindex 8baff0d4..f3abe44b 100644--- a/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts+++ b/apps/api/src/modules/notifications/__tests__/integration/notifications.test.ts@@ -115,7 +115,7 @@ describe('notifications', () => {});expect(assigned.data!.count).toBe(1);const afterAssigned = (await member.api.notifications.get({ query: {} })).data!.items;- expect(afterAssigned.map((item) => item.issueId).sort((a, b) => a - b)).toEqual(+ expect(afterAssigned.map((item) => item.issueId!).sort((a, b) => a - b)).toEqual([active.id, completed.id].sort((a, b) => a - b),);expect(afterAssigned.find((item) => item.issueId === completed.id)!.readAt).not.toBeNull();diff --git a/apps/api/src/modules/notifications/model.ts b/apps/api/src/modules/notifications/model.tsindex 0a38f745..799a4572 100644--- a/apps/api/src/modules/notifications/model.ts+++ b/apps/api/src/modules/notifications/model.ts@@ -10,10 +10,14 @@ const NotificationResponse = t.Object({readAt: t.Nullable(t.String()),snoozedUntil: t.Nullable(t.String()),createdAt: t.String(),- issueId: t.Number(),- issueSeq: t.Number(),- issueTitle: t.String(),- issueStateType: t.String(),+ issueId: t.Nullable(t.Number()),+ issueSeq: t.Nullable(t.Number()),+ issueTitle: t.Nullable(t.String()),+ issueStateType: t.Nullable(t.String()),+ documentId: t.Nullable(t.Number()),+ documentTitle: t.Nullable(t.String()),+ documentIcon: t.Nullable(t.String()),+ documentCommentId: t.Nullable(t.String()),projectId: t.Number(),projectKey: t.String(),projectName: t.String(),diff --git a/apps/api/src/modules/notifications/outbound.ts b/apps/api/src/modules/notifications/outbound.tsindex 4d37df9a..2035f993 100644--- a/apps/api/src/modules/notifications/outbound.ts+++ b/apps/api/src/modules/notifications/outbound.ts@@ -4,6 +4,7 @@ import {issue,issueActivity,project,+ projectDocument,team,user,emailSource,@@ -16,18 +17,19 @@ import { readRedactedSettings } from '#modules/notification-settings/service';import { getPreferencesForUsers } from '#modules/notification-preferences/service';import { getTelegramChatIds, hasUsableInstanceBot } from '#modules/telegram/service';import { escapeHtml } from '#shared/lib';-import { issueUrl, teamRef } from '#modules/teams/ref';+import { documentUrl, issueUrl, teamRef } from '#modules/teams/ref';import type { NotificationType, NewNotificationRow } from './service';// Outbound notification delivery: turns the inbox notification rows produced by an-// issue event into notification_delivery outbox rows. Delivery is per member and per-// their own preferences: for each inbox row (already one per recipient), the member's-// notification-preferences decide whether it goes by email (to their account address)-// and/or Telegram (to the chat of the Telegram account they linked). The team that-// owns the project supplies the provider credentials (SMTP/Resend, and optionally its-// own bot token — Telegram otherwise goes through the instance bot). The message text-// is composed here at enqueue time and stored on the row; the worker drains the outbox and the-// sender reads the credentials at send time.+// issue or document event into notification_delivery outbox rows. Delivery is per+// member and per their own preferences: for each inbox row (already one per+// recipient), the member's notification-preferences decide whether it goes by email+// (to their account address) and/or Telegram (to the chat of the Telegram account+// they linked). The team that owns the project supplies the provider credentials+// (SMTP/Resend, and optionally its own bot token — Telegram otherwise goes through+// the instance bot). The message text is composed here at enqueue time and stored on+// the row; the worker drains the outbox and the sender reads the credentials at send+// time.//// This is best-effort: enqueue never throws into the caller (a failure here must not// break creating a comment or updating an issue), so callers wrap it in try/catch.@@ -124,9 +126,88 @@ function telegramPayload(return { text, html, url };}+// A document only sends 'mentioned', so its copy has no per-type table. The title is+// the link in Telegram, as the issue reference is.+function documentEmailPayload(+ title: string,+ actor: string,+ url: string | undefined,+ inComment: boolean,+): DeliveryPayload {+ const where = inComment ? 'in a comment on this document' : 'in this document';+ return {+ subject: `${title}: you were mentioned`,+ text: `${actor} mentioned you ${where}.\n\n${title}`,+ url,+ };+}++function documentTelegramPayload(+ title: string,+ actor: string,+ url: string | undefined,+): DeliveryPayload {+ const action = `Mentioned by ${actor}`;+ const titleLink = url+ ? `<a href="${escapeHtml(url)}"><b>${escapeHtml(title)}</b></a>`+ : `<b>${escapeHtml(title)}</b>`;+ return {+ text: `💬 ${title}\n\n${action}`,+ html: `💬 ${titleLink}\n\n<i>${escapeHtml(action)}</i>`,+ url,+ };+}++interface Messages {+ email: (type: NotificationType) => DeliveryPayload;+ telegram: (type: NotificationType) => DeliveryPayload;+}++// The copy of one event, about the issue or the document its rows point at. Null when+// that is gone.+async function composeMessages(+ notifications: NewNotificationRow[],+ projectRow: { key: string; teamId: number; teamSlug: string | null },+ actor: string,+): Promise<Messages | null> {+ const first = notifications[0];+ const ref = teamRef({ id: projectRow.teamId, slug: projectRow.teamSlug });+ if (first.documentId != null) {+ const documentId = first.documentId;+ const [documentRow] = await db+ .select({ title: projectDocument.title })+ .from(projectDocument)+ .where(eq(projectDocument.id, documentId));+ if (!documentRow) return null;+ const title = documentRow.title.trim() || 'Untitled';+ const url = documentUrl(ref, projectRow.key, documentId);+ const inComment = first.documentCommentId != null;+ return {+ email: () => documentEmailPayload(title, actor, url, inComment),+ telegram: () => documentTelegramPayload(title, actor, url),+ };+ }+ if (first.issueId == null) return null;+ const [issueRow] = await db+ .select({ seq: issue.sequenceNumber, title: issue.title })+ .from(issue)+ .where(eq(issue.id, first.issueId));+ if (!issueRow) return null;+ const issueKey = issueRef(projectRow.key, issueRow.seq);+ const url = issueUrl(ref, projectRow.key, issueRow.seq);+ // One issue event, so every 'state_changed' row points at the same activity row.+ const statusActivityId =+ notifications.find((n) => n.type === 'state_changed')?.sourceActivityId ?? null;+ const stateChange = statusActivityId != null ? await readStateChange(statusActivityId) : null;+ return {+ email: (type) => emailPayload(type, issueKey, issueRow.title, actor, url, stateChange),+ telegram: (type) => telegramPayload(type, issueKey, issueRow.title, actor, url, stateChange),+ };+}+// Enqueues outbound delivery rows for the inbox notifications just created for one-// issue event. All rows in `notifications` share the same issue and actor (both call-// sites operate on a single issue). No-op when the team has no enabled provider or+// event. All rows in `notifications` share the same issue or document and actor (every+// call site operates on one of them). No-op when the team has no enabled provider or// no member wants any of the event types present.export async function enqueueOutbound(notifications: NewNotificationRow[],@@ -161,24 +242,8 @@ export async function enqueueOutbound(settings.telegram.enabled && (settings.telegram.hasBotToken || (await hasUsableInstanceBot()));if (!emailEnabled && !telegramEnabled) return;- const issueId = notifications[0].issueId;- const [issueRow] = await db- .select({ seq: issue.sequenceNumber, title: issue.title })- .from(issue)- .where(eq(issue.id, issueId));- if (!issueRow) return;-- const ref = issueRef(projectRow.key, issueRow.seq);- const url = issueUrl(- teamRef({ id: projectRow.teamId, slug: projectRow.teamSlug }),- projectRow.key,- issueRow.seq,- );- const actor = actorName ?? 'Someone';- // One issue event, so every 'state_changed' row points at the same activity row.- const statusActivityId =- notifications.find((n) => n.type === 'state_changed')?.sourceActivityId ?? null;- const stateChange = statusActivityId != null ? await readStateChange(statusActivityId) : null;+ const messages = await composeMessages(notifications, projectRow, actorName ?? 'Someone');+ if (!messages) return;const userIds = [...new Set(notifications.map((n) => n.userId))];const [users, prefsByUser, chatIdByUser] = await Promise.all([@@ -205,7 +270,7 @@ export async function enqueueOutbound(projectId,channel: 'email',recipient: email,- payload: emailPayload(n.type, ref, issueRow.title, actor, url, stateChange),+ payload: messages.email(n.type),});}if (telegramEnabled && prefs.telegramEvents[n.type]) {@@ -217,7 +282,7 @@ export async function enqueueOutbound(projectId,channel: 'telegram',recipient: chatId,- payload: telegramPayload(n.type, ref, issueRow.title, actor, url, stateChange),+ payload: messages.telegram(n.type),});}}diff --git a/apps/api/src/modules/notifications/service.ts b/apps/api/src/modules/notifications/service.tsindex 49986071..c4eca9c6 100644--- a/apps/api/src/modules/notifications/service.ts+++ b/apps/api/src/modules/notifications/service.ts@@ -7,30 +7,36 @@ import {issueActivity,project,projectColumn,+ projectDocument,type ActivityPayload,} from '@repo/db';-import { and, desc, eq, inArray, lt, or, sql, isNull } from 'drizzle-orm';+import { and, desc, eq, inArray, isNotNull, lt, or, sql, isNull } from 'drizzle-orm';import { addedMentionHandles, resolveMentionHandles, type MentionedUsers } from '#shared/mentions';import { autoWatchIssue, watcherUserIds } from '#modules/issues/watchers';+import { mentionReach } from '#modules/mentions/service';import { iso } from '#shared/lib';import { enqueueOutbound } from './outbound';// Inbox notifications. A notification is one (recipient, event) row: a user is told-// about an issue they are involved in. What happens on the issue ('commented',-// 'state_changed') goes to its watchers (issue_watcher, see modules/issues/watchers.ts);-// what is addressed to one person ('assigned', 'mentioned') goes to them whether-// they watch the issue or not, and subscribes them to it. The actor is never+// about an issue they are involved in, or that a document mentions them. What happens+// on the issue ('commented', 'state_changed') goes to its watchers (issue_watcher, see+// modules/issues/watchers.ts); what is addressed to one person ('assigned',+// 'mentioned') goes to them whether they watch the issue or not, and subscribes them+// to it. A document has no watchers, so it only sends 'mentioned'. The actor is never// notified about their own action, and only project members receive notifications,// so agent bot users (assigned via delegate, not members) are excluded.export const NOTIFICATION_TYPES = ['assigned', 'mentioned', 'commented', 'state_changed'] as const;export type NotificationType = (typeof NOTIFICATION_TYPES)[number];+// Points at an issue, or at a document: then documentId is set and issueId is null.export interface NewNotificationRow {userId: string;projectId: number;- issueId: number;+ issueId: number | null;sourceActivityId: number | null;+ documentId?: number;+ documentCommentId?: string | null;type: NotificationType;actorUserId: string | null;}@@ -135,9 +141,8 @@ export async function notifyEditedCommentMentions(// Fan out the mentions an issue's description or markdown custom field gained. Only// the handles the write added are reached, so re-saving a text keeps quiet about the// people it already named. Being mentioned subscribes to the issue, the same as it-// does in a comment. Only the members named are reached: the text describes the work-// rather than addressing anyone, so an agent named in it is neither notified nor-// given a run — an agent is addressed in a comment, or given an issue by delegation.+// does in a comment. A text reaches only the members it names (see mentionReach): an+// agent is addressed in a comment, or given an issue by delegation.export async function notifyTextMentions(input: {projectId: number;issueId: number;@@ -150,7 +155,12 @@ export async function notifyTextMentions(input: {const { projectId, issueId, actorUserId: actor } = input;const handles = addedMentionHandles(input.before, input.after);if (handles.length === 0) return;- const { memberIds } = await resolveMentionHandles(projectId, handles);+ const { memberIds } = await mentionReach(+ projectId,+ actor,+ { on: 'issue', place: 'text' },+ await resolveMentionHandles(projectId, handles),+ );if (memberIds.length === 0) return;await autoWatchIssue(projectId, issueId, memberIds);await insertNotifications(@@ -220,10 +230,37 @@ export async function notifyIssueChange(input: {await insertNotifications(rows);}+// Fan out a mention in a document: in its text, or in the comment documentCommentId+// names. The caller resolves who may read the document; the actor is left out here.+export async function notifyDocumentMentions(input: {+ projectId: number;+ documentId: number;+ documentCommentId: string | null;+ actorUserId: string | null;+ memberIds: string[];+}): Promise<void> {+ await insertNotifications(+ input.memberIds+ .filter((userId) => userId !== input.actorUserId)+ .map((userId) => ({+ userId,+ projectId: input.projectId,+ issueId: null,+ sourceActivityId: null,+ documentId: input.documentId,+ documentCommentId: input.documentCommentId,+ type: 'mentioned' as const,+ actorUserId: input.actorUserId,+ })),+ );+}+// --- Inbox read + mutations -------------------------------------------------------// A notification enriched with the issue and project it points at, so the inbox can-// render a row (identifier, title, project, actor, status) without extra calls.+// A notification enriched with the issue or the document and the project it points at,+// so the inbox can render a row (identifier or title, project, actor, status) without+// extra calls. The issue fields are null on a document's notification, the document+// fields on an issue's.export interface NotificationRow {id: number;type: NotificationType;@@ -232,10 +269,15 @@ export interface NotificationRow {readAt: string | null;snoozedUntil: string | null;createdAt: string;- issueId: number;- issueSeq: number;- issueTitle: string;- issueStateType: string;+ issueId: number | null;+ issueSeq: number | null;+ issueTitle: string | null;+ issueStateType: string | null;+ documentId: number | null;+ documentTitle: string | null;+ documentIcon: string | null;+ // Set when the mention is in a comment on the document.+ documentCommentId: string | null;projectId: number;projectKey: string;projectName: string;@@ -281,10 +323,14 @@ function mapRow(r: {readAt: Date | null;snoozedUntil: Date | null;createdAt: Date;- issueId: number;- issueSeq: number;- issueTitle: string;- issueStateType: string;+ issueId: number | null;+ issueSeq: number | null;+ issueTitle: string | null;+ issueStateType: string | null;+ documentId: number | null;+ documentTitle: string | null;+ documentIcon: string | null;+ documentCommentId: string | null;projectId: number;projectKey: string;projectName: string;@@ -303,6 +349,10 @@ function mapRow(r: {issueSeq: r.issueSeq,issueTitle: r.issueTitle,issueStateType: r.issueStateType,+ documentId: r.documentId,+ documentTitle: r.documentTitle,+ documentIcon: r.documentIcon,+ documentCommentId: r.documentCommentId,projectId: r.projectId,projectKey: r.projectKey,projectName: r.projectName,@@ -311,12 +361,24 @@ function mapRow(r: {};}+// The document of a notification, joined only while the user may still open it: a page+// made private after it mentioned someone is its owner's alone.+function visibleDocument(userId: string) {+ return and(+ eq(projectDocument.id, notification.documentId),+ or(eq(projectDocument.isPrivate, false), eq(projectDocument.ownerUserId, userId)),+ );+}++// A notification whose issue or document the user can still see.+const hasTarget = or(isNotNull(notification.issueId), isNotNull(projectDocument.id));+// One page of a user's inbox, newest first, keyset-paged on (created_at, id).// Only projects the user is still a member of: the row carries the issue title, its-// current state and the project name read at query time, so a removed member must-// not reach them. includeRead defaults to true (the inbox shows read notifications-// too); a snoozed notification (snoozed_until still in the future) is hidden unless-// includeSnoozed. limit is clamped to 1..100.+// current state, the document title and the project name read at query time, so a+// removed member must not reach them. includeRead defaults to true (the inbox shows+// read notifications too); a snoozed notification (snoozed_until still in the future)+// is hidden unless includeSnoozed. limit is clamped to 1..100.export async function listNotifications(userId: string,opts: { before?: NotificationCursor | null; limit?: number; filters?: NotificationFilters } = {},@@ -340,10 +402,14 @@ export async function listNotifications(snoozedUntil: notification.snoozedUntil,createdAt: notification.createdAt,cursorTs: sql<string>`${notification.createdAt}::text`,- issueId: issue.id,+ issueId: notification.issueId,issueSeq: issue.sequenceNumber,issueTitle: issue.title,issueStateType: projectColumn.stateType,+ documentId: projectDocument.id,+ documentTitle: projectDocument.title,+ documentIcon: projectDocument.icon,+ documentCommentId: notification.documentCommentId,projectId: project.id,projectKey: project.key,projectName: project.name,@@ -354,11 +420,12 @@ export async function listNotifications(projectMember,and(eq(projectMember.projectId, notification.projectId), eq(projectMember.userId, userId)),)- .innerJoin(issue, eq(issue.id, notification.issueId)).innerJoin(project, eq(project.id, notification.projectId))- .innerJoin(projectColumn, eq(projectColumn.id, issue.columnId))+ .leftJoin(issue, eq(issue.id, notification.issueId))+ .leftJoin(projectColumn, eq(projectColumn.id, issue.columnId))+ .leftJoin(projectDocument, visibleDocument(userId)).leftJoin(issueActivity, eq(issueActivity.id, notification.sourceActivityId))- .where(and(...conds))+ .where(and(...conds, hasTarget)).orderBy(desc(notification.createdAt), desc(notification.id)).limit(limit + 1);@@ -387,7 +454,8 @@ export async function unreadCount(userId: string, projectId?: number): Promise<nprojectMember,and(eq(projectMember.projectId, notification.projectId), eq(projectMember.userId, userId)),)- .where(and(...conds));+ .leftJoin(projectDocument, visibleDocument(userId))+ .where(and(...conds, hasTarget));return row?.n ?? 0;}diff --git a/apps/api/src/modules/teams/ref.ts b/apps/api/src/modules/teams/ref.tsindex 488dfc55..711a2892 100644--- a/apps/api/src/modules/teams/ref.ts+++ b/apps/api/src/modules/teams/ref.ts@@ -53,3 +53,10 @@ export function issueUrl(teamRef: string, key: string, seq: number): string | unconst base = process.env.APP_URL;return base ? `${base}${issueWebPath(teamRef, key, seq)}` : undefined;}++// The full URL of a document's page, e.g. "/acme/MKT/docs/12" on the web origin, or+// undefined as for issueUrl.+export function documentUrl(teamRef: string, key: string, documentId: number): string | undefined {+ const base = process.env.APP_URL;+ return base ? `${base}/${teamRef}/${key}/docs/${documentId}` : undefined;+}diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.tsindex a69db694..06a748ce 100644--- a/apps/api/src/planner.ts+++ b/apps/api/src/planner.ts@@ -32,6 +32,7 @@ import { gitSettingsRoutes } from './modules/git';import { dashboardRoutes } from './modules/dashboards';import { noteBoardRoutes } from './modules/note-boards';import { documentRoutes } from './modules/documents';+import { mentionRoutes } from './modules/mentions';import { analyticsRoutes } from './modules/analytics';import { chartRoutes } from './modules/charts';import { settingsRoutes } from './modules/settings';@@ -107,6 +108,7 @@ export const planner = new Elysia({ name: 'planner' }).use(dashboardRoutes).use(noteBoardRoutes).use(documentRoutes)+ .use(mentionRoutes).use(analyticsRoutes).use(chartRoutes).use(notificationRoutes)diff --git a/apps/api/src/shared/mentions.ts b/apps/api/src/shared/mentions.tsindex de0ca3a7..27d68926 100644--- a/apps/api/src/shared/mentions.ts+++ b/apps/api/src/shared/mentions.ts@@ -9,7 +9,9 @@ import { and, eq, inArray, sql } from 'drizzle-orm';// A handle holds letters, digits and . _ -, and never ends on . or -, so a mention// that closes a sentence keeps the punctuation out of the handle. The lookbehind// keeps an email address ([email protected]) and a doubled @ from reading as one.-const MENTION_RE = /(?<![\[email protected]])@([a-zA-Z0-9_](?:[a-zA-Z0-9._-]*[a-zA-Z0-9_])?)/g;+const HANDLE = '[a-zA-Z0-9_](?:[a-zA-Z0-9._-]*[a-zA-Z0-9_])?';+const MENTION_RE = new RegExp(`(?<![\\[email protected]])@(${HANDLE})`, 'g');+export const MENTION_HANDLE_RE = new RegExp(`^${HANDLE}$`);// Markup an @ belongs to rather than addressing anyone: a fenced block, an inline// span of code, a link or an image, and a bare URL. The editor skips the samediff --git a/apps/web/messages/ar/documents.json b/apps/web/messages/ar/documents.jsonindex 954f7fbe..fd8fae2a 100644--- a/apps/web/messages/ar/documents.json+++ b/apps/web/messages/ar/documents.json@@ -39,6 +39,7 @@"saveFailed": "تعذر الحفظ","retrySave": "إعادة محاولة الحفظ","loadFailed": "تعذر تحميل المستندات",+ "pageNotFound": "حُذفت هذه الصفحة أو لم تعد متاحة لك.","conflict": "توجد نسخة أحدث","reload": "إعادة التحميل","reviewConflict": "مراجعة",diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.jsonindex da577977..efe06386 100644--- a/apps/web/messages/ar/settings.json+++ b/apps/web/messages/ar/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "الإسناد إلى مهمة",- "mentioned": "الإشارة في مهمة",+ "mentioned": "الإشارة في مهمة أو مستند","commented": "تعليق جديد على مهمة تتابعها","state_changed": "تغيّر الحالة في مهمة تتابعها"},diff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.jsonindex ed6542b5..9825407f 100644--- a/apps/web/messages/ar/teams.json+++ b/apps/web/messages/ar/teams.json@@ -545,6 +545,7 @@"endOfHistory": "نهاية السجل","manualTask": "مهمة يدوية","scheduledTask": "مهمة مجدولة",+ "documentTask": "تعليق في مستند","failed": "فشل","task": "المهمة","error": "خطأ",diff --git a/apps/web/messages/en/documents.json b/apps/web/messages/en/documents.jsonindex 2d16d4a2..0e83dbd7 100644--- a/apps/web/messages/en/documents.json+++ b/apps/web/messages/en/documents.json@@ -52,6 +52,7 @@"saveFailed": "Could not save","retrySave": "Retry save","loadFailed": "Could not load Docs",+ "pageNotFound": "This page was deleted or is no longer available to you.","conflict": "A newer version exists","reload": "Reload","reviewConflict": "Review",diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.jsonindex 66e659cb..4cea413f 100644--- a/apps/web/messages/en/settings.json+++ b/apps/web/messages/en/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Assigned to an issue",- "mentioned": "Mentioned on an issue",+ "mentioned": "Mentioned on an issue or a document","commented": "New comment on an issue you watch","state_changed": "State changed on an issue you watch"},diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.jsonindex 8e0f8cd9..89bfea1b 100644--- a/apps/web/messages/en/teams.json+++ b/apps/web/messages/en/teams.json@@ -545,6 +545,7 @@"endOfHistory": "End of history","manualTask": "Manual task","scheduledTask": "Scheduled task",+ "documentTask": "Document comment","failed": "Failed","task": "Task","error": "Error",diff --git a/apps/web/messages/es-ES/documents.json b/apps/web/messages/es-ES/documents.jsonindex b5a230da..640b6ffc 100644--- a/apps/web/messages/es-ES/documents.json+++ b/apps/web/messages/es-ES/documents.json@@ -52,6 +52,7 @@"saveFailed": "No se ha podido guardar","retrySave": "Reintentar el guardado","loadFailed": "No se han podido cargar los documentos",+ "pageNotFound": "Esta página se ha eliminado o ya no está disponible para ti.","conflict": "Existe una versión más nueva","reload": "Recargar","reviewConflict": "Revisar",diff --git a/apps/web/messages/es-ES/settings.json b/apps/web/messages/es-ES/settings.jsonindex 6c18b67b..74d42954 100644--- a/apps/web/messages/es-ES/settings.json+++ b/apps/web/messages/es-ES/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Asignado a un ticket",- "mentioned": "Mencionado en un ticket",+ "mentioned": "Mencionado en un ticket o un documento","commented": "Comentario nuevo en un ticket que sigues","state_changed": "Estado cambiado en un ticket que sigues"},diff --git a/apps/web/messages/es-ES/teams.json b/apps/web/messages/es-ES/teams.jsonindex 60933c39..a2e7e51a 100644--- a/apps/web/messages/es-ES/teams.json+++ b/apps/web/messages/es-ES/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Fin del historial","manualTask": "Tarea manual","scheduledTask": "Tarea programada",+ "documentTask": "Comentario en un documento","failed": "Fallida","task": "Tarea","error": "Error",diff --git a/apps/web/messages/fa/documents.json b/apps/web/messages/fa/documents.jsonindex 6a279ea8..936780b6 100644--- a/apps/web/messages/fa/documents.json+++ b/apps/web/messages/fa/documents.json@@ -52,6 +52,7 @@"saveFailed": "ذخیره نشد","retrySave": "تلاش دوباره برای ذخیره","loadFailed": "بارگذاری مستندات ممکن نشد",+ "pageNotFound": "این صفحه حذف شده است یا دیگر در دسترس شما نیست.","conflict": "نسخه جدیدتری وجود دارد","reload": "بارگذاری دوباره","reviewConflict": "بررسی",diff --git a/apps/web/messages/fa/settings.json b/apps/web/messages/fa/settings.jsonindex 733ddfc4..b5e992ce 100644--- a/apps/web/messages/fa/settings.json+++ b/apps/web/messages/fa/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "به یک تسک تخصیص داده شدید",- "mentioned": "در یک تسک منشن شدید",+ "mentioned": "در یک تسک یا مستند منشن شدید","commented": "دیدگاه جدید در تسکی که دنبال میکنید","state_changed": "تغییر وضعیت در تسکی که دنبال میکنید"},diff --git a/apps/web/messages/fa/teams.json b/apps/web/messages/fa/teams.jsonindex 1feccc32..5efaa8d3 100644--- a/apps/web/messages/fa/teams.json+++ b/apps/web/messages/fa/teams.json@@ -545,6 +545,7 @@"endOfHistory": "پایان تاریخچه","manualTask": "وظیفه دستی","scheduledTask": "وظیفه زمانبندیشده",+ "documentTask": "نظر در سند","failed": "ناموفق","task": "وظیفه","error": "خطا",diff --git a/apps/web/messages/fr/documents.json b/apps/web/messages/fr/documents.jsonindex f80aeb07..8ff47524 100644--- a/apps/web/messages/fr/documents.json+++ b/apps/web/messages/fr/documents.json@@ -52,6 +52,7 @@"saveFailed": "Impossible d'enregistrer","retrySave": "Réessayer","loadFailed": "Impossible de charger les documents",+ "pageNotFound": "Cette page a été supprimée ou ne vous est plus accessible.","conflict": "Une version plus récente existe","reload": "Recharger","reviewConflict": "Examiner",diff --git a/apps/web/messages/fr/settings.json b/apps/web/messages/fr/settings.jsonindex 696e2af1..2f98edd0 100644--- a/apps/web/messages/fr/settings.json+++ b/apps/web/messages/fr/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Assigné à un ticket",- "mentioned": "Mentionné sur un ticket",+ "mentioned": "Mentionné sur un ticket ou un document","commented": "Nouveau commentaire sur un ticket que vous suivez","state_changed": "Changement d'état sur un ticket que vous suivez"},diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.jsonindex cce44591..9083df97 100644--- a/apps/web/messages/fr/teams.json+++ b/apps/web/messages/fr/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Fin de l'historique","manualTask": "Tâche manuelle","scheduledTask": "Tâche planifiée",+ "documentTask": "Commentaire dans un document","failed": "En échec","task": "Tâche","error": "Erreur",diff --git a/apps/web/messages/id/documents.json b/apps/web/messages/id/documents.jsonindex ce3f61ee..898f5732 100644--- a/apps/web/messages/id/documents.json+++ b/apps/web/messages/id/documents.json@@ -52,6 +52,7 @@"saveFailed": "Gagal menyimpan","retrySave": "Coba simpan lagi","loadFailed": "Gagal memuat Dokumen",+ "pageNotFound": "Halaman ini telah dihapus atau tidak lagi tersedia untuk Anda.","conflict": "Versi yang lebih baru tersedia","reload": "Muat ulang","reviewConflict": "Tinjau",diff --git a/apps/web/messages/id/settings.json b/apps/web/messages/id/settings.jsonindex 31246254..38f4b138 100644--- a/apps/web/messages/id/settings.json+++ b/apps/web/messages/id/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Ditugaskan ke suatu issue",- "mentioned": "Disebutkan dalam suatu issue",+ "mentioned": "Disebutkan dalam suatu issue atau dokumen","commented": "Komentar baru pada issue yang Anda pantau","state_changed": "Perubahan status pada issue yang Anda pantau"},diff --git a/apps/web/messages/id/teams.json b/apps/web/messages/id/teams.jsonindex 8931a866..351ace3e 100644--- a/apps/web/messages/id/teams.json+++ b/apps/web/messages/id/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Akhir riwayat","manualTask": "Tugas manual","scheduledTask": "Tugas terjadwal",+ "documentTask": "Komentar di dokumen","failed": "Gagal","task": "Tugas","error": "Kesalahan",diff --git a/apps/web/messages/ko/documents.json b/apps/web/messages/ko/documents.jsonindex 515f8d0f..a5514b45 100644--- a/apps/web/messages/ko/documents.json+++ b/apps/web/messages/ko/documents.json@@ -52,6 +52,7 @@"saveFailed": "저장할 수 없습니다.","retrySave": "다시 저장","loadFailed": "문서를 불러올 수 없습니다.",+ "pageNotFound": "이 페이지는 삭제되었거나 더 이상 볼 수 없습니다.","conflict": "새 버전이 있습니다.","reload": "새로고침","reviewConflict": "확인",diff --git a/apps/web/messages/ko/settings.json b/apps/web/messages/ko/settings.jsonindex c12369ae..3b3e5641 100644--- a/apps/web/messages/ko/settings.json+++ b/apps/web/messages/ko/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "이슈 담당자로 지정됨",- "mentioned": "이슈에서 멘션됨",+ "mentioned": "이슈 또는 문서에서 멘션됨","commented": "구독 중인 이슈에 새 댓글","state_changed": "구독 중인 이슈의 상태 변경"},diff --git a/apps/web/messages/ko/teams.json b/apps/web/messages/ko/teams.jsonindex 09e2a2d7..29e7a124 100644--- a/apps/web/messages/ko/teams.json+++ b/apps/web/messages/ko/teams.json@@ -545,6 +545,7 @@"endOfHistory": "기록의 끝","manualTask": "수동 작업","scheduledTask": "예약 작업",+ "documentTask": "문서 댓글","failed": "실패","task": "작업","error": "오류",diff --git a/apps/web/messages/pt-BR/documents.json b/apps/web/messages/pt-BR/documents.jsonindex f4843aaa..94147eae 100644--- a/apps/web/messages/pt-BR/documents.json+++ b/apps/web/messages/pt-BR/documents.json@@ -52,6 +52,7 @@"saveFailed": "Não foi possível salvar","retrySave": "Tentar salvar novamente","loadFailed": "Não foi possível carregar os documentos",+ "pageNotFound": "Esta página foi excluída ou não está mais disponível para você.","conflict": "Existe uma versão mais nova","reload": "Recarregar","reviewConflict": "Revisar",diff --git a/apps/web/messages/pt-BR/settings.json b/apps/web/messages/pt-BR/settings.jsonindex 88d2cf09..21a1c093 100644--- a/apps/web/messages/pt-BR/settings.json+++ b/apps/web/messages/pt-BR/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Atribuído a uma issue",- "mentioned": "Mencionado em uma issue",+ "mentioned": "Mencionado em uma issue ou um documento","commented": "Novo comentário em uma issue que você acompanha","state_changed": "Estado alterado em uma issue que você acompanha"},diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.jsonindex 2c6824b8..cd40705c 100644--- a/apps/web/messages/pt-BR/teams.json+++ b/apps/web/messages/pt-BR/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Fim do histórico","manualTask": "Tarefa manual","scheduledTask": "Tarefa agendada",+ "documentTask": "Comentário em um documento","failed": "Com falha","task": "Tarefa","error": "Erro",diff --git a/apps/web/messages/ru/documents.json b/apps/web/messages/ru/documents.jsonindex e7c1d18a..2d926646 100644--- a/apps/web/messages/ru/documents.json+++ b/apps/web/messages/ru/documents.json@@ -39,6 +39,7 @@"saveFailed": "Не удалось сохранить","retrySave": "Повторить сохранение","loadFailed": "Не удалось загрузить документы",+ "pageNotFound": "Эта страница удалена или больше вам недоступна.","conflict": "Есть более новая версия","reload": "Обновить","reviewConflict": "Разобраться",diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.jsonindex a4d0be6c..a7b694f8 100644--- a/apps/web/messages/ru/settings.json+++ b/apps/web/messages/ru/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Назначен на задачу",- "mentioned": "Упомянут в задаче",+ "mentioned": "Упомянут в задаче или документе","commented": "Новый комментарий в задаче, за которой вы следите","state_changed": "Изменился статус задачи, за которой вы следите"},diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.jsonindex b2c950e2..2464e399 100644--- a/apps/web/messages/ru/teams.json+++ b/apps/web/messages/ru/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Конец истории","manualTask": "Ручная задача","scheduledTask": "Задача по расписанию",+ "documentTask": "Комментарий в документе","failed": "Сбой","task": "Задача","error": "Ошибка",diff --git a/apps/web/messages/tr/documents.json b/apps/web/messages/tr/documents.jsonindex 057d8bfd..37e21f38 100644--- a/apps/web/messages/tr/documents.json+++ b/apps/web/messages/tr/documents.json@@ -52,6 +52,7 @@"saveFailed": "Kaydedilemedi","retrySave": "Kaydetmeyi tekrar dene","loadFailed": "Belgeler yüklenemedi",+ "pageNotFound": "Bu sayfa silindi veya artık erişiminize açık değil.","conflict": "Daha yeni bir sürüm mevcut","reload": "Yeniden yükle","reviewConflict": "İncele",diff --git a/apps/web/messages/tr/settings.json b/apps/web/messages/tr/settings.jsonindex f274d3a7..d2716835 100644--- a/apps/web/messages/tr/settings.json+++ b/apps/web/messages/tr/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Bir işe sorumlu olarak atandığımda",- "mentioned": "Bir işte benden bahsedildiğinde",+ "mentioned": "Bir işte veya belgede benden bahsedildiğinde","commented": "Takip ettiğim bir işe yeni yorum yapıldığında","state_changed": "Takip ettiğim bir işin durumu değiştiğinde"},diff --git a/apps/web/messages/tr/teams.json b/apps/web/messages/tr/teams.jsonindex 1ba50c0a..17e430be 100644--- a/apps/web/messages/tr/teams.json+++ b/apps/web/messages/tr/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Geçmişin sonu","manualTask": "Manuel görev","scheduledTask": "Zamanlanmış görev",+ "documentTask": "Belge yorumu","failed": "Başarısız","task": "Görev","error": "Hata",diff --git a/apps/web/messages/uk/documents.json b/apps/web/messages/uk/documents.jsonindex 31624623..508272fe 100644--- a/apps/web/messages/uk/documents.json+++ b/apps/web/messages/uk/documents.json@@ -39,6 +39,7 @@"saveFailed": "Не вдалося зберегти","retrySave": "Повторити збереження","loadFailed": "Не вдалося завантажити документи",+ "pageNotFound": "Цю сторінку видалено, або вона вам більше недоступна.","conflict": "Існує новіша версія","reload": "Оновити","reviewConflict": "Переглянути",diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.jsonindex 1a23dbe2..439cdf8f 100644--- a/apps/web/messages/uk/settings.json+++ b/apps/web/messages/uk/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "Призначено на задачу",- "mentioned": "Згадали в задачі",+ "mentioned": "Згадали в задачі або документі","commented": "Новий коментар до задачі, за якою ви стежите","state_changed": "Змінився статус задачі, за якою ви стежите"},diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.jsonindex 9f50299f..5711f237 100644--- a/apps/web/messages/uk/teams.json+++ b/apps/web/messages/uk/teams.json@@ -545,6 +545,7 @@"endOfHistory": "Кінець історії","manualTask": "Ручна задача","scheduledTask": "Задача за розкладом",+ "documentTask": "Коментар у документі","failed": "Збій","task": "Задача","error": "Помилка",diff --git a/apps/web/messages/zh-CN/documents.json b/apps/web/messages/zh-CN/documents.jsonindex 8fc981c9..cb37291c 100644--- a/apps/web/messages/zh-CN/documents.json+++ b/apps/web/messages/zh-CN/documents.json@@ -39,6 +39,7 @@"saveFailed": "保存失败","retrySave": "重试保存","loadFailed": "无法加载文档",+ "pageNotFound": "此页面已被删除,或你已无法访问。","conflict": "存在更新版本","reload": "重新加载","reviewConflict": "查看",diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.jsonindex 319fa6f9..232d445d 100644--- a/apps/web/messages/zh-CN/settings.json+++ b/apps/web/messages/zh-CN/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "被指派处理某一工作项",- "mentioned": "在工作项中被提及",+ "mentioned": "在工作项或文档中被提及","commented": "关注的工作项有新评论","state_changed": "关注的工作项状态发生变化"},diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.jsonindex 9b9f905e..3a7a78cd 100644--- a/apps/web/messages/zh-CN/teams.json+++ b/apps/web/messages/zh-CN/teams.json@@ -545,6 +545,7 @@"endOfHistory": "已显示全部记录","manualTask": "手动任务","scheduledTask": "定时任务",+ "documentTask": "文档评论","failed": "失败","task": "任务","error": "错误",diff --git a/apps/web/messages/zh-TW/documents.json b/apps/web/messages/zh-TW/documents.jsonindex ed460ce3..82f0f3b6 100644--- a/apps/web/messages/zh-TW/documents.json+++ b/apps/web/messages/zh-TW/documents.json@@ -39,6 +39,7 @@"saveFailed": "儲存失敗","retrySave": "重試儲存","loadFailed": "無法載入文件",+ "pageNotFound": "此頁面已被刪除,或你已無法存取。","conflict": "存在更新版本","reload": "重新載入","reviewConflict": "檢視",diff --git a/apps/web/messages/zh-TW/settings.json b/apps/web/messages/zh-TW/settings.jsonindex deaa2e97..e0e46f77 100644--- a/apps/web/messages/zh-TW/settings.json+++ b/apps/web/messages/zh-TW/settings.json@@ -97,7 +97,7 @@"telegram": "Telegram","events": {"assigned": "被指派處理某一工作項目",- "mentioned": "在工作項目中被提及",+ "mentioned": "在工作項目或文件中被提及","commented": "關注的工作項目有新留言","state_changed": "關注的工作項目狀態發生變化"},diff --git a/apps/web/messages/zh-TW/teams.json b/apps/web/messages/zh-TW/teams.jsonindex d4024447..0bcd2673 100644--- a/apps/web/messages/zh-TW/teams.json+++ b/apps/web/messages/zh-TW/teams.json@@ -545,6 +545,7 @@"endOfHistory": "已顯示全部記錄","manualTask": "手動任務","scheduledTask": "排程任務",+ "documentTask": "文件留言","failed": "失敗","task": "任務","error": "錯誤",diff --git a/apps/web/src/components/common/editor/MarkdownEditor.tsx b/apps/web/src/components/common/editor/MarkdownEditor.tsxindex 436eef09..f1ddbd9b 100644--- a/apps/web/src/components/common/editor/MarkdownEditor.tsx+++ b/apps/web/src/components/common/editor/MarkdownEditor.tsx@@ -27,7 +27,8 @@ import EditorImagePicker from './EditorImagePicker';import EditorSelectionMenu from './EditorSelectionMenu';import EditorTableMenu from './EditorTableMenu';import EditorLinkPreview from './EditorLinkPreview';-import { useMentionCandidates } from '@/hooks/useMentionCandidates';+import { useMentionCandidates, useMentionNames } from '@/hooks/useMentionCandidates';+import type { MentionSource } from '@/lib/api/endpoints/mentions';import { useTranslations } from 'next-intl';// Shared by every editor instance. A block with no language is detected by@@ -54,6 +55,7 @@ export default function MarkdownEditor({uploadFile,imageAttachments,readingLinks = true,+ mentions,}: {defaultValue: string;onChange?: (markdown: string) => void;@@ -73,6 +75,9 @@ export default function MarkdownEditor({// stored to read them from yet (a create dialog), which drops the picker.imageAttachments?: Embeddable[];readingLinks?: boolean;+ // Where the text is written, which decides who the "@" menu offers. Without it the+ // menu offers nobody: a mention in the text would reach no one.+ mentions?: MentionSource;}) {const t = useTranslations('common.editor');const editorRef = useRef<Editor | null>(null);@@ -82,9 +87,12 @@ export default function MarkdownEditor({const router = useRouter();const { data: session } = useSession();const issueRefs = useIssueRefs();- const mentionCandidates = useMentionCandidates();+ const mentionCandidates = useMentionCandidates(mentions ?? null);const mentionCandidatesRef = useRef(mentionCandidates);mentionCandidatesRef.current = mentionCandidates;+ const mentionNames = useMentionNames();+ const mentionNamesRef = useRef(mentionNames);+ mentionNamesRef.current = mentionNames;const issueRefsRef = useRef(issueRefs);issueRefsRef.current = issueRefs;const openIssueRefRef = useRef(router.push);@@ -137,11 +145,12 @@ export default function MarkdownEditor({}),// Renders  markdown inline.ResizableImage,- // Renders an @username in the text as a mention chip, and offers the project's- // members and agents while one is typed.+ // Renders an @username in the text as a mention chip, and offers who a mention+ // written here reaches while one is typed.Mention.configure({items: () => mentionCandidatesRef.current,self: () => selfHandleRef.current,+ name: (handle) => mentionNamesRef.current.get(handle),}),// Paints KEY-123 as a link without writing the link into the markdown.IssueRef.configure({diff --git a/apps/web/src/components/common/editor/EditorMentionMenu.tsx b/apps/web/src/components/common/inputs/MentionMenu.tsxsimilarity index 63%rename from apps/web/src/components/common/editor/EditorMentionMenu.tsxrename to apps/web/src/components/common/inputs/MentionMenu.tsxindex a1c0374d..e8060fc2 100644--- a/apps/web/src/components/common/editor/EditorMentionMenu.tsx+++ b/apps/web/src/components/common/inputs/MentionMenu.tsx@@ -1,20 +1,24 @@import { useEffect, useImperativeHandle, useState, type Ref } from 'react';import { Bot, User } from 'lucide-react';import { cn } from '@/lib/utils';-import { type MentionCandidate } from '@/lib/tiptap-mention';+import type { MentionCandidate } from '@/lib/api/endpoints/mentions';-export type MentionMenuRef = { onKeyDown: (props: { event: KeyboardEvent }) => boolean };+export type MentionMenuHandle = { onKeyDown: (event: { key: string }) => boolean };-// The list shown after typing "@": who can be mentioned, by name and by the handle-// the mention is written with. Escape is handled by the suggestion plugin.-export default function EditorMentionMenu({+// The list shown after typing "@", in an editor and in a comment box alike: who can be+// mentioned, by name and by the handle the mention is written with. The arrow keys+// move the highlight and Enter or Tab picks it; Escape is left to the owner of the+// text, which closes the menu.+export default function MentionMenu({items,- command,+ onPick,+ className,ref,}: {items: MentionCandidate[];- command: (item: MentionCandidate) => void;- ref?: Ref<MentionMenuRef>;+ onPick: (item: MentionCandidate) => void;+ className?: string;+ ref?: Ref<MentionMenuHandle>;}) {const [activeIndex, setActiveIndex] = useState(0);@@ -22,9 +26,9 @@ export default function EditorMentionMenu({useEffect(() => setActiveIndex(0), [items]);useImperativeHandle(ref, () => ({- onKeyDown: ({ event }) => {+ onKeyDown: ({ key }) => {if (items.length === 0) return false;- switch (event.key) {+ switch (key) {case 'ArrowDown':setActiveIndex((index) => (index + 1) % items.length);return true;@@ -34,7 +38,7 @@ export default function EditorMentionMenu({case 'Enter':case 'Tab': {const item = items[activeIndex];- if (item) command(item);+ if (item) onPick(item);return true;}default:@@ -46,17 +50,22 @@ export default function EditorMentionMenu({if (items.length === 0) return null;return (- <div className="max-h-64 w-64 overflow-y-auto rounded-md border bg-popover p-1 shadow-md">+ <div+ className={cn(+ 'max-h-64 w-64 overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md',+ className,+ )}+ >{items.map((item, index) => (<buttonkey={item.userId}type="button"- // The caret must stay in the typed "@query": the command replaces it.+ // Keeps the caret in the typed "@query", which the pick replaces.onMouseDown={(e) => e.preventDefault()}- onClick={() => command(item)}+ onClick={() => onPick(item)}onMouseEnter={() => setActiveIndex(index)}className={cn(- 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm',+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-start text-sm',index === activeIndex && 'bg-accent text-accent-foreground',)}>diff --git a/apps/web/src/features/documents/DocumentsPage.tsx b/apps/web/src/features/documents/DocumentsPage.tsxindex eb886941..238be01d 100644--- a/apps/web/src/features/documents/DocumentsPage.tsx+++ b/apps/web/src/features/documents/DocumentsPage.tsx@@ -14,18 +14,13 @@ import { Skeleton } from '@/components/ui/skeleton';import { ApiError } from '@/lib/api/core/client';import {useCreateDocument,- useDeleteDocument,- useDuplicateDocument,useDocumentQuery,useDocumentsQuery,} from './services/documents.service';-import DocumentEditor from './components/DocumentEditor';-import DocumentLoadError from './components/DocumentLoadError';-import DocumentLoadingState from './components/DocumentLoadingState';+import DocumentView from './components/DocumentView';import DocumentsIndex from './components/DocumentsIndex';import { importedMarkdownJson, markdownTitle } from './utils/documentImport';import { documentBelongsToTab, type DocumentListTab } from './utils/documentList';-import { documentAncestors } from './utils/documentTree';import { useDebouncedValue } from '@/hooks/useDebouncedValue';import { titlePath, useDocumentTitle } from '@/hooks/useDocumentTitle';import { useDocumentNavigation, useRecentDocuments } from '@/hooks/useDocumentNavigation';@@ -38,7 +33,7 @@ export default function DocumentsPage() {const params = useParams<{ documentId?: string }>();const router = useRouter();const t = useTranslations('documents');- const { can, isOwner } = usePermissions();+ const { can } = usePermissions();const projectKey = useShellRoute().projectKey ?? '';const routeId = params.documentId ? Number(params.documentId) : null;const documentId = routeId && Number.isFinite(routeId) ? routeId : null;@@ -54,13 +49,6 @@ export default function DocumentsPage() {useEffect(() => {if (documentId !== null) visit(documentId);}, [documentId, visit]);- const allDocumentsQuery = useDocumentsQuery(projectKey);- const allArchivedDocumentsQuery = useDocumentsQuery(- projectKey,- '',- true,- documentId !== null || listTab === 'archived',- );const activeDocumentsQuery = useDocumentsQuery(projectKey,deferredSearch,@@ -94,29 +82,13 @@ export default function DocumentsPage() {(documentQuery.data.title.trim() || t('untitled'));useDocumentTitle(titlePath(project?.project.name, documentTitle));const createDocument = useCreateDocument(projectKey);- const deleteDocument = useDeleteDocument(projectKey);- const duplicateDocument = useDuplicateDocument(projectKey);const canRead = can('documents', 'read');const canCreate = can('documents', 'create');const canEdit = can('documents', 'edit');- const canDelete = can('documents', 'delete');- const canReadWorkItems = can('work_items', 'read');- const canLinkWorkItems = canEdit && can('work_items', 'edit');useLiveRefresh({scope: project ? revScope.documents(project.project.id) : null,- targets: [- qk.documentListsForProject(projectKey),- ...(documentId === null- ? []- : [- qk.document(projectKey, documentId),- qk.documentRevisions(projectKey, documentId),- qk.documentAssets(projectKey, documentId),- qk.documentComments(projectKey, documentId),- qk.documentIssueLinks(projectKey, documentId),- ]),- ],+ targets: [qk.documentListsForProject(projectKey)],});useEffect(() => {@@ -142,7 +114,7 @@ export default function DocumentsPage() {);}- const create = async (parentId: number | null, isPrivate = false) => {+ const create = async (parentId: number | null, isPrivate: boolean) => {try {setSearch('');const newDocument = await createDocument.mutateAsync({ parentId, isPrivate });@@ -179,42 +151,6 @@ export default function DocumentsPage() {}};- const remove = async (version: number) => {- if (documentId === null) return;- await deleteDocument.mutateAsync({ documentId, version });- router.push(documentsPath(projectKey));- };-- const duplicate = async (title: string, version: number) => {- if (!activeDocument) return;- try {- const copy = await duplicateDocument.mutateAsync({- documentId: activeDocument.id,- version,- title: t('copyTitle', { title: title.trim() || t('untitled') }),- parentId: activeDocument.parentId,- });- router.push(documentPath(projectKey, copy.id));- } catch {- // Mutation errors are reported by the shared query client.- }- };-- const activeDocument = documentQuery.data;- const author = activeDocument?.updatedByUserId- ? project.assignees.find((candidate) => candidate.userId === activeDocument.updatedByUserId)- : null;- const ancestors = activeDocument- ? documentAncestors(activeDocument, [- ...(allDocumentsQuery.data ?? []),- ...(allArchivedDocumentsQuery.data ?? []),- ])- : [];- const detailFailed =- documentId !== null &&- documentQuery.isError &&- !(documentQuery.error instanceof ApiError && documentQuery.error.status === 404);-if (documentId === null) {return (<DocumentsIndex@@ -241,36 +177,14 @@ export default function DocumentsPage() {);}- if (detailFailed) return <DocumentLoadError onRetry={() => void documentQuery.refetch()} />;- if (!activeDocument) return <DocumentLoadingState />;-return (- <DocumentEditor- key={activeDocument.id}+ <DocumentView+ key={documentId}projectKey={projectKey}- projectName={project.project.name}- document={activeDocument}- ancestors={ancestors}- documents={allDocumentsQuery.data ?? []}- authorName={author?.name ?? null}- authorNames={Object.fromEntries(- project.assignees.map((candidate) => [candidate.userId, candidate.name]),- )}- canEdit={canEdit}- canReadWorkItems={canReadWorkItems}- canLinkWorkItems={canLinkWorkItems}- isProjectOwner={isOwner}- canCreate={canCreate}- canDelete={canDelete}+ documentId={documentId}onBack={() => router.push(documentsPath(projectKey))}- onCreate={(parentId, isPrivate) => void create(parentId, isPrivate)}- onDuplicate={duplicate}- onDelete={remove}- onReload={async () => {- const result = await documentQuery.refetch();- if (result.isError) throw result.error;- return result.data ?? null;- }}+ onCreated={() => setSearch('')}+ onDeleted={() => router.push(documentsPath(projectKey))}/>);}diff --git a/apps/web/src/features/documents/components/DocumentCommentInput.tsx b/apps/web/src/features/documents/components/DocumentCommentInput.tsxnew file mode 100644index 00000000..931df859--- /dev/null+++ b/apps/web/src/features/documents/components/DocumentCommentInput.tsx@@ -0,0 +1,50 @@+import type { ComponentProps } from 'react';+import MentionMenu from '@/components/common/inputs/MentionMenu';+import { Textarea } from '@/components/ui/textarea';+import { useMentionCandidates } from '@/hooks/useMentionCandidates';+import { useMentionMenu } from '@/hooks/useMentionMenu';++// The text box of a document comment, with the "@" menu of who a comment on the+// document reaches.+export default function DocumentCommentInput({+ projectKey,+ documentId,+ value,+ onValueChange,+ onKeyDown,+ ...props+}: Omit<ComponentProps<typeof Textarea>, 'value' | 'onChange' | 'ref'> & {+ projectKey: string;+ documentId: number;+ value: string;+ onValueChange: (value: string) => void;+}) {+ const candidates = useMentionCandidates({+ projectKey,+ on: 'document',+ documentId,+ place: 'comment',+ });+ const mention = useMentionMenu(value, onValueChange, candidates);+ return (+ <div className="relative">+ <Textarea+ {...props}+ ref={mention.ref}+ value={value}+ maxLength={10000}+ onChange={mention.onChange}+ onBlur={mention.close}+ onKeyDown={(event) => {+ if (!mention.onKeyDown(event)) onKeyDown?.(event);+ }}+ />+ <MentionMenu+ ref={mention.menuRef}+ items={mention.matches}+ onPick={mention.pick}+ className="absolute inset-x-0 top-full z-20 mt-1 w-auto"+ />+ </div>+ );+}diff --git a/apps/web/src/features/documents/components/DocumentCommentThread.tsx b/apps/web/src/features/documents/components/DocumentCommentThread.tsxindex 88d3c3ab..a0bc1a05 100644--- a/apps/web/src/features/documents/components/DocumentCommentThread.tsx+++ b/apps/web/src/features/documents/components/DocumentCommentThread.tsx@@ -2,10 +2,13 @@ import { useState } from 'react';import { Check, CornerDownRight, Pencil, RotateCcw } from 'lucide-react';import { useTranslations } from 'next-intl';import type { DocumentComment } from '@/lib/api/endpoints/documents';+import MarkdownEditor from '@/components/common/editor/MarkdownEditor';import { Button } from '@/components/ui/button';-import { Textarea } from '@/components/ui/textarea';+import DocumentCommentInput from './DocumentCommentInput';export default function DocumentCommentThread({+ projectKey,+ documentId,comment,replies,userId,@@ -15,6 +18,8 @@ export default function DocumentCommentThread({onUpdate,onJump,}: {+ projectKey: string;+ documentId: number;comment: DocumentComment;replies: DocumentComment[];userId: string | null;@@ -67,10 +72,11 @@ export default function DocumentCommentThread({}}className="space-y-2">- <Textarea+ <DocumentCommentInput+ projectKey={projectKey}+ documentId={documentId}value={edit.body}- maxLength={10000}- onChange={(event) => setEdit({ id: item.id, body: event.target.value })}+ onValueChange={(body) => setEdit({ id: item.id, body })}aria-label={t('edit')}/><Button size="sm" disabled={busy || !edit.body.trim()}>@@ -81,9 +87,12 @@ export default function DocumentCommentThread({</Button></form>) : (- <p className="text-sm leading-6 break-words whitespace-pre-wrap" dir="auto">- {item.body}- </p>+ <MarkdownEditor+ key={item.body}+ className="text-sm leading-6 break-words"+ defaultValue={item.body}+ editable={false}+ />)}</div>))}@@ -123,10 +132,11 @@ export default function DocumentCommentThread({.catch(() => undefined);}}>- <Textarea+ <DocumentCommentInput+ projectKey={projectKey}+ documentId={documentId}value={reply}- onChange={(event) => setReply(event.target.value)}- maxLength={10000}+ onValueChange={setReply}aria-label={t('reply')}placeholder={t('replyPlaceholder')}/>diff --git a/apps/web/src/features/documents/components/DocumentCommentsPanel.tsx b/apps/web/src/features/documents/components/DocumentCommentsPanel.tsxindex ff4de531..e3bc5cc4 100644--- a/apps/web/src/features/documents/components/DocumentCommentsPanel.tsx+++ b/apps/web/src/features/documents/components/DocumentCommentsPanel.tsx@@ -11,7 +11,7 @@ import {import { qk } from '@/services/queryKeys';import { useSession } from '@/lib/auth-client';import { Button } from '@/components/ui/button';-import { Textarea } from '@/components/ui/textarea';+import DocumentCommentInput from './DocumentCommentInput';import DocumentCommentThread from './DocumentCommentThread';import type { DocumentSelection } from './DocumentSelectionActions';@@ -100,13 +100,14 @@ export default function DocumentCommentsPanel({<blockquote className="line-clamp-3 border-s-2 border-primary/40 ps-3 text-xs leading-5 text-muted-foreground">{selection.quote}</blockquote>- <Textarea+ <DocumentCommentInput+ projectKey={projectKey}+ documentId={documentId}autoFocusaria-label={t('add')}placeholder={t('placeholder')}value={body}- maxLength={10000}- onChange={(event) => setBody(event.target.value)}+ onValueChange={setBody}onKeyDown={(event) => {if ((event.metaKey || event.ctrlKey) && event.key === 'Enter')event.currentTarget.form?.requestSubmit();@@ -148,6 +149,8 @@ export default function DocumentCommentsPanel({roots.map((comment) => (<DocumentCommentThreadkey={comment.id}+ projectKey={projectKey}+ documentId={documentId}comment={comment}replies={comments.filter((item) => item.parentId === comment.id)}userId={session?.user.id ?? null}diff --git a/apps/web/src/features/documents/components/DocumentEditor.tsx b/apps/web/src/features/documents/components/DocumentEditor.tsxindex 5f5d0ae2..2bc3ccd1 100644--- a/apps/web/src/features/documents/components/DocumentEditor.tsx+++ b/apps/web/src/features/documents/components/DocumentEditor.tsx@@ -45,6 +45,7 @@ export default function DocumentEditor({isProjectOwner,canCreate,canDelete,+ defaultCommentsOpen = false,onBack,onCreate,onDuplicate,@@ -64,7 +65,9 @@ export default function DocumentEditor({isProjectOwner: boolean;canCreate: boolean;canDelete: boolean;- onBack: () => void;+ defaultCommentsOpen?: boolean;+ // Left out where the page around the document has its own way back.+ onBack?: () => void;onCreate: (parentId: number | null, isPrivate: boolean) => void;onDuplicate: (title: string, version: number) => Promise<void>;onDelete: (version: number) => Promise<void>;@@ -78,7 +81,7 @@ export default function DocumentEditor({const [deleteOpen, setDeleteOpen] = useState(false);const [discardOpen, setDiscardOpen] = useState(false);const [historyOpen, setHistoryOpen] = useState(false);- const [commentsOpen, setCommentsOpen] = useState(false);+ const [commentsOpen, setCommentsOpen] = useState(defaultCommentsOpen);const [commentSelection, setCommentSelection] = useState<DocumentSelection | null>(null);const [inspectorOpen, setInspectorOpen] = useState(false);const documentAction = useDocumentActionGate();@@ -138,6 +141,7 @@ export default function DocumentEditor({setInspectorOpen(false);},editable ? collaboration.version : document.version,+ collaboration.ready,);const providerActionPending =updateDocument.isPending ||@@ -274,7 +278,7 @@ export default function DocumentEditor({void runVersioned((baseVersion) =>archiveDocument.mutateAsync({ documentId: document.id, version: baseVersion }),).then((changed) => {- if (changed) onBack();+ if (changed) onBack?.();});}}onRestore={() => {diff --git a/apps/web/src/features/documents/components/DocumentEditorHeader.tsx b/apps/web/src/features/documents/components/DocumentEditorHeader.tsxindex bc6f617c..a758447f 100644--- a/apps/web/src/features/documents/components/DocumentEditorHeader.tsx+++ b/apps/web/src/features/documents/components/DocumentEditorHeader.tsx@@ -71,7 +71,7 @@ export default function DocumentEditorHeader({canManageLifecycle: boolean;canDelete: boolean;busy: boolean;- onBack: () => void;+ onBack?: () => void;onRetrySave: () => void;onFullWidthChange: (value: boolean) => void;onStickyToolbarChange: (value: boolean) => void;@@ -114,16 +114,18 @@ export default function DocumentEditorHeader({return (<header className="flex h-12 shrink-0 items-center gap-2 border-b bg-background/90 px-2.5 backdrop-blur-md md:px-4">- <Button- type="button"- variant="ghost"- size="icon-sm"- className="shrink-0 md:hidden"- aria-label={t('backToDocuments')}- onClick={onBack}- >- <ArrowLeft className="rtl:rotate-180" />- </Button>+ {onBack && (+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ className="shrink-0 md:hidden"+ aria-label={t('backToDocuments')}+ onClick={onBack}+ >+ <ArrowLeft className="rtl:rotate-180" />+ </Button>+ )}<DocumentBreadcrumbsprojectKey={projectKey}diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.ts b/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.tsindex 2a399c5a..21006376 100644--- a/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.ts+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.test.ts@@ -68,6 +68,7 @@ let previousDocument: PropertyDescriptor | undefined;let previousNavigator: PropertyDescriptor | undefined;let previousAnimationFrame: PropertyDescriptor | undefined;let previousNode: PropertyDescriptor | undefined;+let previousNodeFilter: PropertyDescriptor | undefined;beforeEach(() => {previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');@@ -75,6 +76,7 @@ beforeEach(() => {previousNavigator = Object.getOwnPropertyDescriptor(globalThis, 'navigator');previousAnimationFrame = Object.getOwnPropertyDescriptor(globalThis, 'requestAnimationFrame');previousNode = Object.getOwnPropertyDescriptor(globalThis, 'Node');+ previousNodeFilter = Object.getOwnPropertyDescriptor(globalThis, 'NodeFilter');dom = new JSDOM('<!doctype html><div id="one"></div><div id="two"></div>');dom.window.Range.prototype.getClientRects = () => [] as unknown as DOMRectList;dom.window.Range.prototype.getBoundingClientRect = () => new dom.window.DOMRect();@@ -83,6 +85,7 @@ beforeEach(() => {document: { configurable: true, value: dom.window.document },navigator: { configurable: true, value: dom.window.navigator },Node: { configurable: true, value: dom.window.Node },+ NodeFilter: { configurable: true, value: dom.window.NodeFilter },requestAnimationFrame: {configurable: true,value: (callback: FrameRequestCallback) => setTimeout(callback, 0),@@ -98,6 +101,7 @@ afterEach(() => {['navigator', previousNavigator],['requestAnimationFrame', previousAnimationFrame],['Node', previousNode],+ ['NodeFilter', previousNodeFilter],] as const) {if (descriptor) Object.defineProperty(globalThis, name, descriptor);else Reflect.deleteProperty(globalThis, name);@@ -371,6 +375,7 @@ describe('DocumentMarkdownEditor schema attrs', () => {heading: ['blockId', 'level', 'textAlign'],horizontalRule: ['blockId'],hardBreak: [],+ mention: ['username'],codeBlock: ['blockId', 'language'],image: ['alt', 'blockId', 'src', 'style', 'title', 'width'],table: ['blockId'],diff --git a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsxindex 11a5d17a..b7ad6dcd 100644--- a/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx+++ b/apps/web/src/features/documents/components/DocumentMarkdownEditor.tsx@@ -34,6 +34,9 @@ import { DocumentBlockId } from '../extensions/documentBlockId';import DocumentBlockMenu from './DocumentBlockMenu';import DocumentSelectionActions, { type DocumentSelection } from './DocumentSelectionActions';import { SlashCommand } from '@/lib/tiptap-slash-command';+import { Mention, type MentionOptions } from '@/lib/tiptap-mention';+import { useMentionCandidates, useMentionNames } from '@/hooks/useMentionCandidates';+import { useSession } from '@/lib/auth-client';const lowlight = createLowlight(common);const DOCUMENT_ASSET_PATH =@@ -80,7 +83,9 @@ type EditorLabels = {type EditorValue = { markdown: string; json: JSONContent };-export function documentEditorExtensions(labels: EditorLabels) {+// Without `mentions` the mention node is still known, so a page that holds one parses,+// but typing "@" offers nobody.+export function documentEditorExtensions(labels: EditorLabels, mentions?: MentionOptions) {return [DocumentBlockId,StarterKit.configure({@@ -108,6 +113,7 @@ export function documentEditorExtensions(labels: EditorLabels) {Color,Highlight.configure({ multicolor: true }),TextAlign.configure({ types: ['heading', 'paragraph'] }),+ mentions ? Mention.configure(mentions) : Mention,SlashCommand.configure({codeBlockLabel: labels.codeBlockLabel,tableLabel: labels.tableLabel,@@ -168,32 +174,51 @@ export default function DocumentMarkdownEditor({issueRefsRef.current = issueRefs;const openIssueRefRef = useRef(router.push);openIssueRefRef.current = (href: string) => router.push(href);+ const mentionCandidates = useMentionCandidates(+ projectKey && documentId ? { projectKey, on: 'document', documentId, place: 'text' } : null,+ );+ const mentionCandidatesRef = useRef(mentionCandidates);+ mentionCandidatesRef.current = mentionCandidates;+ const mentionNames = useMentionNames();+ const mentionNamesRef = useRef(mentionNames);+ mentionNamesRef.current = mentionNames;+ const { data: session } = useSession();+ const selfHandle = session?.user.username ?? '';+ const selfHandleRef = useRef(selfHandle);+ selfHandleRef.current = selfHandle;const editor = useEditor({immediatelyRender: false,editable,- extensions: documentEditorExtensions({- placeholder,- codeBlockLabel: t('codeBlock'),- tableLabel: t('table'),- blocks: {- paragraph: t('text'),- headings: [- t('heading1'),- t('heading2'),- t('heading3'),- t('heading4'),- t('heading5'),- t('heading6'),- ],- bulletList: t('bulletList'),- orderedList: t('numberedList'),- taskList: t('todoList'),- quote: t('quote'),- divider: t('divider'),+ extensions: documentEditorExtensions(+ {+ placeholder,+ codeBlockLabel: t('codeBlock'),+ tableLabel: t('table'),+ blocks: {+ paragraph: t('text'),+ headings: [+ t('heading1'),+ t('heading2'),+ t('heading3'),+ t('heading4'),+ t('heading5'),+ t('heading6'),+ ],+ bulletList: t('bulletList'),+ orderedList: t('numberedList'),+ taskList: t('todoList'),+ quote: t('quote'),+ divider: t('divider'),+ },+ image: onPickImage ? { label: t('uploadImage'), onPick: onPickImage } : undefined,+ },+ {+ items: () => mentionCandidatesRef.current,+ self: () => selfHandleRef.current,+ name: (handle) => mentionNamesRef.current.get(handle),},- image: onPickImage ? { label: t('uploadImage'), onPick: onPickImage } : undefined,- }).concat(+ ).concat(IssueRef.configure({refs: () => issueRefsRef.current.refs,open: (href) => openIssueRefRef.current(href),@@ -275,7 +300,7 @@ export default function DocumentMarkdownEditor({useEffect(() => {const frame = requestAnimationFrame(() => refreshDecorations(editor));return () => cancelAnimationFrame(frame);- }, [editor, issueRefList, issueRefs.resolve, editable, focused]);+ }, [editor, issueRefList, issueRefs.resolve, selfHandle, editable, focused]);useLayoutEffect(() => {syncDocumentEditorEditable(editor, editable);diff --git a/apps/web/src/features/documents/components/DocumentView.tsx b/apps/web/src/features/documents/components/DocumentView.tsxnew file mode 100644index 00000000..d3f5bfc2--- /dev/null+++ b/apps/web/src/features/documents/components/DocumentView.tsx@@ -0,0 +1,140 @@+'use client';++import { useRouter } from 'next/navigation';+import { useTranslations } from 'next-intl';+import { useShell } from '@/context/shellContext';+import { usePermissions } from '@/hooks/usePermissions';+import { useLiveRefresh } from '@/hooks/useLiveRefresh';+import { ApiError } from '@/lib/api/core/client';+import { qk } from '@/services/queryKeys';+import { documentPath } from '@/utils/paths';+import { revScope } from '@/utils/revScopes';+import {+ useCreateDocument,+ useDeleteDocument,+ useDocumentQuery,+ useDocumentsQuery,+ useDuplicateDocument,+} from '../services/documents.service';+import { documentAncestors } from '../utils/documentTree';+import DocumentEditor from './DocumentEditor';+import DocumentLoadError from './DocumentLoadError';+import DocumentLoadingState from './DocumentLoadingState';++// One document in its editor, loaded by id: the documents page shows it, and so does+// the inbox beside a notification about it. A page it creates or copies opens on the+// documents page.+export default function DocumentView({+ projectKey,+ documentId,+ defaultCommentsOpen,+ onBack,+ onCreated,+ onDeleted,+}: {+ projectKey: string;+ documentId: number;+ defaultCommentsOpen?: boolean;+ onBack?: () => void;+ onCreated?: () => void;+ onDeleted: () => void;+}) {+ const t = useTranslations('documents');+ const router = useRouter();+ const { project } = useShell();+ const { can, isOwner } = usePermissions();+ const documentQuery = useDocumentQuery(projectKey, documentId);+ const allDocumentsQuery = useDocumentsQuery(projectKey);+ const allArchivedDocumentsQuery = useDocumentsQuery(projectKey, '', true);+ const createDocument = useCreateDocument(projectKey);+ const deleteDocument = useDeleteDocument(projectKey);+ const duplicateDocument = useDuplicateDocument(projectKey);+ const canEdit = can('documents', 'edit');++ useLiveRefresh({+ scope: project ? revScope.documents(project.project.id) : null,+ targets: [+ qk.documentListsForProject(projectKey),+ qk.document(projectKey, documentId),+ qk.documentRevisions(projectKey, documentId),+ qk.documentAssets(projectKey, documentId),+ qk.documentComments(projectKey, documentId),+ qk.documentIssueLinks(projectKey, documentId),+ ],+ });++ const document = documentQuery.data;+ if (documentQuery.error instanceof ApiError && documentQuery.error.status === 404) {+ return (+ <main className="flex min-w-0 flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground">+ {t('pageNotFound')}+ </main>+ );+ }+ if (documentQuery.isError) {+ return <DocumentLoadError onRetry={() => void documentQuery.refetch()} />;+ }+ if (!project || !document) return <DocumentLoadingState />;++ const assignees = project.assignees;+ const authorNames = Object.fromEntries(assignees.map((a) => [a.userId, a.name]));+ const create = async (parentId: number | null, isPrivate: boolean) => {+ try {+ const created = await createDocument.mutateAsync({ parentId, isPrivate });+ onCreated?.();+ router.push(documentPath(projectKey, created.id));+ } catch {+ // Mutation errors are reported by the shared query client.+ }+ };+ const duplicate = async (title: string, version: number) => {+ try {+ const copy = await duplicateDocument.mutateAsync({+ documentId: document.id,+ version,+ title: t('copyTitle', { title: title.trim() || t('untitled') }),+ parentId: document.parentId,+ });+ router.push(documentPath(projectKey, copy.id));+ } catch {+ // Mutation errors are reported by the shared query client.+ }+ };++ return (+ <DocumentEditor+ key={document.id}+ projectKey={projectKey}+ projectName={project.project.name}+ document={document}+ ancestors={documentAncestors(document, [+ ...(allDocumentsQuery.data ?? []),+ ...(allArchivedDocumentsQuery.data ?? []),+ ])}+ documents={allDocumentsQuery.data ?? []}+ authorName={+ assignees.find((candidate) => candidate.userId === document.updatedByUserId)?.name ?? null+ }+ authorNames={authorNames}+ canEdit={canEdit}+ canReadWorkItems={can('work_items', 'read')}+ canLinkWorkItems={canEdit && can('work_items', 'edit')}+ isProjectOwner={isOwner}+ canCreate={can('documents', 'create')}+ canDelete={can('documents', 'delete')}+ defaultCommentsOpen={defaultCommentsOpen}+ onBack={onBack}+ onCreate={(parentId, isPrivate) => void create(parentId, isPrivate)}+ onDuplicate={duplicate}+ onDelete={async (version) => {+ await deleteDocument.mutateAsync({ documentId: document.id, version });+ onDeleted();+ }}+ onReload={async () => {+ const result = await documentQuery.refetch();+ if (result.isError) throw result.error;+ return result.data ?? null;+ }}+ />+ );+}diff --git a/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx b/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsxindex f9ae4bac..6627a00d 100644--- a/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx+++ b/apps/web/src/features/documents/hooks/useDocumentCollaboration.test.tsx@@ -16,6 +16,7 @@ const replacedGlobals = ['document','navigator','Node',+ 'NodeFilter','HTMLElement','requestAnimationFrame','IS_REACT_ACT_ENVIRONMENT',@@ -88,6 +89,7 @@ beforeEach(async () => {document: { configurable: true, value: dom.window.document },navigator: { configurable: true, value: dom.window.navigator },Node: { configurable: true, value: dom.window.Node },+ NodeFilter: { configurable: true, value: dom.window.NodeFilter },HTMLElement: { configurable: true, value: dom.window.HTMLElement },requestAnimationFrame: {configurable: true,diff --git a/apps/web/src/features/documents/hooks/useDocumentCommentMarks.test.tsx b/apps/web/src/features/documents/hooks/useDocumentCommentMarks.test.tsxnew file mode 100644index 00000000..873b86b6--- /dev/null+++ b/apps/web/src/features/documents/hooks/useDocumentCommentMarks.test.tsx@@ -0,0 +1,216 @@+import assert from 'node:assert/strict';+import { afterEach, beforeEach, describe, it } from 'node:test';+import { act } from 'react';+import type { Root } from 'react-dom/client';+import { Editor } from '@tiptap/core';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { JSDOM } from 'jsdom';+import type { DocumentComment, ProjectDocument } from '@/lib/api/endpoints/documents';+import { documentEditorExtensions } from '../components/DocumentMarkdownEditor';++type Hooks = typeof import('./useDocumentCollaboration') &+ typeof import('./useDocumentCommentMarks');++const replacedGlobals = [+ 'window',+ 'document',+ 'navigator',+ 'Node',+ 'NodeFilter',+ 'Element',+ 'HTMLElement',+ 'requestAnimationFrame',+ 'IS_REACT_ACT_ENVIRONMENT',+] as const;++const contentJson = {+ type: 'doc',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello world' }] }],+};++const comment: DocumentComment = {+ documentVersion: 2,+ id: '00000000-0000-4000-8000-000000000001',+ documentId: 42,+ parentId: null,+ authorId: 'user-2',+ authorName: 'Ann',+ body: 'Is this right?',+ quote: 'Hello',+ from: 1,+ to: 6,+ orphaned: false,+ resolvedAt: null,+ createdAt: '2026-09-01T00:00:00.000Z',+ updatedAt: '2026-09-01T00:00:00.000Z',+};++const projectDocument: ProjectDocument = {+ id: 42,+ projectId: 7,+ parentId: null,+ title: 'Runbook',+ content: 'Hello world',+ contentJson,+ icon: null,+ metadata: {},+ fullWidth: false,+ isPrivate: false,+ isLocked: false,+ isFavorite: false,+ archivedAt: null,+ position: 0,+ version: 2,+ ownerUserId: 'user-2',+ createdByUserId: 'user-2',+ updatedByUserId: 'user-2',+ createdAt: '2026-09-01T00:00:00.000Z',+ updatedAt: '2026-09-01T00:00:00.000Z',+};++let dom: JSDOM;+let root: Root;+let editor: Editor;+let queryClient: QueryClient;+let hooks: Hooks;+let originalFetch: typeof fetch;+let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;+let commentsServed: () => void;+let opened: number;++// Wired the way DocumentEditor wires the two hooks: a member who may edit joins the+// collaborative session, a reader does not.+function Probe({ editable }: { editable: boolean }) {+ const collaboration = hooks.useDocumentCollaboration({+ editor,+ projectKey: 'SEKTA',+ document: projectDocument,+ userId: 'user-1',+ enabled: editable,+ onSaved: () => undefined,+ });+ hooks.useDocumentCommentMarks(+ editor,+ 'SEKTA',+ 42,+ () => (opened += 1),+ editable ? collaboration.version : projectDocument.version,+ collaboration.ready,+ );+ return null;+}++const marks = () => editor.view.dom.querySelectorAll('.document-comment-mark');++async function open(editable: boolean) {+ await act(async () => {+ root.render(+ <QueryClientProvider client={queryClient}>+ <Probe editable={editable} />+ </QueryClientProvider>,+ );+ });+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 100));+ });+}++beforeEach(async () => {+ originalGlobalDescriptors = new Map(+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),+ );+ dom = new JSDOM('<!doctype html><div id="root"></div><div id="editor"></div>', {+ url: 'https://plan.example.test',+ });+ dom.window.__ITSAPLAN_ENV__ = {+ apiUrl: 'https://api.example.test',+ privacyUrl: '',+ termsUrl: '',+ };+ dom.window.Range.prototype.getClientRects = () => [] as unknown as DOMRectList;+ dom.window.Range.prototype.getBoundingClientRect = () => new dom.window.DOMRect();+ Object.defineProperties(globalThis, {+ window: { configurable: true, value: dom.window },+ document: { configurable: true, value: dom.window.document },+ navigator: { configurable: true, value: dom.window.navigator },+ Node: { configurable: true, value: dom.window.Node },+ NodeFilter: { configurable: true, value: dom.window.NodeFilter },+ Element: { configurable: true, value: dom.window.Element },+ HTMLElement: { configurable: true, value: dom.window.HTMLElement },+ requestAnimationFrame: {+ configurable: true,+ value: (callback: FrameRequestCallback) => setTimeout(callback, 0),+ },+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },+ });+ hooks = {+ ...(await import('./useDocumentCollaboration')),+ ...(await import('./useDocumentCommentMarks')),+ };+ originalFetch = globalThis.fetch;+ opened = 0;+ // The comments arrive before the session opens, the order a page load usually has.+ const served = new Promise<void>((resolve) => (commentsServed = resolve));+ globalThis.fetch = (async (input: RequestInfo | URL) => {+ const url = String(input);+ if (url.endsWith('/comments')) {+ setTimeout(commentsServed, 10);+ return Response.json([comment]);+ }+ if (url.endsWith('/session')) {+ await served;+ await new Promise((resolve) => setTimeout(resolve, 10));+ return Response.json({ documentId: 42, epoch: 'e1', version: 0, contentJson });+ }+ return Response.json({+ epoch: 'e1',+ version: 0,+ steps: [],+ hasMore: false,+ documentVersion: 2,+ });+ }) as typeof fetch;+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ editor = new Editor({+ element: document.querySelector('#editor') as HTMLElement,+ extensions: documentEditorExtensions({ placeholder: '', codeBlockLabel: '', tableLabel: '' }),+ content: contentJson,+ });+ const { createRoot } = await import('react-dom/client');+ root = createRoot(document.querySelector('#root')!);+});++afterEach(() => {+ globalThis.fetch = originalFetch;+ act(() => root.unmount());+ editor.destroy();+ queryClient.clear();+ dom.window.close();+ for (const [name, descriptor] of originalGlobalDescriptors) {+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);+ else Reflect.deleteProperty(globalThis, name);+ }+});++describe('useDocumentCommentMarks', () => {+ it('keeps the marks of the open threads once the collaborative session loads', async () => {+ await open(true);++ assert.equal(marks().length, 1);+ assert.equal(marks()[0].textContent, 'Hello');+ });++ it('marks the threads for a reader, and opens the comments from a mark', async () => {+ await open(false);+ assert.equal(marks().length, 1);++ const handled = editor.view.someProp('handleClick', (handleClick) =>+ handleClick(editor.view, 2, { target: marks()[0] } as unknown as MouseEvent),+ );++ assert.equal(handled, true);+ assert.equal(opened, 1);+ // The click scrolls to the thread on the next frame.+ await new Promise((resolve) => setTimeout(resolve, 10));+ });+});diff --git a/apps/web/src/features/documents/hooks/useDocumentCommentMarks.ts b/apps/web/src/features/documents/hooks/useDocumentCommentMarks.tsindex 77a8a742..cc7487e4 100644--- a/apps/web/src/features/documents/hooks/useDocumentCommentMarks.ts+++ b/apps/web/src/features/documents/hooks/useDocumentCommentMarks.ts@@ -9,12 +9,15 @@ import { listDocumentComments } from '@/lib/api/endpoints/documents';import { qk } from '@/services/queryKeys';const commentMarks = new PluginKey<DecorationSet>('documentCommentMarks');+// A collaborative session replaces the editor's content when it opens, which drops the+// marks, so they are drawn again once sessionReady turns true.export function useDocumentCommentMarks(editor: Editor | null,projectKey: string,documentId: number,onOpen: () => void,version: number,+ sessionReady: boolean,) {const open = useRef(onOpen);open.current = onOpen;@@ -85,5 +88,5 @@ export function useDocumentCommentMarks(editor.view.dispatch(editor.state.tr.setMeta(commentMarks, DecorationSet.create(editor.state.doc, decorations)),);- }, [data, editor, version]);+ }, [data, editor, version, sessionReady]);}diff --git a/apps/web/src/features/documents/utils/documentImport.test.ts b/apps/web/src/features/documents/utils/documentImport.test.tsindex ac1657a3..1a553c00 100644--- a/apps/web/src/features/documents/utils/documentImport.test.ts+++ b/apps/web/src/features/documents/utils/documentImport.test.ts@@ -4,7 +4,7 @@ import { JSDOM } from 'jsdom';import { importedMarkdownJson, markdownTitle } from './documentImport';describe('importedMarkdownJson', () => {- const globals = ['window', 'document', 'navigator', 'Node'] as const;+ const globals = ['window', 'document', 'navigator', 'Node', 'NodeFilter'] as const;const previous = globals.map((name) => Object.getOwnPropertyDescriptor(globalThis, name));before(() => {const { window } = new JSDOM('<!doctype html>');diff --git a/apps/web/src/features/inbox/components/InboxDetail.tsx b/apps/web/src/features/inbox/components/InboxDetail.tsxindex 4142d462..390fdb9d 100644--- a/apps/web/src/features/inbox/components/InboxDetail.tsx+++ b/apps/web/src/features/inbox/components/InboxDetail.tsx@@ -1,43 +1,55 @@'use client';import type { ProjectDetail } from '@/lib/api/endpoints/projects';+import type { Notification } from '@/lib/api/endpoints/notifications';+import DocumentView from '@/features/documents/components/DocumentView';import IssueDetailContent from '@/features/issue/components/detail/IssueDetailContent';import InboxDetailHeader from './InboxDetailHeader';-// The issue of the selected notification. On a narrow screen it takes the whole-// inbox and returns to the list through the back button; on a wide one it is the-// right pane next to the list.+// The issue or the document of the selected notification. On a narrow screen it takes+// the whole inbox and returns to the list through the back button; on a wide one it is+// the right pane next to the list. A mention in a document comment opens its comments.export default function InboxDetail({project,- issueId,- issueSeq,+ notification,isMobile,onBack,onDeleted,}: {project: ProjectDetail;- issueId: number;- issueSeq: number;+ notification: Notification;isMobile: boolean;onBack: () => void;onDeleted: () => void;}) {+ const projectKey = project.project.ref;return (<div className="flex min-h-0 flex-1 flex-col"><InboxDetailHeader- projectKey={project.project.ref}- issueSeq={issueSeq}+ projectKey={projectKey}+ notification={notification}isMobile={isMobile}onBack={onBack}/>- <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4 sm:px-6 sm:py-6 xl:px-10">- <IssueDetailContent- project={project}- issueId={issueId}- layout={isMobile ? 'panel' : 'split'}- onDeleted={onDeleted}- />- </div>+ {notification.documentId != null ? (+ <div className="flex min-h-0 flex-1">+ <DocumentView+ projectKey={projectKey}+ documentId={notification.documentId}+ defaultCommentsOpen={notification.documentCommentId != null}+ onDeleted={onDeleted}+ />+ </div>+ ) : (+ <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4 sm:px-6 sm:py-6 xl:px-10">+ <IssueDetailContent+ project={project}+ issueId={notification.issueId!}+ layout={isMobile ? 'panel' : 'split'}+ onDeleted={onDeleted}+ />+ </div>+ )}</div>);}diff --git a/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsx b/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsxindex 71709ed1..882ecb52 100644--- a/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsx+++ b/apps/web/src/features/inbox/components/InboxDetailHeader.test.tsx@@ -4,6 +4,7 @@ import { act } from 'react';import type { Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';import { JSDOM } from 'jsdom';+import documents from '../../../../messages/en/documents.json';import inbox from '../../../../messages/en/inbox.json';import issue from '../../../../messages/en/issue.json';import InboxDetailHeader from './InboxDetailHeader';@@ -20,13 +21,19 @@ let root: Root;let backCalls: number;let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;-function render({ projectKey = 'acme.TEST', issueSeq = 42, isMobile = false } = {}) {+function render({+ projectKey = 'acme.TEST',+ issueSeq = 42 as number | null,+ documentId = null as number | null,+ documentTitle = null as string | null,+ isMobile = false,+} = {}) {act(() =>root.render(- <NextIntlClientProvider locale="en" messages={{ inbox, issue }} timeZone="UTC">+ <NextIntlClientProvider locale="en" messages={{ documents, inbox, issue }} timeZone="UTC"><InboxDetailHeaderprojectKey={projectKey}- issueSeq={issueSeq}+ notification={{ issueSeq, documentId, documentTitle }}isMobile={isMobile}onBack={() => {backCalls += 1;@@ -103,4 +110,12 @@ describe('InboxDetailHeader', () => {render({ projectKey: '12.R&D', issueSeq: 9 });assert.equal(document.querySelector('a')?.getAttribute('href'), '/12/issue/R%26D-9');});++ it('names a document by its title and links to its page', () => {+ render({ issueSeq: null, documentId: 12, documentTitle: 'Plan' });+ assert.equal(document.querySelector('a')?.getAttribute('href'), '/acme/TEST/docs/12');+ assert.ok(document.querySelector('#root')?.textContent?.includes('Plan'));+ render({ issueSeq: null, documentId: 12, documentTitle: ' ' });+ assert.ok(document.querySelector('#root')?.textContent?.includes(documents.untitled));+ });});diff --git a/apps/web/src/features/inbox/components/InboxDetailHeader.tsx b/apps/web/src/features/inbox/components/InboxDetailHeader.tsxindex b391bfb5..956f6d24 100644--- a/apps/web/src/features/inbox/components/InboxDetailHeader.tsx+++ b/apps/web/src/features/inbox/components/InboxDetailHeader.tsx@@ -3,23 +3,35 @@import Link from 'next/link';import { ChevronLeft, Maximize2 } from 'lucide-react';import { useTranslations } from 'next-intl';+import type { Notification } from '@/lib/api/endpoints/notifications';import { Button } from '@/components/ui/button';-import { issuePath, splitProjectRef } from '@/utils/paths';+import { documentPath, issuePath, splitProjectRef } from '@/utils/paths';export default function InboxDetailHeader({projectKey,- issueSeq,+ notification: n,isMobile,onBack,}: {projectKey: string;- issueSeq: number;+ notification: Pick<Notification, 'issueSeq' | 'documentId' | 'documentTitle'>;isMobile: boolean;onBack: () => void;}) {const t = useTranslations('inbox');const tIssue = useTranslations('issue');+ const tDocuments = useTranslations('documents');const openLabel = tIssue('openAsPage');+ const { label, href } =+ n.documentId != null+ ? {+ label: n.documentTitle?.trim() || tDocuments('untitled'),+ href: documentPath(projectKey, n.documentId),+ }+ : {+ label: `${splitProjectRef(projectKey).key}-${n.issueSeq}`,+ href: issuePath(projectKey, n.issueSeq!),+ };return (<div className="flex h-11 shrink-0 items-center gap-2 border-b px-4 sm:px-6 xl:px-10">@@ -29,16 +41,14 @@ export default function InboxDetailHeader({{t('backToList')}</Button>)}- <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">- {splitProjectRef(projectKey).key}-{issueSeq}- </span>+ <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">{label}</span><ButtonasChildvariant="ghost"size="icon"className="size-9 text-muted-foreground hover:text-foreground sm:size-7">- <Link href={issuePath(projectKey, issueSeq)} title={openLabel} aria-label={openLabel}>+ <Link href={href} title={openLabel} aria-label={openLabel}><Maximize2 aria-hidden="true" /></Link></Button>diff --git a/apps/web/src/features/inbox/components/InboxListItem.tsx b/apps/web/src/features/inbox/components/InboxListItem.tsxindex bbe2e6ef..6953fe87 100644--- a/apps/web/src/features/inbox/components/InboxListItem.tsx+++ b/apps/web/src/features/inbox/components/InboxListItem.tsx@@ -62,10 +62,10 @@ const contextMenu = {SubContent: ContextMenuSubContent,};-// One inbox row: the issue identifier and title, the event line, elapsed time, an-// unread dot, and the actions menu (opened from the "…" button or a right-click).-// Read rows are dimmed. Clicking the row selects it; the menu handles its own-// clicks without selecting.+// One inbox row: the issue identifier and title or the document title, the event line,+// elapsed time, an unread dot, and the actions menu (opened from the "…" button or a+// right-click). Read rows are dimmed. Clicking the row selects it; the menu handles its+// own clicks without selecting.export default function InboxListItem({notification: n,selected,@@ -83,8 +83,15 @@ export default function InboxListItem({}) {const tCommon = useTranslations('common');const te = useTranslations('inbox.event');+ const tDocuments = useTranslations('documents');const [pickOpen, setPickOpen] = useState(false);const Icon = TYPE_ICON[n.type];+ const subject =+ n.documentId != null+ ? [n.documentIcon, n.documentTitle?.trim() || tDocuments('untitled')]+ .filter(Boolean)+ .join(' ')+ : `${n.projectKey}-${n.issueSeq} ${n.issueTitle}`;const who = n.actorName ?? te('someone');// The verb phrase for a notification, addressed to the reader ("you").const eventText =@@ -132,7 +139,7 @@ export default function InboxListItem({unread ? 'font-medium text-foreground' : 'text-muted-foreground',)}>- {n.projectKey}-{n.issueSeq} {n.issueTitle}+ {subject}</span><span className="mt-0.5 flex items-center gap-1 text-xs text-muted-foreground">{snoozed && <Clock className="size-3 shrink-0" />}diff --git a/apps/web/src/features/inbox/components/InboxView.tsx b/apps/web/src/features/inbox/components/InboxView.tsxindex cc933bba..d5d818cf 100644--- a/apps/web/src/features/inbox/components/InboxView.tsx+++ b/apps/web/src/features/inbox/components/InboxView.tsx@@ -91,10 +91,11 @@ export default function InboxView({ project }: { project: ProjectDetail }) {{selected ? (<InboxDetail- key={selected.issueId}+ // A document is keyed by the notification: whether its comments open is read+ // when it mounts.+ key={selected.documentId != null ? `notification-${selected.id}` : selected.issueId}project={project}- issueId={selected.issueId}- issueSeq={selected.issueSeq}+ notification={selected}isMobile={isMobile}onBack={() => setSelected(null)}onDeleted={() => setSelected(null)}diff --git a/apps/web/src/features/issue/components/create/NewIssueBody.tsx b/apps/web/src/features/issue/components/create/NewIssueBody.tsxindex 033850e4..7300993d 100644--- a/apps/web/src/features/issue/components/create/NewIssueBody.tsx+++ b/apps/web/src/features/issue/components/create/NewIssueBody.tsx@@ -2,6 +2,7 @@ import { type Editor } from '@tiptap/react';import type { CustomField } from '@/lib/api/endpoints/customFields';import type { Assignee } from '@/lib/api/endpoints/projects';import type { IssueFieldValueInput } from '@/lib/api/endpoints/issues';+import type { MentionSource } from '@/lib/api/endpoints/mentions';import { cn } from '@/lib/utils';import { type Embeddable } from '@/components/common/editor/attachmentEmbed';import { DESCRIPTION_SECTION, OTHER_SECTION, fieldSection } from '../../utils/bodySections';@@ -25,6 +26,7 @@ export default function NewIssueBody({onDescriptionReady,bodyDefs,fieldValues,+ projectKey,assignees,onFieldValue,onFieldEditorReady,@@ -40,6 +42,7 @@ export default function NewIssueBody({onDescriptionReady: (editor: Editor | null) => void;bodyDefs: CustomField[];fieldValues: Record<number, IssueFieldValueInput>;+ projectKey: string;assignees: Assignee[];onFieldValue: (id: number, patch: IssueFieldValueInput) => void;onFieldEditorReady: (id: number, editor: Editor | null) => void;@@ -48,6 +51,7 @@ export default function NewIssueBody({const t = useTranslations('issue.create');const tEditor = useTranslations('issue.editor');const tFields = useTranslations('issue.fields');+ const mentions: MentionSource = { projectKey, on: 'issue', place: 'text' };const markdownDefs = bodyDefs.filter((d) => d.fieldType === 'markdown');const pillDefs = bodyDefs.filter((d) => d.fieldType !== 'markdown');@@ -64,6 +68,7 @@ export default function NewIssueBody({onChange={onDescriptionChange}onReady={onDescriptionReady}uploadFile={uploadFile}+ mentions={mentions}/>);@@ -114,6 +119,7 @@ export default function NewIssueBody({onChange={(md) => onFieldValue(def.id, { value: md })}onReady={(editor) => onFieldEditorReady(def.id, editor)}uploadFile={uploadFile}+ mentions={mentions}/></div>))}diff --git a/apps/web/src/features/issue/components/create/NewIssueModal.tsx b/apps/web/src/features/issue/components/create/NewIssueModal.tsxindex 3edf4078..5dfb3723 100644--- a/apps/web/src/features/issue/components/create/NewIssueModal.tsx+++ b/apps/web/src/features/issue/components/create/NewIssueModal.tsx@@ -374,6 +374,7 @@ export default function NewIssueModal({onDescriptionReady={setDescEditor}bodyDefs={bodyDefs}fieldValues={fieldValues}+ projectKey={project.project.ref}assignees={project.assignees}onFieldValue={setFieldValue}onFieldEditorReady={(id, editor) => {diff --git a/apps/web/src/features/issue/components/detail/CommentComposer.test.tsx b/apps/web/src/features/issue/components/detail/CommentComposer.test.tsxindex ee9d5362..2209a2f0 100644--- a/apps/web/src/features/issue/components/detail/CommentComposer.test.tsx+++ b/apps/web/src/features/issue/components/detail/CommentComposer.test.tsx@@ -5,7 +5,6 @@ import type { Root } from 'react-dom/client';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { NextIntlClientProvider } from 'next-intl';import { JSDOM } from 'jsdom';-import type { Assignee } from '@/lib/api/endpoints/projects';import common from '../../../../../messages/en/common.json';import issue from '../../../../../messages/en/issue.json';@@ -20,21 +19,12 @@ const replacedGlobals = ['IS_REACT_ACT_ENVIRONMENT',] as const;-function assignee(over: Partial<Assignee>): Assignee {- return {- userId: over.username ?? 'u',- name: over.username ?? 'u',- email: '',- username: null,- image: null,- kind: 'member',- agentKind: null,- restrictedToUserId: null,- respondsToMention: null,- canReadWorkItems: true,- ...over,- };-}+// The candidates the api returns for a comment on the project's issues.+const candidates = [+ { userId: 'u-ana', name: 'Ana', username: 'ana', kind: 'member' },+ { userId: 'u-triage', name: 'Triage', username: 'triage', kind: 'agent' },+];+let requested: string[];let dom: JSDOM;let root: Root;@@ -42,6 +32,7 @@ let client: QueryClient;let originalGlobalDescriptors: Map<string, PropertyDescriptor | undefined>;beforeEach(async () => {+ requested = [];originalGlobalDescriptors = new Map(replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),);@@ -55,7 +46,14 @@ beforeEach(async () => {}}Object.defineProperties(globalThis, {- fetch: { configurable: true, value: async () => Response.json(null) },+ fetch: {+ configurable: true,+ value: async (input: RequestInfo | URL) => {+ const url = String(input);+ requested.push(url);+ return Response.json(url.includes('/mention-candidates') ? candidates : null);+ },+ },IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },});Object.defineProperty(window, '__ITSAPLAN_ENV__', {@@ -79,7 +77,7 @@ afterEach(async () => {});describe('CommentComposer', () => {- it('leaves an agent that does not answer mentions out of the @ menu', async () => {+ it('offers in the @ menu who the api says a comment on the project reaches', async () => {const { default: CommentComposer } = await import('./CommentComposer');await act(async () => {root.render(@@ -87,11 +85,7 @@ describe('CommentComposer', () => {<NextIntlClientProvider locale="en" messages={{ common, issue }} timeZone="UTC"><CommentComposerissueId={1}- assignees={[- assignee({ username: 'ana' }),- assignee({ username: 'triage', kind: 'agent', respondsToMention: true }),- assignee({ username: 'cleanup', kind: 'agent', respondsToMention: false }),- ]}+ projectKey="acme.TEST"authorName="Ana"authorImage={null}/>@@ -110,7 +104,10 @@ describe('CommentComposer', () => {textarea.dispatchEvent(new Event('input', { bubbles: true }));});- const offered = [...document.querySelectorAll('li button span')]+ assert.ok(+ requested.some((url) => url.endsWith('/projects/acme.TEST/mention-candidates?place=comment')),+ );+ const offered = [...document.querySelectorAll('button span')].map((span) => span.textContent!).filter((text) => text.startsWith('@'));assert.deepEqual(offered, ['@ana', '@triage']);diff --git a/apps/web/src/features/issue/components/detail/CommentComposer.tsx b/apps/web/src/features/issue/components/detail/CommentComposer.tsxindex e9233ca5..31fbb6f0 100644--- a/apps/web/src/features/issue/components/detail/CommentComposer.tsx+++ b/apps/web/src/features/issue/components/detail/CommentComposer.tsx@@ -1,41 +1,30 @@-import { useEffect, useMemo, useRef, useState } from 'react';-import { Bot, User } from 'lucide-react';-import type { Assignee } from '@/lib/api/endpoints/projects';+import { useEffect, useState } from 'react';import Avatar from '@/components/common/Avatar';+import MentionMenu from '@/components/common/inputs/MentionMenu';import { Button } from '@/components/ui/button';import { Textarea } from '@/components/ui/textarea';import { cn } from '@/lib/utils';-import { useSession } from '@/lib/auth-client';-import { offersMention } from '@/hooks/useMentionCandidates';+import { useMentionCandidates } from '@/hooks/useMentionCandidates';+import { useMentionMenu } from '@/hooks/useMentionMenu';import { useCreateComment, useUpdateComment } from '../../services/comments.service';import { useTranslations } from 'next-intl';// The comment box, for a new comment or for editing one: a plain markdown textarea-// with an @-mention menu. Typing "@" opens a menu of the project's members and-// agents; picking one writes their handle as @username into the body. That handle is-// what the backend resolves to notify a member or trigger an agent, and what the-// feed renders as a chip. Posts or saves as the current session user on the button-// or Cmd/Ctrl+Enter.+// with an @-mention menu (useMentionMenu). The feed renders a handle in the body as a+// chip. Posts or saves as the current session user on the button or Cmd/Ctrl+Enter.// What every composer needs to post, gathered once by the activity feed: the issue,-// who can be mentioned, and the author the avatar stands for.+// the project its "@" menu reads, and the author the avatar stands for.export interface ComposerContext {issueId: number;- assignees: Assignee[];+ projectKey: string;authorName: string;authorImage: string | null;}-// The active "@query" being typed: the text after the "@" and the body index of the-// "@" itself, so a pick can replace the whole "@query" span.-interface MentionQuery {- query: string;- anchor: number;-}-export default function CommentComposer({issueId,- assignees,+ projectKey,authorName,authorImage,replyToId,@@ -60,78 +49,23 @@ export default function CommentComposer({const createComment = useCreateComment();const updateComment = useUpdateComment();const [body, setBody] = useState(initialBody ?? '');- const [menu, setMenu] = useState<MentionQuery | null>(null);- const [active, setActive] = useState(0);- const [pendingCaret, setPendingCaret] = useState<number | null>(null);const [focused, setFocused] = useState(false);- const taRef = useRef<HTMLTextAreaElement | null>(null);- const { data: session } = useSession();- const currentUserId = session?.user.id ?? null;+ const candidates = useMentionCandidates({ projectKey, on: 'issue', place: 'comment' });+ const mention = useMentionMenu(body, setBody, candidates);const isReply = replyToId != null;const isEdit = commentId != null;const posting = (isEdit ? updateComment : createComment).isPending;const cmdKey = typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform) ? '⌘' : 'Ctrl';- // The same people and agents the markdown editors offer: an agent a mention would- // leave silent is not listed. An internal agent runs in the built-in runtime; an- // external agent is reached over its operator's webhook, which receives the comment.- const matches = useMemo(() => {- if (!menu) return [];- const q = menu.query.toLowerCase();- return assignees- .filter(- (a) =>- offersMention(a, currentUserId) &&- (a.name.toLowerCase().includes(q) || a.username!.toLowerCase().includes(q)),- )- .slice(0, 8);- }, [assignees, menu, currentUserId]);-// A reply box or an edit box is opened by a deliberate click, so it takes the// caret — at the end of the text being edited.useEffect(() => {- const ta = taRef.current;+ const ta = mention.ref.current;if (!ta || (!isReply && !isEdit)) return;ta.focus();if (isEdit) ta.setSelectionRange(ta.value.length, ta.value.length);- }, [isReply, isEdit]);-- // Restore the caret after a mention is inserted (the body change is async, so the- // caret has to be set once the new value has rendered).- useEffect(() => {- if (pendingCaret == null) return;- const ta = taRef.current;- if (ta) {- ta.focus();- ta.setSelectionRange(pendingCaret, pendingCaret);- }- setPendingCaret(null);- }, [pendingCaret]);-- // Opens the mention menu when the text right before the caret is an "@query"- // (an @ at a word boundary followed by non-space, non-@ characters).- function onChange(value: string, caret: number) {- setBody(value);- const before = value.slice(0, caret);- const m = before.match(/(?:^|\s)@([^\s@]*)$/);- if (m) {- setMenu({ query: m[1], anchor: caret - m[1].length - 1 });- setActive(0);- } else {- setMenu(null);- }- }-- function selectMention(a: Assignee) {- if (!menu || !a.username) return;- const handle = `@${a.username}`;- const caret = taRef.current?.selectionStart ?? body.length;- const next = `${body.slice(0, menu.anchor)}${handle} ${body.slice(caret)}`;- setBody(next);- setMenu(null);- setPendingCaret(menu.anchor + handle.length + 1);- }+ }, [isReply, isEdit, mention.ref]);async function post() {const next = body.trim();@@ -143,33 +77,12 @@ export default function CommentComposer({await createComment.mutateAsync({ issueId, input: { body: next, replyToId } });setBody('');}- setMenu(null);+ mention.close();onClose?.();}function onKeyDown(e: React.KeyboardEvent<HTMLTextAreaElement>) {- if (menu && matches.length > 0) {- if (e.key === 'ArrowDown') {- e.preventDefault();- setActive((i) => (i + 1) % matches.length);- return;- }- if (e.key === 'ArrowUp') {- e.preventDefault();- setActive((i) => (i - 1 + matches.length) % matches.length);- return;- }- if (e.key === 'Enter' || e.key === 'Tab') {- e.preventDefault();- selectMention(matches[Math.min(active, matches.length - 1)]);- return;- }- if (e.key === 'Escape') {- e.preventDefault();- setMenu(null);- return;- }- }+ if (mention.onKeyDown(e)) return;if (e.key === 'Escape' && onClose) {e.preventDefault();onClose();@@ -206,18 +119,16 @@ export default function CommentComposer({<div className="relative min-w-0 flex-1"><div className="overflow-hidden rounded-lg border bg-muted/20 shadow-xs transition-[border-color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/30"><Textarea- ref={taRef}+ ref={mention.ref}// `auto` once there is something to read, so a comment keeps the// script it was typed in. An empty box has nothing to read from, and// would fall back to left-to-right and strand the placeholder.dir={body ? 'auto' : undefined}value={body}- onChange={(e) =>- onChange(e.target.value, e.target.selectionStart ?? e.target.value.length)- }+ onChange={mention.onChange}onFocus={() => setFocused(true)}onBlur={() => {- setMenu(null);+ mention.close();setFocused(false);}}placeholder={placeholder}@@ -253,39 +164,12 @@ export default function CommentComposer({)}</div>- {menu && matches.length > 0 && (- <ul className="absolute top-full right-0 left-0 z-20 mt-1 max-h-64 overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md">- {matches.map((a, i) => (- <li key={a.userId}>- <button- type="button"- // Keep the textarea focused so the caret survives the click.- onMouseDown={(e) => {- e.preventDefault();- selectMention(a);- }}- onMouseEnter={() => setActive(i)}- className={`flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm ${- i === active ? 'bg-accent text-accent-foreground' : ''- }`}- >- {a.kind === 'agent' ? (- <Bot className="size-4 shrink-0" />- ) : (- <User className="size-4 shrink-0" />- )}- <span className="truncate">{a.name}</span>- <span className="flex-1 truncate text-xs text-muted-foreground">- @{a.username}- </span>- {a.kind === 'agent' && (- <span className="text-[10px] text-muted-foreground uppercase">agent</span>- )}- </button>- </li>- ))}- </ul>- )}+ <MentionMenu+ ref={mention.menuRef}+ items={mention.matches}+ onPick={mention.pick}+ className="absolute inset-x-0 top-full z-20 mt-1 w-auto"+ /></div></div></div>diff --git a/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx b/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsxindex d975c8df..ef9e65ab 100644--- a/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx+++ b/apps/web/src/features/issue/components/detail/IssueActivityFeed.tsx@@ -1,6 +1,5 @@import { useTranslations } from 'next-intl';import type { Column } from '@/lib/api/endpoints/columns';-import type { Assignee } from '@/lib/api/endpoints/projects';import { useSession } from '@/lib/auth-client';import { Tabs, TabsContent } from '@/components/ui/tabs';import { type ActivityFeedView, type ActivityTab } from '../../hooks/useActivityFeedView';@@ -20,14 +19,14 @@ const EMPTY_TEXT = {export default function IssueActivityFeed({issueId,- assignees,+ projectKey,columns,imageByUserId,view,canReadAgentRuns,}: {issueId: number;- assignees: Assignee[];+ projectKey: string;columns: Column[];imageByUserId: Map<string, string | null>;view: ActivityFeedView;@@ -40,7 +39,7 @@ export default function IssueActivityFeed({const user = session?.user ?? null;const composer: ComposerContext = {issueId,- assignees,+ projectKey,authorName: user?.name || user?.email || t('you'),authorImage: (user as { image?: string | null } | null)?.image ?? null,};diff --git a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsxindex 5c6b020a..29e4375d 100644--- a/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx+++ b/apps/web/src/features/issue/components/detail/IssueDetailContent.tsx@@ -2,6 +2,7 @@ import { type CSSProperties, useRef, useState } from 'react';import { Direction } from 'radix-ui';import type { ProjectDetail } from '@/lib/api/endpoints/projects';import type { IssueDetail as IssueDetailRow } from '@/lib/api/endpoints/issues';+import type { MentionSource } from '@/lib/api/endpoints/mentions';import { usePermissions } from '@/hooks/usePermissions';import { usePersistedWidth } from '@/hooks/usePersistedWidth';import { useProjectFeatures } from '@/hooks/useProjectFeatures';@@ -100,6 +101,11 @@ export default function IssueDetailContent({// never requested again. Counting the replacements remounts the editors, which// builds the element anew and lets the raw route revalidate it.const [replacements, setReplacements] = useState(0);+ const textMentions: MentionSource = {+ projectKey: project.project.ref,+ on: 'issue',+ place: 'text',+ };const feedRef = useRef<HTMLDivElement>(null);if (!issue) return <IssueDetailSkeleton />;@@ -154,6 +160,7 @@ export default function IssueDetailContent({onReady={setDescEditor}uploadFile={uploadFile}imageAttachments={imageAttachments}+ mentions={textMentions}onBlur={(md) => {if (md !== issue.description) patch({ description: md });}}@@ -173,6 +180,7 @@ export default function IssueDetailContent({imageAttachments={imageAttachments}onSetField={setField}readOnly={!canEdit}+ mentions={textMentions}/>))}</>@@ -274,7 +282,7 @@ export default function IssueDetailContent({<div ref={feedRef}><IssueActivityFeedissueId={issue.id}- assignees={project.assignees}+ projectKey={project.project.ref}columns={project.columns}imageByUserId={imageByUserId}view={effectiveActivityView}diff --git a/apps/web/src/features/issue/components/detail/IssueProperties.tsx b/apps/web/src/features/issue/components/detail/IssueProperties.tsxindex 6bc9b64a..7e7e4df8 100644--- a/apps/web/src/features/issue/components/detail/IssueProperties.tsx+++ b/apps/web/src/features/issue/components/detail/IssueProperties.tsx@@ -296,6 +296,7 @@ export default function IssueProperties({imageAttachments={imageAttachments}onSetField={onSetField}readOnly={readOnly}+ mentions={{ projectKey: project.project.ref, on: 'issue', place: 'text' }}/></div>);diff --git a/apps/web/src/features/issue/components/fields/IssueCustomFieldBody.tsx b/apps/web/src/features/issue/components/fields/IssueCustomFieldBody.tsxindex 03b7f660..ed984bf1 100644--- a/apps/web/src/features/issue/components/fields/IssueCustomFieldBody.tsx+++ b/apps/web/src/features/issue/components/fields/IssueCustomFieldBody.tsx@@ -1,6 +1,7 @@import type { CustomField } from '@/lib/api/endpoints/customFields';import type { Assignee } from '@/lib/api/endpoints/projects';import type { IssueFieldValue, IssueFieldValueInput } from '@/lib/api/endpoints/issues';+import type { MentionSource } from '@/lib/api/endpoints/mentions';import MarkdownEditor from '@/components/common/editor/MarkdownEditor';import { type Embeddable } from '@/components/common/editor/attachmentEmbed';import IssueCustomFieldControl from './IssueCustomFieldControl';@@ -19,6 +20,7 @@ export default function IssueCustomFieldBody({imageAttachments,onSetField,readOnly,+ mentions,}: {def: CustomField;current: IssueFieldValue | undefined;@@ -28,6 +30,7 @@ export default function IssueCustomFieldBody({imageAttachments?: Embeddable[];onSetField: (fieldId: number, value: IssueFieldValueInput) => void;readOnly?: boolean;+ mentions?: MentionSource;}) {const t = useTranslations('issue.fields');return (@@ -43,6 +46,7 @@ export default function IssueCustomFieldBody({editable={!readOnly}uploadFile={uploadFile}imageAttachments={imageAttachments}+ mentions={mentions}onBlur={(md) => {const next = md.trim() === '' ? null : md;if (next !== ((current?.value as string | null) ?? null))diff --git a/apps/web/src/features/settings/utils/notificationEvents.ts b/apps/web/src/features/settings/utils/notificationEvents.tsindex 1abf70bf..e27f8f98 100644--- a/apps/web/src/features/settings/utils/notificationEvents.ts+++ b/apps/web/src/features/settings/utils/notificationEvents.ts@@ -1,6 +1,6 @@import type { NotificationEventToggles } from '@/lib/api/endpoints/notificationSettings';-// The issue events a channel can send, matching the inbox notification types.+// The events a channel can send, matching the inbox notification types.// Shared by the email and telegram event sections; the label of an event is a// message under `settings.notifications.events`.export const NOTIFICATION_EVENTS: (keyof NotificationEventToggles)[] = [diff --git a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRunItem.tsx b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRunItem.tsxindex 8888da13..e119c035 100644--- a/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRunItem.tsx+++ b/apps/web/src/features/teams/components/ai-agents/TeamAiAgentRunItem.tsx@@ -11,6 +11,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltipimport TeamAiAgentRunStatus from './TeamAiAgentRunStatus';function runSubject(r: AgentRun, t: ReturnType<typeof useTranslations<'teams.agents'>>): string {+ if (r.documentId != null) {+ return [t('documentTask'), r.documentTitle?.trim()].filter(Boolean).join(' · ');+ }if (r.issueId == null) return r.trigger === 'manual' ? t('manualTask') : t('scheduledTask');if (!r.issueIdentifier) return `issue #${r.issueId}`;return `${r.issueIdentifier}${r.issueTitle ? ` · ${r.issueTitle}` : ''}`;diff --git a/apps/web/src/hooks/useMentionCandidates.test.ts b/apps/web/src/hooks/useMentionCandidates.test.tsdeleted file mode 100644index eaf47de9..00000000--- a/apps/web/src/hooks/useMentionCandidates.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import assert from 'node:assert/strict';-import { describe, it } from 'node:test';-import type { Assignee } from '@/lib/api/endpoints/projects';-import { mentionCandidatesFrom, offersMention } from './useMentionCandidates';--function assignee(over: Partial<Assignee>): Assignee {- return {- userId: over.username ?? 'u',- name: over.username ?? 'u',- email: '',- username: null,- image: null,- kind: 'member',- agentKind: null,- restrictedToUserId: null,- respondsToMention: null,- canReadWorkItems: true,- ...over,- };-}--describe('mentionCandidatesFrom', () => {- it('offers people and the agents a mention by this user would start', () => {- const offered = mentionCandidatesFrom(- [- assignee({ username: 'ana' }),- assignee({ username: 'refinar', kind: 'agent', respondsToMention: true }),- assignee({ username: 'consultas', kind: 'agent', respondsToMention: false }),- assignee({- username: 'mine',- kind: 'agent',- respondsToMention: true,- restrictedToUserId: 'me',- }),- assignee({- username: 'theirs',- kind: 'agent',- respondsToMention: true,- restrictedToUserId: 'someone-else',- }),- assignee({ username: null }),- ],- 'me',- );-- assert.deepEqual(- offered.map((c) => c.username),- ['ana', 'refinar', 'mine'],- );- });-});--// The comment box filters the project's assignees with this, as the editors do.-describe('offersMention', () => {- it('offers people with a handle and the agents that answer mentions', () => {- assert.equal(offersMention(assignee({ username: 'ana' }), 'me'), true);- assert.equal(- offersMention(- assignee({ username: 'refinar', kind: 'agent', respondsToMention: true }),- 'me',- ),- true,- );- assert.equal(- offersMention(- assignee({ username: 'higiene', kind: 'agent', respondsToMention: false }),- 'me',- ),- false,- );- assert.equal(offersMention(assignee({ username: null }), 'me'), false);- });-});diff --git a/apps/web/src/hooks/useMentionCandidates.ts b/apps/web/src/hooks/useMentionCandidates.tsindex 85588add..14aa983c 100644--- a/apps/web/src/hooks/useMentionCandidates.ts+++ b/apps/web/src/hooks/useMentionCandidates.ts@@ -1,37 +1,39 @@import { useContext, useMemo } from 'react';+import { useQuery } from '@tanstack/react-query';import { ShellCtx } from '@/context/shellContext';-import { useSession } from '@/lib/auth-client';-import type { Assignee } from '@/lib/api/endpoints/projects';-import { type MentionCandidate } from '@/lib/tiptap-mention';-import { isForeignAgent } from '@/utils/foreignAgent';+import {+ listMentionCandidates,+ type MentionCandidate,+ type MentionSource,+} from '@/lib/api/endpoints/mentions';+import { qk } from '@/services/queryKeys';-// An agent is offered only when a mention by this user would start a run: one that-// does not answer mentions, or works only for another member, would stay silent.-export function offersMention(a: Assignee, currentUserId: string | null): boolean {- if (!a.username) return false;- return a.kind !== 'agent' || (!!a.respondsToMention && !isForeignAgent(a, currentUserId));-}+const NONE: MentionCandidate[] = [];-export function mentionCandidatesFrom(- assignees: Assignee[],- currentUserId: string | null,-): MentionCandidate[] {- return assignees.flatMap((a) =>- offersMention(a, currentUserId)- ? [{ userId: a.userId, name: a.name, username: a.username!, kind: a.kind }]- : [],- );+// Who the "@" menu offers where a mention is written. The api builds the list with the+// rule that then decides whom the mention reaches, so the menu offers nobody a mention+// would leave silent. Empty without a source, for a text no mention reaches, and while+// the list loads.+export function useMentionCandidates(source: MentionSource | null): MentionCandidate[] {+ const query = useQuery({+ queryKey: source ? qk.mentionCandidates(source) : ['mentionCandidates'],+ queryFn: () => listMentionCandidates(source!),+ enabled: source != null,+ });+ return query.data ?? NONE;}-// Who the editors offer after an "@": the active project's members and agents that-// have a handle. Read from the payload the Shell loads, so an editor needs no props-// for it. Empty outside a project (the public share pages), where nothing is written.-export function useMentionCandidates(): MentionCandidate[] {+// The name behind each handle of the active project, lowercased, for the tooltip of a+// mention chip. Empty outside a project (the public share pages).+export function useMentionNames(): Map<string, string> {const assignees = useContext(ShellCtx)?.project?.assignees;- const { data: session } = useSession();- const currentUserId = session?.user.id ?? null;return useMemo(- () => mentionCandidatesFrom(assignees ?? [], currentUserId),- [assignees, currentUserId],+ () =>+ new Map(+ (assignees ?? []).flatMap((a) =>+ a.username ? [[a.username.toLowerCase(), a.name] as const] : [],+ ),+ ),+ [assignees],);}diff --git a/apps/web/src/hooks/useMentionMenu.ts b/apps/web/src/hooks/useMentionMenu.tsnew file mode 100644index 00000000..3e562eb0--- /dev/null+++ b/apps/web/src/hooks/useMentionMenu.ts@@ -0,0 +1,73 @@+import { useEffect, useMemo, useRef, useState, type ChangeEvent, type KeyboardEvent } from 'react';+import type { MentionMenuHandle } from '@/components/common/inputs/MentionMenu';+import type { MentionCandidate } from '@/lib/api/endpoints/mentions';+import { matchMentionCandidates } from '@/utils/mentions';++// The "@" menu of a plain textarea. Typing "@" opens a list of who can be mentioned;+// picking one writes their handle as @username into the text, which is what the api+// resolves to notify a member or start an agent's run. The caller passes `ref` and the+// handlers to its textarea, and renders MentionMenu with `menuRef`, `matches` and+// `pick` in a container that does not clip it.++// The "@query" being typed: the text after the "@", and the index of the "@" itself,+// so a pick replaces the whole span.+interface MentionQuery {+ query: string;+ anchor: number;+}++export function useMentionMenu(+ value: string,+ onValueChange: (value: string) => void,+ candidates: MentionCandidate[],+) {+ const ref = useRef<HTMLTextAreaElement | null>(null);+ const menuRef = useRef<MentionMenuHandle | null>(null);+ const [menu, setMenu] = useState<MentionQuery | null>(null);+ const [pendingCaret, setPendingCaret] = useState<number | null>(null);++ const matches = useMemo(+ () => (menu ? matchMentionCandidates(candidates, menu.query) : []),+ [candidates, menu],+ );++ // The value changes asynchronously, so the caret is set once the new text renders.+ useEffect(() => {+ if (pendingCaret == null) return;+ const textarea = ref.current;+ if (textarea) {+ textarea.focus();+ textarea.setSelectionRange(pendingCaret, pendingCaret);+ }+ setPendingCaret(null);+ }, [pendingCaret]);++ // An "@" at a word boundary followed by characters that are neither a space nor an "@".+ const onChange = (event: ChangeEvent<HTMLTextAreaElement>) => {+ const next = event.target.value;+ const caret = event.target.selectionStart ?? next.length;+ onValueChange(next);+ const typed = next.slice(0, caret).match(/(?:^|\s)@([^\s@]*)$/);+ setMenu(typed ? { query: typed[1], anchor: caret - typed[1].length - 1 } : null);+ };++ const pick = (candidate: MentionCandidate) => {+ if (!menu) return;+ const handle = `@${candidate.username}`;+ const caret = ref.current?.selectionStart ?? value.length;+ onValueChange(`${value.slice(0, menu.anchor)}${handle} ${value.slice(caret)}`);+ setMenu(null);+ setPendingCaret(menu.anchor + handle.length + 1);+ };++ // True when the key belonged to the open menu, so the caller does nothing with it.+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (matches.length === 0) return false;+ if (event.key === 'Escape') setMenu(null);+ else if (!menuRef.current?.onKeyDown(event)) return false;+ event.preventDefault();+ return true;+ };++ return { ref, menuRef, matches, onChange, onKeyDown, pick, close: () => setMenu(null) };+}diff --git a/apps/web/src/lib/api/endpoints/agents.ts b/apps/web/src/lib/api/endpoints/agents.tsindex 38ff0cf6..d1dc5929 100644--- a/apps/web/src/lib/api/endpoints/agents.ts+++ b/apps/web/src/lib/api/endpoints/agents.ts@@ -101,6 +101,10 @@ export interface AgentRun {issueId: number | null;issueIdentifier: string | null;issueTitle: string | null;+ // A run started by a mention in a document comment. The title is null for a document+ // that is private now.+ documentId: number | null;+ documentTitle: string | null;prompt: string;attempts: number;lastError: string | null;diff --git a/apps/web/src/lib/api/endpoints/mentions.ts b/apps/web/src/lib/api/endpoints/mentions.tsnew file mode 100644index 00000000..a8161ea9--- /dev/null+++ b/apps/web/src/lib/api/endpoints/mentions.ts@@ -0,0 +1,22 @@+import { request } from '@/lib/api/core/client';++// Who can be mentioned: a project member or an agent, addressed by their handle.+export interface MentionCandidate {+ userId: string;+ name: string;+ username: string;+ kind: 'member' | 'agent';+}++export type MentionPlace = 'comment' | 'text';++// Where a mention is written, which decides whom it reaches.+export type MentionSource =+ | { projectKey: string; on: 'issue'; place: MentionPlace }+ | { projectKey: string; on: 'document'; documentId: number; place: MentionPlace };++export function listMentionCandidates(source: MentionSource): Promise<MentionCandidate[]> {+ const project = `/projects/${encodeURIComponent(source.projectKey)}`;+ const base = source.on === 'document' ? `${project}/documents/${source.documentId}` : project;+ return request<MentionCandidate[]>(`${base}/mention-candidates?place=${source.place}`);+}diff --git a/apps/web/src/lib/api/endpoints/notifications.ts b/apps/web/src/lib/api/endpoints/notifications.tsindex 3876fdad..13ac32cd 100644--- a/apps/web/src/lib/api/endpoints/notifications.ts+++ b/apps/web/src/lib/api/endpoints/notifications.ts@@ -1,10 +1,12 @@import { request } from '@/lib/api/core/client';import type { StateType } from '@/lib/api/endpoints/columns';-// Inbox notifications. Each row is enriched with the issue and project it points at-// so the list renders without extra calls.+// Inbox notifications. Each row is enriched with the issue or the document and the+// project it points at, so the list renders without extra calls.export type NotificationType = 'assigned' | 'mentioned' | 'commented' | 'state_changed';+// The issue fields are set on an issue's notification, the document fields on a+// document's.export interface Notification {id: number;type: NotificationType;@@ -13,10 +15,15 @@ export interface Notification {readAt: string | null;snoozedUntil: string | null;createdAt: string;- issueId: number;- issueSeq: number;- issueTitle: string;- issueStateType: StateType;+ issueId: number | null;+ issueSeq: number | null;+ issueTitle: string | null;+ issueStateType: StateType | null;+ documentId: number | null;+ documentTitle: string | null;+ documentIcon: string | null;+ // Set when the mention is in a comment on the document.+ documentCommentId: string | null;projectId: number;projectKey: string;projectName: string;diff --git a/apps/web/src/lib/tiptap-mention.ts b/apps/web/src/lib/tiptap-mention.tsindex 0fc64bee..21e8ffc5 100644--- a/apps/web/src/lib/tiptap-mention.ts+++ b/apps/web/src/lib/tiptap-mention.ts@@ -5,24 +5,18 @@ import { Decoration, DecorationSet } from '@tiptap/pm/view';import { ReactRenderer } from '@tiptap/react';import { REFRESH_DECORATIONS } from '@/components/common/editor/refreshDecorations';import Suggestion from '@tiptap/suggestion';-import EditorMentionMenu, {- type MentionMenuRef,-} from '@/components/common/editor/EditorMentionMenu';--// Who can be mentioned: a project member or an agent, addressed by their handle.-export interface MentionCandidate {- userId: string;- name: string;- username: string;- kind: 'member' | 'agent';-}+import MentionMenu, { type MentionMenuHandle } from '@/components/common/inputs/MentionMenu';+import type { MentionCandidate } from '@/lib/api/endpoints/mentions';+import { matchMentionCandidates } from '@/utils/mentions';export type MentionOptions = {- // Read on every keystroke rather than captured once, so a roster that arrives- // after the editor was built is still offered.+ // Who the "@" menu offers. Read on every keystroke rather than captured once, so a+ // list that arrives after the editor was built is still offered.items: () => MentionCandidate[];// The viewer's own handle. A mention of it is painted in a second colour.self: () => string;+ // The name behind a lowercased handle, shown as the chip's tooltip.+ name: (handle: string) => string | undefined;};// Its own key, so this suggestion plugin and the slash command's can both run in@@ -95,7 +89,7 @@ export const Mention = Node.create<MentionOptions>({selectable: false,addOptions() {- return { items: () => [], self: () => '' };+ return { items: () => [], self: () => '', name: () => undefined };},addAttributes() {@@ -116,9 +110,7 @@ export const Mention = Node.create<MentionOptions>({const username = String(node.attrs.username);// The name behind the handle is only known while the roster is loaded, so it is// a tooltip rather than part of the chip.- const name = this.options- .items()- .find((c) => c.username.toLowerCase() === username.toLowerCase())?.name;+ const name = this.options.name(username.toLowerCase());return ['span',mergeAttributes(HTMLAttributes, { class: 'mention', ...(name ? { title: name } : {}) }),@@ -165,15 +157,7 @@ export const Mention = Node.create<MentionOptions>({// Radix makes everything outside an open overlay inert, so the list mounts// inside the dialog the editor sits in.container: '[data-slot="dialog-content"]',- items: ({ query }) => {- const needle = query.toLowerCase();- return items()- .filter(- (c) =>- c.name.toLowerCase().includes(needle) || c.username.toLowerCase().includes(needle),- )- .slice(0, 8);- },+ items: ({ query }) => matchMentionCandidates(items(), query),command: ({ editor, range, props }) => {editor.chain()@@ -185,20 +169,21 @@ export const Mention = Node.create<MentionOptions>({.run();},render: () => {- let component: ReactRenderer<MentionMenuRef> | null = null;+ let component: ReactRenderer<MentionMenuHandle> | null = null;let unmount: (() => void) | null = null;return {onStart: (props) => {- component = new ReactRenderer(EditorMentionMenu, {- props,+ component = new ReactRenderer(MentionMenu, {+ props: { items: props.items, onPick: props.command },editor: props.editor,className: 'z-50',});unmount = props.mount(component.element);},- onUpdate: (props) => component?.updateProps(props),- onKeyDown: (props) => component?.ref?.onKeyDown(props) ?? false,+ onUpdate: (props) =>+ component?.updateProps({ items: props.items, onPick: props.command }),+ onKeyDown: (props) => component?.ref?.onKeyDown(props.event) ?? false,onExit: () => {unmount?.();component?.destroy();diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.tsindex ac77b837..e03393df 100644--- a/apps/web/src/services/queryKeys.ts+++ b/apps/web/src/services/queryKeys.ts@@ -1,4 +1,5 @@import type { FeedFilter, FeedOrder } from '@/lib/api/endpoints/activity';+import type { MentionSource } from '@/lib/api/endpoints/mentions';const scimKey = (workspaceId: number | null) =>workspaceId === null ? (['god', 'scim'] as const) : (['workspace', workspaceId, 'scim'] as const);@@ -108,6 +109,19 @@ export const qk = {['documents', projectKey, 'document', documentId, 'assets'] as const,documentIssueLinks: (projectKey: string, documentId: number) =>['documents', projectKey, 'document', documentId, 'issues'] as const,+ // Who the "@" menu offers where a mention is written. A document's sits under the+ // document, so what refreshes the document refreshes it too.+ mentionCandidates: (source: MentionSource) =>+ source.on === 'document'+ ? ([+ 'documents',+ source.projectKey,+ 'document',+ source.documentId,+ 'mentions',+ source.place,+ ] as const)+ : (['mentionCandidates', source.projectKey, source.place] as const),issueDocumentLinks: (projectKey: string, issueId: number) =>['documents', projectKey, 'issue', issueId] as const,initiativeDocumentLinks: (projectKey: string, initiativeId: number) =>diff --git a/apps/web/src/utils/mentions.ts b/apps/web/src/utils/mentions.tsnew file mode 100644index 00000000..e304d1ef--- /dev/null+++ b/apps/web/src/utils/mentions.ts@@ -0,0 +1,15 @@+import type { MentionCandidate } from '@/lib/api/endpoints/mentions';++// The candidates whose name or handle holds the text typed after "@", as many as the+// menu shows.+export function matchMentionCandidates(+ candidates: MentionCandidate[],+ query: string,+): MentionCandidate[] {+ const needle = query.toLowerCase();+ return candidates+ .filter(+ (c) => c.name.toLowerCase().includes(needle) || c.username.toLowerCase().includes(needle),+ )+ .slice(0, 8);+}diff --git a/packages/db/drizzle/0157_document_mentions.sql b/packages/db/drizzle/0157_document_mentions.sqlnew file mode 100644index 00000000..20754c7c--- /dev/null+++ b/packages/db/drizzle/0157_document_mentions.sql@@ -0,0 +1,10 @@+ALTER TABLE "notification" ALTER COLUMN "issue_id" DROP NOT NULL;--> statement-breakpoint+ALTER TABLE "agent_run" ADD COLUMN "document_id" integer;--> statement-breakpoint+ALTER TABLE "agent_run" ADD COLUMN "source_document_comment_id" uuid;--> statement-breakpoint+ALTER TABLE "notification" ADD COLUMN "document_id" integer;--> statement-breakpoint+ALTER TABLE "notification" ADD COLUMN "document_comment_id" uuid;--> statement-breakpoint+ALTER TABLE "agent_run" ADD CONSTRAINT "agent_run_document_id_project_document_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."project_document"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "agent_run" ADD CONSTRAINT "agent_run_source_document_comment_id_document_comment_id_fk" FOREIGN KEY ("source_document_comment_id") REFERENCES "public"."document_comment"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "notification" ADD CONSTRAINT "notification_document_id_project_document_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."project_document"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "notification" ADD CONSTRAINT "notification_document_comment_id_document_comment_id_fk" FOREIGN KEY ("document_comment_id") REFERENCES "public"."document_comment"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint+ALTER TABLE "notification" ADD CONSTRAINT "notification_target_check" CHECK (("notification"."issue_id" IS NULL) <> ("notification"."document_id" IS NULL));\ No newline at end of filediff --git a/packages/db/drizzle/meta/0157_snapshot.json b/packages/db/drizzle/meta/0157_snapshot.jsonnew file mode 100644index 00000000..f78e2a41--- /dev/null+++ b/packages/db/drizzle/meta/0157_snapshot.json@@ -0,0 +1,12598 @@+{+ "id": "62c1cef3-df16-4a57-a0ad-a01c9e74a71a",+ "prevId": "f64b2913-b5dc-47e2-bddd-d1877e675b5c",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "config_id": {+ "name": "config_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'default'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 100+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_configId_idx": {+ "name": "apikey_configId_idx",+ "columns": [+ {+ "expression": "config_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_referenceId_idx": {+ "name": "apikey_referenceId_idx",+ "columns": [+ {+ "expression": "reference_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.jwks": {+ "name": "jwks",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "public_key": {+ "name": "public_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "private_key": {+ "name": "private_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "alg": {+ "name": "alg",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "crv": {+ "name": "crv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_access_token": {+ "name": "oauth_access_token",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "authorization_code_id": {+ "name": "authorization_code_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resources": {+ "name": "resources",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "requested_user_info_claims": {+ "name": "requested_user_info_claims",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_id": {+ "name": "refresh_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "revoked": {+ "name": "revoked",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "confirmation": {+ "name": "confirmation",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "oauthAccessToken_clientId_idx": {+ "name": "oauthAccessToken_clientId_idx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthAccessToken_sessionId_idx": {+ "name": "oauthAccessToken_sessionId_idx",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthAccessToken_userId_idx": {+ "name": "oauthAccessToken_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthAccessToken_authorizationCodeId_idx": {+ "name": "oauthAccessToken_authorizationCodeId_idx",+ "columns": [+ {+ "expression": "authorization_code_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthAccessToken_refreshId_idx": {+ "name": "oauthAccessToken_refreshId_idx",+ "columns": [+ {+ "expression": "refresh_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_access_token_client_id_oauth_client_client_id_fk": {+ "name": "oauth_access_token_client_id_oauth_client_client_id_fk",+ "tableFrom": "oauth_access_token",+ "tableTo": "oauth_client",+ "columnsFrom": [+ "client_id"+ ],+ "columnsTo": [+ "client_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_access_token_session_id_session_id_fk": {+ "name": "oauth_access_token_session_id_session_id_fk",+ "tableFrom": "oauth_access_token",+ "tableTo": "session",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "oauth_access_token_user_id_user_id_fk": {+ "name": "oauth_access_token_user_id_user_id_fk",+ "tableFrom": "oauth_access_token",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_access_token_refresh_id_oauth_refresh_token_id_fk": {+ "name": "oauth_access_token_refresh_id_oauth_refresh_token_id_fk",+ "tableFrom": "oauth_access_token",+ "tableTo": "oauth_refresh_token",+ "columnsFrom": [+ "refresh_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauth_access_token_token_unique": {+ "name": "oauth_access_token_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_client": {+ "name": "oauth_client",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "client_secret": {+ "name": "client_secret",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "client_discovery_id": {+ "name": "client_discovery_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "skip_consent": {+ "name": "skip_consent",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "enable_end_session": {+ "name": "enable_end_session",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "subject_type": {+ "name": "subject_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "client_credentials_scopes": {+ "name": "client_credentials_scopes",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false,+ "default": "'{}'"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "uri": {+ "name": "uri",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "contacts": {+ "name": "contacts",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "tos": {+ "name": "tos",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "policy": {+ "name": "policy",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "software_id": {+ "name": "software_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "software_version": {+ "name": "software_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "software_statement": {+ "name": "software_statement",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "redirect_uris": {+ "name": "redirect_uris",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true+ },+ "post_logout_redirect_uris": {+ "name": "post_logout_redirect_uris",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "backchannel_logout_uri": {+ "name": "backchannel_logout_uri",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "backchannel_logout_session_required": {+ "name": "backchannel_logout_session_required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "token_endpoint_auth_method": {+ "name": "token_endpoint_auth_method",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "application_type": {+ "name": "application_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "jwks": {+ "name": "jwks",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "jwks_uri": {+ "name": "jwks_uri",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "grant_types": {+ "name": "grant_types",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "response_types": {+ "name": "response_types",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "require_pkce": {+ "name": "require_pkce",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "dpop_bound_access_tokens": {+ "name": "dpop_bound_access_tokens",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "oauthClient_userId_idx": {+ "name": "oauthClient_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_client_user_id_user_id_fk": {+ "name": "oauth_client_user_id_user_id_fk",+ "tableFrom": "oauth_client",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauth_client_client_id_unique": {+ "name": "oauth_client_client_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "client_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_client_assertion": {+ "name": "oauth_client_assertion",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_client_resource": {+ "name": "oauth_client_resource",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "oauthClientResource_clientId_resourceId_uidx": {+ "name": "oauthClientResource_clientId_resourceId_uidx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthClientResource_clientId_idx": {+ "name": "oauthClientResource_clientId_idx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthClientResource_resourceId_idx": {+ "name": "oauthClientResource_resourceId_idx",+ "columns": [+ {+ "expression": "resource_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_client_resource_client_id_oauth_client_client_id_fk": {+ "name": "oauth_client_resource_client_id_oauth_client_client_id_fk",+ "tableFrom": "oauth_client_resource",+ "tableTo": "oauth_client",+ "columnsFrom": [+ "client_id"+ ],+ "columnsTo": [+ "client_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_client_resource_resource_id_oauth_resource_identifier_fk": {+ "name": "oauth_client_resource_resource_id_oauth_resource_identifier_fk",+ "tableFrom": "oauth_client_resource",+ "tableTo": "oauth_resource",+ "columnsFrom": [+ "resource_id"+ ],+ "columnsTo": [+ "identifier"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_consent": {+ "name": "oauth_consent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resources": {+ "name": "resources",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "requested_user_info_claims": {+ "name": "requested_user_info_claims",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "oauthConsent_clientId_idx": {+ "name": "oauthConsent_clientId_idx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthConsent_userId_idx": {+ "name": "oauthConsent_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_consent_client_id_oauth_client_client_id_fk": {+ "name": "oauth_consent_client_id_oauth_client_client_id_fk",+ "tableFrom": "oauth_consent",+ "tableTo": "oauth_client",+ "columnsFrom": [+ "client_id"+ ],+ "columnsTo": [+ "client_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_consent_user_id_user_id_fk": {+ "name": "oauth_consent_user_id_user_id_fk",+ "tableFrom": "oauth_consent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_refresh_token": {+ "name": "oauth_refresh_token",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reference_id": {+ "name": "reference_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "authorization_code_id": {+ "name": "authorization_code_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resources": {+ "name": "resources",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "requested_user_info_claims": {+ "name": "requested_user_info_claims",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "revoked": {+ "name": "revoked",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "rotated_at": {+ "name": "rotated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "rotation_replay_response": {+ "name": "rotation_replay_response",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "rotation_replay_expires_at": {+ "name": "rotation_replay_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "auth_time": {+ "name": "auth_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "confirmation": {+ "name": "confirmation",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "scopes": {+ "name": "scopes",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "oauthRefreshToken_clientId_idx": {+ "name": "oauthRefreshToken_clientId_idx",+ "columns": [+ {+ "expression": "client_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthRefreshToken_sessionId_idx": {+ "name": "oauthRefreshToken_sessionId_idx",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthRefreshToken_userId_idx": {+ "name": "oauthRefreshToken_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "oauthRefreshToken_authorizationCodeId_idx": {+ "name": "oauthRefreshToken_authorizationCodeId_idx",+ "columns": [+ {+ "expression": "authorization_code_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "oauth_refresh_token_client_id_oauth_client_client_id_fk": {+ "name": "oauth_refresh_token_client_id_oauth_client_client_id_fk",+ "tableFrom": "oauth_refresh_token",+ "tableTo": "oauth_client",+ "columnsFrom": [+ "client_id"+ ],+ "columnsTo": [+ "client_id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "oauth_refresh_token_session_id_session_id_fk": {+ "name": "oauth_refresh_token_session_id_session_id_fk",+ "tableFrom": "oauth_refresh_token",+ "tableTo": "session",+ "columnsFrom": [+ "session_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "oauth_refresh_token_user_id_user_id_fk": {+ "name": "oauth_refresh_token_user_id_user_id_fk",+ "tableFrom": "oauth_refresh_token",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauth_refresh_token_token_unique": {+ "name": "oauth_refresh_token_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.oauth_resource": {+ "name": "oauth_resource",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token_ttl": {+ "name": "access_token_ttl",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_ttl": {+ "name": "refresh_token_ttl",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "signing_algorithm": {+ "name": "signing_algorithm",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "signing_key_id": {+ "name": "signing_key_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "allowed_scopes": {+ "name": "allowed_scopes",+ "type": "text[]",+ "primaryKey": false,+ "notNull": false+ },+ "custom_claims": {+ "name": "custom_claims",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "dpop_bound_access_tokens_required": {+ "name": "dpop_bound_access_tokens_required",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "disabled": {+ "name": "disabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "policy_version": {+ "name": "policy_version",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "oauth_resource_identifier_unique": {+ "name": "oauth_resource_identifier_unique",+ "nullsNotDistinct": false,+ "columns": [+ "identifier"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.passkey": {+ "name": "passkey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "public_key": {+ "name": "public_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_id": {+ "name": "credential_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "counter": {+ "name": "counter",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "device_type": {+ "name": "device_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "backed_up": {+ "name": "backed_up",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "transports": {+ "name": "transports",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "aaguid": {+ "name": "aaguid",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "passkey_userId_idx": {+ "name": "passkey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "passkey_credentialID_idx": {+ "name": "passkey_credentialID_idx",+ "columns": [+ {+ "expression": "credential_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "passkey_user_id_user_id_fk": {+ "name": "passkey_user_id_user_id_fk",+ "tableFrom": "passkey",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "display_username": {+ "name": "display_username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'user'"+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": [+ "email"+ ]+ },+ "user_username_unique": {+ "name": "user_username_unique",+ "nullsNotDistinct": false,+ "columns": [+ "username"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_event": {+ "name": "agent_chat_event",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "bigserial",+ "primaryKey": true,+ "notNull": true+ },+ "message_id": {+ "name": "message_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_event_message_idx": {+ "name": "agent_chat_event_message_idx",+ "columns": [+ {+ "expression": "message_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_event_message_id_agent_chat_message_id_fk": {+ "name": "agent_chat_event_message_id_agent_chat_message_id_fk",+ "tableFrom": "agent_chat_event",+ "tableTo": "agent_chat_message",+ "columnsFrom": [+ "message_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_favorite": {+ "name": "agent_chat_favorite",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_chat_favorite_user_id_user_id_fk": {+ "name": "agent_chat_favorite_user_id_user_id_fk",+ "tableFrom": "agent_chat_favorite",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_favorite_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_favorite_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_favorite",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_chat_favorite_user_id_thread_id_pk": {+ "name": "agent_chat_favorite_user_id_thread_id_pk",+ "columns": [+ "user_id",+ "thread_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_message": {+ "name": "agent_chat_message",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_message_thread_idx": {+ "name": "agent_chat_message_thread_idx",+ "columns": [+ {+ "expression": "thread_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_chat_message_due_idx": {+ "name": "agent_chat_message_due_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_message_thread_id_agent_chat_thread_id_fk": {+ "name": "agent_chat_message_thread_id_agent_chat_thread_id_fk",+ "tableFrom": "agent_chat_message",+ "tableTo": "agent_chat_thread",+ "columnsFrom": [+ "thread_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_message_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_message_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_message",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_chat_message_role_check": {+ "name": "agent_chat_message_role_check",+ "value": "\"agent_chat_message\".\"role\" IN ('user', 'assistant')"+ },+ "agent_chat_message_status_check": {+ "name": "agent_chat_message_status_check",+ "value": "\"agent_chat_message\".\"status\" IN ('pending', 'streaming', 'success', 'failed', 'canceled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_chat_thread": {+ "name": "agent_chat_thread",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cli_session_id": {+ "name": "cli_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_thread_agent_user_idx": {+ "name": "agent_chat_thread_agent_user_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_thread_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_thread_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_thread",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_chat_thread_user_id_user_id_fk": {+ "name": "agent_chat_thread_user_id_user_id_fk",+ "tableFrom": "agent_chat_thread",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_chat_usage": {+ "name": "agent_chat_usage",+ "schema": "",+ "columns": {+ "thread_id": {+ "name": "thread_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_chat_usage_agent_idx": {+ "name": "agent_chat_usage_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_chat_usage_agent_id_ai_agent_id_fk": {+ "name": "agent_chat_usage_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_chat_usage",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_field_trigger": {+ "name": "agent_field_trigger",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "delay_sec": {+ "name": "delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 120+ }+ },+ "indexes": {+ "agent_field_trigger_field_idx": {+ "name": "agent_field_trigger_field_idx",+ "columns": [+ {+ "expression": "field_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_field_trigger_agent_id_ai_agent_id_fk": {+ "name": "agent_field_trigger_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_field_trigger",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_field_trigger_field_id_custom_field_id_fk": {+ "name": "agent_field_trigger_field_id_custom_field_id_fk",+ "tableFrom": "agent_field_trigger",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_field_trigger_agent_id_field_id_pk": {+ "name": "agent_field_trigger_agent_id_field_id_pk",+ "columns": [+ "agent_id",+ "field_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_field_trigger_delay_check": {+ "name": "agent_field_trigger_delay_check",+ "value": "\"agent_field_trigger\".\"delay_sec\" >= 0 AND \"agent_field_trigger\".\"delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_run": {+ "name": "agent_run",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "schedule_id": {+ "name": "schedule_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "trigger": {+ "name": "trigger",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'delegation'"+ },+ "scheduled_for": {+ "name": "scheduled_for",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "source_activity_id": {+ "name": "source_activity_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "source_document_comment_id": {+ "name": "source_document_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "output": {+ "name": "output",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "execution_started_at": {+ "name": "execution_started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_run_schedule_fire_uq": {+ "name": "agent_run_schedule_fire_uq",+ "columns": [+ {+ "expression": "schedule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "scheduled_for",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_due_idx": {+ "name": "agent_run_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_schedule_idx": {+ "name": "agent_run_schedule_idx",+ "columns": [+ {+ "expression": "schedule_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_run_project_idx": {+ "name": "agent_run_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_run_agent_id_ai_agent_id_fk": {+ "name": "agent_run_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_project_id_project_id_fk": {+ "name": "agent_run_project_id_project_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_issue_id_issue_id_fk": {+ "name": "agent_run_issue_id_issue_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_schedule_id_agent_schedule_id_fk": {+ "name": "agent_run_schedule_id_agent_schedule_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "agent_schedule",+ "columnsFrom": [+ "schedule_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_source_activity_id_issue_activity_id_fk": {+ "name": "agent_run_source_activity_id_issue_activity_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "source_activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "agent_run_document_id_project_document_id_fk": {+ "name": "agent_run_document_id_project_document_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_run_source_document_comment_id_document_comment_id_fk": {+ "name": "agent_run_source_document_comment_id_document_comment_id_fk",+ "tableFrom": "agent_run",+ "tableTo": "document_comment",+ "columnsFrom": [+ "source_document_comment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "agent_run_status_check": {+ "name": "agent_run_status_check",+ "value": "\"agent_run\".\"status\" IN ('pending', 'success', 'failed', 'canceled')"+ },+ "agent_run_trigger_check": {+ "name": "agent_run_trigger_check",+ "value": "\"agent_run\".\"trigger\" IN ('mention', 'delegation', 'field', 'schedule', 'manual', 'status', 'event')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_run_trace": {+ "name": "agent_run_trace",+ "schema": "",+ "columns": {+ "run_id": {+ "name": "run_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "attempt": {+ "name": "attempt",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "events": {+ "name": "events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "next_offset": {+ "name": "next_offset",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "truncated": {+ "name": "truncated",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "agent_run_trace_run_id_agent_run_id_fk": {+ "name": "agent_run_trace_run_id_agent_run_id_fk",+ "tableFrom": "agent_run_trace",+ "tableTo": "agent_run",+ "columnsFrom": [+ "run_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_run_trace_run_id_attempt_pk": {+ "name": "agent_run_trace_run_id_attempt_pk",+ "columns": [+ "run_id",+ "attempt"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_schedule": {+ "name": "agent_schedule",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "prompt": {+ "name": "prompt",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'cron'"+ },+ "cron": {+ "name": "cron",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "next_run_at": {+ "name": "next_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "delay_sec": {+ "name": "delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "options": {+ "name": "options",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "last_run_at": {+ "name": "last_run_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_schedule_due_idx": {+ "name": "agent_schedule_due_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_run_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_schedule_agent_idx": {+ "name": "agent_schedule_agent_idx",+ "columns": [+ {+ "expression": "agent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_schedule_project_idx": {+ "name": "agent_schedule_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_schedule_column_idx": {+ "name": "agent_schedule_column_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_schedule_agent_id_ai_agent_id_fk": {+ "name": "agent_schedule_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_schedule",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_schedule_project_id_project_id_fk": {+ "name": "agent_schedule_project_id_project_id_fk",+ "tableFrom": "agent_schedule",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_schedule_column_id_project_column_id_fk": {+ "name": "agent_schedule_column_id_project_column_id_fk",+ "tableFrom": "agent_schedule",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_schedule_project_id_agent_id_name_unique": {+ "name": "agent_schedule_project_id_agent_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "agent_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "agent_schedule_status_check": {+ "name": "agent_schedule_status_check",+ "value": "\"agent_schedule\".\"status\" IN ('active', 'paused')"+ },+ "agent_schedule_type_check": {+ "name": "agent_schedule_type_check",+ "value": "(\"agent_schedule\".\"type\" = 'cron' AND \"agent_schedule\".\"cron\" IS NOT NULL AND \"agent_schedule\".\"next_run_at\" IS NOT NULL AND \"agent_schedule\".\"column_id\" IS NULL)\n OR (\"agent_schedule\".\"type\" = 'status' AND \"agent_schedule\".\"column_id\" IS NOT NULL AND \"agent_schedule\".\"cron\" IS NULL AND \"agent_schedule\".\"next_run_at\" IS NULL)\n OR (\"agent_schedule\".\"type\" NOT IN ('cron', 'status') AND \"agent_schedule\".\"cron\" IS NULL AND \"agent_schedule\".\"next_run_at\" IS NULL AND \"agent_schedule\".\"column_id\" IS NULL)"+ },+ "agent_schedule_delay_check": {+ "name": "agent_schedule_delay_check",+ "value": "\"agent_schedule\".\"delay_sec\" >= 0 AND \"agent_schedule\".\"delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_skill": {+ "name": "agent_skill",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_url": {+ "name": "source_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_prefix": {+ "name": "s3_prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "files": {+ "name": "files",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_skill_team_idx": {+ "name": "agent_skill_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_skill_team_id_team_id_fk": {+ "name": "agent_skill_team_id_team_id_fk",+ "tableFrom": "agent_skill",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_skill_team_id_name_unique": {+ "name": "agent_skill_team_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "agent_skill_source_check": {+ "name": "agent_skill_source_check",+ "value": "\"agent_skill\".\"source\" IN ('upload', 'inline', 'github')"+ }+ },+ "isRLSEnabled": false+ },+ "public.agent_skill_link": {+ "name": "agent_skill_link",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "skill_id": {+ "name": "skill_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_skill_link_skill_idx": {+ "name": "agent_skill_link_skill_idx",+ "columns": [+ {+ "expression": "skill_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_skill_link_agent_id_ai_agent_id_fk": {+ "name": "agent_skill_link_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_skill_link",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_skill_link_skill_id_agent_skill_id_fk": {+ "name": "agent_skill_link_skill_id_agent_skill_id_fk",+ "tableFrom": "agent_skill_link",+ "tableTo": "agent_skill",+ "columnsFrom": [+ "skill_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_skill_link_agent_id_skill_id_pk": {+ "name": "agent_skill_link_agent_id_skill_id_pk",+ "columns": [+ "agent_id",+ "skill_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_tool": {+ "name": "agent_tool",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "tool_key": {+ "name": "tool_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "credential_id": {+ "name": "credential_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "agent_tool_team_tool_keyless_uq": {+ "name": "agent_tool_team_tool_keyless_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "tool_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"agent_tool\".\"credential_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_tool_team_idx": {+ "name": "agent_tool_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "agent_tool_credential_idx": {+ "name": "agent_tool_credential_idx",+ "columns": [+ {+ "expression": "credential_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_tool_team_id_team_id_fk": {+ "name": "agent_tool_team_id_team_id_fk",+ "tableFrom": "agent_tool",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_tool_credential_id_integration_credential_id_fk": {+ "name": "agent_tool_credential_id_integration_credential_id_fk",+ "tableFrom": "agent_tool",+ "tableTo": "integration_credential",+ "columnsFrom": [+ "credential_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "agent_tool_team_id_tool_key_credential_id_unique": {+ "name": "agent_tool_team_id_tool_key_credential_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "tool_key",+ "credential_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.agent_tool_link": {+ "name": "agent_tool_link",+ "schema": "",+ "columns": {+ "agent_id": {+ "name": "agent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "agent_tool_id": {+ "name": "agent_tool_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "agent_tool_link_tool_idx": {+ "name": "agent_tool_link_tool_idx",+ "columns": [+ {+ "expression": "agent_tool_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "agent_tool_link_agent_id_ai_agent_id_fk": {+ "name": "agent_tool_link_agent_id_ai_agent_id_fk",+ "tableFrom": "agent_tool_link",+ "tableTo": "ai_agent",+ "columnsFrom": [+ "agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "agent_tool_link_agent_tool_id_agent_tool_id_fk": {+ "name": "agent_tool_link_agent_tool_id_agent_tool_id_fk",+ "tableFrom": "agent_tool_link",+ "tableTo": "agent_tool",+ "columnsFrom": [+ "agent_tool_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "agent_tool_link_agent_id_agent_tool_id_pk": {+ "name": "agent_tool_link_agent_id_agent_tool_id_pk",+ "columns": [+ "agent_id",+ "agent_tool_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.ai_agent": {+ "name": "ai_agent",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "model_credential_id": {+ "name": "model_credential_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "instructions": {+ "name": "instructions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "tools": {+ "name": "tools",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "temperature": {+ "name": "temperature",+ "type": "double precision",+ "primaryKey": false,+ "notNull": false+ },+ "reasoning_effort": {+ "name": "reasoning_effort",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "max_steps": {+ "name": "max_steps",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "run_timeout_sec": {+ "name": "run_timeout_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_on_mention": {+ "name": "trigger_on_mention",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "trigger_on_assign": {+ "name": "trigger_on_assign",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "delegation_delay_sec": {+ "name": "delegation_delay_sec",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 120+ },+ "api_key_ciphertext": {+ "name": "api_key_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_iv": {+ "name": "api_key_iv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "api_key_auth_tag": {+ "name": "api_key_auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "memory_enabled": {+ "name": "memory_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "memory_last_messages": {+ "name": "memory_last_messages",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runner_scope": {+ "name": "runner_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'team'"+ },+ "last_seen_at": {+ "name": "last_seen_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "invocation_url": {+ "name": "invocation_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "invocation_secret_ciphertext": {+ "name": "invocation_secret_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "invocation_secret_iv": {+ "name": "invocation_secret_iv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "invocation_secret_auth_tag": {+ "name": "invocation_secret_auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_agent_team_username_uq": {+ "name": "ai_agent_team_username_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(\"username\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_agent_team_idx": {+ "name": "ai_agent_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_agent_team_id_team_id_fk": {+ "name": "ai_agent_team_id_team_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_agent_user_id_user_id_fk": {+ "name": "ai_agent_user_id_user_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_agent_model_credential_id_integration_credential_id_fk": {+ "name": "ai_agent_model_credential_id_integration_credential_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "integration_credential",+ "columnsFrom": [+ "model_credential_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "ai_agent_owner_user_id_user_id_fk": {+ "name": "ai_agent_owner_user_id_user_id_fk",+ "tableFrom": "ai_agent",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "ai_agent_user_id_unique": {+ "name": "ai_agent_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "ai_agent_kind_check": {+ "name": "ai_agent_kind_check",+ "value": "\"ai_agent\".\"kind\" IN ('external', 'internal')"+ },+ "ai_agent_runner_scope_check": {+ "name": "ai_agent_runner_scope_check",+ "value": "\"ai_agent\".\"runner_scope\" IN ('owner', 'team')"+ },+ "ai_agent_reasoning_effort_check": {+ "name": "ai_agent_reasoning_effort_check",+ "value": "\"ai_agent\".\"reasoning_effort\" IN ('low', 'medium', 'high')"+ },+ "ai_agent_delegation_delay_check": {+ "name": "ai_agent_delegation_delay_check",+ "value": "\"ai_agent\".\"delegation_delay_sec\" >= 0 AND \"ai_agent\".\"delegation_delay_sec\" <= 86400"+ }+ },+ "isRLSEnabled": false+ },+ "public.app_secret": {+ "name": "app_secret",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.app_setting": {+ "name": "app_setting",+ "schema": "",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.chat_attachment": {+ "name": "chat_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "uploaded_by_user_id": {+ "name": "uploaded_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_attachment_project_idx": {+ "name": "chat_attachment_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_attachment_project_id_project_id_fk": {+ "name": "chat_attachment_project_id_project_id_fk",+ "tableFrom": "chat_attachment",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_attachment_uploaded_by_user_id_user_id_fk": {+ "name": "chat_attachment_uploaded_by_user_id_user_id_fk",+ "tableFrom": "chat_attachment",+ "tableTo": "user",+ "columnsFrom": [+ "uploaded_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_attachment_public_id_unique": {+ "name": "chat_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.custom_field": {+ "name": "custom_field",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_type_id": {+ "name": "issue_type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "field_type": {+ "name": "field_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "member_scope": {+ "name": "member_scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "show_in_body": {+ "name": "show_in_body",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "custom_field_project_id_project_id_fk": {+ "name": "custom_field_project_id_project_id_fk",+ "tableFrom": "custom_field",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "custom_field_issue_type_id_issue_type_id_fk": {+ "name": "custom_field_issue_type_id_issue_type_id_fk",+ "tableFrom": "custom_field",+ "tableTo": "issue_type",+ "columnsFrom": [+ "issue_type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "custom_field_field_type_check": {+ "name": "custom_field_field_type_check",+ "value": "\"custom_field\".\"field_type\" IN ('text', 'markdown', 'url', 'number', 'boolean', 'date', 'datetime', 'datetime_range', 'select', 'multi_select', 'member')"+ },+ "custom_field_member_scope_check": {+ "name": "custom_field_member_scope_check",+ "value": "(\"custom_field\".\"field_type\" = 'member') = (\"custom_field\".\"member_scope\" IS NOT NULL) AND (\"custom_field\".\"member_scope\" IS NULL OR \"custom_field\".\"member_scope\" IN ('all', 'humans', 'agents'))"+ }+ },+ "isRLSEnabled": false+ },+ "public.custom_field_option": {+ "name": "custom_field_option",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {},+ "foreignKeys": {+ "custom_field_option_field_id_custom_field_id_fk": {+ "name": "custom_field_option_field_id_custom_field_id_fk",+ "tableFrom": "custom_field_option",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "custom_field_option_field_id_value_unique": {+ "name": "custom_field_option_field_id_value_unique",+ "nullsNotDistinct": false,+ "columns": [+ "field_id",+ "value"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.cycle": {+ "name": "cycle",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "goal": {+ "name": "goal",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "end_date": {+ "name": "end_date",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "completed_at": {+ "name": "completed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "cycle_project_idx": {+ "name": "cycle_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "start_date",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "cycle_project_id_project_id_fk": {+ "name": "cycle_project_id_project_id_fk",+ "tableFrom": "cycle",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "cycle_dates_check": {+ "name": "cycle_dates_check",+ "value": "\"cycle\".\"end_date\" >= \"cycle\".\"start_date\""+ }+ },+ "isRLSEnabled": false+ },+ "public.document_asset": {+ "name": "document_asset",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "uploaded_by_user_id": {+ "name": "uploaded_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_asset_document_idx": {+ "name": "document_asset_document_idx",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "document_asset_document_id_project_document_id_fk": {+ "name": "document_asset_document_id_project_document_id_fk",+ "tableFrom": "document_asset",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "document_asset_uploaded_by_user_id_user_id_fk": {+ "name": "document_asset_uploaded_by_user_id_user_id_fk",+ "tableFrom": "document_asset",+ "tableTo": "user",+ "columnsFrom": [+ "uploaded_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "document_asset_public_id_unique": {+ "name": "document_asset_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_collaboration": {+ "name": "document_collaboration",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "epoch": {+ "name": "epoch",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "content_json": {+ "name": "content_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "document_collaboration_document_id_project_document_id_fk": {+ "name": "document_collaboration_document_id_project_document_id_fk",+ "tableFrom": "document_collaboration",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_comment": {+ "name": "document_comment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_id": {+ "name": "author_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "quote": {+ "name": "quote",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "selection_from": {+ "name": "selection_from",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "selection_to": {+ "name": "selection_to",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "orphaned": {+ "name": "orphaned",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "document_comment_document_idx": {+ "name": "document_comment_document_idx",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "document_comment_document_id_project_document_id_fk": {+ "name": "document_comment_document_id_project_document_id_fk",+ "tableFrom": "document_comment",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "document_comment_parent_id_document_comment_id_fk": {+ "name": "document_comment_parent_id_document_comment_id_fk",+ "tableFrom": "document_comment",+ "tableTo": "document_comment",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "document_comment_author_id_user_id_fk": {+ "name": "document_comment_author_id_user_id_fk",+ "tableFrom": "document_comment",+ "tableTo": "user",+ "columnsFrom": [+ "author_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.document_step": {+ "name": "document_step",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "client_id": {+ "name": "client_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "step": {+ "name": "step",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "document_step_document_id_project_document_id_fk": {+ "name": "document_step_document_id_project_document_id_fk",+ "tableFrom": "document_step",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "document_step_document_id_version_pk": {+ "name": "document_step_document_id_version_pk",+ "columns": [+ "document_id",+ "version"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.git_managed_repository": {+ "name": "git_managed_repository",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "full_name": {+ "name": "full_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "web_url": {+ "name": "web_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "webhook_external_id": {+ "name": "webhook_external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'connected'"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "git_managed_repository_project_connection_idx": {+ "name": "git_managed_repository_project_connection_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "connection_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "git_managed_repository_project_id_project_id_fk": {+ "name": "git_managed_repository_project_id_project_id_fk",+ "tableFrom": "git_managed_repository",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "git_managed_repository_connection_id_git_provider_connection_id_fk": {+ "name": "git_managed_repository_connection_id_git_provider_connection_id_fk",+ "tableFrom": "git_managed_repository",+ "tableTo": "git_provider_connection",+ "columnsFrom": [+ "connection_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "git_managed_repository_project_connection_external_unique": {+ "name": "git_managed_repository_project_connection_external_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "connection_id",+ "external_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.git_provider_connection": {+ "name": "git_provider_connection",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "base_url": {+ "name": "base_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "account_login": {+ "name": "account_login",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "git_provider_connection_team_idx": {+ "name": "git_provider_connection_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "git_provider_connection_team_id_team_id_fk": {+ "name": "git_provider_connection_team_id_team_id_fk",+ "tableFrom": "git_provider_connection",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.import_job": {+ "name": "import_job",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "phase": {+ "name": "phase",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'discover'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "cursor": {+ "name": "cursor",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "credential_ciphertext": {+ "name": "credential_ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_iv": {+ "name": "credential_iv",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "credential_auth_tag": {+ "name": "credential_auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "import_job_project_idx": {+ "name": "import_job_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_job_due_idx": {+ "name": "import_job_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"import_job\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_job_project_id_project_id_fk": {+ "name": "import_job_project_id_project_id_fk",+ "tableFrom": "import_job",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "import_job_created_by_user_id_user_id_fk": {+ "name": "import_job_created_by_user_id_user_id_fk",+ "tableFrom": "import_job",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "import_job_source_check": {+ "name": "import_job_source_check",+ "value": "\"import_job\".\"source\" IN ('plane', 'linear')"+ },+ "import_job_phase_check": {+ "name": "import_job_phase_check",+ "value": "\"import_job\".\"phase\" IN ('discover', 'create', 'link', 'rewrite', 'attachments', 'done')"+ },+ "import_job_status_check": {+ "name": "import_job_status_check",+ "value": "\"import_job\".\"status\" IN ('pending', 'running', 'paused', 'completed', 'failed')"+ }+ },+ "isRLSEnabled": false+ },+ "public.import_record": {+ "name": "import_record",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "import_job_id": {+ "name": "import_job_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "source_entity_type": {+ "name": "source_entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_id": {+ "name": "source_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_display_id": {+ "name": "source_display_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "local_entity_type": {+ "name": "local_entity_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "local_id": {+ "name": "local_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "import_record_job_source_uq": {+ "name": "import_record_job_source_uq",+ "columns": [+ {+ "expression": "import_job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_record_job_local_idx": {+ "name": "import_record_job_local_idx",+ "columns": [+ {+ "expression": "import_job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "local_entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "local_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "import_record_job_display_idx": {+ "name": "import_record_job_display_idx",+ "columns": [+ {+ "expression": "import_job_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_entity_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_display_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "import_record_import_job_id_import_job_id_fk": {+ "name": "import_record_import_job_id_import_job_id_fk",+ "tableFrom": "import_record",+ "tableTo": "import_job",+ "columnsFrom": [+ "import_job_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "import_record_source_entity_type_check": {+ "name": "import_record_source_entity_type_check",+ "value": "\"import_record\".\"source_entity_type\" IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')"+ },+ "import_record_local_entity_type_check": {+ "name": "import_record_local_entity_type_check",+ "value": "\"import_record\".\"local_entity_type\" IS NULL OR \"import_record\".\"local_entity_type\" IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')"+ }+ },+ "isRLSEnabled": false+ },+ "public.initiative": {+ "name": "initiative",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'planned'"+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "target_date": {+ "name": "target_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "initiative_project_idx": {+ "name": "initiative_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "initiative_project_id_project_id_fk": {+ "name": "initiative_project_id_project_id_fk",+ "tableFrom": "initiative",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "initiative_owner_user_id_user_id_fk": {+ "name": "initiative_owner_user_id_user_id_fk",+ "tableFrom": "initiative",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "initiative_status_check": {+ "name": "initiative_status_check",+ "value": "\"initiative\".\"status\" IN ('proposed', 'planned', 'active', 'completed', 'canceled')"+ }+ },+ "isRLSEnabled": false+ },+ "public.initiative_attachment": {+ "name": "initiative_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "initiative_attachment_initiative_idx": {+ "name": "initiative_attachment_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "initiative_attachment_initiative_id_initiative_id_fk": {+ "name": "initiative_attachment_initiative_id_initiative_id_fk",+ "tableFrom": "initiative_attachment",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "initiative_attachment_public_id_unique": {+ "name": "initiative_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.initiative_label": {+ "name": "initiative_label",+ "schema": "",+ "columns": {+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "initiative_label_initiative_id_initiative_id_fk": {+ "name": "initiative_label_initiative_id_initiative_id_fk",+ "tableFrom": "initiative_label",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "initiative_label_label_id_label_id_fk": {+ "name": "initiative_label_label_id_label_id_fk",+ "tableFrom": "initiative_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "initiative_label_initiative_id_label_id_pk": {+ "name": "initiative_label_initiative_id_label_id_pk",+ "columns": [+ "initiative_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration_credential": {+ "name": "integration_credential",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "integration_key": {+ "name": "integration_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "label": {+ "name": "label",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_credential_team_idx": {+ "name": "integration_credential_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_credential_team_id_team_id_fk": {+ "name": "integration_credential_team_id_team_id_fk",+ "tableFrom": "integration_credential",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue": {+ "name": "issue",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "sequence_number": {+ "name": "sequence_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "type_id": {+ "name": "type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "cycle_id": {+ "name": "cycle_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "delegate_user_id": {+ "name": "delegate_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "estimate_points": {+ "name": "estimate_points",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false+ },+ "estimate_minutes": {+ "name": "estimate_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "start_date": {+ "name": "start_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "due_date": {+ "name": "due_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "share_token": {+ "name": "share_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "share_extended": {+ "name": "share_extended",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_project_active_idx": {+ "name": "issue_project_active_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"archived_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_project_title_idx": {+ "name": "issue_project_title_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "lower(btrim(\"title\"))",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_parent_idx": {+ "name": "issue_parent_idx",+ "columns": [+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"parent_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_idx": {+ "name": "issue_cycle_idx",+ "columns": [+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue\".\"cycle_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_project_id_project_id_fk": {+ "name": "issue_project_id_project_id_fk",+ "tableFrom": "issue",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_type_id_issue_type_id_fk": {+ "name": "issue_type_id_issue_type_id_fk",+ "tableFrom": "issue",+ "tableTo": "issue_type",+ "columnsFrom": [+ "type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_initiative_id_initiative_id_fk": {+ "name": "issue_initiative_id_initiative_id_fk",+ "tableFrom": "issue",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_cycle_id_cycle_id_fk": {+ "name": "issue_cycle_id_cycle_id_fk",+ "tableFrom": "issue",+ "tableTo": "cycle",+ "columnsFrom": [+ "cycle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_column_id_project_column_id_fk": {+ "name": "issue_column_id_project_column_id_fk",+ "tableFrom": "issue",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "issue_parent_id_issue_id_fk": {+ "name": "issue_parent_id_issue_id_fk",+ "tableFrom": "issue",+ "tableTo": "issue",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_assignee_user_id_user_id_fk": {+ "name": "issue_assignee_user_id_user_id_fk",+ "tableFrom": "issue",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_delegate_user_id_user_id_fk": {+ "name": "issue_delegate_user_id_user_id_fk",+ "tableFrom": "issue",+ "tableTo": "user",+ "columnsFrom": [+ "delegate_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_share_token_unique": {+ "name": "issue_share_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "share_token"+ ]+ },+ "issue_project_id_sequence_number_unique": {+ "name": "issue_project_id_sequence_number_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "sequence_number"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "issue_estimate_points_check": {+ "name": "issue_estimate_points_check",+ "value": "\"issue\".\"estimate_points\" >= 0"+ },+ "issue_estimate_minutes_check": {+ "name": "issue_estimate_minutes_check",+ "value": "\"issue\".\"estimate_minutes\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_activity": {+ "name": "issue_activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "reply_to_id": {+ "name": "reply_to_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_name": {+ "name": "actor_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "action": {+ "name": "action",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "edited_at": {+ "name": "edited_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_activity_issue_idx": {+ "name": "issue_activity_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_activity_reply_idx": {+ "name": "issue_activity_reply_idx",+ "columns": [+ {+ "expression": "reply_to_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_activity_initiative_idx": {+ "name": "issue_activity_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_activity_issue_id_issue_id_fk": {+ "name": "issue_activity_issue_id_issue_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_initiative_id_initiative_id_fk": {+ "name": "issue_activity_initiative_id_initiative_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_reply_to_id_issue_activity_id_fk": {+ "name": "issue_activity_reply_to_id_issue_activity_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "reply_to_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_activity_actor_user_id_user_id_fk": {+ "name": "issue_activity_actor_user_id_user_id_fk",+ "tableFrom": "issue_activity",+ "tableTo": "user",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_activity_kind_check": {+ "name": "issue_activity_kind_check",+ "value": "\"issue_activity\".\"kind\" IN ('comment', 'activity')"+ },+ "issue_activity_owner_check": {+ "name": "issue_activity_owner_check",+ "value": "(\"issue_activity\".\"issue_id\" IS NOT NULL) <> (\"issue_activity\".\"initiative_id\" IS NOT NULL)"+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_attachment": {+ "name": "issue_attachment",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "s3_key": {+ "name": "s3_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_type": {+ "name": "content_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "size_bytes": {+ "name": "size_bytes",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_attachment_issue_idx": {+ "name": "issue_attachment_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_attachment_issue_id_issue_id_fk": {+ "name": "issue_attachment_issue_id_issue_id_fk",+ "tableFrom": "issue_attachment",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_attachment_public_id_unique": {+ "name": "issue_attachment_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_checklist": {+ "name": "issue_checklist",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_checklist_issue_idx": {+ "name": "issue_checklist_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_checklist_issue_id_issue_id_fk": {+ "name": "issue_checklist_issue_id_issue_id_fk",+ "tableFrom": "issue_checklist",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_checklist_item": {+ "name": "issue_checklist_item",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "checklist_id": {+ "name": "checklist_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "done": {+ "name": "done",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_checklist_item_checklist_idx": {+ "name": "issue_checklist_item_checklist_idx",+ "columns": [+ {+ "expression": "checklist_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_checklist_item_checklist_id_issue_checklist_id_fk": {+ "name": "issue_checklist_item_checklist_id_issue_checklist_id_fk",+ "tableFrom": "issue_checklist_item",+ "tableTo": "issue_checklist",+ "columnsFrom": [+ "checklist_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_cycle": {+ "name": "issue_cycle",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "cycle_id": {+ "name": "cycle_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "entered_at": {+ "name": "entered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "left_at": {+ "name": "left_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "issue_cycle_issue_idx": {+ "name": "issue_cycle_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_cycle_idx": {+ "name": "issue_cycle_cycle_idx",+ "columns": [+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_cycle_open_idx": {+ "name": "issue_cycle_open_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cycle_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_cycle\".\"left_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_cycle_issue_id_issue_id_fk": {+ "name": "issue_cycle_issue_id_issue_id_fk",+ "tableFrom": "issue_cycle",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_cycle_cycle_id_cycle_id_fk": {+ "name": "issue_cycle_cycle_id_cycle_id_fk",+ "tableFrom": "issue_cycle",+ "tableTo": "cycle",+ "columnsFrom": [+ "cycle_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_development_check": {+ "name": "issue_development_check",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "development_link_id": {+ "name": "development_link_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "app_id": {+ "name": "app_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "head_sha": {+ "name": "head_sha",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_development_check_link_sha_idx": {+ "name": "issue_development_check_link_sha_idx",+ "columns": [+ {+ "expression": "development_link_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "head_sha",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_development_check_development_link_id_issue_development_link_id_fk": {+ "name": "issue_development_check_development_link_id_issue_development_link_id_fk",+ "tableFrom": "issue_development_check",+ "tableTo": "issue_development_link",+ "columnsFrom": [+ "development_link_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_development_check_development_link_id_app_id_name_unique": {+ "name": "issue_development_check_development_link_id_app_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "development_link_id",+ "app_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_development_link": {+ "name": "issue_development_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository": {+ "name": "repository",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pull_request'"+ },+ "external_key": {+ "name": "external_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "draft": {+ "name": "draft",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "source_branch": {+ "name": "source_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "target_branch": {+ "name": "target_branch",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "head_sha": {+ "name": "head_sha",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pipeline_status": {+ "name": "pipeline_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "pipeline_url": {+ "name": "pipeline_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_development_link_issue_idx": {+ "name": "issue_development_link_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_development_link_pr_idx": {+ "name": "issue_development_link_pr_idx",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "number",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_development_link_sha_idx": {+ "name": "issue_development_link_sha_idx",+ "columns": [+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "repository",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "head_sha",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_development_link_issue_id_issue_id_fk": {+ "name": "issue_development_link_issue_id_issue_id_fk",+ "tableFrom": "issue_development_link",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_development_link_issue_id_provider_repository_external_key_unique": {+ "name": "issue_development_link_issue_id_provider_repository_external_key_unique",+ "nullsNotDistinct": false,+ "columns": [+ "issue_id",+ "provider",+ "repository",+ "external_key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_field_option": {+ "name": "issue_field_option",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "option_id": {+ "name": "option_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_field_option_issue_id_issue_id_fk": {+ "name": "issue_field_option_issue_id_issue_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_option_field_id_custom_field_id_fk": {+ "name": "issue_field_option_field_id_custom_field_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_option_option_id_custom_field_option_id_fk": {+ "name": "issue_field_option_option_id_custom_field_option_id_fk",+ "tableFrom": "issue_field_option",+ "tableTo": "custom_field_option",+ "columnsFrom": [+ "option_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_field_option_issue_id_field_id_option_id_pk": {+ "name": "issue_field_option_issue_id_field_id_option_id_pk",+ "columns": [+ "issue_id",+ "field_id",+ "option_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_field_value": {+ "name": "issue_field_value",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "field_id": {+ "name": "field_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "value_text": {+ "name": "value_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "value_number": {+ "name": "value_number",+ "type": "numeric",+ "primaryKey": false,+ "notNull": false+ },+ "value_bool": {+ "name": "value_bool",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false+ },+ "value_date": {+ "name": "value_date",+ "type": "date",+ "primaryKey": false,+ "notNull": false+ },+ "value_datetime": {+ "name": "value_datetime",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "value_datetime_end": {+ "name": "value_datetime_end",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "value_user_id": {+ "name": "value_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_field_value_issue_id_issue_id_fk": {+ "name": "issue_field_value_issue_id_issue_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_value_field_id_custom_field_id_fk": {+ "name": "issue_field_value_field_id_custom_field_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "custom_field",+ "columnsFrom": [+ "field_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_field_value_value_user_id_user_id_fk": {+ "name": "issue_field_value_value_user_id_user_id_fk",+ "tableFrom": "issue_field_value",+ "tableTo": "user",+ "columnsFrom": [+ "value_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_field_value_issue_id_field_id_unique": {+ "name": "issue_field_value_issue_id_field_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "issue_id",+ "field_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_import": {+ "name": "issue_import",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "public_id": {+ "name": "public_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'mapped'"+ },+ "mapping": {+ "name": "mapping",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "error_text": {+ "name": "error_text",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_import_project_idx": {+ "name": "issue_import_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_import_project_id_project_id_fk": {+ "name": "issue_import_project_id_project_id_fk",+ "tableFrom": "issue_import",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_import_attachment_id_chat_attachment_id_fk": {+ "name": "issue_import_attachment_id_chat_attachment_id_fk",+ "tableFrom": "issue_import",+ "tableTo": "chat_attachment",+ "columnsFrom": [+ "attachment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_import_public_id_unique": {+ "name": "issue_import_public_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "public_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_key_alias": {+ "name": "issue_key_alias",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "sequence_number": {+ "name": "sequence_number",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "issue_key_alias_issue_idx": {+ "name": "issue_key_alias_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_key_alias_project_id_project_id_fk": {+ "name": "issue_key_alias_project_id_project_id_fk",+ "tableFrom": "issue_key_alias",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_key_alias_issue_id_issue_id_fk": {+ "name": "issue_key_alias_issue_id_issue_id_fk",+ "tableFrom": "issue_key_alias",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_key_alias_project_id_sequence_number_pk": {+ "name": "issue_key_alias_project_id_sequence_number_pk",+ "columns": [+ "project_id",+ "sequence_number"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_label": {+ "name": "issue_label",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_label_issue_id_issue_id_fk": {+ "name": "issue_label_issue_id_issue_id_fk",+ "tableFrom": "issue_label",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_label_label_id_label_id_fk": {+ "name": "issue_label_label_id_label_id_fk",+ "tableFrom": "issue_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_label_issue_id_label_id_pk": {+ "name": "issue_label_issue_id_label_id_pk",+ "columns": [+ "issue_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_link": {+ "name": "issue_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "source_issue_id": {+ "name": "source_issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "target_issue_id": {+ "name": "target_issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "kind": {+ "name": "kind",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_link_pair_kind_idx": {+ "name": "issue_link_pair_kind_idx",+ "columns": [+ {+ "expression": "least(\"source_issue_id\", \"target_issue_id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "greatest(\"source_issue_id\", \"target_issue_id\")",+ "asc": true,+ "isExpression": true,+ "nulls": "last"+ },+ {+ "expression": "kind",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_link_source_idx": {+ "name": "issue_link_source_idx",+ "columns": [+ {+ "expression": "source_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_link_target_idx": {+ "name": "issue_link_target_idx",+ "columns": [+ {+ "expression": "target_issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_link_source_issue_id_issue_id_fk": {+ "name": "issue_link_source_issue_id_issue_id_fk",+ "tableFrom": "issue_link",+ "tableTo": "issue",+ "columnsFrom": [+ "source_issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_link_target_issue_id_issue_id_fk": {+ "name": "issue_link_target_issue_id_issue_id_fk",+ "tableFrom": "issue_link",+ "tableTo": "issue",+ "columnsFrom": [+ "target_issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_link_kind_check": {+ "name": "issue_link_kind_check",+ "value": "\"issue_link\".\"kind\" IN ('blocks', 'relates', 'duplicates')"+ },+ "issue_link_self_check": {+ "name": "issue_link_self_check",+ "value": "\"issue_link\".\"source_issue_id\" <> \"issue_link\".\"target_issue_id\""+ }+ },+ "isRLSEnabled": false+ },+ "public.issue_status": {+ "name": "issue_status",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_name": {+ "name": "column_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "state_type": {+ "name": "state_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "entered_at": {+ "name": "entered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "left_at": {+ "name": "left_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "issue_status_issue_idx": {+ "name": "issue_status_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "entered_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_status_column_idx": {+ "name": "issue_status_column_idx",+ "columns": [+ {+ "expression": "column_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"issue_status\".\"column_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "issue_status_open_idx": {+ "name": "issue_status_open_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"issue_status\".\"left_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_status_issue_id_issue_id_fk": {+ "name": "issue_status_issue_id_issue_id_fk",+ "tableFrom": "issue_status",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_status_column_id_project_column_id_fk": {+ "name": "issue_status_column_id_project_column_id_fk",+ "tableFrom": "issue_status",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_template": {+ "name": "issue_template",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "title_template": {+ "name": "title_template",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "description_template": {+ "name": "description_template",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "type_id": {+ "name": "type_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "column_id": {+ "name": "column_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "assignee_user_id": {+ "name": "assignee_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_template_project_id_project_id_fk": {+ "name": "issue_template_project_id_project_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_template_type_id_issue_type_id_fk": {+ "name": "issue_template_type_id_issue_type_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "issue_type",+ "columnsFrom": [+ "type_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_template_column_id_project_column_id_fk": {+ "name": "issue_template_column_id_project_column_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "project_column",+ "columnsFrom": [+ "column_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "issue_template_assignee_user_id_user_id_fk": {+ "name": "issue_template_assignee_user_id_user_id_fk",+ "tableFrom": "issue_template",+ "tableTo": "user",+ "columnsFrom": [+ "assignee_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_template_project_id_name_unique": {+ "name": "issue_template_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_template_label": {+ "name": "issue_template_label",+ "schema": "",+ "columns": {+ "template_id": {+ "name": "template_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "label_id": {+ "name": "label_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_template_label_template_id_issue_template_id_fk": {+ "name": "issue_template_label_template_id_issue_template_id_fk",+ "tableFrom": "issue_template_label",+ "tableTo": "issue_template",+ "columnsFrom": [+ "template_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_template_label_label_id_label_id_fk": {+ "name": "issue_template_label_label_id_label_id_fk",+ "tableFrom": "issue_template_label",+ "tableTo": "label",+ "columnsFrom": [+ "label_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_template_label_template_id_label_id_pk": {+ "name": "issue_template_label_template_id_label_id_pk",+ "columns": [+ "template_id",+ "label_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_type": {+ "name": "issue_type",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_type_project_id_project_id_fk": {+ "name": "issue_type_project_id_project_id_fk",+ "tableFrom": "issue_type",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "issue_type_project_id_name_unique": {+ "name": "issue_type_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_watcher": {+ "name": "issue_watcher",+ "schema": "",+ "columns": {+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "subscribed": {+ "name": "subscribed",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "issue_watcher_issue_id_issue_id_fk": {+ "name": "issue_watcher_issue_id_issue_id_fk",+ "tableFrom": "issue_watcher",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_watcher_user_id_user_id_fk": {+ "name": "issue_watcher_user_id_user_id_fk",+ "tableFrom": "issue_watcher",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "issue_watcher_issue_id_user_id_pk": {+ "name": "issue_watcher_issue_id_user_id_pk",+ "columns": [+ "issue_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.issue_worklog": {+ "name": "issue_worklog",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "minutes": {+ "name": "minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "spent_on": {+ "name": "spent_on",+ "type": "date",+ "primaryKey": false,+ "notNull": true+ },+ "note": {+ "name": "note",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "issue_worklog_issue_idx": {+ "name": "issue_worklog_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "spent_on",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "issue_worklog_issue_id_issue_id_fk": {+ "name": "issue_worklog_issue_id_issue_id_fk",+ "tableFrom": "issue_worklog",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "issue_worklog_user_id_user_id_fk": {+ "name": "issue_worklog_user_id_user_id_fk",+ "tableFrom": "issue_worklog",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "issue_worklog_minutes_check": {+ "name": "issue_worklog_minutes_check",+ "value": "\"issue_worklog\".\"minutes\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "group_id": {+ "name": "group_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_project_id_project_id_fk": {+ "name": "label_project_id_project_id_fk",+ "tableFrom": "label",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "label_group_id_label_group_id_fk": {+ "name": "label_group_id_label_group_id_fk",+ "tableFrom": "label",+ "tableTo": "label_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_project_id_name_unique": {+ "name": "label_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label_group": {+ "name": "label_group",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_group_project_id_project_id_fk": {+ "name": "label_group_project_id_project_id_fk",+ "tableFrom": "label_group",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "label_group_project_id_name_unique": {+ "name": "label_group_project_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.model_price": {+ "name": "model_price",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "input": {+ "name": "input",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "output": {+ "name": "output",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "cache_read": {+ "name": "cache_read",+ "type": "double precision",+ "primaryKey": false,+ "notNull": false+ },+ "cache_write": {+ "name": "cache_write",+ "type": "double precision",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "model_price_workspace_id_workspace_id_fk": {+ "name": "model_price_workspace_id_workspace_id_fk",+ "tableFrom": "model_price",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "model_price_workspace_id_provider_model_unique": {+ "name": "model_price_workspace_id_provider_model_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "provider",+ "model"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "model_price_rates_check": {+ "name": "model_price_rates_check",+ "value": "\"model_price\".\"input\" >= 0 AND \"model_price\".\"output\" >= 0 AND coalesce(\"model_price\".\"cache_read\", 0) >= 0 AND coalesce(\"model_price\".\"cache_write\", 0) >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.note_board": {+ "name": "note_board",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "canvas": {+ "name": "canvas",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "note_board_project_idx": {+ "name": "note_board_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "note_board_project_id_project_id_fk": {+ "name": "note_board_project_id_project_id_fk",+ "tableFrom": "note_board",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_owner_user_id_user_id_fk": {+ "name": "note_board_owner_user_id_user_id_fk",+ "tableFrom": "note_board",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_created_by_user_id_user_id_fk": {+ "name": "note_board_created_by_user_id_user_id_fk",+ "tableFrom": "note_board",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.note_board_member": {+ "name": "note_board_member",+ "schema": "",+ "columns": {+ "board_id": {+ "name": "board_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "note_board_member_user_idx": {+ "name": "note_board_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "note_board_member_board_id_note_board_id_fk": {+ "name": "note_board_member_board_id_note_board_id_fk",+ "tableFrom": "note_board_member",+ "tableTo": "note_board",+ "columnsFrom": [+ "board_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "note_board_member_user_id_user_id_fk": {+ "name": "note_board_member_user_id_user_id_fk",+ "tableFrom": "note_board_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "note_board_member_board_id_user_id_pk": {+ "name": "note_board_member_board_id_user_id_pk",+ "columns": [+ "board_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "source_activity_id": {+ "name": "source_activity_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "document_comment_id": {+ "name": "document_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "actor_user_id": {+ "name": "actor_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "actor_name": {+ "name": "actor_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "read_at": {+ "name": "read_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "snoozed_until": {+ "name": "snoozed_until",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_user_idx": {+ "name": "notification_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "notification_user_unread_idx": {+ "name": "notification_user_unread_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": false,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"notification\".\"read_at\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_project_id_project_id_fk": {+ "name": "notification_project_id_project_id_fk",+ "tableFrom": "notification",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_issue_id_issue_id_fk": {+ "name": "notification_issue_id_issue_id_fk",+ "tableFrom": "notification",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_source_activity_id_issue_activity_id_fk": {+ "name": "notification_source_activity_id_issue_activity_id_fk",+ "tableFrom": "notification",+ "tableTo": "issue_activity",+ "columnsFrom": [+ "source_activity_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "notification_document_id_project_document_id_fk": {+ "name": "notification_document_id_project_document_id_fk",+ "tableFrom": "notification",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "notification_document_comment_id_document_comment_id_fk": {+ "name": "notification_document_comment_id_document_comment_id_fk",+ "tableFrom": "notification",+ "tableTo": "document_comment",+ "columnsFrom": [+ "document_comment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "notification_actor_user_id_user_id_fk": {+ "name": "notification_actor_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": [+ "actor_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "notification_type_check": {+ "name": "notification_type_check",+ "value": "\"notification\".\"type\" IN ('assigned', 'mentioned', 'commented', 'state_changed')"+ },+ "notification_target_check": {+ "name": "notification_target_check",+ "value": "(\"notification\".\"issue_id\" IS NULL) <> (\"notification\".\"document_id\" IS NULL)"+ }+ },+ "isRLSEnabled": false+ },+ "public.notification_delivery": {+ "name": "notification_delivery",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "channel": {+ "name": "channel",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "recipient": {+ "name": "recipient",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "notification_delivery_due_idx": {+ "name": "notification_delivery_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"notification_delivery\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "notification_delivery_project_id_project_id_fk": {+ "name": "notification_delivery_project_id_project_id_fk",+ "tableFrom": "notification_delivery",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "notification_delivery_channel_check": {+ "name": "notification_delivery_channel_check",+ "value": "\"notification_delivery\".\"channel\" IN ('email', 'telegram')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "next_sequence": {+ "name": "next_sequence",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "mcp_enabled": {+ "name": "mcp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "initiatives_enabled": {+ "name": "initiatives_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "dashboards_enabled": {+ "name": "dashboards_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "documents_enabled": {+ "name": "documents_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "notes_enabled": {+ "name": "notes_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "cycles_enabled": {+ "name": "cycles_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "subtasks_enabled": {+ "name": "subtasks_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "checklists_enabled": {+ "name": "checklists_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "issue_stats_enabled": {+ "name": "issue_stats_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "points_estimate_enabled": {+ "name": "points_estimate_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "time_estimate_enabled": {+ "name": "time_estimate_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "time_logging_enabled": {+ "name": "time_logging_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_team_id_team_id_fk": {+ "name": "project_team_id_team_id_fk",+ "tableFrom": "project",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_team_key_uq": {+ "name": "project_team_key_uq",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "key"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_action": {+ "name": "project_action",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "condition": {+ "name": "condition",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "effect": {+ "name": "effect",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_action_project_idx": {+ "name": "project_action_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_action_project_id_project_id_fk": {+ "name": "project_action_project_id_project_id_fk",+ "tableFrom": "project_action",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_column": {+ "name": "project_column",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state_type": {+ "name": "state_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'unstarted'"+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'#6b7280'"+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "wip_limit": {+ "name": "wip_limit",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "wip_mode": {+ "name": "wip_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'soft'"+ },+ "auto_assign_user_id": {+ "name": "auto_assign_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_column_project_id_project_id_fk": {+ "name": "project_column_project_id_project_id_fk",+ "tableFrom": "project_column",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_column_auto_assign_user_id_user_id_fk": {+ "name": "project_column_auto_assign_user_id_user_id_fk",+ "tableFrom": "project_column",+ "tableTo": "user",+ "columnsFrom": [+ "auto_assign_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_column_project_id_position_unique": {+ "name": "project_column_project_id_position_unique",+ "nullsNotDistinct": false,+ "columns": [+ "project_id",+ "position"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "project_column_state_type_check": {+ "name": "project_column_state_type_check",+ "value": "\"project_column\".\"state_type\" IN ('backlog', 'unstarted', 'started', 'completed', 'canceled')"+ },+ "project_column_wip_mode_check": {+ "name": "project_column_wip_mode_check",+ "value": "\"project_column\".\"wip_mode\" IN ('soft', 'hard')"+ },+ "project_column_wip_limit_check": {+ "name": "project_column_wip_limit_check",+ "value": "\"project_column\".\"wip_limit\" IS NULL OR \"project_column\".\"wip_limit\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_dashboard": {+ "name": "project_dashboard",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "layout": {+ "name": "layout",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_dashboard_project_idx": {+ "name": "project_dashboard_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_dashboard_project_id_project_id_fk": {+ "name": "project_dashboard_project_id_project_id_fk",+ "tableFrom": "project_dashboard",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document": {+ "name": "project_document",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "content_json": {+ "name": "content_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "full_width": {+ "name": "full_width",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_private": {+ "name": "is_private",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_locked": {+ "name": "is_locked",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "archived_by_ancestor_id": {+ "name": "archived_by_ancestor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "updated_by_user_id": {+ "name": "updated_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_project_tree_idx": {+ "name": "project_document_project_tree_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "parent_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_document_owner_idx": {+ "name": "project_document_owner_idx",+ "columns": [+ {+ "expression": "owner_user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "project_document_project_archive_idx": {+ "name": "project_document_project_archive_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "archived_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_project_id_project_id_fk": {+ "name": "project_document_project_id_project_id_fk",+ "tableFrom": "project_document",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_parent_id_project_document_id_fk": {+ "name": "project_document_parent_id_project_document_id_fk",+ "tableFrom": "project_document",+ "tableTo": "project_document",+ "columnsFrom": [+ "parent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_archived_by_ancestor_id_project_document_id_fk": {+ "name": "project_document_archived_by_ancestor_id_project_document_id_fk",+ "tableFrom": "project_document",+ "tableTo": "project_document",+ "columnsFrom": [+ "archived_by_ancestor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_owner_user_id_user_id_fk": {+ "name": "project_document_owner_user_id_user_id_fk",+ "tableFrom": "project_document",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_created_by_user_id_user_id_fk": {+ "name": "project_document_created_by_user_id_user_id_fk",+ "tableFrom": "project_document",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_updated_by_user_id_user_id_fk": {+ "name": "project_document_updated_by_user_id_user_id_fk",+ "tableFrom": "project_document",+ "tableTo": "user",+ "columnsFrom": [+ "updated_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "project_document_version_check": {+ "name": "project_document_version_check",+ "value": "\"project_document\".\"version\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_document_initiative": {+ "name": "project_document_initiative",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "initiative_id": {+ "name": "initiative_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_initiative_initiative_idx": {+ "name": "project_document_initiative_initiative_idx",+ "columns": [+ {+ "expression": "initiative_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_initiative_document_id_project_document_id_fk": {+ "name": "project_document_initiative_document_id_project_document_id_fk",+ "tableFrom": "project_document_initiative",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_initiative_initiative_id_initiative_id_fk": {+ "name": "project_document_initiative_initiative_id_initiative_id_fk",+ "tableFrom": "project_document_initiative",+ "tableTo": "initiative",+ "columnsFrom": [+ "initiative_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_initiative_created_by_user_id_user_id_fk": {+ "name": "project_document_initiative_created_by_user_id_user_id_fk",+ "tableFrom": "project_document_initiative",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_document_initiative_document_id_initiative_id_pk": {+ "name": "project_document_initiative_document_id_initiative_id_pk",+ "columns": [+ "document_id",+ "initiative_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document_issue": {+ "name": "project_document_issue",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_issue_issue_idx": {+ "name": "project_document_issue_issue_idx",+ "columns": [+ {+ "expression": "issue_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_issue_document_id_project_document_id_fk": {+ "name": "project_document_issue_document_id_project_document_id_fk",+ "tableFrom": "project_document_issue",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_issue_issue_id_issue_id_fk": {+ "name": "project_document_issue_issue_id_issue_id_fk",+ "tableFrom": "project_document_issue",+ "tableTo": "issue",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_issue_created_by_user_id_user_id_fk": {+ "name": "project_document_issue_created_by_user_id_user_id_fk",+ "tableFrom": "project_document_issue",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_document_issue_document_id_issue_id_pk": {+ "name": "project_document_issue_document_id_issue_id_pk",+ "columns": [+ "document_id",+ "issue_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document_preference": {+ "name": "project_document_preference",+ "schema": "",+ "columns": {+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_favorite": {+ "name": "is_favorite",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_preference_user_idx": {+ "name": "project_document_preference_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_preference_document_id_project_document_id_fk": {+ "name": "project_document_preference_document_id_project_document_id_fk",+ "tableFrom": "project_document_preference",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_preference_user_id_user_id_fk": {+ "name": "project_document_preference_user_id_user_id_fk",+ "tableFrom": "project_document_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_document_preference_document_id_user_id_pk": {+ "name": "project_document_preference_document_id_user_id_pk",+ "columns": [+ "document_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_document_revision": {+ "name": "project_document_revision",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "document_id": {+ "name": "document_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "parent_id": {+ "name": "parent_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content_json": {+ "name": "content_json",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "full_width": {+ "name": "full_width",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_private": {+ "name": "is_private",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_locked": {+ "name": "is_locked",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "archived_at": {+ "name": "archived_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true+ },+ "owner_user_id": {+ "name": "owner_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_by_user_id": {+ "name": "created_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_document_revision_document_idx": {+ "name": "project_document_revision_document_idx",+ "columns": [+ {+ "expression": "document_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "version",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_document_revision_document_id_project_document_id_fk": {+ "name": "project_document_revision_document_id_project_document_id_fk",+ "tableFrom": "project_document_revision",+ "tableTo": "project_document",+ "columnsFrom": [+ "document_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_document_revision_owner_user_id_user_id_fk": {+ "name": "project_document_revision_owner_user_id_user_id_fk",+ "tableFrom": "project_document_revision",+ "tableTo": "user",+ "columnsFrom": [+ "owner_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "project_document_revision_created_by_user_id_user_id_fk": {+ "name": "project_document_revision_created_by_user_id_user_id_fk",+ "tableFrom": "project_document_revision",+ "tableTo": "user",+ "columnsFrom": [+ "created_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_document_revision_document_version_unique": {+ "name": "project_document_revision_document_version_unique",+ "nullsNotDistinct": false,+ "columns": [+ "document_id",+ "version"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_member": {+ "name": "project_member",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "''"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'invite'"+ },+ "is_favorite": {+ "name": "is_favorite",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "is_hidden": {+ "name": "is_hidden",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_member_user_idx": {+ "name": "project_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_member_project_id_project_id_fk": {+ "name": "project_member_project_id_project_id_fk",+ "tableFrom": "project_member",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_member_user_id_user_id_fk": {+ "name": "project_member_user_id_user_id_fk",+ "tableFrom": "project_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_member_role_id_team_role_id_fk": {+ "name": "project_member_role_id_team_role_id_fk",+ "tableFrom": "project_member",+ "tableTo": "team_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_member_project_id_user_id_pk": {+ "name": "project_member_project_id_user_id_pk",+ "columns": [+ "project_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "project_member_role_check": {+ "name": "project_member_role_check",+ "value": "\"project_member\".\"role\" IN ('owner', 'member')"+ },+ "project_member_source_check": {+ "name": "project_member_source_check",+ "value": "\"project_member\".\"source\" IN ('invite', 'scim')"+ }+ },+ "isRLSEnabled": false+ },+ "public.project_setting": {+ "name": "project_setting",+ "schema": "",+ "columns": {+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_setting_project_id_project_id_fk": {+ "name": "project_setting_project_id_project_id_fk",+ "tableFrom": "project_setting",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_setting_project_id_key_pk": {+ "name": "project_setting_project_id_key_pk",+ "columns": [+ "project_id",+ "key"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_view": {+ "name": "project_view",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "filters": {+ "name": "filters",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "display": {+ "name": "display",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "position": {+ "name": "position",+ "type": "double precision",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "share_token": {+ "name": "share_token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "share_extended": {+ "name": "share_extended",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "project_view_project_idx": {+ "name": "project_view_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "position",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "project_view_project_id_project_id_fk": {+ "name": "project_view_project_id_project_id_fk",+ "tableFrom": "project_view",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "project_view_share_token_unique": {+ "name": "project_view_share_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "share_token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project_view_favorite": {+ "name": "project_view_favorite",+ "schema": "",+ "columns": {+ "view_id": {+ "name": "view_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_view_favorite_view_id_project_view_id_fk": {+ "name": "project_view_favorite_view_id_project_view_id_fk",+ "tableFrom": "project_view_favorite",+ "tableTo": "project_view",+ "columnsFrom": [+ "view_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "project_view_favorite_user_id_user_id_fk": {+ "name": "project_view_favorite_user_id_user_id_fk",+ "tableFrom": "project_view_favorite",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "project_view_favorite_view_id_user_id_pk": {+ "name": "project_view_favorite_view_id_user_id_pk",+ "columns": [+ "view_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.revision": {+ "name": "revision",+ "schema": "",+ "columns": {+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "rev": {+ "name": "rev",+ "type": "bigint",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ }+ },+ "indexes": {+ "revision_project_idx": {+ "name": "revision_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "mcp_enabled": {+ "name": "mcp_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "default_agent_ids": {+ "name": "default_agent_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_workspace_idx": {+ "name": "team_workspace_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_slug_unique": {+ "name": "team_slug_unique",+ "nullsNotDistinct": false,+ "columns": [+ "slug"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_invite": {+ "name": "team_invite",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "team_role": {+ "name": "team_role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "project_role": {+ "name": "project_role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "invited_by_user_id": {+ "name": "invited_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "accepted_by_user_id": {+ "name": "accepted_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "responded_at": {+ "name": "responded_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_invite_team_pending_uq": {+ "name": "team_invite_team_pending_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"team_invite\".\"status\" = 'pending' AND \"team_invite\".\"project_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_invite_project_pending_uq": {+ "name": "team_invite_project_pending_uq",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"team_invite\".\"status\" = 'pending' AND \"team_invite\".\"project_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_invite_team_idx": {+ "name": "team_invite_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_invite_project_idx": {+ "name": "team_invite_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_invite_team_id_team_id_fk": {+ "name": "team_invite_team_id_team_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_invite_project_id_project_id_fk": {+ "name": "team_invite_project_id_project_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_invite_role_id_team_role_id_fk": {+ "name": "team_invite_role_id_team_role_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "team_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "team_invite_invited_by_user_id_user_id_fk": {+ "name": "team_invite_invited_by_user_id_user_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "user",+ "columnsFrom": [+ "invited_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "team_invite_accepted_by_user_id_user_id_fk": {+ "name": "team_invite_accepted_by_user_id_user_id_fk",+ "tableFrom": "team_invite",+ "tableTo": "user",+ "columnsFrom": [+ "accepted_by_user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_invite_token_unique": {+ "name": "team_invite_token_unique",+ "nullsNotDistinct": false,+ "columns": [+ "token"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "team_invite_team_role_check": {+ "name": "team_invite_team_role_check",+ "value": "\"team_invite\".\"team_role\" IN ('owner', 'manager', 'member')"+ },+ "team_invite_project_role_check": {+ "name": "team_invite_project_role_check",+ "value": "(\"team_invite\".\"project_id\" IS NULL AND \"team_invite\".\"project_role\" IS NULL)\n OR (\"team_invite\".\"project_id\" IS NOT NULL AND \"team_invite\".\"project_role\" IN ('owner', 'member'))"+ },+ "team_invite_status_check": {+ "name": "team_invite_status_check",+ "value": "\"team_invite\".\"status\" IN ('pending', 'accepted', 'rejected')"+ }+ },+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "source": {+ "name": "source",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'invite'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_member_user_idx": {+ "name": "team_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "team_member_team_id_user_id_pk": {+ "name": "team_member_team_id_user_id_pk",+ "columns": [+ "team_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "team_member_role_check": {+ "name": "team_member_role_check",+ "value": "\"team_member\".\"role\" IN ('owner', 'manager', 'member', 'agent')"+ },+ "team_member_source_check": {+ "name": "team_member_source_check",+ "value": "\"team_member\".\"source\" IN ('invite', 'scim')"+ }+ },+ "isRLSEnabled": false+ },+ "public.team_notification_setting": {+ "name": "team_notification_setting",+ "schema": "",+ "columns": {+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "ciphertext": {+ "name": "ciphertext",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "iv": {+ "name": "iv",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "auth_tag": {+ "name": "auth_tag",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "redacted": {+ "name": "redacted",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "team_notification_setting_team_id_team_id_fk": {+ "name": "team_notification_setting_team_id_team_id_fk",+ "tableFrom": "team_notification_setting",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_role": {+ "name": "team_role",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_default": {+ "name": "is_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "permissions": {+ "name": "permissions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "team_role_default_uq": {+ "name": "team_role_default_uq",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"team_role\".\"is_default\"",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "team_role_team_idx": {+ "name": "team_role_team_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_role_team_id_team_id_fk": {+ "name": "team_role_team_id_team_id_fk",+ "tableFrom": "team_role",+ "tableTo": "team",+ "columnsFrom": [+ "team_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "team_role_team_id_name_unique": {+ "name": "team_role_team_id_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "team_id",+ "name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_notification_preference": {+ "name": "user_notification_preference",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "email_events": {+ "name": "email_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "telegram_events": {+ "name": "telegram_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::jsonb"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_notification_preference_user_id_user_id_fk": {+ "name": "user_notification_preference_user_id_user_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_notification_preference_project_id_project_id_fk": {+ "name": "user_notification_preference_project_id_project_id_fk",+ "tableFrom": "user_notification_preference",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_notification_pref_user_project_unique": {+ "name": "user_notification_pref_user_project_unique",+ "nullsNotDistinct": false,+ "columns": [+ "user_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user_preference": {+ "name": "user_preference",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "timezone": {+ "name": "timezone",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'UTC'"+ },+ "locale": {+ "name": "locale",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'en'"+ },+ "theme": {+ "name": "theme",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'system'"+ },+ "issue_open_mode": {+ "name": "issue_open_mode",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'panel'"+ },+ "start_page": {+ "name": "start_page",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'work-items'"+ },+ "show_chat_by_default": {+ "name": "show_chat_by_default",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "issue_stats_open": {+ "name": "issue_stats_open",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "issue_stats_view": {+ "name": "issue_stats_view",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'compact'"+ },+ "issue_activity_view": {+ "name": "issue_activity_view",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'flat'"+ },+ "auto_watch": {+ "name": "auto_watch",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "hotkeys": {+ "name": "hotkeys",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "last_project_id": {+ "name": "last_project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "seen_version": {+ "name": "seen_version",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "user_preference_user_id_user_id_fk": {+ "name": "user_preference_user_id_user_id_fk",+ "tableFrom": "user_preference",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "user_preference_last_project_id_project_id_fk": {+ "name": "user_preference_last_project_id_project_id_fk",+ "tableFrom": "user_preference",+ "tableTo": "project",+ "columnsFrom": [+ "last_project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "user_preference_theme_check": {+ "name": "user_preference_theme_check",+ "value": "\"user_preference\".\"theme\" IN ('light', 'dark', 'system')"+ },+ "user_preference_issue_open_mode_check": {+ "name": "user_preference_issue_open_mode_check",+ "value": "\"user_preference\".\"issue_open_mode\" IN ('panel', 'page')"+ },+ "user_preference_start_page_check": {+ "name": "user_preference_start_page_check",+ "value": "\"user_preference\".\"start_page\" IN ('inbox', 'dashboard', 'work-items', 'initiatives')"+ },+ "user_preference_issue_stats_view_check": {+ "name": "user_preference_issue_stats_view_check",+ "value": "\"user_preference\".\"issue_stats_view\" IN ('compact', 'timeline')"+ },+ "user_preference_issue_activity_view_check": {+ "name": "user_preference_issue_activity_view_check",+ "value": "\"user_preference\".\"issue_activity_view\" IN ('flat', 'grouped')"+ }+ },+ "isRLSEnabled": false+ },+ "public.user_telegram_account": {+ "name": "user_telegram_account",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "chat_id": {+ "name": "chat_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "username": {+ "name": "username",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "first_name": {+ "name": "first_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_code": {+ "name": "link_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "link_code_expires_at": {+ "name": "link_code_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "linked_at": {+ "name": "linked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "user_telegram_account_chat_id_unique": {+ "name": "user_telegram_account_chat_id_unique",+ "columns": [+ {+ "expression": "chat_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_telegram_account\".\"chat_id\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "user_telegram_account_link_code_unique": {+ "name": "user_telegram_account_link_code_unique",+ "columns": [+ {+ "expression": "link_code",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"user_telegram_account\".\"link_code\" IS NOT NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "user_telegram_account_user_id_user_id_fk": {+ "name": "user_telegram_account_user_id_user_id_fk",+ "tableFrom": "user_telegram_account",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook": {+ "name": "webhook",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "events": {+ "name": "events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "webhook_project_idx": {+ "name": "webhook_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_project_id_project_id_fk": {+ "name": "webhook_project_id_project_id_fk",+ "tableFrom": "webhook",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.webhook_delivery": {+ "name": "webhook_delivery",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "event_id": {+ "name": "event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "event_type": {+ "name": "event_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "next_attempt_at": {+ "name": "next_attempt_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_status": {+ "name": "response_status",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "response_body": {+ "name": "response_body",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "webhook_delivery_due_idx": {+ "name": "webhook_delivery_due_idx",+ "columns": [+ {+ "expression": "next_attempt_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"webhook_delivery\".\"status\" = 'pending'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "webhook_delivery_webhook_idx": {+ "name": "webhook_delivery_webhook_idx",+ "columns": [+ {+ "expression": "webhook_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "webhook_delivery_webhook_id_webhook_id_fk": {+ "name": "webhook_delivery_webhook_id_webhook_id_fk",+ "tableFrom": "webhook_delivery",+ "tableTo": "webhook",+ "columnsFrom": [+ "webhook_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_creation": {+ "name": "team_creation",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'owner'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "workspace_team_creation_check": {+ "name": "workspace_team_creation_check",+ "value": "\"workspace\".\"team_creation\" IN ('owner', 'managers', 'members')"+ }+ },+ "isRLSEnabled": false+ },+ "public.workspace_manager": {+ "name": "workspace_manager",+ "schema": "",+ "columns": {+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'admin'"+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "workspace_manager_owner_uq": {+ "name": "workspace_manager_owner_uq",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"workspace_manager\".\"role\" = 'owner'",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_manager_user_idx": {+ "name": "workspace_manager_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_manager_workspace_id_workspace_id_fk": {+ "name": "workspace_manager_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_manager",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_manager_user_id_user_id_fk": {+ "name": "workspace_manager_user_id_user_id_fk",+ "tableFrom": "workspace_manager",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "workspace_manager_workspace_id_user_id_pk": {+ "name": "workspace_manager_workspace_id_user_id_pk",+ "columns": [+ "workspace_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "workspace_manager_role_check": {+ "name": "workspace_manager_role_check",+ "value": "\"workspace_manager\".\"role\" IN ('owner', 'admin')"+ }+ },+ "isRLSEnabled": false+ },+ "public.scim_group": {+ "name": "scim_group",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "display_name": {+ "name": "display_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "scim_group_instance_display_name_uq": {+ "name": "scim_group_instance_display_name_uq",+ "columns": [+ {+ "expression": "display_name",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"scim_group\".\"workspace_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_workspace_id_workspace_id_fk": {+ "name": "scim_group_workspace_id_workspace_id_fk",+ "tableFrom": "scim_group",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_group_workspace_id_display_name_unique": {+ "name": "scim_group_workspace_id_display_name_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "display_name"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.scim_group_mapping": {+ "name": "scim_group_mapping",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "group_id": {+ "name": "group_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "role_id": {+ "name": "role_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "scim_group_mapping_project_idx": {+ "name": "scim_group_mapping_project_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_mapping_group_id_scim_group_id_fk": {+ "name": "scim_group_mapping_group_id_scim_group_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "scim_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_mapping_project_id_project_id_fk": {+ "name": "scim_group_mapping_project_id_project_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "project",+ "columnsFrom": [+ "project_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_mapping_role_id_team_role_id_fk": {+ "name": "scim_group_mapping_role_id_team_role_id_fk",+ "tableFrom": "scim_group_mapping",+ "tableTo": "team_role",+ "columnsFrom": [+ "role_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_group_mapping_group_id_project_id_unique": {+ "name": "scim_group_mapping_group_id_project_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "group_id",+ "project_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "scim_group_mapping_role_check": {+ "name": "scim_group_mapping_role_check",+ "value": "\"scim_group_mapping\".\"role\" IN ('owner', 'member')"+ }+ },+ "isRLSEnabled": false+ },+ "public.scim_group_member": {+ "name": "scim_group_member",+ "schema": "",+ "columns": {+ "group_id": {+ "name": "group_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "scim_group_member_user_idx": {+ "name": "scim_group_member_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_group_member_group_id_scim_group_id_fk": {+ "name": "scim_group_member_group_id_scim_group_id_fk",+ "tableFrom": "scim_group_member",+ "tableTo": "scim_group",+ "columnsFrom": [+ "group_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_group_member_user_id_user_id_fk": {+ "name": "scim_group_member_user_id_user_id_fk",+ "tableFrom": "scim_group_member",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "scim_group_member_group_id_user_id_pk": {+ "name": "scim_group_member_group_id_user_id_pk",+ "columns": [+ "group_id",+ "user_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.scim_user": {+ "name": "scim_user",+ "schema": "",+ "columns": {+ "workspace_id": {+ "name": "workspace_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active": {+ "name": "active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "scim_user_instance_user_uq": {+ "name": "scim_user_instance_user_uq",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "where": "\"scim_user\".\"workspace_id\" IS NULL",+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "scim_user_user_idx": {+ "name": "scim_user_user_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "scim_user_workspace_id_workspace_id_fk": {+ "name": "scim_user_workspace_id_workspace_id_fk",+ "tableFrom": "scim_user",+ "tableTo": "workspace",+ "columnsFrom": [+ "workspace_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "scim_user_user_id_user_id_fk": {+ "name": "scim_user_user_id_user_id_fk",+ "tableFrom": "scim_user",+ "tableTo": "user",+ "columnsFrom": [+ "user_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "scim_user_workspace_id_user_id_unique": {+ "name": "scim_user_workspace_id_user_id_unique",+ "nullsNotDistinct": false,+ "columns": [+ "workspace_id",+ "user_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 10d1f2b0..c0d97f2f 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -1100,6 +1100,13 @@"when": 1792788993549,"tag": "0156_agent_tool_keyless","breakpoints": true+ },+ {+ "idx": 157,+ "version": "7",+ "when": 1792948521460,+ "tag": "0157_document_mentions",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.tsindex a600730d..20dada96 100644--- a/packages/db/src/schema/app.ts+++ b/packages/db/src/schema/app.ts@@ -705,6 +705,15 @@ export const agentRun = pgTable(sourceActivityId: integer('source_activity_id').references(() => issueActivity.id, {onDelete: 'set null',}),+ // A mention in a document comment: the document and the comment. Such a run has no+ // issue.+ documentId: integer('document_id').references(() => projectDocument.id, {+ onDelete: 'cascade',+ }),+ sourceDocumentCommentId: uuid('source_document_comment_id').references(+ () => documentComment.id,+ { onDelete: 'set null' },+ ),// The mention comment body at enqueue time, framed into the agent's prompt.prompt: text('prompt').notNull(),// pending -> success | failed | canceled. Like webhook_delivery, a claim keeps the row@@ -2402,10 +2411,12 @@ export const importRecord = pgTable(// Per-user inbox notifications. One row per (recipient, event): a user is notified// about an issue they are involved in (assigned to them, mentioned, or watching it-// when it is commented on or moved). The actor's own actions never notify the actor.-// project_id is denormalized from the issue so the inbox can filter and scope by-// project. source_activity_id points at the issue_activity row that produced the-// notification (set null if that entry is later removed). type selects the kind.+// when it is commented on or moved), or about a document that mentions them in its+// text or in a comment. A row points at either an issue or a document. The actor's own+// actions never notify the actor. project_id is denormalized from the issue or the+// document so the inbox can filter and scope by project. source_activity_id points at+// the issue_activity row that produced the notification, document_comment_id at the+// document comment (each set null if that entry is later removed). type selects the kind.// read_at NULL means unread; snoozed_until, when set and still in the future, hides// the row from the default inbox until then.export const notification = pgTable(@@ -2418,12 +2429,16 @@ export const notification = pgTable(projectId: integer('project_id').notNull().references(() => project.id, { onDelete: 'cascade' }),- issueId: integer('issue_id')- .notNull()- .references(() => issue.id, { onDelete: 'cascade' }),+ issueId: integer('issue_id').references(() => issue.id, { onDelete: 'cascade' }),sourceActivityId: integer('source_activity_id').references(() => issueActivity.id, {onDelete: 'set null',}),+ documentId: integer('document_id').references(() => projectDocument.id, {+ onDelete: 'cascade',+ }),+ documentCommentId: uuid('document_comment_id').references(() => documentComment.id, {+ onDelete: 'set null',+ }),type: text('type').notNull(),actorUserId: text('actor_user_id').references(() => user.id, {onDelete: 'set null',@@ -2438,6 +2453,7 @@ export const notification = pgTable('notification_type_check',sql`${t.type} IN ('assigned', 'mentioned', 'commented', 'state_changed')`,),+ check('notification_target_check', sql`(${t.issueId} IS NULL) <> (${t.documentId} IS NULL)`),// Backs the inbox list: a user's notifications newest first.index('notification_user_idx').on(t.userId, t.createdAt.desc(), t.id.desc()),// Backs the unread count and the unread-only inbox view.