Skip to content

⭐️⭐️⭐️ 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.

feat: implement Plane import/export with job management and UI (#389)

Muhammad Salman88a43a9197f4
diff --git a/.env.example b/.env.example
index bfceb2b1..907fe38c 100644
--- a/.env.example
+++ b/.env.example
@@ -109,6 +109,7 @@ APP_ENCRYPTION_KEY=
# NOTIFICATION_BATCH_SIZE=20 # notification deliveries claimed per tick
# NOTIFICATION_MAX_ATTEMPTS=5 # attempts before a delivery is marked failed
# NOTIFICATION_LEASE_SECONDS=120 # claim lease for crash recovery
+# IMPORT_POLL_INTERVAL_MS=3000 # how often to poll for a due import job
# ── Background jobs (apps/api): the agent run queue and the auto-archive sweep ──
# AGENT_RUN_POLL_INTERVAL_MS=2000 # how often to poll for due agent runs
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile
index 3c5d7386..ec937bd8 100644
--- a/apps/api/Dockerfile
+++ b/apps/api/Dockerfile
@@ -18,6 +18,7 @@ COPY packages/agent-tools/package.json ./packages/agent-tools/
COPY packages/crypto/package.json ./packages/crypto/
COPY packages/mailer/package.json ./packages/mailer/
COPY packages/net/package.json ./packages/net/
+COPY packages/storage/package.json ./packages/storage/
COPY packages/runner/package.json ./packages/runner/
COPY packages/eslint-config/package.json ./packages/eslint-config/
# INSTALL_FILTER installs only the api workspace and its dependency closure, so the
diff --git a/apps/api/package.json b/apps/api/package.json
index 0e044bb7..60866a39 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -33,6 +33,7 @@
"@repo/db": "workspace:*",
"@repo/mailer": "workspace:*",
"@repo/net": "workspace:*",
+ "@repo/storage": "workspace:*",
"@tiptap/pm": "3.30.5",
"croner": "^10.0.1",
"decode-named-character-reference": "^1.3.0",
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index dbed49ee..3edac086 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -121,6 +121,12 @@ export const app = new Elysia()
description: 'Files uploaded in an agent chat and their raw bytes',
},
{ name: 'Imports', description: 'Import drafts that turn an uploaded file into issues' },
+ {
+ name: 'Import/Export',
+ description:
+ 'Background jobs that import issues from an external tracker (Plane), and a ' +
+ "project's own data exported as a portable JSON snapshot",
+ },
{ name: 'Avatars', description: "Current user's avatar image (upload and raw bytes)" },
{ name: 'Views', description: 'Saved work items views' },
{ name: 'Share', description: 'Public read-only sharing of issues and views' },
diff --git a/apps/api/src/modules/agents/skills/service.ts b/apps/api/src/modules/agents/skills/service.ts
index 3d5724ed..673df01d 100644
--- a/apps/api/src/modules/agents/skills/service.ts
+++ b/apps/api/src/modules/agents/skills/service.ts
@@ -1,7 +1,7 @@
import { db, agentSkill, agentSkillLink } from '@repo/db';
import { and, eq, inArray, sql } from 'drizzle-orm';
import { iso, rethrowDuplicate, HttpError } from '#shared/lib';
-import { putObject, getObjectText, deleteObjects } from '#shared/s3';
+import { putObject, getObjectText, deleteObjects } from '@repo/storage';
import { parseFrontmatter, isDisallowedRef } from './skill-format';
// Data access for the team skill library, shared by every project the team owns. A
diff --git a/apps/api/src/modules/attachments/index.ts b/apps/api/src/modules/attachments/index.ts
index a464dcf6..3370fe0e 100644
--- a/apps/api/src/modules/attachments/index.ts
+++ b/apps/api/src/modules/attachments/index.ts
@@ -7,7 +7,7 @@ import { pinnedFetch } from '#shared/net';
import { mcpTool } from '#mcp/generate';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { getIssueProjectId } from '#modules/issues/service';
-import { getStorageSettings, MB } from '#modules/settings/service';
+import { getStorageSettings, MB } from '@repo/db';
import {
AttachmentResponse,
AttachmentListResponse,
diff --git a/apps/api/src/modules/attachments/service.ts b/apps/api/src/modules/attachments/service.ts
index 7048c49c..4ac64efb 100644
--- a/apps/api/src/modules/attachments/service.ts
+++ b/apps/api/src/modules/attachments/service.ts
@@ -8,7 +8,7 @@ import {
} from './storage';
// Data access for issue attachments. File bytes live in the S3-compatible object
-// store (#shared/s3); these rows hold the metadata and the object key. publicId is
+// store (@repo/storage); these rows hold the metadata and the object key. publicId is
// the unguessable id used in the public download URL.
export interface AttachmentRow {
diff --git a/apps/api/src/modules/attachments/storage.ts b/apps/api/src/modules/attachments/storage.ts
index 4443de5c..2a51d04e 100644
--- a/apps/api/src/modules/attachments/storage.ts
+++ b/apps/api/src/modules/attachments/storage.ts
@@ -1,103 +1,37 @@
-import { createHash, randomUUID } from 'node:crypto';
+import { createHash } from 'node:crypto';
import {
- chatAttachment,
db,
- documentAsset,
- initiative,
- initiativeAttachment,
- issue,
- issueAttachment,
- project,
- projectDocument,
+ type DbExecutor,
+ getStorageSettings,
+ mimeAllowed,
+ MB,
+ projectStoredBytes,
+ projectTeamId,
+ teamStoredBytes,
} from '@repo/db';
-import { eq, sql } from 'drizzle-orm';
-import { putObject, getObject, deleteObject } from '#shared/s3';
-import { HttpError, num } from '#shared/lib';
-import { getStorageSettings, mimeAllowed, MB } from '#modules/settings/service';
+import { putObject, getObject, deleteObject } from '@repo/storage';
+import { HttpError } from '#shared/lib';
import { getLimits } from '#shared/limits';
-export type AttachmentStorageExecutor =
- typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
-
-const ATTACHMENT_QUOTA_LOCK_NAMESPACE = 1_145_390_932;
-
-async function projectStoredBytes(
- executor: AttachmentStorageExecutor,
- projectId: number,
-): Promise<number> {
- // Keep these sequential: callers commonly pass a transaction-bound executor,
- // and all four reads must observe the same post-lock snapshot/connection.
- const issues = await executor
- .select({ total: sql<string>`coalesce(sum(${issueAttachment.sizeBytes}), 0)` })
- .from(issueAttachment)
- .innerJoin(issue, eq(issue.id, issueAttachment.issueId))
- .where(eq(issue.projectId, projectId));
- const chats = await executor
- .select({ total: sql<string>`coalesce(sum(${chatAttachment.sizeBytes}), 0)` })
- .from(chatAttachment)
- .where(eq(chatAttachment.projectId, projectId));
- const documents = await executor
- .select({ total: sql<string>`coalesce(sum(${documentAsset.sizeBytes}), 0)` })
- .from(documentAsset)
- .innerJoin(projectDocument, eq(projectDocument.id, documentAsset.documentId))
- .where(eq(projectDocument.projectId, projectId));
- const initiatives = await executor
- .select({ total: sql<string>`coalesce(sum(${initiativeAttachment.sizeBytes}), 0)` })
- .from(initiativeAttachment)
- .innerJoin(initiative, eq(initiative.id, initiativeAttachment.initiativeId))
- .where(eq(initiative.projectId, projectId));
- return (
- num(issues[0]?.total ?? 0) +
- num(chats[0]?.total ?? 0) +
- num(documents[0]?.total ?? 0) +
- num(initiatives[0]?.total ?? 0)
- );
-}
-
-async function teamStoredBytes(
- executor: AttachmentStorageExecutor,
- teamId: number,
-): Promise<number> {
- const issues = await executor
- .select({ total: sql<string>`coalesce(sum(${issueAttachment.sizeBytes}), 0)` })
- .from(issueAttachment)
- .innerJoin(issue, eq(issue.id, issueAttachment.issueId))
- .innerJoin(project, eq(project.id, issue.projectId))
- .where(eq(project.teamId, teamId));
- const chats = await executor
- .select({ total: sql<string>`coalesce(sum(${chatAttachment.sizeBytes}), 0)` })
- .from(chatAttachment)
- .innerJoin(project, eq(project.id, chatAttachment.projectId))
- .where(eq(project.teamId, teamId));
- const documents = await executor
- .select({ total: sql<string>`coalesce(sum(${documentAsset.sizeBytes}), 0)` })
- .from(documentAsset)
- .innerJoin(projectDocument, eq(projectDocument.id, documentAsset.documentId))
- .innerJoin(project, eq(project.id, projectDocument.projectId))
- .where(eq(project.teamId, teamId));
- const initiatives = await executor
- .select({ total: sql<string>`coalesce(sum(${initiativeAttachment.sizeBytes}), 0)` })
- .from(initiativeAttachment)
- .innerJoin(initiative, eq(initiative.id, initiativeAttachment.initiativeId))
- .innerJoin(project, eq(project.id, initiative.projectId))
- .where(eq(project.teamId, teamId));
- return (
- num(issues[0]?.total ?? 0) +
- num(chats[0]?.total ?? 0) +
- num(documents[0]?.total ?? 0) +
- num(initiatives[0]?.total ?? 0)
- );
-}
+// Re-exported so this stays the one place every attachment-owning module (issue,
+// chat, document, initiative) imports the key/filename helpers from — the
+// functions themselves live in @repo/storage so the worker can use them too.
+export { safeAttachmentFilename, attachmentObjectKey } from '@repo/storage';
+// Same reasoning: the worker takes this same advisory lock (by the same
+// namespace constant) before it checks an imported attachment against the
+// project's quota, so the two processes actually contend on one lock rather
+// than each thinking it has exclusive access.
+export { lockAttachmentStorage } from '@repo/db';
export async function assertAttachmentStorageCapacity(
projectId: number,
addedBytes: number,
replacedBytes = 0,
- executor: AttachmentStorageExecutor = db,
+ executor: DbExecutor = db,
): Promise<void> {
const limits = await getStorageSettings();
if (limits.projectQuotaMb > 0) {
- const used = (await projectStoredBytes(executor, projectId)) - replacedBytes;
+ const used = (await projectStoredBytes(projectId, executor)) - replacedBytes;
if (used + addedBytes > limits.projectQuotaMb * MB) {
throw new HttpError(
413,
@@ -108,15 +42,11 @@ export async function assertAttachmentStorageCapacity(
// The instance quota above is per project; a team may hold a ceiling of its own
// across all of them. The team is read through the same executor: a project copy
// checks the quota of a project its own transaction has not committed yet.
- const [owner] = await executor
- .select({ teamId: project.teamId })
- .from(project)
- .where(eq(project.id, projectId));
- if (!owner) throw new HttpError(404, 'Project not found');
- const teamId = owner.teamId;
+ const teamId = await projectTeamId(projectId, executor);
+ if (teamId == null) throw new HttpError(404, 'Project not found');
const { maxStorageBytes } = await getLimits({ teamId });
if (maxStorageBytes > 0) {
- const used = (await teamStoredBytes(executor, teamId)) - replacedBytes;
+ const used = (await teamStoredBytes(teamId, executor)) - replacedBytes;
if (used + addedBytes > maxStorageBytes) {
throw new HttpError(
413,
@@ -126,15 +56,6 @@ export async function assertAttachmentStorageCapacity(
}
}
-export async function lockAttachmentStorage(
- executor: AttachmentStorageExecutor,
- projectId: number,
-): Promise<void> {
- await executor.execute(
- sql`select pg_advisory_xact_lock(${ATTACHMENT_QUOTA_LOCK_NAMESPACE}, ${projectId})`,
- );
-}
-
export async function assertAttachmentUploadAllowed(
projectId: number,
size: number,
@@ -158,32 +79,6 @@ export async function assertAttachmentFileAllowed(
}
}
-export function safeAttachmentFilename(input: string, fallback = 'file'): string {
- const basename = input.split(/[\\/]/).pop() ?? '';
- const printable = [...basename]
- .map((character) => {
- const code = character.charCodeAt(0);
- return code < 32 || code === 127 ? '_' : character;
- })
- .join('')
- .trim();
- const filename = printable.slice(-255);
- return filename && filename !== '.' && filename !== '..' ? filename : fallback;
-}
-
-export function attachmentObjectKey(
- projectId: number,
- namespace: 'attachments' | 'chat' | 'documents' | 'initiatives',
- ownerId: number | null,
- filename: string,
-): string {
- const safeName = safeAttachmentFilename(filename)
- .replace(/[^\w.-]+/g, '_')
- .slice(-100);
- const ownerPath = ownerId === null ? '' : `${ownerId}/`;
- return `projects/${projectId}/${namespace}/${ownerPath}${randomUUID()}-${safeName}`;
-}
-
export async function storeAttachmentObject(
key: string,
bytes: Buffer,
diff --git a/apps/api/src/modules/avatars/service.ts b/apps/api/src/modules/avatars/service.ts
index 24d27d95..2ae0e4bb 100644
--- a/apps/api/src/modules/avatars/service.ts
+++ b/apps/api/src/modules/avatars/service.ts
@@ -1,9 +1,8 @@
-import { db, user } from '@repo/db';
+import { db, user, getStorageSettings, MB } from '@repo/db';
import { eq } from 'drizzle-orm';
import { randomUUID } from 'node:crypto';
import { HttpError } from '#shared/lib';
-import { putObject, getObject, deleteObject } from '#shared/s3';
-import { getStorageSettings, MB } from '#modules/settings/service';
+import { putObject, getObject, deleteObject } from '@repo/storage';
// Avatar images for the signed-in user. The bytes live in the S3-compatible
// object store under `avatars/<uuid>`; the user's `image` column (managed by
diff --git a/apps/api/src/modules/chat-attachments/index.ts b/apps/api/src/modules/chat-attachments/index.ts
index e184a95d..08fb2ad5 100644
--- a/apps/api/src/modules/chat-attachments/index.ts
+++ b/apps/api/src/modules/chat-attachments/index.ts
@@ -2,7 +2,7 @@ import { Elysia } from 'elysia';
import { authContext } from '#shared/auth-context';
import { guards, entityGuard } from '#shared/guards';
import { HttpError } from '#shared/lib';
-import { getObject } from '#shared/s3';
+import { getObject } from '@repo/storage';
import { mcpTool } from '#mcp/generate';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { requireUser } from '#shared/access';
diff --git a/apps/api/src/modules/chat-attachments/service.ts b/apps/api/src/modules/chat-attachments/service.ts
index be86be12..730e07b8 100644
--- a/apps/api/src/modules/chat-attachments/service.ts
+++ b/apps/api/src/modules/chat-attachments/service.ts
@@ -1,7 +1,7 @@
import { db, chatAttachment } from '@repo/db';
import { eq, sql } from 'drizzle-orm';
import { HttpError, iso, num } from '#shared/lib';
-import { getObject } from '#shared/s3';
+import { getObject } from '@repo/storage';
import { isTableFilename, parseImportFile } from './parse';
import {
assertAttachmentStorageCapacity,
@@ -9,7 +9,7 @@ import {
} from '#modules/attachments/storage';
// Data access for chat attachments. File bytes live in the S3-compatible object
-// store (#shared/s3); these rows hold the metadata and the object key. publicId is
+// store (@repo/storage); these rows hold the metadata and the object key. publicId is
// the unguessable id used in the public download URL and in the marker a chat
// message carries for an attached file.
diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.ts
index ad0e7995..eadd989b 100644
--- a/apps/api/src/modules/god/index.ts
+++ b/apps/api/src/modules/god/index.ts
@@ -17,7 +17,7 @@ import {
setScimSettings,
rotateScimToken,
} from '@repo/auth';
-import { hasConfiguredEmailProvider } from '@repo/db';
+import { hasConfiguredEmailProvider, getStorageSettings } from '@repo/db';
import { emailBody, hasEmailProvider, sendEmail } from '@repo/mailer';
import { authContext } from '#shared/auth-context';
import { requireGod } from '#shared/access';
@@ -80,7 +80,6 @@ import { emailTestError } from './email-test';
import { getInstanceBotSettings, setInstanceBotSettings } from '#modules/telegram/service';
import { SCIM_BASE_URL } from '#modules/scim/resource';
import {
- getStorageSettings,
setStorageSettings,
getHotkeySettings,
setHotkeySettings,
diff --git a/apps/api/src/modules/import-export/__tests__/integration/import-export.test.ts b/apps/api/src/modules/import-export/__tests__/integration/import-export.test.ts
new file mode 100644
index 00000000..f39a7ee1
--- /dev/null
+++ b/apps/api/src/modules/import-export/__tests__/integration/import-export.test.ts
@@ -0,0 +1,420 @@
+import { describe, it, expect, beforeEach } from 'bun:test';
+import { db, importJob } from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { authedApi } from '#tests/helpers/app';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { createRole } from '#tests/helpers/roles';
+
+type Client = ReturnType<typeof authedApi>;
+
+async function setupOwnerProject(): Promise<{ api: Client; userId: string }> {
+ const owner = await signUpTestUser();
+ const api = authedApi(owner.cookie);
+ await api.projects.post({ key: 'MKT', name: 'Marketing' });
+ return { api, userId: owner.userId };
+}
+
+// Adds a member to project MKT through the invite flow, optionally on a custom role.
+async function addMember(owner: Client, opts: { roleId?: number } = {}): Promise<Client> {
+ const user = await signUpTestUser();
+ const invite = await owner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email: user.email, role: 'member' });
+ const api = authedApi(user.cookie);
+ await api.invites({ token: invite.data!.token }).accept.post();
+ if (opts.roleId != null) {
+ await owner
+ .projects({ projectKey: 'MKT' })
+ .members({ userId: user.userId })
+ .patch({ role: 'member', roleId: opts.roleId });
+ }
+ return api;
+}
+
+function jobs(api: Client) {
+ return api.projects({ projectKey: 'MKT' })['import-jobs'];
+}
+
+function entity(api: Client, id: number) {
+ return api['import-jobs']({ id });
+}
+
+const validBody = {
+ baseUrl: 'https://plane.example.com',
+ workspaceSlug: 'acme',
+ apiToken: 'plane_api_token_123',
+ planeProjectId: 'db95831f-b1ff-49e1-91c1-df28cd99bc41',
+ planeProjectKey: 'ROOMS',
+};
+
+const zeroCounts = { discovered: 0, created: 0 };
+const zeroedCounts = {
+ issue: zeroCounts,
+ comment: zeroCounts,
+ label: zeroCounts,
+ state: zeroCounts,
+ cycle: zeroCounts,
+ attachment: zeroCounts,
+};
+
+describe('import jobs', () => {
+ beforeEach(async () => {
+ await resetDb();
+ });
+
+ describe('create', () => {
+ it('creates a pending job and never returns the credential', async () => {
+ const { api } = await setupOwnerProject();
+
+ const res = await jobs(api).post(validBody);
+ expect(res.status).toBe(201);
+ expect(res.data).toMatchObject({
+ source: 'plane',
+ phase: 'discover',
+ status: 'pending',
+ counts: zeroedCounts,
+ lastError: null,
+ });
+ expect(typeof res.data?.id).toBe('number');
+ expect(res.data).not.toHaveProperty('baseUrl');
+ expect(res.data).not.toHaveProperty('apiToken');
+ expect(res.data).not.toHaveProperty('config');
+ expect(res.data).not.toHaveProperty('credentialCiphertext');
+ });
+
+ it('defaults unmatchedUserPolicy and accepts stateOverrides', async () => {
+ const { api } = await setupOwnerProject();
+
+ const res = await jobs(api).post({
+ ...validBody,
+ unmatchedUserPolicy: 'skip',
+ stateOverrides: { 'plane-state-1': 'started' },
+ });
+ expect(res.status).toBe(201);
+ expect(res.data?.status).toBe('pending');
+ });
+
+ it('rejects a missing required field', async () => {
+ const { api } = await setupOwnerProject();
+ const { baseUrl: _baseUrl, ...withoutBaseUrl } = validBody;
+ const res = await jobs(api).post(withoutBaseUrl as never);
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a missing planeProjectKey', async () => {
+ const { api } = await setupOwnerProject();
+ const { planeProjectKey: _planeProjectKey, ...withoutKey } = validBody;
+ const res = await jobs(api).post(withoutKey as never);
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects an empty required field', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api).post({ ...validBody, workspaceSlug: '' });
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a malformed baseUrl', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api).post({ ...validBody, baseUrl: 'not a url' });
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects an unknown unmatchedUserPolicy value', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api).post({ ...validBody, unmatchedUserPolicy: 'bogus' as never });
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects an unknown stateOverrides category', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api).post({
+ ...validBody,
+ stateOverrides: { 'plane-state-1': 'bogus' as never },
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe('list', () => {
+ it("lists a project's import jobs, newest first", async () => {
+ const { api } = await setupOwnerProject();
+ const first = (await jobs(api).post(validBody)).data!;
+ const second = (await jobs(api).post({ ...validBody, planeProjectId: 'other-project' }))
+ .data!;
+
+ const res = await jobs(api).get();
+ expect(res.status).toBe(200);
+ expect(res.data?.map((j) => j.id)).toEqual([second.id, first.id]);
+ });
+
+ it('returns an empty list for a project with no import jobs', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api).get();
+ expect(res.status).toBe(200);
+ expect(res.data).toEqual([]);
+ });
+ });
+
+ describe('get status', () => {
+ it('returns the status and progress counts of a job', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+
+ const res = await entity(api, created.id).get();
+ expect(res.status).toBe(200);
+ expect(res.data).toMatchObject({
+ id: created.id,
+ phase: 'discover',
+ status: 'pending',
+ counts: zeroedCounts,
+ });
+ });
+
+ it('returns 404 for an unknown job id', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await entity(api, 999999).get();
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('pause, resume, cancel', () => {
+ it('pauses a pending job and resumes it', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+
+ const paused = await entity(api, created.id).pause.post();
+ expect(paused.status).toBe(200);
+ expect(paused.data?.status).toBe('paused');
+
+ const resumed = await entity(api, created.id).resume.post();
+ expect(resumed.status).toBe(200);
+ expect(resumed.data?.status).toBe('pending');
+ });
+
+ it('preserves a real retry cooldown across pause and resume', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+ const futureRetry = new Date(Date.now() + 59_000);
+ await db
+ .update(importJob)
+ .set({ lastError: 'rate limited', nextAttemptAt: futureRetry })
+ .where(eq(importJob.id, created.id));
+
+ await entity(api, created.id).pause.post();
+ const resumed = await entity(api, created.id).resume.post();
+
+ expect(resumed.status).toBe(200);
+ expect(resumed.data?.status).toBe('pending');
+ expect(new Date(resumed.data!.nextAttemptAt).getTime()).toBe(futureRetry.getTime());
+ });
+
+ it('resumes immediately when the stored cooldown already elapsed', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+ await db
+ .update(importJob)
+ .set({ lastError: 'rate limited', nextAttemptAt: new Date(Date.now() - 1000) })
+ .where(eq(importJob.id, created.id));
+
+ await entity(api, created.id).pause.post();
+ const before = Date.now();
+ const resumed = await entity(api, created.id).resume.post();
+
+ expect(resumed.status).toBe(200);
+ expect(new Date(resumed.data!.nextAttemptAt).getTime()).toBeGreaterThanOrEqual(before);
+ });
+
+ it('rejects pausing an already-paused job', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+ await entity(api, created.id).pause.post();
+
+ const res = await entity(api, created.id).pause.post();
+ expect(res.status).toBe(409);
+ });
+
+ it('rejects resuming a job that is not paused', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+
+ const res = await entity(api, created.id).resume.post();
+ expect(res.status).toBe(409);
+ });
+
+ it('cancels a pending job', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+
+ const res = await entity(api, created.id).cancel.post();
+ expect(res.status).toBe(200);
+ expect(res.data).toMatchObject({ status: 'failed', lastError: 'Canceled' });
+ });
+
+ it('rejects canceling an already-canceled (failed) job', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+ await entity(api, created.id).cancel.post();
+
+ const res = await entity(api, created.id).cancel.post();
+ expect(res.status).toBe(409);
+ });
+
+ it('returns 404 pausing, resuming, or canceling an unknown job', async () => {
+ const { api } = await setupOwnerProject();
+ expect((await entity(api, 999999).pause.post()).status).toBe(404);
+ expect((await entity(api, 999999).resume.post()).status).toBe(404);
+ expect((await entity(api, 999999).cancel.post()).status).toBe(404);
+ });
+ });
+
+ describe('test connection', () => {
+ it('rejects a missing required field', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api)['test-connection'].post({
+ baseUrl: validBody.baseUrl,
+ workspaceSlug: validBody.workspaceSlug,
+ } as never);
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a base URL the SSRF guard refuses', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api)['test-connection'].post({
+ baseUrl: 'http://localhost:9999',
+ workspaceSlug: validBody.workspaceSlug,
+ apiToken: validBody.apiToken,
+ });
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe('plane preview', () => {
+ it('rejects a missing required field', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api)['plane-preview'].post({
+ baseUrl: validBody.baseUrl,
+ workspaceSlug: validBody.workspaceSlug,
+ apiToken: validBody.apiToken,
+ } as never);
+ expect(res.status).toBe(400);
+ });
+
+ it('rejects a base URL the SSRF guard refuses', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api)['plane-preview'].post({
+ baseUrl: 'http://localhost:9999',
+ workspaceSlug: validBody.workspaceSlug,
+ apiToken: validBody.apiToken,
+ planeProjectId: validBody.planeProjectId,
+ });
+ expect(res.status).toBe(400);
+ });
+
+ it('denies a member whose role lacks the import_export permission', async () => {
+ const { api } = await setupOwnerProject();
+ const member = await addMember(api);
+ const res = await jobs(member)['plane-preview'].post({
+ baseUrl: validBody.baseUrl,
+ workspaceSlug: validBody.workspaceSlug,
+ apiToken: validBody.apiToken,
+ planeProjectId: validBody.planeProjectId,
+ });
+ expect(res.status).toBe(403);
+ });
+ });
+
+ describe('access', () => {
+ it('returns 404 for an unknown project', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await api.projects({ projectKey: 'NOPE' })['import-jobs'].get();
+ expect(res.status).toBe(404);
+ });
+
+ it('denies a non-member on project-scoped and entity routes', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+ const outsider = authedApi((await signUpTestUser()).cookie);
+
+ expect((await jobs(outsider).get()).status).toBe(403);
+ expect((await jobs(outsider).post(validBody)).status).toBe(403);
+ expect((await entity(outsider, created.id).get()).status).toBe(403);
+ expect((await entity(outsider, created.id).pause.post()).status).toBe(403);
+ });
+
+ it('denies a member whose role lacks the import_export permission', async () => {
+ const { api } = await setupOwnerProject();
+ const created = (await jobs(api).post(validBody)).data!;
+ const member = await addMember(api);
+
+ expect((await jobs(member).get()).status).toBe(403);
+ expect((await jobs(member).post(validBody)).status).toBe(403);
+ expect((await entity(member, created.id).get()).status).toBe(403);
+ expect((await entity(member, created.id).pause.post()).status).toBe(403);
+ });
+
+ it('allows a member whose role grants the import_export permission', async () => {
+ const { api } = await setupOwnerProject();
+ const role = await createRole(api, 'MKT', {
+ name: 'Importer',
+ permissions: { import_export: { create: true, read: true, edit: true } },
+ });
+ const member = await addMember(api, { roleId: role.data!.id });
+
+ const created = await jobs(member).post(validBody);
+ expect(created.status).toBe(201);
+
+ const list = await jobs(member).get();
+ expect(list.status).toBe(200);
+
+ const paused = await entity(member, created.data!.id).pause.post();
+ expect(paused.status).toBe(200);
+ });
+
+ it('always allows the project owner, regardless of role', async () => {
+ const { api } = await setupOwnerProject();
+ const res = await jobs(api).post(validBody);
+ expect(res.status).toBe(201);
+ });
+ });
+
+ describe('export', () => {
+ it("exports the project's states, labels, cycles, and an issue with a comment", async () => {
+ const { api } = await setupOwnerProject();
+ const view = await api.projects({ projectKey: 'MKT' }).get();
+ const columnId = view.data!.columns[0]!.id;
+
+ const label = (
+ await api.projects({ projectKey: 'MKT' }).labels.post({ name: 'bug', color: '#ff0000' })
+ ).data!;
+ const issue = (
+ await api
+ .projects({ projectKey: 'MKT' })
+ .issues.post({ columnId, title: 'Fix the thing', labelIds: [label.id] })
+ ).data!;
+ await api.issues({ issueId: issue.id }).comments.post({ body: 'looking into it' });
+
+ const res = await jobs(api).export.get();
+ expect(res.status).toBe(200);
+ expect(res.data?.project.key).toBe('MKT');
+ expect(res.data?.labels).toContainEqual({ name: 'bug', color: '#ff0000' });
+
+ const exportedIssue = res.data?.issues.find(
+ (i) => i.identifier === `MKT-${issue.sequenceNumber}`,
+ );
+ expect(exportedIssue).toMatchObject({
+ title: 'Fix the thing',
+ labels: ['bug'],
+ });
+ expect(exportedIssue?.comments).toMatchObject([{ body: 'looking into it' }]);
+ });
+
+ it('denies a member whose role lacks the import_export permission', async () => {
+ const { api } = await setupOwnerProject();
+ const member = await addMember(api);
+ const res = await jobs(member).export.get();
+ expect(res.status).toBe(403);
+ });
+ });
+});
diff --git a/apps/api/src/modules/import-export/export.ts b/apps/api/src/modules/import-export/export.ts
new file mode 100644
index 00000000..39148e4a
--- /dev/null
+++ b/apps/api/src/modules/import-export/export.ts
@@ -0,0 +1,232 @@
+import {
+ db,
+ project,
+ projectColumn,
+ label,
+ cycle,
+ issue,
+ issueLabel,
+ issueActivity,
+ issueLink,
+ user,
+} from '@repo/db';
+import { eq, and, inArray } from 'drizzle-orm';
+import { HttpError } from '#shared/lib';
+
+// A project's own data, read directly (no import_job involved) and shaped into a
+// self-contained, human-readable snapshot: states/cycles/parents/relations are named,
+// not id-referenced, and issues carry their own identifier ("MKT-42") rather than a
+// database id, so the file reads sensibly opened on its own. No write-back target
+// exists yet — this is a download, not round-tripping into anything.
+
+export interface ExportedComment {
+ authorName: string | null;
+ authorEmail: string | null;
+ body: string;
+ createdAt: string;
+ replyToIndex: number | null;
+}
+
+export interface ExportedRelation {
+ kind: string;
+ targetIdentifier: string;
+}
+
+export interface ExportedIssue {
+ identifier: string;
+ title: string;
+ description: string;
+ state: string;
+ labels: string[];
+ cycle: string | null;
+ priority: string | null;
+ startDate: string | null;
+ dueDate: string | null;
+ parentIdentifier: string | null;
+ assigneeEmail: string | null;
+ comments: ExportedComment[];
+ relations: ExportedRelation[];
+}
+
+export interface ProjectExport {
+ exportedAt: string;
+ project: { key: string; name: string; description: string };
+ states: { name: string; category: string }[];
+ labels: { name: string; color: string }[];
+ cycles: { name: string; startDate: string; endDate: string; goal: string }[];
+ issues: ExportedIssue[];
+}
+
+export async function exportProject(projectId: number): Promise<ProjectExport> {
+ const [projectRow] = await db
+ .select({ key: project.key, name: project.name, description: project.description })
+ .from(project)
+ .where(eq(project.id, projectId));
+ if (!projectRow) throw new HttpError(404, 'Project not found');
+
+ const columns = await db
+ .select({ id: projectColumn.id, name: projectColumn.name, category: projectColumn.stateType })
+ .from(projectColumn)
+ .where(eq(projectColumn.projectId, projectId));
+ const columnNameById = new Map(columns.map((c) => [c.id, c.name]));
+
+ const labelRows = await db
+ .select({ id: label.id, name: label.name, color: label.color })
+ .from(label)
+ .where(eq(label.projectId, projectId));
+ const labelNameById = new Map(labelRows.map((l) => [l.id, l.name]));
+
+ const cycleRows = await db
+ .select({
+ id: cycle.id,
+ name: cycle.name,
+ startDate: cycle.startDate,
+ endDate: cycle.endDate,
+ goal: cycle.goal,
+ })
+ .from(cycle)
+ .where(eq(cycle.projectId, projectId));
+ const cycleNameById = new Map(cycleRows.map((c) => [c.id, c.name]));
+
+ const issueRows = await db
+ .select({
+ id: issue.id,
+ sequenceNumber: issue.sequenceNumber,
+ title: issue.title,
+ description: issue.description,
+ columnId: issue.columnId,
+ cycleId: issue.cycleId,
+ parentId: issue.parentId,
+ assigneeUserId: issue.assigneeUserId,
+ priority: issue.priority,
+ startDate: issue.startDate,
+ dueDate: issue.dueDate,
+ })
+ .from(issue)
+ .where(eq(issue.projectId, projectId))
+ .orderBy(issue.sequenceNumber);
+ const identifierByIssueId = new Map(
+ issueRows.map((i) => [i.id, `${projectRow.key}-${i.sequenceNumber}`]),
+ );
+ const issueIds = issueRows.map((i) => i.id);
+
+ const labelLinks = issueIds.length
+ ? await db
+ .select({ issueId: issueLabel.issueId, labelId: issueLabel.labelId })
+ .from(issueLabel)
+ .where(inArray(issueLabel.issueId, issueIds))
+ : [];
+ const labelsByIssueId = new Map<number, string[]>();
+ for (const link of labelLinks) {
+ const name = labelNameById.get(link.labelId);
+ if (!name) continue;
+ const names = labelsByIssueId.get(link.issueId);
+ if (names) names.push(name);
+ else labelsByIssueId.set(link.issueId, [name]);
+ }
+
+ const comments = issueIds.length
+ ? await db
+ .select({
+ id: issueActivity.id,
+ issueId: issueActivity.issueId,
+ actorName: issueActivity.actorName,
+ actorUserId: issueActivity.actorUserId,
+ body: issueActivity.body,
+ createdAt: issueActivity.createdAt,
+ replyToId: issueActivity.replyToId,
+ })
+ .from(issueActivity)
+ .where(and(inArray(issueActivity.issueId, issueIds), eq(issueActivity.kind, 'comment')))
+ .orderBy(issueActivity.createdAt)
+ : [];
+
+ const relations = issueIds.length
+ ? await db
+ .select({
+ sourceIssueId: issueLink.sourceIssueId,
+ targetIssueId: issueLink.targetIssueId,
+ kind: issueLink.kind,
+ })
+ .from(issueLink)
+ .where(inArray(issueLink.sourceIssueId, issueIds))
+ : [];
+ const relationsBySourceId = new Map<number, typeof relations>();
+ for (const relation of relations) {
+ const forIssue = relationsBySourceId.get(relation.sourceIssueId);
+ if (forIssue) forIssue.push(relation);
+ else relationsBySourceId.set(relation.sourceIssueId, [relation]);
+ }
+
+ const userIds = [
+ ...new Set(
+ [...issueRows.map((i) => i.assigneeUserId), ...comments.map((c) => c.actorUserId)].filter(
+ (id): id is string => id != null,
+ ),
+ ),
+ ];
+ const emailByUserId = userIds.length
+ ? new Map(
+ (
+ await db
+ .select({ id: user.id, email: user.email })
+ .from(user)
+ .where(inArray(user.id, userIds))
+ ).map((u) => [u.id, u.email]),
+ )
+ : new Map<string, string>();
+
+ const commentsByIssueId = new Map<number, typeof comments>();
+ for (const comment of comments) {
+ // issue_activity.issue_id is nullable in general (an activity can belong to an
+ // initiative instead), but every row here was matched by inArray(..., issueIds).
+ const issueId = comment.issueId!;
+ const forIssue = commentsByIssueId.get(issueId);
+ if (forIssue) forIssue.push(comment);
+ else commentsByIssueId.set(issueId, [comment]);
+ }
+
+ const issues: ExportedIssue[] = issueRows.map((row) => {
+ const issueComments = commentsByIssueId.get(row.id) ?? [];
+ const commentIndexById = new Map(issueComments.map((c, index) => [c.id, index]));
+ return {
+ identifier: identifierByIssueId.get(row.id)!,
+ title: row.title,
+ description: row.description,
+ state: columnNameById.get(row.columnId) ?? '',
+ labels: labelsByIssueId.get(row.id) ?? [],
+ cycle: row.cycleId != null ? (cycleNameById.get(row.cycleId) ?? null) : null,
+ priority: row.priority,
+ startDate: row.startDate,
+ dueDate: row.dueDate,
+ parentIdentifier:
+ row.parentId != null ? (identifierByIssueId.get(row.parentId) ?? null) : null,
+ assigneeEmail:
+ row.assigneeUserId != null ? (emailByUserId.get(row.assigneeUserId) ?? null) : null,
+ comments: issueComments.map((c) => ({
+ authorName: c.actorName,
+ authorEmail: c.actorUserId != null ? (emailByUserId.get(c.actorUserId) ?? null) : null,
+ body: c.body ?? '',
+ createdAt: c.createdAt.toISOString(),
+ replyToIndex: c.replyToId != null ? (commentIndexById.get(c.replyToId) ?? null) : null,
+ })),
+ relations: (relationsBySourceId.get(row.id) ?? [])
+ .map((r) => ({ kind: r.kind, targetIdentifier: identifierByIssueId.get(r.targetIssueId) }))
+ .filter((r): r is ExportedRelation => r.targetIdentifier != null),
+ };
+ });
+
+ return {
+ exportedAt: new Date().toISOString(),
+ project: projectRow,
+ states: columns.map((c) => ({ name: c.name, category: c.category })),
+ labels: labelRows.map((l) => ({ name: l.name, color: l.color })),
+ cycles: cycleRows.map((c) => ({
+ name: c.name,
+ startDate: c.startDate,
+ endDate: c.endDate,
+ goal: c.goal,
+ })),
+ issues,
+ };
+}
diff --git a/apps/api/src/modules/import-export/index.ts b/apps/api/src/modules/import-export/index.ts
new file mode 100644
index 00000000..292ea853
--- /dev/null
+++ b/apps/api/src/modules/import-export/index.ts
@@ -0,0 +1,158 @@
+import { Elysia, t } from 'elysia';
+import { authContext } from '#shared/auth-context';
+import { guards, entityGuard, assertMcpAllowed, requiresPermission } from '#shared/guards';
+import { assertPermission, requireUser } from '#shared/access';
+import { HttpError } from '#shared/lib';
+import { accessErrors, commonErrors, errors } from '#shared/responses';
+import {
+ ImportJobResponse,
+ TestConnectionResponse,
+ PlanePreviewResponse,
+ ProjectExportResponse,
+ createImportJobBody,
+ importJobParams,
+ testConnectionBody,
+ planePreviewBody,
+} from './model';
+import {
+ cancelImportJob,
+ createImportJob,
+ getImportJobDto,
+ getImportJobProjectId,
+ listImportJobs,
+ pauseImportJob,
+ resumeImportJob,
+ testPlaneConnection,
+ testPlaneStatesPreview,
+} from './service';
+import { exportProject } from './export';
+
+// Import jobs bring issues from an external tracker into a project. Creating one
+// stores an encrypted credential and leaves it 'pending' for the worker
+// (apps/worker/src/import-worker.ts) to drive through its phases; this module never
+// touches the worker's queue directly, only the import_job/import_record rows it reads
+// and writes too.
+
+export const importExportRoutes = new Elysia({
+ name: 'import-export',
+ detail: { tags: ['Import/Export'] },
+})
+ .use(authContext)
+ .use(guards)
+ .macro({
+ importJobEntity: entityGuard('import_export', 'Import job not found', (p) =>
+ getImportJobProjectId(Number(p.id)),
+ ),
+ })
+
+ .post(
+ '/projects/:projectKey/import-jobs/test-connection',
+ ({ body }) => testPlaneConnection(body.baseUrl, body.workspaceSlug, body.apiToken),
+ {
+ permission: ['import_export', 'create'],
+ body: testConnectionBody,
+ response: { 200: TestConnectionResponse, ...commonErrors, ...errors(502) },
+ detail: {
+ summary: 'Test a Plane connection',
+ description:
+ 'Validate a base URL, workspace slug, and API token against the source live, without ' +
+ 'storing anything. Returns the projects of the workspace to pick a source project from.',
+ },
+ },
+ )
+
+ .post(
+ '/projects/:projectKey/import-jobs/plane-preview',
+ ({ body }) =>
+ testPlaneStatesPreview(body.baseUrl, body.workspaceSlug, body.apiToken, body.planeProjectId),
+ {
+ permission: ['import_export', 'create'],
+ body: planePreviewBody,
+ response: { 200: PlanePreviewResponse, ...commonErrors, ...errors(502) },
+ detail: {
+ summary: 'Preview a Plane project before importing it',
+ description:
+ "Fetch the source project's states, each with the category itsaplan would " +
+ 'automatically map it to, for review before a job is created.',
+ },
+ },
+ )
+
+ .get('/projects/:projectKey/import-jobs/export', ({ project }) => exportProject(project.id), {
+ permission: ['import_export', 'create'],
+ response: { 200: ProjectExportResponse, ...accessErrors },
+ detail: {
+ summary: "Export a project's data",
+ description:
+ "A self-contained snapshot of the project's states, labels, cycles, and issues " +
+ '(with their comments and relations), as portable JSON. Not a live sync to any ' +
+ 'target — a download.',
+ },
+ })
+
+ .post(
+ '/projects/:projectKey/import-jobs',
+ ({ project, body, user, set }) => {
+ set.status = 201;
+ return createImportJob(project.id, requireUser(user).id, body);
+ },
+ {
+ permission: ['import_export', 'create'],
+ body: createImportJobBody,
+ response: { 201: ImportJobResponse, ...commonErrors },
+ detail: {
+ summary: 'Create a Plane import job',
+ description:
+ "Encrypt and store the submitted credential and leave the job 'pending' for the worker.",
+ },
+ },
+ )
+
+ .get('/projects/:projectKey/import-jobs', ({ project }) => listImportJobs(project.id), {
+ permission: ['import_export', 'read'],
+ response: { 200: t.Array(ImportJobResponse), ...accessErrors },
+ detail: { summary: "List a project's import jobs" },
+ })
+
+ // Fetches the row itself and asserts on it, like GET /issues/:issueId — the entity
+ // guard would resolve the project id with a second query this handler doesn't need.
+ .get(
+ '/import-jobs/:id',
+ async ({ params, user, request }) => {
+ const job = await getImportJobDto(params.id);
+ if (!job) throw new HttpError(404, 'Import job not found');
+ await assertPermission(job.projectId, user, 'import_export', 'read');
+ await assertMcpAllowed(job.projectId, request.headers);
+ return job;
+ },
+ {
+ params: importJobParams,
+ response: { 200: ImportJobResponse, ...commonErrors },
+ detail: {
+ summary: 'Get an import job',
+ description: 'Get the status and per-entity progress counts of an import job.',
+ ...requiresPermission(['import_export', 'read']),
+ },
+ },
+ )
+
+ .post('/import-jobs/:id/pause', ({ params }) => pauseImportJob(params.id), {
+ params: importJobParams,
+ importJobEntity: 'edit',
+ response: { 200: ImportJobResponse, ...accessErrors, ...errors(409) },
+ detail: { summary: 'Pause an import job' },
+ })
+
+ .post('/import-jobs/:id/resume', ({ params }) => resumeImportJob(params.id), {
+ params: importJobParams,
+ importJobEntity: 'edit',
+ response: { 200: ImportJobResponse, ...accessErrors, ...errors(409) },
+ detail: { summary: 'Resume a paused import job' },
+ })
+
+ .post('/import-jobs/:id/cancel', ({ params }) => cancelImportJob(params.id), {
+ params: importJobParams,
+ importJobEntity: 'edit',
+ response: { 200: ImportJobResponse, ...accessErrors, ...errors(409) },
+ detail: { summary: 'Cancel an import job' },
+ });
diff --git a/apps/api/src/modules/import-export/model.ts b/apps/api/src/modules/import-export/model.ts
new file mode 100644
index 00000000..9e7812e3
--- /dev/null
+++ b/apps/api/src/modules/import-export/model.ts
@@ -0,0 +1,114 @@
+import { t } from 'elysia';
+
+export const importJobParams = t.Object({ id: t.Numeric() });
+
+const stateCategory = t.UnionEnum(['backlog', 'unstarted', 'started', 'completed', 'canceled']);
+
+// The fields Plane needs to reach the source project, plus the mapping choices made
+// at creation time.
+export const createImportJobBody = t.Object({
+ baseUrl: t.String({ minLength: 1, description: 'Origin of the source Plane instance.' }),
+ workspaceSlug: t.String({ minLength: 1 }),
+ apiToken: t.String({ minLength: 1, description: 'Plane workspace or personal API key.' }),
+ planeProjectId: t.String({ minLength: 1, description: 'The Plane project id to import from.' }),
+ planeProjectKey: t.String({
+ minLength: 1,
+ description:
+ 'The Plane project\'s own short identifier (e.g. "ROOMS"), used to recognize and ' +
+ 'rewrite cross-references like "ROOMS-524" in imported text.',
+ }),
+ unmatchedUserPolicy: t.Optional(
+ t.UnionEnum(['unassigned', 'skip'], {
+ description:
+ 'How to handle an assignee or comment author with no matching project member by email. ' +
+ "'unassigned' (default) leaves the field empty; 'skip' drops the assignment or comment.",
+ }),
+ ),
+ stateOverrides: t.Optional(
+ t.Record(t.String(), stateCategory, {
+ description: 'Plane state id -> itsaplan state category, overriding the automatic mapping.',
+ }),
+ ),
+});
+
+export const testConnectionBody = t.Object({
+ baseUrl: t.String({ minLength: 1 }),
+ workspaceSlug: t.String({ minLength: 1 }),
+ apiToken: t.String({ minLength: 1 }),
+});
+
+export const TestConnectionResponse = t.Object({
+ projects: t.Array(t.Object({ id: t.String(), name: t.String(), identifier: t.String() })),
+});
+
+export const planePreviewBody = t.Object({
+ baseUrl: t.String({ minLength: 1 }),
+ workspaceSlug: t.String({ minLength: 1 }),
+ apiToken: t.String({ minLength: 1 }),
+ planeProjectId: t.String({ minLength: 1 }),
+});
+
+export const PlanePreviewResponse = t.Object({
+ states: t.Array(t.Object({ id: t.String(), name: t.String(), category: stateCategory })),
+});
+
+// Mirrors import_record_source_entity_type_check in packages/db/src/schema/app.ts.
+const entityCount = t.Object({ discovered: t.Number(), created: t.Number() });
+const CountsResponse = t.Object({
+ issue: entityCount,
+ comment: entityCount,
+ label: entityCount,
+ state: entityCount,
+ cycle: entityCount,
+ attachment: entityCount,
+});
+
+const ExportedComment = t.Object({
+ authorName: t.Nullable(t.String()),
+ authorEmail: t.Nullable(t.String()),
+ body: t.String(),
+ createdAt: t.String(),
+ replyToIndex: t.Nullable(t.Number()),
+});
+
+const ExportedRelation = t.Object({ kind: t.String(), targetIdentifier: t.String() });
+
+const ExportedIssue = t.Object({
+ identifier: t.String(),
+ title: t.String(),
+ description: t.String(),
+ state: t.String(),
+ labels: t.Array(t.String()),
+ cycle: t.Nullable(t.String()),
+ priority: t.Nullable(t.String()),
+ startDate: t.Nullable(t.String()),
+ dueDate: t.Nullable(t.String()),
+ parentIdentifier: t.Nullable(t.String()),
+ assigneeEmail: t.Nullable(t.String()),
+ comments: t.Array(ExportedComment),
+ relations: t.Array(ExportedRelation),
+});
+
+export const ProjectExportResponse = t.Object({
+ exportedAt: t.String(),
+ project: t.Object({ key: t.String(), name: t.String(), description: t.String() }),
+ states: t.Array(t.Object({ name: t.String(), category: t.String() })),
+ labels: t.Array(t.Object({ name: t.String(), color: t.String() })),
+ cycles: t.Array(
+ t.Object({ name: t.String(), startDate: t.String(), endDate: t.String(), goal: t.String() }),
+ ),
+ issues: t.Array(ExportedIssue),
+});
+
+export const ImportJobResponse = t.Object({
+ id: t.Number(),
+ projectId: t.Number(),
+ source: t.Literal('plane'),
+ phase: t.UnionEnum(['discover', 'create', 'link', 'rewrite', 'attachments', 'done']),
+ status: t.UnionEnum(['pending', 'running', 'paused', 'completed', 'failed']),
+ counts: CountsResponse,
+ lastError: t.Nullable(t.String()),
+ nextAttemptAt: t.String(),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+});
diff --git a/apps/api/src/modules/import-export/service.ts b/apps/api/src/modules/import-export/service.ts
new file mode 100644
index 00000000..eef176ac
--- /dev/null
+++ b/apps/api/src/modules/import-export/service.ts
@@ -0,0 +1,361 @@
+import { db, importJob, importRecord } from '@repo/db';
+import { desc, eq, sql } from 'drizzle-orm';
+import { encryptSecret } from '@repo/crypto';
+import { HttpError, iso } from '#shared/lib';
+import { pinnedFetch } from '#shared/net';
+
+// Data access and the Plane connection check for import jobs. Creating a job only
+// encrypts and stores the submitted credential and leaves the row 'pending' for the
+// worker (apps/worker/src/import-worker.ts) to pick up and drive through its phases —
+// this module never talks to the worker or reads the credential back. Progress is
+// read from import_record, the worker's own source-id-to-local-id mapping table.
+
+// Mirrors import_record_source_entity_type_check in packages/db/src/schema/app.ts.
+export const IMPORT_ENTITY_TYPES = [
+ 'issue',
+ 'comment',
+ 'label',
+ 'state',
+ 'cycle',
+ 'attachment',
+] as const;
+export type ImportEntityType = (typeof IMPORT_ENTITY_TYPES)[number];
+
+export type ImportJobPhase = 'discover' | 'create' | 'link' | 'rewrite' | 'attachments' | 'done';
+export type ImportJobStatus = 'pending' | 'running' | 'paused' | 'completed' | 'failed';
+export type UnmatchedUserPolicy = 'unassigned' | 'skip';
+type StateCategory = 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled';
+
+interface EntityCount {
+ discovered: number;
+ created: number;
+}
+
+export interface ImportJobDto {
+ id: number;
+ projectId: number;
+ source: 'plane';
+ phase: ImportJobPhase;
+ status: ImportJobStatus;
+ counts: Record<ImportEntityType, EntityCount>;
+ lastError: string | null;
+ nextAttemptAt: string;
+ createdAt: string;
+ updatedAt: string;
+}
+
+type ImportJobRow = typeof importJob.$inferSelect;
+
+async function entityCounts(jobId: number): Promise<Record<ImportEntityType, EntityCount>> {
+ const rows = await db
+ .select({
+ entityType: importRecord.sourceEntityType,
+ discovered: sql<number>`count(*)::int`,
+ created: sql<number>`count(${importRecord.localId})::int`,
+ })
+ .from(importRecord)
+ .where(eq(importRecord.importJobId, jobId))
+ .groupBy(importRecord.sourceEntityType);
+ const counts = Object.fromEntries(
+ IMPORT_ENTITY_TYPES.map((type) => [type, { discovered: 0, created: 0 }]),
+ ) as Record<ImportEntityType, EntityCount>;
+ for (const row of rows) {
+ counts[row.entityType as ImportEntityType] = {
+ discovered: row.discovered,
+ created: row.created,
+ };
+ }
+ return counts;
+}
+
+function toDto(row: ImportJobRow, counts: Record<ImportEntityType, EntityCount>): ImportJobDto {
+ return {
+ id: row.id,
+ projectId: row.projectId,
+ source: row.source as 'plane',
+ phase: row.phase as ImportJobPhase,
+ status: row.status as ImportJobStatus,
+ counts,
+ lastError: row.lastError,
+ nextAttemptAt: iso(row.nextAttemptAt),
+ createdAt: iso(row.createdAt),
+ updatedAt: iso(row.updatedAt),
+ };
+}
+
+async function getRow(id: number): Promise<ImportJobRow | null> {
+ const rows = await db.select().from(importJob).where(eq(importJob.id, id));
+ return rows[0] ?? null;
+}
+
+export async function getImportJobProjectId(id: number): Promise<number | null> {
+ const rows = await db
+ .select({ projectId: importJob.projectId })
+ .from(importJob)
+ .where(eq(importJob.id, id));
+ return rows[0]?.projectId ?? null;
+}
+
+export async function getImportJobDto(id: number): Promise<ImportJobDto | null> {
+ const row = await getRow(id);
+ return row ? toDto(row, await entityCounts(id)) : null;
+}
+
+// Not paged: a project accumulates at most a handful of import jobs, never a list
+// long enough to need it (see apps/api/AGENTS.md's paged-vs-whole-list rule).
+export async function listImportJobs(projectId: number): Promise<ImportJobDto[]> {
+ const rows = await db
+ .select()
+ .from(importJob)
+ .where(eq(importJob.projectId, projectId))
+ .orderBy(desc(importJob.createdAt));
+ return Promise.all(rows.map(async (row) => toDto(row, await entityCounts(row.id))));
+}
+
+// Normalizes and validates a base URL without resolving it — the worker's own
+// pinnedFetch call (apps/worker/src/plane-adapter.ts) is what enforces the SSRF
+// guards against the address actually used, on every request it makes.
+function normalizePlaneBaseUrl(raw: string): string {
+ let url: URL;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ throw new HttpError(400, 'baseUrl must be a valid URL');
+ }
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
+ throw new HttpError(400, 'baseUrl must be a valid URL');
+ }
+ return url.origin;
+}
+
+export interface CreateImportJobInput {
+ baseUrl: string;
+ workspaceSlug: string;
+ apiToken: string;
+ planeProjectId: string;
+ planeProjectKey: string;
+ unmatchedUserPolicy?: UnmatchedUserPolicy;
+ stateOverrides?: Record<string, StateCategory>;
+}
+
+// Stores the submitted credential encrypted and leaves the job 'pending' — the
+// worker picks it up on its next poll. The plaintext token exists only in this
+// function's local variables; it is never persisted or logged.
+export async function createImportJob(
+ projectId: number,
+ actorUserId: string,
+ input: CreateImportJobInput,
+): Promise<ImportJobDto> {
+ const baseUrl = normalizePlaneBaseUrl(input.baseUrl);
+ const workspaceSlug = input.workspaceSlug.trim();
+ const apiToken = input.apiToken.trim();
+ const planeProjectId = input.planeProjectId.trim();
+ const planeProjectKey = input.planeProjectKey.trim();
+ if (!workspaceSlug) throw new HttpError(400, 'workspaceSlug is required');
+ if (!apiToken) throw new HttpError(400, 'apiToken is required');
+ if (!planeProjectId) throw new HttpError(400, 'planeProjectId is required');
+ if (!planeProjectKey) throw new HttpError(400, 'planeProjectKey is required');
+
+ const encrypted = encryptSecret(JSON.stringify({ baseUrl, workspaceSlug, apiKey: apiToken }));
+ const config = {
+ planeProjectId,
+ planeProjectKey,
+ unmatchedUserPolicy: input.unmatchedUserPolicy ?? 'unassigned',
+ ...(input.stateOverrides && Object.keys(input.stateOverrides).length > 0
+ ? { stateOverrides: input.stateOverrides }
+ : {}),
+ };
+ const [row] = await db
+ .insert(importJob)
+ .values({
+ projectId,
+ createdByUserId: actorUserId,
+ source: 'plane',
+ config,
+ credentialCiphertext: encrypted.ciphertext,
+ credentialIv: encrypted.iv,
+ credentialAuthTag: encrypted.authTag,
+ })
+ .returning();
+ return toDto(row!, await entityCounts(row!.id));
+}
+
+// Only import_job.status values the worker's claim query (status = 'pending') will
+// ever pick up are eligible to pause; a job the worker has already finished cannot.
+export async function pauseImportJob(id: number): Promise<ImportJobDto> {
+ const row = await getRow(id);
+ if (!row) throw new HttpError(404, 'Import job not found');
+ if (row.status !== 'pending' && row.status !== 'running') {
+ throw new HttpError(409, `Cannot pause a job that is ${row.status}`);
+ }
+ const [updated] = await db
+ .update(importJob)
+ .set({ status: 'paused', updatedAt: new Date() })
+ .where(eq(importJob.id, id))
+ .returning();
+ return toDto(updated!, await entityCounts(id));
+}
+
+// Resets attempts so the job gets a fresh run of retries. next_attempt_at is only
+// reset to now when the job was paused with no real reason to wait (lastError null,
+// or a stored deadline that already passed by itself) - pausing does not touch
+// either column, so a job paused mid-retry (a rate limit, a transient error) still
+// carries its real cooldown. Resuming into "now" regardless would bypass that wait
+// entirely: the external rate limit it was waiting out has not actually cleared
+// just because the job was paused, so the immediate retry only gets rate-limited
+// again right away, with a fresh countdown that reads as if resume broke something.
+export async function resumeImportJob(id: number): Promise<ImportJobDto> {
+ const row = await getRow(id);
+ if (!row) throw new HttpError(404, 'Import job not found');
+ if (row.status !== 'paused')
+ throw new HttpError(409, `Cannot resume a job that is ${row.status}`);
+ const now = new Date();
+ const nextAttemptAt = row.lastError != null && row.nextAttemptAt > now ? row.nextAttemptAt : now;
+ const [updated] = await db
+ .update(importJob)
+ .set({ status: 'pending', attempts: 0, nextAttemptAt, updatedAt: now })
+ .where(eq(importJob.id, id))
+ .returning();
+ return toDto(updated!, await entityCounts(id));
+}
+
+// import_job_status_check has no 'canceled' value, so a cancel lands on 'failed' —
+// the terminal status the worker already treats as done, clearing the credential
+// the same way completeImportJob/failImportJob do.
+export async function cancelImportJob(id: number): Promise<ImportJobDto> {
+ const row = await getRow(id);
+ if (!row) throw new HttpError(404, 'Import job not found');
+ if (row.status === 'completed' || row.status === 'failed') {
+ throw new HttpError(409, `Cannot cancel a job that is already ${row.status}`);
+ }
+ const [updated] = await db
+ .update(importJob)
+ .set({
+ status: 'failed',
+ lastError: 'Canceled',
+ credentialCiphertext: null,
+ credentialIv: null,
+ credentialAuthTag: null,
+ updatedAt: new Date(),
+ })
+ .where(eq(importJob.id, id))
+ .returning();
+ return toDto(updated!, await entityCounts(id));
+}
+
+export interface PlaneProjectOption {
+ id: string;
+ name: string;
+ identifier: string;
+}
+
+interface PlaneProjectListEnvelope {
+ results?: { id: string; name: string; identifier: string }[];
+}
+
+// Confirms a submitted token can reach the workspace before it is ever encrypted
+// or stored, with the single lightweight call docs/dev/plane-import-source-notes.md
+// confirms live: GET /workspaces/{slug}/projects/. The returned projects are what a
+// create form offers as candidates for planeProjectId.
+export async function testPlaneConnection(
+ baseUrl: string,
+ workspaceSlug: string,
+ apiToken: string,
+): Promise<{ projects: PlaneProjectOption[] }> {
+ const url = normalizePlaneBaseUrl(baseUrl);
+ const slug = workspaceSlug.trim();
+ const token = apiToken.trim();
+ if (!slug) throw new HttpError(400, 'workspaceSlug is required');
+ if (!token) throw new HttpError(400, 'apiToken is required');
+
+ let response: Response;
+ try {
+ response = await pinnedFetch(`${url}/api/v1/workspaces/${slug}/projects/`, {
+ headers: { 'X-Api-Key': token },
+ timeoutMs: 15_000,
+ });
+ } catch (err) {
+ if (err instanceof HttpError) throw err;
+ throw new HttpError(502, 'The Plane instance could not be reached.');
+ }
+ if (response.status === 401 || response.status === 403) {
+ throw new HttpError(400, 'Plane rejected the API token.');
+ }
+ if (!response.ok) {
+ throw new HttpError(502, `Plane request failed with status ${response.status}.`);
+ }
+ const body = (await response.json()) as PlaneProjectListEnvelope;
+ return {
+ projects: (body.results ?? []).map((p) => ({
+ id: p.id,
+ name: p.name,
+ identifier: p.identifier,
+ })),
+ };
+}
+
+export interface PlaneStateOption {
+ id: string;
+ name: string;
+ category: StateCategory;
+}
+
+interface PlaneStateListEnvelope {
+ results?: { id: string; name: string; group: string }[];
+}
+
+// Mirrors apps/worker/src/plane-adapter.ts's STATE_CATEGORY_MAP/normalizeStateCategory:
+// duplicated here rather than imported, since the api does not depend on the worker
+// (see root AGENTS.md's dependency graph) - the same reasoning as testPlaneConnection
+// above already re-implementing its own small Plane fetch.
+const STATE_CATEGORY_MAP: Record<string, StateCategory> = {
+ backlog: 'backlog',
+ unstarted: 'unstarted',
+ started: 'started',
+ completed: 'completed',
+ cancelled: 'canceled',
+ triage: 'backlog',
+};
+
+// The source project's states, each with the category itsaplan would automatically
+// map it to - what the mapping review step shows before a job is created, so a user
+// can override one before anything is imported.
+export async function testPlaneStatesPreview(
+ baseUrl: string,
+ workspaceSlug: string,
+ apiToken: string,
+ planeProjectId: string,
+): Promise<{ states: PlaneStateOption[] }> {
+ const url = normalizePlaneBaseUrl(baseUrl);
+ const slug = workspaceSlug.trim();
+ const token = apiToken.trim();
+ const projectId = planeProjectId.trim();
+ if (!slug) throw new HttpError(400, 'workspaceSlug is required');
+ if (!token) throw new HttpError(400, 'apiToken is required');
+ if (!projectId) throw new HttpError(400, 'planeProjectId is required');
+
+ let response: Response;
+ try {
+ response = await pinnedFetch(`${url}/api/v1/workspaces/${slug}/projects/${projectId}/states/`, {
+ headers: { 'X-Api-Key': token },
+ timeoutMs: 15_000,
+ });
+ } catch (err) {
+ if (err instanceof HttpError) throw err;
+ throw new HttpError(502, 'The Plane instance could not be reached.');
+ }
+ if (response.status === 401 || response.status === 403) {
+ throw new HttpError(400, 'Plane rejected the API token.');
+ }
+ if (!response.ok) {
+ throw new HttpError(502, `Plane request failed with status ${response.status}.`);
+ }
+ const body = (await response.json()) as PlaneStateListEnvelope;
+ return {
+ states: (body.results ?? []).map((s) => ({
+ id: s.id,
+ name: s.name,
+ category: STATE_CATEGORY_MAP[s.group] ?? 'backlog',
+ })),
+ };
+}
diff --git a/apps/api/src/modules/initiatives/index.ts b/apps/api/src/modules/initiatives/index.ts
index 72835bf3..8ba935b0 100644
--- a/apps/api/src/modules/initiatives/index.ts
+++ b/apps/api/src/modules/initiatives/index.ts
@@ -7,7 +7,7 @@ import { requireUser } from '#shared/access';
import { HttpError } from '#shared/lib';
import { commonErrors, errors } from '#shared/responses';
import { paginate } from '#shared/pagination';
-import { deleteObjects } from '#shared/s3';
+import { deleteObjects } from '@repo/storage';
import {
AttachmentResponse,
AttachmentListResponse,
diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.ts
index 7dfbdd9f..10de2a60 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -6,7 +6,7 @@ import { authContext } from '#shared/auth-context';
import { assertPermission, assertProjectOwner, requireUser } from '#shared/access';
import { HttpError } from '#shared/lib';
import { accessErrors, commonErrors, errors } from '#shared/responses';
-import { deleteObject } from '#shared/s3';
+import { deleteObject } from '@repo/storage';
import {
createIssue,
searchIssues,
diff --git a/apps/api/src/modules/projects/service.ts b/apps/api/src/modules/projects/service.ts
index 34ccda42..95654cf0 100644
--- a/apps/api/src/modules/projects/service.ts
+++ b/apps/api/src/modules/projects/service.ts
@@ -31,7 +31,7 @@ import { getLimits } from '#shared/limits';
import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';
import { getProjectDefaults } from '#modules/settings/service';
import { dropUnusedTeamMembership } from '#modules/scim/reconcile';
-import { deleteObjects } from '#shared/s3';
+import { deleteObjects } from '@repo/storage';
import { lockAttachmentStorage } from '#modules/attachments/storage';
// Data access for projects: the top-level container that groups its own columns,
diff --git a/apps/api/src/modules/settings/index.ts b/apps/api/src/modules/settings/index.ts
index 4c40d044..192bc858 100644
--- a/apps/api/src/modules/settings/index.ts
+++ b/apps/api/src/modules/settings/index.ts
@@ -2,7 +2,8 @@ import { Elysia } from 'elysia';
import { requireUser } from '#shared/access';
import { authContext } from '#shared/auth-context';
import { errors } from '#shared/responses';
-import { getStorageSettings, getHotkeySettings } from './service';
+import { getStorageSettings } from '@repo/db';
+import { getHotkeySettings } from './service';
import { getAppVersion } from './updates';
import { getWhatsNew, markWhatsNewSeen } from './whats-new';
import {
diff --git a/apps/api/src/modules/settings/service.ts b/apps/api/src/modules/settings/service.ts
index f7680ca3..b4c748b9 100644
--- a/apps/api/src/modules/settings/service.ts
+++ b/apps/api/src/modules/settings/service.ts
@@ -1,69 +1,19 @@
-import { getSetting, setSetting } from '@repo/db';
+import {
+ getSetting,
+ setSetting,
+ STORAGE_SETTING_KEY,
+ getStorageSettings,
+ type StorageSettings,
+} from '@repo/db';
// The instance settings kept in app_setting: the upload limits and the keyboard
// shortcuts.
-// Instance-wide upload limits (app_setting key 'storage'). They apply to every
-// upload path in the api and are read by the web app before a file is picked, so
-// the limit is visible in the UI instead of only surfacing as a 413.
-//
-// The row is seeded by migration 0046, so the limits are set in the database and
-// edited in god mode — there is no env var for them. defaultStorageSettings() is
-// the fallback for a missing row and the source of the seeded values; keep the two
-// in sync.
-
-const STORAGE_SETTING_KEY = 'storage';
-
-export const MB = 1024 * 1024;
-
-export interface StorageSettings {
- // Upper bound on a single attachment. The multipart body is buffered in memory,
- // so this also bounds per-upload memory.
- maxAttachmentMb: number;
- // Upper bound on a single avatar image.
- maxAvatarMb: number;
- // Accepted attachment content types. An entry is a full type ('application/pdf')
- // or a wildcard ('image/*'). An empty list accepts any type.
- attachmentMimeTypes: string[];
- // Total stored attachment bytes allowed per project, in MB. 0 means unlimited.
- projectQuotaMb: number;
-}
-
-// Images, video, PDF, office documents and plain text formats. Executables,
-// archives and anything else are refused until an admin adds them.
-const DEFAULT_ATTACHMENT_MIME_TYPES = [
- 'image/*',
- 'video/*',
- 'application/pdf',
- 'text/plain',
- 'text/csv',
- 'text/markdown',
- 'application/msword',
- 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- 'application/vnd.oasis.opendocument.text',
- 'application/vnd.ms-excel',
- 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- 'application/vnd.oasis.opendocument.spreadsheet',
- 'application/vnd.ms-powerpoint',
- 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
- 'application/vnd.oasis.opendocument.presentation',
-];
-
-function defaultStorageSettings(): StorageSettings {
- return {
- maxAttachmentMb: 25,
- maxAvatarMb: 5,
- attachmentMimeTypes: DEFAULT_ATTACHMENT_MIME_TYPES,
- projectQuotaMb: 50 * 1024,
- };
-}
-
-export async function getStorageSettings(): Promise<StorageSettings> {
- const stored = await getSetting<Partial<StorageSettings>>(STORAGE_SETTING_KEY);
- // Merge over the default so a value written before a field was added stays valid.
- return { ...defaultStorageSettings(), ...(stored ?? {}) };
-}
-
+// Instance-wide upload limits (app_setting key 'storage'). getStorageSettings/
+// mimeAllowed/MB/StorageSettings live in @repo/db (packages/db/src/domains/storage.ts) —
+// the worker checks an imported Plane attachment against the same limits. This module
+// keeps only the write side: the limits are set in the database and edited in god mode,
+// there is no env var for them.
export async function setStorageSettings(
patch: Partial<StorageSettings>,
): Promise<StorageSettings> {
@@ -77,16 +27,6 @@ export async function setStorageSettings(
return next;
}
-// Whether a content type passes the allowlist. An empty list accepts anything.
-// Entries are already normalized by setStorageSettings.
-export function mimeAllowed(contentType: string, allowed: string[]): boolean {
- if (allowed.length === 0) return true;
- const ct = contentType.split(';')[0]?.trim().toLowerCase() ?? '';
- return allowed.some((pattern) =>
- pattern.endsWith('/*') ? ct.startsWith(pattern.slice(0, -1)) : ct === pattern,
- );
-}
-
// Instance-wide project defaults (app_setting key 'projects'): what a newly
// created project starts with. Only the defaults live here — every one of them
// stays editable per project afterwards, so this decides the starting value and
diff --git a/apps/api/src/planner.ts b/apps/api/src/planner.ts
index 43c28c18..5e491a52 100644
--- a/apps/api/src/planner.ts
+++ b/apps/api/src/planner.ts
@@ -21,6 +21,7 @@ import { cycleRoutes } from './modules/cycles';
import { attachmentRoutes } from './modules/attachments';
import { chatAttachmentRoutes } from './modules/chat-attachments';
import { importRoutes } from './modules/imports';
+import { importExportRoutes } from './modules/import-export';
import { avatarRoutes } from './modules/avatars';
import { viewRoutes } from './modules/views';
import { shareRoutes } from './modules/share';
@@ -104,6 +105,7 @@ export const planner = new Elysia({ name: 'planner' })
.use(attachmentRoutes)
.use(chatAttachmentRoutes)
.use(importRoutes)
+ .use(importExportRoutes)
.use(avatarRoutes)
.use(viewRoutes)
.use(shareRoutes)
diff --git a/apps/api/src/shared/account-deletion.ts b/apps/api/src/shared/account-deletion.ts
index 7c936389..41026191 100644
--- a/apps/api/src/shared/account-deletion.ts
+++ b/apps/api/src/shared/account-deletion.ts
@@ -1,6 +1,6 @@
import { db, documentAsset, projectDocument, user } from '@repo/db';
import { and, asc, eq, inArray, or, sql } from 'drizzle-orm';
-import { deleteObjects } from './s3';
+import { deleteObjects } from '@repo/storage';
const DOCUMENT_TREE_LOCK_NAMESPACE = 1_145_390_931;
diff --git a/apps/bot/Dockerfile b/apps/bot/Dockerfile
index fdf67e50..a6b397da 100644
--- a/apps/bot/Dockerfile
+++ b/apps/bot/Dockerfile
@@ -18,6 +18,7 @@ COPY packages/agent-tools/package.json ./packages/agent-tools/
COPY packages/crypto/package.json ./packages/crypto/
COPY packages/mailer/package.json ./packages/mailer/
COPY packages/net/package.json ./packages/net/
+COPY packages/storage/package.json ./packages/storage/
COPY packages/runner/package.json ./packages/runner/
COPY packages/eslint-config/package.json ./packages/eslint-config/
# --filter bot installs only the bot workspace and its dependency closure.
diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile
index 076afca4..b12f6aef 100644
--- a/apps/web/Dockerfile
+++ b/apps/web/Dockerfile
@@ -18,6 +18,7 @@ COPY packages/agent-tools/package.json ./packages/agent-tools/
COPY packages/crypto/package.json ./packages/crypto/
COPY packages/mailer/package.json ./packages/mailer/
COPY packages/net/package.json ./packages/net/
+COPY packages/storage/package.json ./packages/storage/
COPY packages/runner/package.json ./packages/runner/
COPY packages/eslint-config/package.json ./packages/eslint-config/
RUN bun install --frozen-lockfile
diff --git a/apps/web/messages/ar/permissions.json b/apps/web/messages/ar/permissions.json
index 361374e5..0fb2c528 100644
--- a/apps/web/messages/ar/permissions.json
+++ b/apps/web/messages/ar/permissions.json
@@ -23,6 +23,7 @@
"actions": "الإجراءات",
"webhooks": "خطافات الويب (webhooks)",
"note_boards": "لوحات الملاحظات",
+ "import_export": "استيراد/تصدير",
"danger_zone": "منطقة الخطر"
},
"actions": {
diff --git a/apps/web/messages/ar/sections.json b/apps/web/messages/ar/sections.json
index 3df2c6a0..73a34f37 100644
--- a/apps/web/messages/ar/sections.json
+++ b/apps/web/messages/ar/sections.json
@@ -101,6 +101,10 @@
"label": "المستودعات",
"description": "قفل المهام لما طلبات السحب بتاعتها تتدمج على GitHub أو GitLab أو Gitea أو Forgejo أو Bitbucket."
},
+ "import-export": {
+ "label": "استيراد/تصدير",
+ "description": "استورد المهام والتعليقات والوسوم من نسخة Plane مستضافة ذاتيًا، أو صدّر بيانات المشروع كملف JSON."
+ },
"ai-agents": {
"label": "وكلاء الذكاء الاصطناعي",
"description": "وكلاء الذكاء الاصطناعي العاملون في هذا المشروع."
diff --git a/apps/web/messages/ar/settings.json b/apps/web/messages/ar/settings.json
index 0a617fc7..d3e5bfc1 100644
--- a/apps/web/messages/ar/settings.json
+++ b/apps/web/messages/ar/settings.json
@@ -472,6 +472,68 @@
"changeState": "تغيير الحالة…",
"noState": "لا توجد حالة."
},
+ "importExport": {
+ "connect": "الاتصال بـ Plane",
+ "connectHint": "حط بيانات نسخة Plane المستضافة ذاتيًا عشان نتأكد من الاتصال ونجيب مشاريعها.",
+ "baseUrl": "رابط Plane",
+ "workspaceSlug": "مساحة العمل",
+ "apiToken": "مفتاح API",
+ "apiTokenHint": "مفتاح API لمساحة العمل أو شخصي، له صلاحية قراءة مشاريع المساحة ومهامها وأعضائها.",
+ "testConnection": "اختبار الاتصال",
+ "testing": "بنختبر…",
+ "sourceProject": "المشروع المصدر",
+ "sourceProjectHint": "اختار مشروع Plane اللي عايز تستورد منه.",
+ "sourceProjectLabel": "مشروع Plane",
+ "sourceProjectPlaceholder": "اختار مشروع",
+ "noProjects": "مافيش مشاريع في مساحة العمل دي تقدر تستورد منها.",
+ "stateMapping": "تعيين الحالات",
+ "unmatchedUserPolicyLabel": "المكلفين ومعلقين الكومنتات اللي مش متطابقين",
+ "unmatchedUserPolicyUnassigned": "سيبها من غير تكليف",
+ "unmatchedUserPolicySkip": "تجاهل التكليف أو الكومنت",
+ "previewFailed": "معرفناش نجيب حالات المشروع ده.",
+ "tryAgain": "جرب تاني",
+ "startImport": "ابدأ الاستيراد",
+ "starting": "بيبدأ…",
+ "importStarted": "الاستيراد بدأ",
+ "jobs": "مهام الاستيراد",
+ "jobsHint": "كل مهمة بتشتغل في الخلفية، وتقدر توقفها مؤقتًا أو تكمّلها أو تلغيها وهي شغالة.",
+ "emptyTitle": "مافيش عمليات استيراد لسه",
+ "emptyHint": "اتصل بنسخة Plane فوق وابدأ استيراد عشان تجيب مهامها.",
+ "export": "التصدير",
+ "exportHint": "نزّل نسخة كاملة من حالات وليبلز ودورات وتذاكر المشروع ده كـ JSON.",
+ "exportProjectData": "صدّر بيانات المشروع",
+ "exportFailed": "معرفناش نصدّر المشروع.",
+ "pause": "إيقاف مؤقت",
+ "resume": "استكمال",
+ "cancel": "إلغاء",
+ "countsLegend": "اتعمل / اتلاقى",
+ "countsNotDiscovered": "لم يتم اكتشافها بعد",
+ "rateLimitedRetrying": "تم الوصول إلى حد معدل الطلبات في Plane. ستتم إعادة المحاولة خلال {seconds} ثانية.",
+ "transientErrorRetrying": "{error} — ستتم إعادة المحاولة خلال {seconds} ثانية.",
+ "statuses": {
+ "pending": "قيد الانتظار",
+ "running": "شغّال",
+ "paused": "متوقف مؤقتًا",
+ "completed": "مكتمل",
+ "failed": "فشل"
+ },
+ "phases": {
+ "discover": "بيكتشف",
+ "create": "بيعمل",
+ "link": "بيربط",
+ "rewrite": "بيعدّل",
+ "attachments": "المرفقات",
+ "done": "خلص"
+ },
+ "entities": {
+ "issue": "المهام",
+ "comment": "التعليقات",
+ "label": "الوسوم",
+ "state": "الحالات",
+ "cycle": "الدورات",
+ "attachment": "المرفقات"
+ }
+ },
"issueTemplates": {
"addTemplate": "قالب جديد",
"editTemplate": "تعديل القالب",
diff --git a/apps/web/messages/en/permissions.json b/apps/web/messages/en/permissions.json
index ad7760b2..d24f4d74 100644
--- a/apps/web/messages/en/permissions.json
+++ b/apps/web/messages/en/permissions.json
@@ -23,6 +23,7 @@
"actions": "Actions",
"webhooks": "Webhooks",
"note_boards": "Note boards",
+ "import_export": "Import/Export",
"danger_zone": "Danger zone"
},
"actions": {
diff --git a/apps/web/messages/en/sections.json b/apps/web/messages/en/sections.json
index 3154261b..36488149 100644
--- a/apps/web/messages/en/sections.json
+++ b/apps/web/messages/en/sections.json
@@ -101,6 +101,10 @@
"label": "Repositories",
"description": "Close issues when their pull requests merge on GitHub, GitLab, Gitea, Forgejo, or Bitbucket."
},
+ "import-export": {
+ "label": "Import/Export",
+ "description": "Bring issues, comments, and labels in from a self-hosted Plane instance, or export this project's data as JSON."
+ },
"ai-agents": {
"label": "AI Agents",
"description": "AI agents working in this project."
diff --git a/apps/web/messages/en/settings.json b/apps/web/messages/en/settings.json
index f53ef7eb..e75ed976 100644
--- a/apps/web/messages/en/settings.json
+++ b/apps/web/messages/en/settings.json
@@ -472,6 +472,68 @@
"changeState": "Change state…",
"noState": "No state."
},
+ "importExport": {
+ "connect": "Connect to Plane",
+ "connectHint": "Enter a self-hosted Plane instance to check the connection and load its projects.",
+ "baseUrl": "Plane URL",
+ "workspaceSlug": "Workspace",
+ "apiToken": "API token",
+ "apiTokenHint": "A workspace or personal API key with read access to the workspace's projects, issues, and members.",
+ "testConnection": "Test connection",
+ "testing": "Testing…",
+ "sourceProject": "Source project",
+ "sourceProjectHint": "Pick the Plane project to import from.",
+ "sourceProjectLabel": "Plane project",
+ "sourceProjectPlaceholder": "Select a project",
+ "noProjects": "This workspace has no projects to import from.",
+ "stateMapping": "State mapping",
+ "unmatchedUserPolicyLabel": "Unmatched assignees and comment authors",
+ "unmatchedUserPolicyUnassigned": "Leave unassigned",
+ "unmatchedUserPolicySkip": "Skip the assignment or comment",
+ "previewFailed": "Couldn't load this project's states.",
+ "tryAgain": "Try again",
+ "startImport": "Start import",
+ "starting": "Starting…",
+ "importStarted": "Import started",
+ "jobs": "Import jobs",
+ "jobsHint": "Each job runs in the background and can be paused, resumed, or canceled while it is in progress.",
+ "emptyTitle": "No imports yet",
+ "emptyHint": "Connect to a Plane instance above and start an import to bring in its issues.",
+ "export": "Export",
+ "exportHint": "Download a self-contained snapshot of this project's states, labels, cycles, and issues as JSON.",
+ "exportProjectData": "Export project data",
+ "exportFailed": "Couldn't export the project.",
+ "pause": "Pause",
+ "resume": "Resume",
+ "cancel": "Cancel",
+ "countsLegend": "created / discovered",
+ "countsNotDiscovered": "not yet discovered",
+ "rateLimitedRetrying": "Plane's rate limit was reached. Retrying in {seconds}s.",
+ "transientErrorRetrying": "{error} — retrying in {seconds}s.",
+ "statuses": {
+ "pending": "Pending",
+ "running": "Running",
+ "paused": "Paused",
+ "completed": "Completed",
+ "failed": "Failed"
+ },
+ "phases": {
+ "discover": "Discovering",
+ "create": "Creating",
+ "link": "Linking",
+ "rewrite": "Rewriting",
+ "attachments": "Attachments",
+ "done": "Done"
+ },
+ "entities": {
+ "issue": "Issues",
+ "comment": "Comments",
+ "label": "Labels",
+ "state": "States",
+ "cycle": "Cycles",
+ "attachment": "Attachments"
+ }
+ },
"issueTemplates": {
"addTemplate": "New template",
"editTemplate": "Edit template",
diff --git a/apps/web/messages/es-ES/permissions.json b/apps/web/messages/es-ES/permissions.json
index b8564794..322f1ef2 100644
--- a/apps/web/messages/es-ES/permissions.json
+++ b/apps/web/messages/es-ES/permissions.json
@@ -23,6 +23,7 @@
"actions": "Acciones",
"webhooks": "Webhooks",
"note_boards": "Tableros de notas",
+ "import_export": "Importar/Exportar",
"danger_zone": "Zona de riesgo"
},
"actions": {
diff --git a/apps/web/messages/es-ES/sections.json b/apps/web/messages/es-ES/sections.json
index 1d9a5501..5be8b83d 100644
--- a/apps/web/messages/es-ES/sections.json
+++ b/apps/web/messages/es-ES/sections.json
@@ -101,6 +101,10 @@
"label": "Repositorios",
"description": "Cerrar tickets cuando sus pull requests se integran en GitHub, GitLab, Gitea, Forgejo o Bitbucket."
},
+ "import-export": {
+ "label": "Importar/Exportar",
+ "description": "Traer tickets, comentarios y etiquetas desde una instancia autoalojada de Plane, o exportar los datos de este proyecto como JSON."
+ },
"ai-agents": {
"label": "Agentes de IA",
"description": "Agentes de IA que trabajan en este proyecto."
diff --git a/apps/web/messages/es-ES/settings.json b/apps/web/messages/es-ES/settings.json
index ab6869cb..5a124d75 100644
--- a/apps/web/messages/es-ES/settings.json
+++ b/apps/web/messages/es-ES/settings.json
@@ -472,6 +472,68 @@
"changeState": "Cambiar el estado…",
"noState": "Sin estado."
},
+ "importExport": {
+ "connect": "Conectar con Plane",
+ "connectHint": "Introduce una instancia autoalojada de Plane para comprobar la conexión y cargar sus proyectos.",
+ "baseUrl": "URL de Plane",
+ "workspaceSlug": "Espacio de trabajo",
+ "apiToken": "Token de API",
+ "apiTokenHint": "Una clave de API de espacio de trabajo o personal con acceso de lectura a los proyectos, tickets y miembros del espacio de trabajo.",
+ "testConnection": "Probar conexión",
+ "testing": "Probando…",
+ "sourceProject": "Proyecto de origen",
+ "sourceProjectHint": "Elige el proyecto de Plane desde el que importar.",
+ "sourceProjectLabel": "Proyecto de Plane",
+ "sourceProjectPlaceholder": "Selecciona un proyecto",
+ "noProjects": "Este espacio de trabajo no tiene proyectos desde los que importar.",
+ "stateMapping": "Correspondencia de estados",
+ "unmatchedUserPolicyLabel": "Asignados y autores de comentarios sin coincidencia",
+ "unmatchedUserPolicyUnassigned": "Dejar sin asignar",
+ "unmatchedUserPolicySkip": "Omitir la asignación o el comentario",
+ "previewFailed": "No se pudieron cargar los estados de este proyecto.",
+ "tryAgain": "Reintentar",
+ "startImport": "Iniciar importación",
+ "starting": "Iniciando…",
+ "importStarted": "Importación iniciada",
+ "jobs": "Trabajos de importación",
+ "jobsHint": "Cada trabajo se ejecuta en segundo plano y se puede pausar, reanudar o cancelar mientras está en curso.",
+ "emptyTitle": "Aún no hay importaciones",
+ "emptyHint": "Conéctate a una instancia de Plane arriba e inicia una importación para traer sus tickets.",
+ "export": "Exportar",
+ "exportHint": "Descarga una instantánea autocontenida de los estados, etiquetas, ciclos y tickets de este proyecto como JSON.",
+ "exportProjectData": "Exportar datos del proyecto",
+ "exportFailed": "No se pudo exportar el proyecto.",
+ "pause": "Pausar",
+ "resume": "Reanudar",
+ "cancel": "Cancelar",
+ "countsLegend": "creados / detectados",
+ "countsNotDiscovered": "aún no detectados",
+ "rateLimitedRetrying": "Se alcanzó el límite de peticiones de Plane. Reintentando en {seconds}s.",
+ "transientErrorRetrying": "{error} — reintentando en {seconds}s.",
+ "statuses": {
+ "pending": "Pendiente",
+ "running": "En ejecución",
+ "paused": "Pausado",
+ "completed": "Completado",
+ "failed": "Fallido"
+ },
+ "phases": {
+ "discover": "Detectando",
+ "create": "Creando",
+ "link": "Vinculando",
+ "rewrite": "Reescribiendo",
+ "attachments": "Adjuntos",
+ "done": "Hecho"
+ },
+ "entities": {
+ "issue": "Tickets",
+ "comment": "Comentarios",
+ "label": "Etiquetas",
+ "state": "Estados",
+ "cycle": "Ciclos",
+ "attachment": "Adjuntos"
+ }
+ },
"issueTemplates": {
"addTemplate": "Nueva plantilla",
"editTemplate": "Editar la plantilla",
diff --git a/apps/web/messages/fr/permissions.json b/apps/web/messages/fr/permissions.json
index 5439c681..b532efce 100644
--- a/apps/web/messages/fr/permissions.json
+++ b/apps/web/messages/fr/permissions.json
@@ -23,6 +23,7 @@
"actions": "Actions",
"webhooks": "Webhooks",
"note_boards": "Tableaux de notes",
+ "import_export": "Import/Export",
"danger_zone": "Zone sensible"
},
"actions": {
diff --git a/apps/web/messages/fr/sections.json b/apps/web/messages/fr/sections.json
index f10eb88a..1a947fe4 100644
--- a/apps/web/messages/fr/sections.json
+++ b/apps/web/messages/fr/sections.json
@@ -101,6 +101,10 @@
"label": "Dépôts",
"description": "Fermez les tickets quand leurs pull requests sont fusionnées sur GitHub, GitLab, Gitea, Forgejo ou Bitbucket."
},
+ "import-export": {
+ "label": "Import/Export",
+ "description": "Importez les tickets, commentaires et étiquettes depuis une instance Plane auto-hébergée, ou exportez les données du projet au format JSON."
+ },
"ai-agents": {
"label": "Agents",
"description": "Des comptes bots auxquels vous pouvez déléguer des tickets."
diff --git a/apps/web/messages/fr/settings.json b/apps/web/messages/fr/settings.json
index 2777752d..90a2cf44 100644
--- a/apps/web/messages/fr/settings.json
+++ b/apps/web/messages/fr/settings.json
@@ -472,6 +472,68 @@
"changeState": "Changer l'état…",
"noState": "Aucun état."
},
+ "importExport": {
+ "connect": "Se connecter à Plane",
+ "connectHint": "Indiquez une instance Plane auto-hébergée pour vérifier la connexion et charger ses projets.",
+ "baseUrl": "URL de Plane",
+ "workspaceSlug": "Espace de travail",
+ "apiToken": "Jeton API",
+ "apiTokenHint": "Une clé API d'espace de travail ou personnelle avec un accès en lecture aux projets, tickets et membres de l'espace de travail.",
+ "testConnection": "Tester la connexion",
+ "testing": "Test en cours…",
+ "sourceProject": "Projet source",
+ "sourceProjectHint": "Choisissez le projet Plane à importer.",
+ "sourceProjectLabel": "Projet Plane",
+ "sourceProjectPlaceholder": "Sélectionner un projet",
+ "noProjects": "Cet espace de travail n'a aucun projet à importer.",
+ "stateMapping": "Correspondance des états",
+ "unmatchedUserPolicyLabel": "Assignés et auteurs de commentaires non reconnus",
+ "unmatchedUserPolicyUnassigned": "Laisser non assigné",
+ "unmatchedUserPolicySkip": "Ignorer l'assignation ou le commentaire",
+ "previewFailed": "Impossible de charger les états de ce projet.",
+ "tryAgain": "Réessayer",
+ "startImport": "Démarrer l'import",
+ "starting": "Démarrage…",
+ "importStarted": "Import démarré",
+ "jobs": "Imports",
+ "jobsHint": "Chaque import s'exécute en arrière-plan et peut être mis en pause, repris ou annulé pendant son exécution.",
+ "emptyTitle": "Aucun import pour l'instant",
+ "emptyHint": "Connectez-vous à une instance Plane ci-dessus et démarrez un import pour récupérer ses tickets.",
+ "export": "Export",
+ "exportHint": "Téléchargez un instantané autonome des états, étiquettes, cycles et tickets de ce projet au format JSON.",
+ "exportProjectData": "Exporter les données du projet",
+ "exportFailed": "Impossible d'exporter le projet.",
+ "pause": "Mettre en pause",
+ "resume": "Reprendre",
+ "cancel": "Annuler",
+ "countsLegend": "créés / trouvés",
+ "countsNotDiscovered": "pas encore découvert",
+ "rateLimitedRetrying": "La limite de requêtes de Plane a été atteinte. Nouvel essai dans {seconds} s.",
+ "transientErrorRetrying": "{error} — nouvel essai dans {seconds} s.",
+ "statuses": {
+ "pending": "En attente",
+ "running": "En cours",
+ "paused": "En pause",
+ "completed": "Terminé",
+ "failed": "Échoué"
+ },
+ "phases": {
+ "discover": "Découverte",
+ "create": "Création",
+ "link": "Liaison",
+ "rewrite": "Réécriture",
+ "attachments": "Pièces jointes",
+ "done": "Terminé"
+ },
+ "entities": {
+ "issue": "Tickets",
+ "comment": "Commentaires",
+ "label": "Étiquettes",
+ "state": "États",
+ "cycle": "Cycles",
+ "attachment": "Pièces jointes"
+ }
+ },
"issueTemplates": {
"addTemplate": "Nouveau modèle",
"editTemplate": "Modifier le modèle",
diff --git a/apps/web/messages/id/permissions.json b/apps/web/messages/id/permissions.json
index 4a456d02..0b7a1f15 100644
--- a/apps/web/messages/id/permissions.json
+++ b/apps/web/messages/id/permissions.json
@@ -23,6 +23,7 @@
"actions": "Tindakan",
"webhooks": "Webhook",
"note_boards": "Papan catatan",
+ "import_export": "Impor/Ekspor",
"danger_zone": "Zona bahaya"
},
"actions": {
diff --git a/apps/web/messages/id/sections.json b/apps/web/messages/id/sections.json
index 008b27e0..45573483 100644
--- a/apps/web/messages/id/sections.json
+++ b/apps/web/messages/id/sections.json
@@ -101,6 +101,10 @@
"label": "Repositori",
"description": "Tutup issue saat pull request digabungkan di GitHub, GitLab, Gitea, Forgejo, atau Bitbucket."
},
+ "import-export": {
+ "label": "Impor/Ekspor",
+ "description": "Impor issue, komentar, dan label dari instans Plane self-hosted, atau ekspor data proyek ini sebagai JSON."
+ },
"ai-agents": {
"label": "Agen AI",
"description": "Agen AI yang bekerja dalam proyek ini."
diff --git a/apps/web/messages/id/settings.json b/apps/web/messages/id/settings.json
index 0b159cb4..69a0e61a 100644
--- a/apps/web/messages/id/settings.json
+++ b/apps/web/messages/id/settings.json
@@ -472,6 +472,68 @@
"changeState": "Ubah status…",
"noState": "Tidak ada status."
},
+ "importExport": {
+ "connect": "Hubungkan ke Plane",
+ "connectHint": "Masukkan instans Plane self-hosted untuk memeriksa koneksi dan memuat proyeknya.",
+ "baseUrl": "URL Plane",
+ "workspaceSlug": "Workspace",
+ "apiToken": "Token API",
+ "apiTokenHint": "Kunci API workspace atau pribadi dengan akses baca ke proyek, issue, dan anggota workspace.",
+ "testConnection": "Uji koneksi",
+ "testing": "Menguji…",
+ "sourceProject": "Proyek sumber",
+ "sourceProjectHint": "Pilih proyek Plane yang akan diimpor.",
+ "sourceProjectLabel": "Proyek Plane",
+ "sourceProjectPlaceholder": "Pilih proyek",
+ "noProjects": "Workspace ini tidak punya proyek untuk diimpor.",
+ "stateMapping": "Pemetaan status",
+ "unmatchedUserPolicyLabel": "Penerima tugas dan penulis komentar yang tidak cocok",
+ "unmatchedUserPolicyUnassigned": "Biarkan tidak ditugaskan",
+ "unmatchedUserPolicySkip": "Lewati penugasan atau komentar",
+ "previewFailed": "Tidak dapat memuat status proyek ini.",
+ "tryAgain": "Coba lagi",
+ "startImport": "Mulai impor",
+ "starting": "Memulai…",
+ "importStarted": "Impor dimulai",
+ "jobs": "Tugas impor",
+ "jobsHint": "Setiap tugas berjalan di latar belakang dan bisa dijeda, dilanjutkan, atau dibatalkan selama masih berlangsung.",
+ "emptyTitle": "Belum ada impor",
+ "emptyHint": "Hubungkan ke instans Plane di atas dan mulai impor untuk mengambil issue-nya.",
+ "export": "Ekspor",
+ "exportHint": "Unduh snapshot mandiri dari status, label, siklus, dan isu proyek ini sebagai JSON.",
+ "exportProjectData": "Ekspor data proyek",
+ "exportFailed": "Tidak dapat mengekspor proyek.",
+ "pause": "Jeda",
+ "resume": "Lanjutkan",
+ "cancel": "Batal",
+ "countsLegend": "dibuat / ditemukan",
+ "countsNotDiscovered": "belum ditemukan",
+ "rateLimitedRetrying": "Batas laju permintaan Plane tercapai. Mencoba lagi dalam {seconds} dtk.",
+ "transientErrorRetrying": "{error} — mencoba lagi dalam {seconds} dtk.",
+ "statuses": {
+ "pending": "Tertunda",
+ "running": "Berjalan",
+ "paused": "Dijeda",
+ "completed": "Selesai",
+ "failed": "Gagal"
+ },
+ "phases": {
+ "discover": "Menemukan",
+ "create": "Membuat",
+ "link": "Menautkan",
+ "rewrite": "Menulis ulang",
+ "attachments": "Lampiran",
+ "done": "Selesai"
+ },
+ "entities": {
+ "issue": "Issue",
+ "comment": "Komentar",
+ "label": "Label",
+ "state": "Status",
+ "cycle": "Cycle",
+ "attachment": "Lampiran"
+ }
+ },
"issueTemplates": {
"addTemplate": "Templat baru",
"editTemplate": "Ubah templat",
diff --git a/apps/web/messages/pt-BR/permissions.json b/apps/web/messages/pt-BR/permissions.json
index 10ea4fc3..55c49355 100644
--- a/apps/web/messages/pt-BR/permissions.json
+++ b/apps/web/messages/pt-BR/permissions.json
@@ -23,6 +23,7 @@
"actions": "Ações",
"webhooks": "Webhooks",
"note_boards": "Quadros de notas",
+ "import_export": "Importar/Exportar",
"danger_zone": "Zona de perigo"
},
"actions": {
diff --git a/apps/web/messages/pt-BR/sections.json b/apps/web/messages/pt-BR/sections.json
index 62216ab0..019dcfd7 100644
--- a/apps/web/messages/pt-BR/sections.json
+++ b/apps/web/messages/pt-BR/sections.json
@@ -101,6 +101,10 @@
"label": "Repositórios",
"description": "Feche issues quando seus pull requests mesclam no GitHub, GitLab, Gitea, Forgejo ou Bitbucket."
},
+ "import-export": {
+ "label": "Importar/Exportar",
+ "description": "Importe issues, comentários e etiquetas de uma instância Plane auto-hospedada, ou exporte os dados deste projeto como JSON."
+ },
"ai-agents": {
"label": "Agentes de IA",
"description": "Agentes de IA trabalhando neste projeto."
diff --git a/apps/web/messages/pt-BR/settings.json b/apps/web/messages/pt-BR/settings.json
index 2c126e64..8c44bbac 100644
--- a/apps/web/messages/pt-BR/settings.json
+++ b/apps/web/messages/pt-BR/settings.json
@@ -472,6 +472,68 @@
"changeState": "Alterar estado…",
"noState": "Sem estado."
},
+ "importExport": {
+ "connect": "Conectar ao Plane",
+ "connectHint": "Informe uma instância Plane auto-hospedada para verificar a conexão e carregar seus projetos.",
+ "baseUrl": "URL do Plane",
+ "workspaceSlug": "Workspace",
+ "apiToken": "Token de API",
+ "apiTokenHint": "Uma chave de API do workspace ou pessoal com acesso de leitura aos projetos, issues e membros do workspace.",
+ "testConnection": "Testar conexão",
+ "testing": "Testando…",
+ "sourceProject": "Projeto de origem",
+ "sourceProjectHint": "Escolha o projeto do Plane a ser importado.",
+ "sourceProjectLabel": "Projeto do Plane",
+ "sourceProjectPlaceholder": "Selecione um projeto",
+ "noProjects": "Este workspace não tem projetos para importar.",
+ "stateMapping": "Mapeamento de estados",
+ "unmatchedUserPolicyLabel": "Responsáveis e autores de comentários não correspondidos",
+ "unmatchedUserPolicyUnassigned": "Deixar sem responsável",
+ "unmatchedUserPolicySkip": "Ignorar a atribuição ou o comentário",
+ "previewFailed": "Não foi possível carregar os estados deste projeto.",
+ "tryAgain": "Tentar novamente",
+ "startImport": "Iniciar importação",
+ "starting": "Iniciando…",
+ "importStarted": "Importação iniciada",
+ "jobs": "Importações",
+ "jobsHint": "Cada importação roda em segundo plano e pode ser pausada, retomada ou cancelada enquanto estiver em andamento.",
+ "emptyTitle": "Nenhuma importação ainda",
+ "emptyHint": "Conecte-se a uma instância Plane acima e inicie uma importação para trazer suas issues.",
+ "export": "Exportar",
+ "exportHint": "Baixe um snapshot autocontido dos estados, etiquetas, ciclos e itens deste projeto em JSON.",
+ "exportProjectData": "Exportar dados do projeto",
+ "exportFailed": "Não foi possível exportar o projeto.",
+ "pause": "Pausar",
+ "resume": "Retomar",
+ "cancel": "Cancelar",
+ "countsLegend": "criados / encontrados",
+ "countsNotDiscovered": "ainda não descoberto",
+ "rateLimitedRetrying": "O limite de requisições do Plane foi atingido. Tentando novamente em {seconds}s.",
+ "transientErrorRetrying": "{error} — tentando novamente em {seconds}s.",
+ "statuses": {
+ "pending": "Pendente",
+ "running": "Em execução",
+ "paused": "Pausado",
+ "completed": "Concluído",
+ "failed": "Falhou"
+ },
+ "phases": {
+ "discover": "Descobrindo",
+ "create": "Criando",
+ "link": "Vinculando",
+ "rewrite": "Reescrevendo",
+ "attachments": "Anexos",
+ "done": "Concluído"
+ },
+ "entities": {
+ "issue": "Issues",
+ "comment": "Comentários",
+ "label": "Etiquetas",
+ "state": "Estados",
+ "cycle": "Ciclos",
+ "attachment": "Anexos"
+ }
+ },
"issueTemplates": {
"addTemplate": "Novo modelo",
"editTemplate": "Editar modelo",
diff --git a/apps/web/messages/ru/permissions.json b/apps/web/messages/ru/permissions.json
index ad0a8cd9..da3cbff2 100644
--- a/apps/web/messages/ru/permissions.json
+++ b/apps/web/messages/ru/permissions.json
@@ -23,6 +23,7 @@
"actions": "Действия",
"webhooks": "Вебхуки",
"note_boards": "Доски заметок",
+ "import_export": "Импорт/Экспорт",
"danger_zone": "Опасная зона"
},
"actions": {
diff --git a/apps/web/messages/ru/sections.json b/apps/web/messages/ru/sections.json
index 432ec31a..b8cdfe3a 100644
--- a/apps/web/messages/ru/sections.json
+++ b/apps/web/messages/ru/sections.json
@@ -101,6 +101,10 @@
"label": "Репозитории",
"description": "Закрытие задач, когда их pull request смержен в GitHub, GitLab, Gitea, Forgejo или Bitbucket."
},
+ "import-export": {
+ "label": "Импорт/Экспорт",
+ "description": "Импортируйте задачи, комментарии и метки из self-hosted инстанса Plane, или экспортируйте данные проекта в формате JSON."
+ },
"ai-agents": {
"label": "ИИ-агенты",
"description": "ИИ-агенты, которые работают в этом проекте."
diff --git a/apps/web/messages/ru/settings.json b/apps/web/messages/ru/settings.json
index e273ff2a..b86343bc 100644
--- a/apps/web/messages/ru/settings.json
+++ b/apps/web/messages/ru/settings.json
@@ -472,6 +472,68 @@
"changeState": "Изменить статус…",
"noState": "Статусов нет."
},
+ "importExport": {
+ "connect": "Подключение к Plane",
+ "connectHint": "Укажите self-hosted инстанс Plane, чтобы проверить соединение и загрузить его проекты.",
+ "baseUrl": "URL Plane",
+ "workspaceSlug": "Рабочее пространство",
+ "apiToken": "API-токен",
+ "apiTokenHint": "API-ключ рабочего пространства или личный ключ с доступом на чтение к проектам, задачам и участникам рабочего пространства.",
+ "testConnection": "Проверить соединение",
+ "testing": "Проверка…",
+ "sourceProject": "Исходный проект",
+ "sourceProjectHint": "Выберите проект Plane, из которого будет выполнен импорт.",
+ "sourceProjectLabel": "Проект Plane",
+ "sourceProjectPlaceholder": "Выберите проект",
+ "noProjects": "В этом рабочем пространстве нет проектов для импорта.",
+ "stateMapping": "Сопоставление статусов",
+ "unmatchedUserPolicyLabel": "Несопоставленные исполнители и авторы комментариев",
+ "unmatchedUserPolicyUnassigned": "Оставить без исполнителя",
+ "unmatchedUserPolicySkip": "Пропустить назначение или комментарий",
+ "previewFailed": "Не удалось загрузить статусы этого проекта.",
+ "tryAgain": "Повторить",
+ "startImport": "Начать импорт",
+ "starting": "Запуск…",
+ "importStarted": "Импорт запущен",
+ "jobs": "Задачи импорта",
+ "jobsHint": "Каждая задача выполняется в фоне, и пока она не завершена, её можно приостановить, возобновить или отменить.",
+ "emptyTitle": "Импортов пока нет",
+ "emptyHint": "Подключитесь к инстансу Plane выше и запустите импорт, чтобы перенести его задачи.",
+ "export": "Экспорт",
+ "exportHint": "Скачайте автономный снимок статусов, меток, циклов и задач этого проекта в формате JSON.",
+ "exportProjectData": "Экспортировать данные проекта",
+ "exportFailed": "Не удалось экспортировать проект.",
+ "pause": "Приостановить",
+ "resume": "Возобновить",
+ "cancel": "Отменить",
+ "countsLegend": "создано / найдено",
+ "countsNotDiscovered": "пока не обнаружено",
+ "rateLimitedRetrying": "Достигнут лимит запросов Plane. Повтор через {seconds} с.",
+ "transientErrorRetrying": "{error} — повтор через {seconds} с.",
+ "statuses": {
+ "pending": "В ожидании",
+ "running": "Выполняется",
+ "paused": "На паузе",
+ "completed": "Завершён",
+ "failed": "Сбой"
+ },
+ "phases": {
+ "discover": "Поиск",
+ "create": "Создание",
+ "link": "Связывание",
+ "rewrite": "Переписывание",
+ "attachments": "Вложения",
+ "done": "Готово"
+ },
+ "entities": {
+ "issue": "Задачи",
+ "comment": "Комментарии",
+ "label": "Метки",
+ "state": "Статусы",
+ "cycle": "Циклы",
+ "attachment": "Вложения"
+ }
+ },
"issueTemplates": {
"addTemplate": "Новый шаблон",
"editTemplate": "Изменить шаблон",
diff --git a/apps/web/messages/uk/permissions.json b/apps/web/messages/uk/permissions.json
index 655b3e3b..cf1a3783 100644
--- a/apps/web/messages/uk/permissions.json
+++ b/apps/web/messages/uk/permissions.json
@@ -23,6 +23,7 @@
"actions": "Дії",
"webhooks": "Вебхуки",
"note_boards": "Дошки нотаток",
+ "import_export": "Імпорт/Експорт",
"danger_zone": "Небезпечна зона"
},
"actions": {
diff --git a/apps/web/messages/uk/sections.json b/apps/web/messages/uk/sections.json
index e4ee5f02..89ee1db4 100644
--- a/apps/web/messages/uk/sections.json
+++ b/apps/web/messages/uk/sections.json
@@ -101,6 +101,10 @@
"label": "Репозиторії",
"description": "Закриття задач, коли їхній pull request змержено в GitHub, GitLab, Gitea, Forgejo або Bitbucket."
},
+ "import-export": {
+ "label": "Імпорт/Експорт",
+ "description": "Імпортуйте задачі, коментарі та мітки із самостійно розміщеного інстансу Plane, або експортуйте дані проєкту у форматі JSON."
+ },
"ai-agents": {
"label": "ШІ-агенти",
"description": "ШІ-агенти, які працюють у цьому проєкті."
diff --git a/apps/web/messages/uk/settings.json b/apps/web/messages/uk/settings.json
index 9f0a57e3..385e71d3 100644
--- a/apps/web/messages/uk/settings.json
+++ b/apps/web/messages/uk/settings.json
@@ -472,6 +472,68 @@
"changeState": "Змінити статус…",
"noState": "Немає статусів."
},
+ "importExport": {
+ "connect": "Підключення до Plane",
+ "connectHint": "Вкажіть самостійно розміщений інстанс Plane, щоб перевірити з'єднання та завантажити його проєкти.",
+ "baseUrl": "URL Plane",
+ "workspaceSlug": "Робочий простір",
+ "apiToken": "API-токен",
+ "apiTokenHint": "API-ключ робочого простору або особистий ключ із доступом на читання до проєктів, задач і учасників робочого простору.",
+ "testConnection": "Перевірити з'єднання",
+ "testing": "Перевірка…",
+ "sourceProject": "Вихідний проєкт",
+ "sourceProjectHint": "Виберіть проєкт Plane, з якого виконати імпорт.",
+ "sourceProjectLabel": "Проєкт Plane",
+ "sourceProjectPlaceholder": "Виберіть проєкт",
+ "noProjects": "У цьому робочому просторі немає проєктів для імпорту.",
+ "stateMapping": "Зіставлення станів",
+ "unmatchedUserPolicyLabel": "Непризначені виконавці та автори коментарів",
+ "unmatchedUserPolicyUnassigned": "Залишити без призначення",
+ "unmatchedUserPolicySkip": "Пропустити призначення або коментар",
+ "previewFailed": "Не вдалося завантажити стани цього проєкту.",
+ "tryAgain": "Спробувати ще раз",
+ "startImport": "Почати імпорт",
+ "starting": "Запуск…",
+ "importStarted": "Імпорт запущено",
+ "jobs": "Завдання імпорту",
+ "jobsHint": "Кожне завдання виконується у фоні, і поки воно не завершене, його можна призупинити, відновити або скасувати.",
+ "emptyTitle": "Імпортів ще немає",
+ "emptyHint": "Підключіться до інстансу Plane вище і почніть імпорт, щоб перенести його задачі.",
+ "export": "Експорт",
+ "exportHint": "Завантажте автономний знімок станів, міток, циклів і задач цього проєкту у форматі JSON.",
+ "exportProjectData": "Експортувати дані проєкту",
+ "exportFailed": "Не вдалося експортувати проєкт.",
+ "pause": "Призупинити",
+ "resume": "Відновити",
+ "cancel": "Скасувати",
+ "countsLegend": "створено / знайдено",
+ "countsNotDiscovered": "ще не знайдено",
+ "rateLimitedRetrying": "Досягнуто ліміту запитів Plane. Повтор через {seconds} с.",
+ "transientErrorRetrying": "{error} — повтор через {seconds} с.",
+ "statuses": {
+ "pending": "В очікуванні",
+ "running": "Виконується",
+ "paused": "На паузі",
+ "completed": "Завершено",
+ "failed": "Збій"
+ },
+ "phases": {
+ "discover": "Пошук",
+ "create": "Створення",
+ "link": "Зв'язування",
+ "rewrite": "Переписування",
+ "attachments": "Вкладення",
+ "done": "Готово"
+ },
+ "entities": {
+ "issue": "Задачі",
+ "comment": "Коментарі",
+ "label": "Мітки",
+ "state": "Статуси",
+ "cycle": "Цикли",
+ "attachment": "Вкладення"
+ }
+ },
"issueTemplates": {
"addTemplate": "Новий шаблон",
"editTemplate": "Змінити шаблон",
diff --git a/apps/web/messages/zh-CN/permissions.json b/apps/web/messages/zh-CN/permissions.json
index 536e8fec..3c23f527 100644
--- a/apps/web/messages/zh-CN/permissions.json
+++ b/apps/web/messages/zh-CN/permissions.json
@@ -23,6 +23,7 @@
"actions": "操作",
"webhooks": "Webhook",
"note_boards": "便签板",
+ "import_export": "导入/导出",
"danger_zone": "危险操作"
},
"actions": {
diff --git a/apps/web/messages/zh-CN/sections.json b/apps/web/messages/zh-CN/sections.json
index 869da947..882047ab 100644
--- a/apps/web/messages/zh-CN/sections.json
+++ b/apps/web/messages/zh-CN/sections.json
@@ -101,6 +101,10 @@
"label": "仓库",
"description": "当关联的拉取请求在 GitHub、GitLab、Gitea、Forgejo 或 Bitbucket 上合并时关闭工作项。"
},
+ "import-export": {
+ "label": "导入/导出",
+ "description": "从自托管的 Plane 实例导入工作项、评论和标签,或将该项目的数据导出为 JSON。"
+ },
"ai-agents": {
"label": "AI 代理",
"description": "在该项目中工作的 AI 代理。"
diff --git a/apps/web/messages/zh-CN/settings.json b/apps/web/messages/zh-CN/settings.json
index 46f3e936..486b7be1 100644
--- a/apps/web/messages/zh-CN/settings.json
+++ b/apps/web/messages/zh-CN/settings.json
@@ -472,6 +472,68 @@
"changeState": "更改状态…",
"noState": "无状态。"
},
+ "importExport": {
+ "connect": "连接 Plane",
+ "connectHint": "输入自托管的 Plane 实例地址以检查连接并加载其项目。",
+ "baseUrl": "Plane 地址",
+ "workspaceSlug": "工作区",
+ "apiToken": "API 令牌",
+ "apiTokenHint": "拥有该工作区项目、工作项和成员读取权限的工作区或个人 API 密钥。",
+ "testConnection": "测试连接",
+ "testing": "测试中…",
+ "sourceProject": "源项目",
+ "sourceProjectHint": "选择要导入的 Plane 项目。",
+ "sourceProjectLabel": "Plane 项目",
+ "sourceProjectPlaceholder": "选择一个项目",
+ "noProjects": "该工作区没有可导入的项目。",
+ "stateMapping": "状态映射",
+ "unmatchedUserPolicyLabel": "未匹配的经办人和评论作者",
+ "unmatchedUserPolicyUnassigned": "留空不分配",
+ "unmatchedUserPolicySkip": "跳过该分配或评论",
+ "previewFailed": "无法加载该项目的状态。",
+ "tryAgain": "重试",
+ "startImport": "开始导入",
+ "starting": "启动中…",
+ "importStarted": "导入已开始",
+ "jobs": "导入任务",
+ "jobsHint": "每个任务都在后台运行,进行中可以暂停、继续或取消。",
+ "emptyTitle": "暂无导入记录",
+ "emptyHint": "在上方连接 Plane 实例并开始导入,以引入其工作项。",
+ "export": "导出",
+ "exportHint": "下载该项目状态、标签、周期和任务的独立 JSON 快照。",
+ "exportProjectData": "导出项目数据",
+ "exportFailed": "无法导出该项目。",
+ "pause": "暂停",
+ "resume": "继续",
+ "cancel": "取消",
+ "countsLegend": "已创建 / 已发现",
+ "countsNotDiscovered": "尚未发现",
+ "rateLimitedRetrying": "已达到 Plane 的速率限制,将在 {seconds} 秒后重试。",
+ "transientErrorRetrying": "{error} — 将在 {seconds} 秒后重试。",
+ "statuses": {
+ "pending": "待处理",
+ "running": "运行中",
+ "paused": "已暂停",
+ "completed": "已完成",
+ "failed": "失败"
+ },
+ "phases": {
+ "discover": "发现中",
+ "create": "创建中",
+ "link": "关联中",
+ "rewrite": "改写中",
+ "attachments": "附件",
+ "done": "完成"
+ },
+ "entities": {
+ "issue": "工作项",
+ "comment": "评论",
+ "label": "标签",
+ "state": "状态",
+ "cycle": "周期",
+ "attachment": "附件"
+ }
+ },
"issueTemplates": {
"addTemplate": "新建模板",
"editTemplate": "编辑模板",
diff --git a/apps/web/src/app/project/[projectKey]/settings/import-export/page.tsx b/apps/web/src/app/project/[projectKey]/settings/import-export/page.tsx
new file mode 100644
index 00000000..deac1383
--- /dev/null
+++ b/apps/web/src/app/project/[projectKey]/settings/import-export/page.tsx
@@ -0,0 +1,5 @@
+import SettingsImportExportPage from '@/features/settings/SettingsImportExportPage';
+
+export default function Page() {
+ return <SettingsImportExportPage />;
+}
diff --git a/apps/web/src/components/ui/progress.tsx b/apps/web/src/components/ui/progress.tsx
new file mode 100644
index 00000000..241d52e5
--- /dev/null
+++ b/apps/web/src/components/ui/progress.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import * as React from 'react';
+import { cn } from 'cn';
+import { Progress as ProgressPrimitive } from 'radix-ui';
+
+function Progress({
+ className,
+ value,
+ ...props
+}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
+ return (
+ <ProgressPrimitive.Root
+ data-slot="progress"
+ className={cn('relative h-2 w-full overflow-hidden rounded-full bg-primary/20', className)}
+ {...props}
+ >
+ <ProgressPrimitive.Indicator
+ data-slot="progress-indicator"
+ className="h-full w-full flex-1 bg-primary transition-all"
+ style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
+ />
+ </ProgressPrimitive.Root>
+ );
+}
+
+export { Progress };
diff --git a/apps/web/src/features/settings/SettingsImportExportPage.tsx b/apps/web/src/features/settings/SettingsImportExportPage.tsx
new file mode 100644
index 00000000..b12b1c23
--- /dev/null
+++ b/apps/web/src/features/settings/SettingsImportExportPage.tsx
@@ -0,0 +1,27 @@
+'use client';
+
+import { useShell } from '@/context/shellContext';
+import { settingsSection } from '@/utils/settingsSections';
+import { useSettingsSectionText } from '@/hooks/useSectionLabels';
+import SectionPageView from '@/components/common/page/SectionPageView';
+import RequirePermission from '@/components/common/permissions/RequirePermission';
+import { SettingsResourceProvider } from './context/settingsPermission';
+import SettingsImportExport from './components/import-export/SettingsImportExport';
+
+const section = settingsSection('import-export');
+
+// The Plane import page (/project/:projectKey/settings/import-export).
+export default function SettingsImportExportPage() {
+ const sectionText = useSettingsSectionText()(section.slug);
+ const { project } = useShell();
+ if (!project) return null;
+ return (
+ <SectionPageView title={sectionText.label} description={sectionText.description}>
+ <SettingsResourceProvider resource={section.resource}>
+ <RequirePermission resource={section.resource} action="read">
+ <SettingsImportExport project={project} />
+ </RequirePermission>
+ </SettingsResourceProvider>
+ </SectionPageView>
+ );
+}
diff --git a/apps/web/src/features/settings/components/custom-fields/FieldChangeWarning.tsx b/apps/web/src/features/settings/components/SettingsWarningBanner.tsx
similarity index 62%
rename from apps/web/src/features/settings/components/custom-fields/FieldChangeWarning.tsx
rename to apps/web/src/features/settings/components/SettingsWarningBanner.tsx
index 0a75533a..bae1eb8e 100644
--- a/apps/web/src/features/settings/components/custom-fields/FieldChangeWarning.tsx
+++ b/apps/web/src/features/settings/components/SettingsWarningBanner.tsx
@@ -1,7 +1,7 @@
+import type { ReactNode } from 'react';
import { TriangleAlert } from 'lucide-react';
-// What a pending change will do to the values issues already hold.
-export default function FieldChangeWarning({ children }: { children: string }) {
+export default function SettingsWarningBanner({ children }: { children: ReactNode }) {
return (
<p className="flex items-start gap-2 rounded-md bg-warning/15 px-2.5 py-2 text-xs">
<TriangleAlert className="mt-0.5 size-3.5 shrink-0 text-warning" />
diff --git a/apps/web/src/features/settings/components/custom-fields/SettingsCustomFieldDialog.tsx b/apps/web/src/features/settings/components/custom-fields/SettingsCustomFieldDialog.tsx
index b17a84cf..1dd8a22a 100644
--- a/apps/web/src/features/settings/components/custom-fields/SettingsCustomFieldDialog.tsx
+++ b/apps/web/src/features/settings/components/custom-fields/SettingsCustomFieldDialog.tsx
@@ -13,7 +13,7 @@ import {
MEMBER_SCOPES,
useFieldTypeLabel,
} from '../../utils/fieldTypes';
-import FieldChangeWarning from './FieldChangeWarning';
+import SettingsWarningBanner from '../SettingsWarningBanner';
import FieldOptionsEditor, { parseOptionValues, type OptionDraft } from './FieldOptionsEditor';
export interface FieldFormValues {
@@ -151,7 +151,7 @@ export default function SettingsCustomFieldDialog({
);
})}
</div>
- {typeChanged && <FieldChangeWarning>{t('typeChangeWarning')}</FieldChangeWarning>}
+ {typeChanged && <SettingsWarningBanner>{t('typeChangeWarning')}</SettingsWarningBanner>}
</div>
{holdsOptions(fieldType) && (
@@ -163,7 +163,7 @@ export default function SettingsCustomFieldDialog({
onPendingChange={setPendingOptions}
/>
{optionsRemoved && (
- <FieldChangeWarning>{t('optionsRemovedWarning')}</FieldChangeWarning>
+ <SettingsWarningBanner>{t('optionsRemovedWarning')}</SettingsWarningBanner>
)}
</div>
)}
@@ -188,7 +188,9 @@ export default function SettingsCustomFieldDialog({
);
})}
</div>
- {scopeNarrowed && <FieldChangeWarning>{t('memberScopeWarning')}</FieldChangeWarning>}
+ {scopeNarrowed && (
+ <SettingsWarningBanner>{t('memberScopeWarning')}</SettingsWarningBanner>
+ )}
</div>
)}
</div>
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsx
new file mode 100644
index 00000000..30f510b0
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExport.tsx
@@ -0,0 +1,77 @@
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import type { ProjectDetail } from '@/lib/api/endpoints/projects';
+import type { PlaneConnectionInput, PlaneProjectOption } from '@/lib/api/endpoints/importExport';
+import { usePermissions } from '@/hooks/usePermissions';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import SettingsSection from '@/components/common/page/SettingsSection';
+import SettingsImportExportConnectForm from './SettingsImportExportConnectForm';
+import SettingsImportExportProjectPicker from './SettingsImportExportProjectPicker';
+import SettingsImportExportMappingReview from './SettingsImportExportMappingReview';
+import SettingsImportExportJobList from './SettingsImportExportJobList';
+import SettingsImportExportDownloadButton from './SettingsImportExportDownloadButton';
+
+export interface PlaneConnection extends PlaneConnectionInput {
+ projects: PlaneProjectOption[];
+}
+
+// The Plane import flow: connect to a source instance, pick a project to import
+// from, and watch the jobs already started. A member who cannot start an import
+// (import_export: create) still sees the job list, since reading it needs only
+// import_export: read, which the page itself already requires.
+export default function SettingsImportExport({ project }: { project: ProjectDetail }) {
+ const t = useTranslations('settings.importExport');
+ const projectKey = project.project.key;
+ const { can } = usePermissions();
+ const canCreate = can('import_export', 'create');
+ const canEdit = can('import_export', 'edit');
+ const [connection, setConnection] = useState<PlaneConnection | null>(null);
+ const [selected, setSelected] = useState<PlaneProjectOption | null>(null);
+
+ function onTested(next: PlaneConnection) {
+ setConnection(next);
+ setSelected(null);
+ }
+
+ return (
+ <div className="space-y-10">
+ {canCreate && (
+ <>
+ <SettingsSection title={t('connect')} description={t('connectHint')}>
+ <SettingsCard className="p-4">
+ <SettingsImportExportConnectForm projectKey={projectKey} onTested={onTested} />
+ </SettingsCard>
+ </SettingsSection>
+ {connection && (
+ <SettingsSection title={t('sourceProject')} description={t('sourceProjectHint')}>
+ <SettingsCard className="space-y-6 p-4">
+ <SettingsImportExportProjectPicker
+ key={connection.baseUrl + connection.workspaceSlug}
+ connection={connection}
+ selected={selected}
+ onSelect={setSelected}
+ />
+ {selected && (
+ <SettingsImportExportMappingReview
+ projectKey={projectKey}
+ connection={connection}
+ selected={selected}
+ onImported={() => setSelected(null)}
+ />
+ )}
+ </SettingsCard>
+ </SettingsSection>
+ )}
+ </>
+ )}
+ <SettingsSection title={t('jobs')} description={t('jobsHint')}>
+ <SettingsImportExportJobList projectKey={projectKey} editable={canEdit} />
+ </SettingsSection>
+ {canCreate && (
+ <SettingsSection title={t('export')} description={t('exportHint')}>
+ <SettingsImportExportDownloadButton projectKey={projectKey} />
+ </SettingsSection>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportConnectForm.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportConnectForm.tsx
new file mode 100644
index 00000000..0c844b16
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportConnectForm.tsx
@@ -0,0 +1,80 @@
+import { useState, type FormEvent } from 'react';
+import { useTranslations } from 'next-intl';
+import { useTestPlaneConnection } from '../../services/settings.service';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import type { PlaneConnection } from './SettingsImportExport';
+
+// baseUrl/workspaceSlug/apiToken for a source Plane instance, checked live
+// against it. Nothing is stored until an import is actually started.
+export default function SettingsImportExportConnectForm({
+ projectKey,
+ onTested,
+}: {
+ projectKey: string;
+ onTested: (connection: PlaneConnection) => void;
+}) {
+ const t = useTranslations('settings.importExport');
+ const testConnection = useTestPlaneConnection(projectKey);
+ const [baseUrl, setBaseUrl] = useState('');
+ const [workspaceSlug, setWorkspaceSlug] = useState('');
+ const [apiToken, setApiToken] = useState('');
+
+ async function submit(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ const input = {
+ baseUrl: baseUrl.trim(),
+ workspaceSlug: workspaceSlug.trim(),
+ apiToken: apiToken.trim(),
+ };
+ try {
+ const result = await testConnection.mutateAsync(input);
+ onTested({ ...input, projects: result.projects });
+ } catch {
+ // Surfaced by the global mutation error toast; nothing local to do.
+ }
+ }
+
+ const valid = baseUrl.trim() !== '' && workspaceSlug.trim() !== '' && apiToken.trim() !== '';
+
+ return (
+ <form onSubmit={(event) => void submit(event)} className="max-w-md space-y-4">
+ <div className="space-y-1.5">
+ <Label htmlFor="plane-base-url">{t('baseUrl')}</Label>
+ <Input
+ id="plane-base-url"
+ type="url"
+ placeholder="https://plane.example.com"
+ value={baseUrl}
+ onChange={(event) => setBaseUrl(event.target.value)}
+ required
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="plane-workspace">{t('workspaceSlug')}</Label>
+ <Input
+ id="plane-workspace"
+ value={workspaceSlug}
+ onChange={(event) => setWorkspaceSlug(event.target.value)}
+ required
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor="plane-token">{t('apiToken')}</Label>
+ <Input
+ id="plane-token"
+ type="password"
+ autoComplete="off"
+ value={apiToken}
+ onChange={(event) => setApiToken(event.target.value)}
+ required
+ />
+ <p className="text-xs text-muted-foreground">{t('apiTokenHint')}</p>
+ </div>
+ <Button type="submit" disabled={testConnection.isPending || !valid}>
+ {testConnection.isPending ? t('testing') : t('testConnection')}
+ </Button>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportDownloadButton.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportDownloadButton.tsx
new file mode 100644
index 00000000..a08e20cc
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportDownloadButton.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Download, Loader2 } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { exportProject } from '@/lib/api/endpoints/importExport';
+
+// Downloads a self-contained JSON snapshot of the project's data. A plain read, not a
+// mutation, so it builds and triggers the file save itself rather than going through
+// React Query - same blob + createObjectURL + synthetic-anchor pattern as
+// DocumentExportDialog's document export.
+export default function SettingsImportExportDownloadButton({ projectKey }: { projectKey: string }) {
+ const t = useTranslations('settings.importExport');
+ const [pending, setPending] = useState(false);
+
+ async function download() {
+ setPending(true);
+ try {
+ const data = await exportProject(projectKey);
+ const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = `${projectKey}-export.json`;
+ anchor.hidden = true;
+ try {
+ document.body.append(anchor);
+ anchor.click();
+ } finally {
+ anchor.remove();
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000);
+ }
+ } catch {
+ toast.error(t('exportFailed'));
+ } finally {
+ setPending(false);
+ }
+ }
+
+ return (
+ <Button variant="outline" disabled={pending} onClick={() => void download()}>
+ {pending ? (
+ <Loader2 className="size-4 animate-spin" />
+ ) : (
+ <Download className="size-4" aria-hidden="true" />
+ )}
+ {t('exportProjectData')}
+ </Button>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportJobCounts.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportJobCounts.tsx
new file mode 100644
index 00000000..68c3bc89
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportJobCounts.tsx
@@ -0,0 +1,41 @@
+import { useTranslations } from 'next-intl';
+import type { ImportEntityType, ImportJob } from '@/lib/api/endpoints/importExport';
+import { Progress } from '@/components/ui/progress';
+
+const ENTITY_ORDER: ImportEntityType[] = [
+ 'issue',
+ 'comment',
+ 'label',
+ 'state',
+ 'cycle',
+ 'attachment',
+];
+
+// Per-entity progress: how many the discover phase found in Plane against how many
+// exist here so far. Attachment counts are metadata captured during create, not
+// downloaded bytes — the job never transfers attachment content.
+export default function SettingsImportExportJobCounts({ counts }: { counts: ImportJob['counts'] }) {
+ const t = useTranslations('settings.importExport');
+ return (
+ <div>
+ <div className="grid grid-cols-1 gap-x-6 gap-y-2 sm:grid-cols-2 lg:grid-cols-3">
+ {ENTITY_ORDER.map((type) => {
+ const { created, discovered } = counts[type];
+ const pct = discovered > 0 ? Math.round((created / discovered) * 100) : 0;
+ return (
+ <div key={type} className="space-y-1">
+ <div className="flex items-center justify-between text-xs">
+ <span className="text-muted-foreground">{t(`entities.${type}`)}</span>
+ <span className="font-medium">
+ {discovered > 0 ? `${created}/${discovered}` : t('countsNotDiscovered')}
+ </span>
+ </div>
+ <Progress value={pct} className="h-1.5" />
+ </div>
+ );
+ })}
+ </div>
+ <p className="mt-2 text-[10px] text-muted-foreground">{t('countsLegend')}</p>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportJobList.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportJobList.tsx
new file mode 100644
index 00000000..f04db3dc
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportJobList.tsx
@@ -0,0 +1,37 @@
+import { useTranslations } from 'next-intl';
+import { useImportJobsQuery } from '../../services/settings.service';
+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';
+import { EmptyState } from '@/components/common/page/EmptyState';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import SettingsImportExportJobRow from './SettingsImportExportJobRow';
+
+export default function SettingsImportExportJobList({
+ projectKey,
+ editable,
+}: {
+ projectKey: string;
+ editable: boolean;
+}) {
+ const t = useTranslations('settings.importExport');
+ const jobsQuery = useImportJobsQuery(projectKey);
+
+ if (jobsQuery.isPending) return <ListSkeleton rows={2} rowClassName="h-24" />;
+
+ const jobs = jobsQuery.data ?? [];
+ if (jobs.length === 0) {
+ return <EmptyState title={t('emptyTitle')} description={t('emptyHint')} />;
+ }
+
+ return (
+ <SettingsCard className="divide-y divide-border/60">
+ {jobs.map((job) => (
+ <SettingsImportExportJobRow
+ key={job.id}
+ job={job}
+ projectKey={projectKey}
+ editable={editable}
+ />
+ ))}
+ </SettingsCard>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportJobRow.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportJobRow.tsx
new file mode 100644
index 00000000..14dc743e
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportJobRow.tsx
@@ -0,0 +1,129 @@
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import type { ImportJob } from '@/lib/api/endpoints/importExport';
+import { formatDateTime } from '@/utils/dates';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ usePauseImportJob,
+ useResumeImportJob,
+ useCancelImportJob,
+} from '../../services/settings.service';
+import SettingsWarningBanner from '../SettingsWarningBanner';
+import SettingsImportExportJobCounts from './SettingsImportExportJobCounts';
+
+const STATUS_VARIANT: Record<
+ ImportJob['status'],
+ 'default' | 'secondary' | 'destructive' | 'outline'
+> = {
+ pending: 'outline',
+ running: 'default',
+ paused: 'secondary',
+ completed: 'secondary',
+ failed: 'destructive',
+};
+
+// One import job: its status, phase, per-entity progress, and the actions its
+// current status allows. Pause/resume/cancel are shown only when the status lets
+// them succeed, matching what the API accepts (409 otherwise).
+export default function SettingsImportExportJobRow({
+ job,
+ projectKey,
+ editable,
+}: {
+ job: ImportJob;
+ projectKey: string;
+ editable: boolean;
+}) {
+ const t = useTranslations('settings.importExport');
+ const pause = usePauseImportJob(projectKey);
+ const resume = useResumeImportJob(projectKey);
+ const cancel = useCancelImportJob(projectKey);
+
+ const canPause = editable && (job.status === 'pending' || job.status === 'running');
+ const canResume = editable && job.status === 'paused';
+ const canCancel =
+ editable && (job.status === 'pending' || job.status === 'running' || job.status === 'paused');
+
+ // lastError is cleared on every successful tick, so seeing one while still
+ // 'pending' means the job is currently waiting out a retry, not stalled —
+ // 'failed' is the only terminal, non-retrying error state.
+ const isRetrying = job.status === 'pending' && job.lastError != null;
+ const isWorking = job.status === 'pending' && job.lastError == null;
+
+ // The 2s poll (useImportJobsQuery) only refreshes nextAttemptAt itself; without
+ // this, the displayed countdown would only move in those 2s jumps instead of
+ // ticking down in real time between polls.
+ const [, forceTick] = useState(0);
+ useEffect(() => {
+ if (!isRetrying) return;
+ const id = setInterval(() => forceTick((n) => n + 1), 1000);
+ return () => clearInterval(id);
+ }, [isRetrying]);
+
+ const retrySeconds = isRetrying
+ ? Math.max(0, Math.round((new Date(job.nextAttemptAt).getTime() - Date.now()) / 1000))
+ : 0;
+
+ return (
+ <div className="space-y-3 p-4">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <Badge variant={STATUS_VARIANT[job.status]}>{t(`statuses.${job.status}`)}</Badge>
+ {(isWorking || isRetrying) && (
+ <>
+ {isWorking && (
+ <span className="size-1.5 animate-pulse rounded-full bg-primary" aria-hidden />
+ )}
+ <span className="text-sm font-medium">{t(`phases.${job.phase}`)}</span>
+ </>
+ )}
+ <span className="text-xs text-muted-foreground">{formatDateTime(job.createdAt)}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ {canPause && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={pause.isPending}
+ onClick={() => pause.mutate(job.id)}
+ >
+ {t('pause')}
+ </Button>
+ )}
+ {canResume && (
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={resume.isPending}
+ onClick={() => resume.mutate(job.id)}
+ >
+ {t('resume')}
+ </Button>
+ )}
+ {canCancel && (
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={cancel.isPending}
+ onClick={() => cancel.mutate(job.id)}
+ >
+ {t('cancel')}
+ </Button>
+ )}
+ </div>
+ </div>
+ {isRetrying && job.lastError && (
+ <SettingsWarningBanner>
+ {job.lastError === 'rate limited'
+ ? t('rateLimitedRetrying', { seconds: retrySeconds })
+ : t('transientErrorRetrying', { error: job.lastError, seconds: retrySeconds })}
+ </SettingsWarningBanner>
+ )}
+ {job.status === 'failed' && job.lastError && (
+ <p className="text-xs text-destructive">{job.lastError}</p>
+ )}
+ <SettingsImportExportJobCounts counts={job.counts} />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsx
new file mode 100644
index 00000000..07139aca
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportMappingReview.tsx
@@ -0,0 +1,134 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { useCreateImportJob, useTestPlaneStatesPreview } from '../../services/settings.service';
+import { Button } from '@/components/ui/button';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import SettingsCard from '@/components/common/page/SettingsCard';
+import ListSkeleton from '@/components/common/skeleton/ListSkeleton';
+import SettingsImportExportStateOverrideRow from './SettingsImportExportStateOverrideRow';
+import type {
+ PlaneProjectOption,
+ StateCategory,
+ UnmatchedUserPolicy,
+} from '@/lib/api/endpoints/importExport';
+import type { PlaneConnection } from './SettingsImportExport';
+
+// Shown once a source project is picked, before the job is created: the states
+// Plane reports for it, each pre-filled with the category itsaplan would map it to
+// automatically, and the unmatched-assignee/comment-author policy. Only a state row
+// the user actually changes from its default is sent as an override.
+export default function SettingsImportExportMappingReview({
+ projectKey,
+ connection,
+ selected,
+ onImported,
+}: {
+ projectKey: string;
+ connection: PlaneConnection;
+ selected: PlaneProjectOption;
+ onImported: () => void;
+}) {
+ const t = useTranslations('settings.importExport');
+ const preview = useTestPlaneStatesPreview(projectKey, {
+ baseUrl: connection.baseUrl,
+ workspaceSlug: connection.workspaceSlug,
+ apiToken: connection.apiToken,
+ planeProjectId: selected.id,
+ });
+ const createJob = useCreateImportJob(projectKey);
+ const [overrides, setOverrides] = useState<Record<string, StateCategory>>({});
+ const [unmatchedUserPolicy, setUnmatchedUserPolicy] = useState<UnmatchedUserPolicy>('unassigned');
+
+ async function start() {
+ try {
+ await createJob.mutateAsync({
+ baseUrl: connection.baseUrl,
+ workspaceSlug: connection.workspaceSlug,
+ apiToken: connection.apiToken,
+ planeProjectId: selected.id,
+ planeProjectKey: selected.identifier,
+ unmatchedUserPolicy,
+ stateOverrides: overrides,
+ });
+ toast.success(t('importStarted'));
+ onImported();
+ } catch {
+ // Surfaced by the global mutation error toast; nothing local to do.
+ }
+ }
+
+ function setOverride(stateId: string, defaultCategory: StateCategory, category: StateCategory) {
+ setOverrides((prev) => {
+ if (category === defaultCategory) {
+ const { [stateId]: _removed, ...rest } = prev;
+ return rest;
+ }
+ return { ...prev, [stateId]: category };
+ });
+ }
+
+ if (preview.isPending) return <ListSkeleton rows={3} rowClassName="h-10" />;
+
+ if (preview.isError) {
+ return (
+ <div className="space-y-2 text-sm">
+ <p className="text-muted-foreground">{t('previewFailed')}</p>
+ <Button variant="outline" size="sm" onClick={() => void preview.refetch()}>
+ {t('tryAgain')}
+ </Button>
+ </div>
+ );
+ }
+
+ const states = preview.data?.states ?? [];
+
+ return (
+ <div className="space-y-6">
+ {states.length > 0 && (
+ <div className="space-y-2">
+ <Label>{t('stateMapping')}</Label>
+ <SettingsCard className="max-h-64 divide-y divide-border/60 overflow-y-auto">
+ {states.map((state) => (
+ <SettingsImportExportStateOverrideRow
+ key={state.id}
+ state={state}
+ value={overrides[state.id] ?? state.category}
+ onChange={(category) => setOverride(state.id, state.category, category)}
+ />
+ ))}
+ </SettingsCard>
+ </div>
+ )}
+
+ <div className="w-64 space-y-1.5">
+ <Label htmlFor="unmatched-user-policy">{t('unmatchedUserPolicyLabel')}</Label>
+ <Select
+ value={unmatchedUserPolicy}
+ onValueChange={(value) => setUnmatchedUserPolicy(value as UnmatchedUserPolicy)}
+ >
+ <SelectTrigger id="unmatched-user-policy" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="unassigned">{t('unmatchedUserPolicyUnassigned')}</SelectItem>
+ <SelectItem value="skip">{t('unmatchedUserPolicySkip')}</SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+
+ <Button disabled={createJob.isPending} onClick={() => void start()}>
+ {createJob.isPending ? t('starting') : t('startImport')}
+ </Button>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportProjectPicker.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportProjectPicker.tsx
new file mode 100644
index 00000000..b068a5a8
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportProjectPicker.tsx
@@ -0,0 +1,50 @@
+import { useTranslations } from 'next-intl';
+import { Label } from '@/components/ui/label';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import type { PlaneConnection } from './SettingsImportExport';
+import type { PlaneProjectOption } from '@/lib/api/endpoints/importExport';
+
+// The projects of the tested workspace. Selecting one is reported to the parent,
+// which shows the mapping review step for it — this component only picks.
+export default function SettingsImportExportProjectPicker({
+ connection,
+ selected,
+ onSelect,
+}: {
+ connection: PlaneConnection;
+ selected: PlaneProjectOption | null;
+ onSelect: (project: PlaneProjectOption | null) => void;
+}) {
+ const t = useTranslations('settings.importExport');
+
+ if (connection.projects.length === 0) {
+ return <p className="text-sm text-muted-foreground">{t('noProjects')}</p>;
+ }
+
+ return (
+ <div className="w-64 space-y-1.5">
+ <Label htmlFor="plane-source-project">{t('sourceProjectLabel')}</Label>
+ <Select
+ value={selected?.id ?? ''}
+ onValueChange={(id) => onSelect(connection.projects.find((p) => p.id === id) ?? null)}
+ >
+ <SelectTrigger id="plane-source-project" className="w-full">
+ <SelectValue placeholder={t('sourceProjectPlaceholder')} />
+ </SelectTrigger>
+ <SelectContent>
+ {connection.projects.map((p) => (
+ <SelectItem key={p.id} value={p.id}>
+ {p.name} ({p.identifier})
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/components/import-export/SettingsImportExportStateOverrideRow.tsx b/apps/web/src/features/settings/components/import-export/SettingsImportExportStateOverrideRow.tsx
new file mode 100644
index 00000000..d0cd53a1
--- /dev/null
+++ b/apps/web/src/features/settings/components/import-export/SettingsImportExportStateOverrideRow.tsx
@@ -0,0 +1,49 @@
+import { useTranslations } from 'next-intl';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import type { PlaneStateOption, StateCategory } from '@/lib/api/endpoints/importExport';
+
+const STATE_CATEGORIES: StateCategory[] = [
+ 'backlog',
+ 'unstarted',
+ 'started',
+ 'completed',
+ 'canceled',
+];
+
+// One Plane state and the itsaplan category it will be created with, changeable
+// from what the automatic mapping picked. A row of the card its parent renders
+// (divide-y, this component only supplies its own padding).
+export default function SettingsImportExportStateOverrideRow({
+ state,
+ value,
+ onChange,
+}: {
+ state: PlaneStateOption;
+ value: StateCategory;
+ onChange: (category: StateCategory) => void;
+}) {
+ const stateTypes = useTranslations('display');
+ return (
+ <div className="flex items-center justify-between gap-4 px-3 py-2">
+ <span className="min-w-0 flex-1 truncate text-sm">{state.name}</span>
+ <Select value={value} onValueChange={(next) => onChange(next as StateCategory)}>
+ <SelectTrigger size="sm" className="w-36 shrink-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {STATE_CATEGORIES.map((category) => (
+ <SelectItem key={category} value={category}>
+ {stateTypes(`stateTypes.${category}`)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/services/settings.service.ts b/apps/web/src/features/settings/services/settings.service.ts
index 88a65911..1bf792ea 100644
--- a/apps/web/src/features/settings/services/settings.service.ts
+++ b/apps/web/src/features/settings/services/settings.service.ts
@@ -41,6 +41,17 @@ import {
connectGitRepositories,
disconnectGitRepository,
} from '@/lib/api/endpoints/git';
+import {
+ type CreateImportJobInput,
+ type PlaneConnectionInput,
+ testPlaneConnection,
+ testPlaneStatesPreview,
+ createImportJob,
+ listImportJobs,
+ pauseImportJob,
+ resumeImportJob,
+ cancelImportJob,
+} from '@/lib/api/endpoints/importExport';
import {
createIssueTemplate,
updateIssueTemplate,
@@ -279,6 +290,73 @@ export function useDisconnectGitRepository(projectKey: string, connectionId: num
});
}
+// Import/export section: testing a connection to a source Plane instance,
+// starting an import job, and tracking the ones already running.
+export function useTestPlaneConnection(projectKey: string) {
+ return useMutation({
+ mutationFn: (input: PlaneConnectionInput) => testPlaneConnection(projectKey, input),
+ });
+}
+
+// Fetched automatically once a source project is picked, in the mapping review step.
+export function useTestPlaneStatesPreview(
+ projectKey: string,
+ input: (PlaneConnectionInput & { planeProjectId: string }) | null,
+) {
+ return useQuery({
+ queryKey: input
+ ? qk.planePreview(projectKey, input.planeProjectId)
+ : qk.planePreview(projectKey, 'none'),
+ queryFn: () => testPlaneStatesPreview(projectKey, input!),
+ enabled: input != null,
+ });
+}
+
+export function useCreateImportJob(projectKey: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (input: CreateImportJobInput) => createImportJob(projectKey, input),
+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.importJobs(projectKey) }),
+ });
+}
+
+// Polled while a job is still pending or running, the same shape as
+// useAgentScheduleRuns.
+export function useImportJobsQuery(projectKey: string) {
+ return useQuery({
+ queryKey: qk.importJobs(projectKey),
+ queryFn: () => listImportJobs(projectKey),
+ refetchInterval: (query) =>
+ query.state.data?.some((job) => job.status === 'running' || job.status === 'pending')
+ ? 2000
+ : false,
+ });
+}
+
+export function usePauseImportJob(projectKey: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: number) => pauseImportJob(id),
+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.importJobs(projectKey) }),
+ });
+}
+
+export function useResumeImportJob(projectKey: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: number) => resumeImportJob(id),
+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.importJobs(projectKey) }),
+ });
+}
+
+export function useCancelImportJob(projectKey: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: number) => cancelImportJob(id),
+ onSuccess: () => qc.invalidateQueries({ queryKey: qk.importJobs(projectKey) }),
+ });
+}
+
// General section: which optional sections the project shows. The current state
// comes with the project payload (getProject), so a write only invalidates it —
// the navigation and the sections themselves read it from there.
diff --git a/apps/web/src/lib/api/endpoints/importExport.ts b/apps/web/src/lib/api/endpoints/importExport.ts
new file mode 100644
index 00000000..e9d8d78c
--- /dev/null
+++ b/apps/web/src/lib/api/endpoints/importExport.ts
@@ -0,0 +1,132 @@
+import { request } from '@/lib/api/core/client';
+
+// Import jobs bring issues in from a source Plane instance (mirrors apps/api
+// modules/import-export/service.ts). Creating one stores an encrypted credential
+// and leaves the job 'pending' for the worker to drive through its phases.
+
+export type ImportJobPhase = 'discover' | 'create' | 'link' | 'rewrite' | 'attachments' | 'done';
+export type ImportJobStatus = 'pending' | 'running' | 'paused' | 'completed' | 'failed';
+export type ImportEntityType = 'issue' | 'comment' | 'label' | 'state' | 'cycle' | 'attachment';
+
+export interface ImportEntityCount {
+ discovered: number;
+ created: number;
+}
+
+export interface ImportJob {
+ id: number;
+ projectId: number;
+ source: 'plane';
+ phase: ImportJobPhase;
+ status: ImportJobStatus;
+ counts: Record<ImportEntityType, ImportEntityCount>;
+ lastError: string | null;
+ nextAttemptAt: string;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface PlaneProjectOption {
+ id: string;
+ name: string;
+ identifier: string;
+}
+
+export type StateCategory = 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled';
+export type UnmatchedUserPolicy = 'unassigned' | 'skip';
+
+export interface PlaneStateOption {
+ id: string;
+ name: string;
+ category: StateCategory;
+}
+
+export interface PlaneConnectionInput {
+ baseUrl: string;
+ workspaceSlug: string;
+ apiToken: string;
+}
+
+export interface CreateImportJobInput extends PlaneConnectionInput {
+ planeProjectId: string;
+ planeProjectKey: string;
+ unmatchedUserPolicy?: UnmatchedUserPolicy;
+ stateOverrides?: Record<string, StateCategory>;
+}
+
+export const testPlaneConnection = (projectKey: string, input: PlaneConnectionInput) =>
+ request<{ projects: PlaneProjectOption[] }>(
+ `/projects/${projectKey}/import-jobs/test-connection`,
+ { method: 'POST', body: JSON.stringify(input) },
+ );
+
+export const testPlaneStatesPreview = (
+ projectKey: string,
+ input: PlaneConnectionInput & { planeProjectId: string },
+) =>
+ request<{ states: PlaneStateOption[] }>(`/projects/${projectKey}/import-jobs/plane-preview`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ });
+
+export const createImportJob = (projectKey: string, input: CreateImportJobInput) =>
+ request<ImportJob>(`/projects/${projectKey}/import-jobs`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ });
+
+export const listImportJobs = (projectKey: string) =>
+ request<ImportJob[]>(`/projects/${projectKey}/import-jobs`);
+
+export const pauseImportJob = (id: number) =>
+ request<ImportJob>(`/import-jobs/${id}/pause`, { method: 'POST' });
+
+export const resumeImportJob = (id: number) =>
+ request<ImportJob>(`/import-jobs/${id}/resume`, { method: 'POST' });
+
+export const cancelImportJob = (id: number) =>
+ request<ImportJob>(`/import-jobs/${id}/cancel`, { method: 'POST' });
+
+export interface ExportedComment {
+ authorName: string | null;
+ authorEmail: string | null;
+ body: string;
+ createdAt: string;
+ replyToIndex: number | null;
+}
+
+export interface ExportedRelation {
+ kind: string;
+ targetIdentifier: string;
+}
+
+export interface ExportedIssue {
+ identifier: string;
+ title: string;
+ description: string;
+ state: string;
+ labels: string[];
+ cycle: string | null;
+ priority: string | null;
+ startDate: string | null;
+ dueDate: string | null;
+ parentIdentifier: string | null;
+ assigneeEmail: string | null;
+ comments: ExportedComment[];
+ relations: ExportedRelation[];
+}
+
+// A self-contained snapshot of a project's data - states, labels, cycles, and issues
+// (with their comments and relations) - as portable JSON. Not a live sync to any
+// target, a download; mirrors apps/api's ProjectExportResponse.
+export interface ProjectExport {
+ exportedAt: string;
+ project: { key: string; name: string; description: string };
+ states: { name: string; category: string }[];
+ labels: { name: string; color: string }[];
+ cycles: { name: string; startDate: string; endDate: string; goal: string }[];
+ issues: ExportedIssue[];
+}
+
+export const exportProject = (projectKey: string) =>
+ request<ProjectExport>(`/projects/${projectKey}/import-jobs/export`);
diff --git a/apps/web/src/lib/api/endpoints/roles.ts b/apps/web/src/lib/api/endpoints/roles.ts
index e8ebbe20..1b03f226 100644
--- a/apps/web/src/lib/api/endpoints/roles.ts
+++ b/apps/web/src/lib/api/endpoints/roles.ts
@@ -27,7 +27,8 @@ export type PermissionResource =
| 'actions'
| 'webhooks'
| 'note_boards'
- | 'danger_zone';
+ | 'danger_zone'
+ | 'import_export';
export type ResourcePermissions = Record<PermissionAction, boolean>;
diff --git a/apps/web/src/services/queryKeys.ts b/apps/web/src/services/queryKeys.ts
index b8d70882..8e567a85 100644
--- a/apps/web/src/services/queryKeys.ts
+++ b/apps/web/src/services/queryKeys.ts
@@ -55,6 +55,11 @@ export const qk = {
actions: (projectKey: string) => ['actions', projectKey] as const,
webhooks: (projectKey: string) => ['webhooks', projectKey] as const,
webhookDeliveries: (webhookId: number) => ['webhookDeliveries', webhookId] as const,
+ // The project's Plane import jobs (the Import/Export settings section).
+ importJobs: (projectKey: string) => ['importJobs', projectKey] as const,
+ // The mapping review preview for one candidate Plane project, before a job exists.
+ planePreview: (projectKey: string, planeProjectId: string) =>
+ ['planePreview', projectKey, planeProjectId] as const,
// Saved dashboards (the analytics tabs) and the read-only metrics behind their
// widgets. `kind` names the metric (stats/pulse/throughput/breakdown/...) and
// `params` scopes it to the widget's query (window, filters).
diff --git a/apps/web/src/utils/settingsSections.ts b/apps/web/src/utils/settingsSections.ts
index 26049484..7fb47481 100644
--- a/apps/web/src/utils/settingsSections.ts
+++ b/apps/web/src/utils/settingsSections.ts
@@ -4,6 +4,7 @@ import {
Columns3,
FileText,
GitPullRequest,
+ Import,
Info,
ListPlus,
type LucideIcon,
@@ -103,6 +104,12 @@ export const SETTINGS_SECTIONS: SettingsSection[] = [
resource: 'integrations',
group: 'automation',
},
+ {
+ slug: 'import-export',
+ icon: Import,
+ resource: 'import_export',
+ group: 'automation',
+ },
];
// The agents section is its own nav route (not a /settings/:section page), but
diff --git a/apps/worker/AGENTS.md b/apps/worker/AGENTS.md
index 4d1e1ce2..a889c50c 100644
--- a/apps/worker/AGENTS.md
+++ b/apps/worker/AGENTS.md
@@ -1,8 +1,8 @@
# worker — rules
-Webhook delivery worker: a standalone Bun process that drains the
-`webhook_delivery` queue and posts signed payloads to subscriber URLs. Runs as its
-own service (own Dockerfile), separate from `apps/api`. See root `AGENTS.md`.
+Standalone Bun process (own Dockerfile, separate from `apps/api`) that drains a
+few background queues: webhook delivery, notification delivery, agent
+scheduling, and source imports. See root `AGENTS.md`.
## What it does
@@ -19,6 +19,54 @@ own service (own Dockerfile), separate from `apps/api`. See root `AGENTS.md`.
`@repo/mailer`, Telegram through the Bot API. The provider credentials are read
from the database and decrypted here (`notification-send.ts`), so the process
needs `APP_ENCRYPTION_KEY`.
+- Drives `import_job` rows through Discover -> Create -> Link -> Rewrite ->
+ Attachments -> Done. See "Source imports" below.
+
+## Source imports
+
+`import-worker.ts` polls `import_job` for a due `pending` row (`import-store.ts`,
+same claim-with-lease shape as `webhook_delivery`) and advances it by one bounded
+chunk of work per tick — a large import interleaves across many ticks rather than
+running to completion in one.
+
+- `canonical.ts` — the source-independent shape an adapter produces
+ (`CanonicalIssue`, `CanonicalState`, ...). Plain types, no logic.
+- `reader.ts` — the `SourceReader` port a source adapter implements.
+- `plane-adapter.ts` — the only implementation today. HTTP against a Plane
+ instance via `pinnedFetch`, using the credential decrypted from the job row
+ (base URL, workspace slug, API key — never from env, since this has to work
+ against any operator's self-hosted instance). `docs/dev/plane-import-source-notes.md`
+ is the spec it follows for pagination, rate limiting, and Plane's actual wire
+ shapes.
+- `cross-reference.ts` — pure text matching for a source's own "KEY-123"-style
+ issue identifier: no `@repo/db`, no network, unit-tested directly. What
+ the Rewrite phase resolves into itsaplan's own issue ids.
+- `import-store.ts` — all `@repo/db` access for imports: claiming due jobs,
+ reading/writing a job's phase/cursor/status, the `import_record`
+ source-id-to-local-id upsert, and creating the local rows (states, labels,
+ cycles, issues, comments, issue links) an import produces.
+- `import-worker.ts` — the phase state machine. Discover snapshots every
+ source id up front (`import_record` rows with no local id yet) before Create
+ begins, rather than treating the source's own pagination cursor as the
+ resumability anchor across the whole job — see the notes file's "Pagination"
+ section for why. Create/Link/Rewrite resume from `import_record`'s own id,
+ not the source's cursor. Link also gives every issue's parent link a second
+ chance to resolve, the same way it already does for relations. Rewrite scans
+ every created issue's description and comments for a mention of the
+ source's own identifier and rewrites it to this project's, purely from
+ already-local data — it makes no further requests to the source.
+- The Attachments phase re-lists each issue's attachments (metadata alone,
+ captured during Create, is not reused — a download needs a fresh resolve of
+ the two-hop, hour-lived URL right before it happens) and downloads the
+ bytes it hasn't already created a local row for. Size and mime type are
+ checked against the instance's own upload settings (`@repo/db`'s
+ `getStorageSettings`/`mimeAllowed`) before the request; the project's
+ storage quota (`@repo/db`'s `projectStoredBytes`, `@repo/storage`'s
+ `putObject`/`attachmentObjectKey`) is checked before the upload and once
+ more inside the same advisory lock (`lockAttachmentStorage`) an interactive
+ upload takes, so the two never both pass a check that only one of them can
+ actually fit. A rejected attachment (`AttachmentRejectedError`) is logged
+ and skipped, not treated as a failed tick.
## Invariants
@@ -41,7 +89,15 @@ own service (own Dockerfile), separate from `apps/api`. See root `AGENTS.md`.
the lease comfortably larger than `WEBHOOK_TIMEOUT_MS`.
- **Pure logic stays dependency-free.** `backoff.ts`, `signature.ts`, and
`isRetryableStatus` import nothing from `@repo/db`, so unit tests run without a
- database. Keep DB access in `store.ts`.
+ database. Keep DB access in `store.ts`. Same split for imports: `canonical.ts`,
+ `reader.ts`, `plane-adapter.ts`, and `cross-reference.ts` import nothing from
+ `@repo/db` (its state-category normalization, markdown conversion,
+ cursor/rate-limit, and cross-reference matching logic are unit-tested
+ directly); `@repo/db` access stays in `import-store.ts`.
+- **An import job's credential is decrypted here, never routed through
+ `packages/db/src/domains/`.** That directory is for config more than one
+ process reads; only the worker ever decrypts a stored import credential (the
+ api sees the raw token once, at creation, before it is encrypted).
## Config
@@ -50,7 +106,12 @@ All via env with defaults (see `src/config.ts`): `WEBHOOK_POLL_INTERVAL_MS`,
`WEBHOOK_DISABLE_THRESHOLD`, `WEBHOOK_LEASE_SECONDS`, `WEBHOOK_CLEANUP_DAYS`,
`WEBHOOK_CLEANUP_EVERY_TICKS`. Only `DATABASE_URL` is required for webhook
delivery. Notification delivery also needs `APP_ENCRYPTION_KEY` (the same value the
-api uses) to read the stored provider credentials.
+api uses) to read the stored provider credentials, and so does source import (it
+decrypts the stored Plane credential with it too). `IMPORT_POLL_INTERVAL_MS` tunes
+the import worker's poll interval. The Attachments phase needs the same `S3_*`
+variables (`S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`,
+`S3_REGION`, `S3_FORCE_PATH_STYLE`) the api reads for its own uploads — both
+processes write to the same bucket.
## Tests
diff --git a/apps/worker/Dockerfile b/apps/worker/Dockerfile
index 61e09cb6..df8690a0 100644
--- a/apps/worker/Dockerfile
+++ b/apps/worker/Dockerfile
@@ -18,6 +18,7 @@ COPY packages/agent-tools/package.json ./packages/agent-tools/
COPY packages/crypto/package.json ./packages/crypto/
COPY packages/mailer/package.json ./packages/mailer/
COPY packages/net/package.json ./packages/net/
+COPY packages/storage/package.json ./packages/storage/
COPY packages/runner/package.json ./packages/runner/
COPY packages/eslint-config/package.json ./packages/eslint-config/
# --filter worker installs only the worker workspace and its dependency closure.
diff --git a/apps/worker/package.json b/apps/worker/package.json
index f3b9c73c..7903e2d2 100644
--- a/apps/worker/package.json
+++ b/apps/worker/package.json
@@ -11,9 +11,11 @@
"test": "bun test --env-file=../../.env.test"
},
"dependencies": {
+ "@repo/crypto": "workspace:*",
"@repo/db": "workspace:*",
"@repo/mailer": "workspace:*",
"@repo/net": "workspace:*",
+ "@repo/storage": "workspace:*",
"croner": "^10.0.1",
"drizzle-orm": "^0.45.2"
},
diff --git a/apps/worker/src/__tests__/integration/import-store.test.ts b/apps/worker/src/__tests__/integration/import-store.test.ts
new file mode 100644
index 00000000..c4865dd6
--- /dev/null
+++ b/apps/worker/src/__tests__/integration/import-store.test.ts
@@ -0,0 +1,392 @@
+import { describe, it, expect, afterEach } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import {
+ db,
+ team,
+ project,
+ projectColumn,
+ issue,
+ issueAttachment,
+ importJob,
+ user,
+ getStorageSettings,
+ setSetting,
+ STORAGE_SETTING_KEY,
+ type StorageSettings,
+} from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { getObject } from '@repo/storage';
+import {
+ claimDueImportJobs,
+ createLocalStateAndRecord,
+ createLocalIssueAndRecord,
+ createLocalAttachmentAndRecord,
+ findImportRecord,
+ AttachmentRejectedError,
+} from '../../import-store';
+
+// Nothing here calls resetDb (the worker has no api to reset for), so every
+// helper below makes its own isolated team/project/user with a random key,
+// matching notification-send.test.ts's own convention.
+
+async function makeProject(): Promise<{ projectId: number; columnId: number; userId: string }> {
+ const [teamRow] = await db.insert(team).values({ name: 'Importers' }).returning({ id: team.id });
+ const [projectRow] = await db
+ .insert(project)
+ .values({ teamId: teamRow!.id, key: randomUUID().slice(0, 8), name: 'Imported' })
+ .returning({ id: project.id });
+ const [columnRow] = await db
+ .insert(projectColumn)
+ .values({ projectId: projectRow!.id, name: 'Backlog', position: 1 })
+ .returning({ id: projectColumn.id });
+ const userId = randomUUID();
+ await db.insert(user).values({ id: userId, name: 'Importer', email: `${userId}@example.test` });
+ return { projectId: projectRow!.id, columnId: columnRow!.id, userId };
+}
+
+async function makeImportJob(projectId: number, userId: string): Promise<number> {
+ const [row] = await db
+ .insert(importJob)
+ .values({ projectId, createdByUserId: userId, source: 'plane' })
+ .returning({ id: importJob.id });
+ return row!.id;
+}
+
+async function makeIssue(projectId: number, columnId: number, title = 'Task'): Promise<number> {
+ const [row] = await db
+ .insert(issue)
+ .values({ projectId, columnId, sequenceNumber: Math.floor(Math.random() * 1_000_000), title })
+ .returning({ id: issue.id });
+ return row!.id;
+}
+
+describe('claimDueImportJobs', () => {
+ it('claims a due pending job, bumps attempts, and clears a stale last_error', async () => {
+ const { projectId, userId } = await makeProject();
+ const jobId = await makeImportJob(projectId, userId);
+ await db
+ .update(importJob)
+ .set({ attempts: 3, lastError: 'rate limited', nextAttemptAt: new Date(Date.now() - 1000) })
+ .where(eq(importJob.id, jobId));
+
+ // A large limit, not 1: other due jobs can be sitting in the shared test
+ // database from earlier runs of this same suite (nothing here truncates
+ // import_job between runs), and claimDueImportJobs orders by next_attempt_at
+ // with no per-test scope to filter on.
+ const claimed = await claimDueImportJobs(1000);
+ const job = claimed.find((j) => j.id === jobId);
+
+ expect(job).toBeDefined();
+ expect(job!.attempts).toBe(4);
+ const [row] = await db.select().from(importJob).where(eq(importJob.id, jobId));
+ expect(row!.lastError).toBeNull();
+ expect(row!.nextAttemptAt.getTime()).toBeGreaterThan(Date.now());
+ });
+
+ it('does not claim a job whose next attempt is still in the future', async () => {
+ const { projectId, userId } = await makeProject();
+ const jobId = await makeImportJob(projectId, userId);
+ await db
+ .update(importJob)
+ .set({ nextAttemptAt: new Date(Date.now() + 60_000) })
+ .where(eq(importJob.id, jobId));
+
+ const claimed = await claimDueImportJobs(50);
+ expect(claimed.some((j) => j.id === jobId)).toBe(false);
+ });
+
+ it('does not claim a paused job', async () => {
+ const { projectId, userId } = await makeProject();
+ const jobId = await makeImportJob(projectId, userId);
+ await db
+ .update(importJob)
+ .set({ status: 'paused', nextAttemptAt: new Date(Date.now() - 1000) })
+ .where(eq(importJob.id, jobId));
+
+ const claimed = await claimDueImportJobs(50);
+ expect(claimed.some((j) => j.id === jobId)).toBe(false);
+ });
+});
+
+describe('createLocalStateAndRecord', () => {
+ it('creates a new column and records the mapping', async () => {
+ const { projectId, userId } = await makeProject();
+ const jobId = await makeImportJob(projectId, userId);
+
+ const columnId = await createLocalStateAndRecord(jobId, 'plane-state-1', projectId, {
+ sourceId: 'plane-state-1',
+ name: 'In Review',
+ category: 'started',
+ });
+
+ const [row] = await db.select().from(projectColumn).where(eq(projectColumn.id, columnId));
+ expect(row?.name).toBe('In Review');
+ expect(row?.stateType).toBe('started');
+ expect(await findImportRecord(jobId, 'state', 'plane-state-1')).toEqual({ localId: columnId });
+ });
+
+ it('reuses an existing column by name without changing its hand-configured state type', async () => {
+ const { projectId, userId } = await makeProject();
+ const jobId = await makeImportJob(projectId, userId);
+ const [existing] = await db
+ .insert(projectColumn)
+ .values({ projectId, name: 'Done', stateType: 'completed', position: 2 })
+ .returning({ id: projectColumn.id });
+
+ const columnId = await createLocalStateAndRecord(jobId, 'plane-state-2', projectId, {
+ sourceId: 'plane-state-2',
+ name: 'Done',
+ category: 'canceled',
+ });
+
+ expect(columnId).toBe(existing!.id);
+ const [row] = await db.select().from(projectColumn).where(eq(projectColumn.id, columnId));
+ expect(row?.stateType).toBe('completed');
+ });
+});
+
+describe('createLocalIssueAndRecord', () => {
+ it('creates a new issue with a sequence number and records the mapping', async () => {
+ const { projectId, columnId, userId } = await makeProject();
+ const jobId = await makeImportJob(projectId, userId);
+
+ const issueId = await createLocalIssueAndRecord(jobId, 'plane-issue-1', 'ROOMS-1', {
+ projectId,
+ columnId,
+ cycleId: null,
+ parentId: null,
+ assigneeUserId: null,
+ title: 'Fix the leak',
+ description: '',
+ priority: null,
+ startDate: null,
+ dueDate: null,
+ });
+
+ const [row] = await db.select().from(issue).where(eq(issue.id, issueId));
+ expect(row?.title).toBe('Fix the leak');
+ expect(await findImportRecord(jobId, 'issue', 'plane-issue-1')).toEqual({ localId: issueId });
+ });
+
+ it('reuses an issue that already has the same title instead of duplicating it', async () => {
+ const { projectId, columnId, userId } = await makeProject();
+ const existingId = await makeIssue(projectId, columnId, ' Fix the LEAK ');
+ const jobId = await makeImportJob(projectId, userId);
+
+ const issueId = await createLocalIssueAndRecord(jobId, 'plane-issue-2', 'ROOMS-2', {
+ projectId,
+ columnId,
+ cycleId: null,
+ parentId: null,
+ assigneeUserId: null,
+ title: 'Fix the leak',
+ description: 'from Plane',
+ priority: null,
+ startDate: null,
+ dueDate: null,
+ });
+
+ expect(issueId).toBe(existingId);
+ const [row] = await db.select().from(issue).where(eq(issue.id, issueId));
+ // The reused issue keeps its own content; the import does not overwrite it.
+ expect(row?.description).toBe('');
+ });
+});
+
+describe('createLocalAttachmentAndRecord', () => {
+ let originalSettings: StorageSettings | null = null;
+
+ afterEach(async () => {
+ if (originalSettings) {
+ await setSetting(STORAGE_SETTING_KEY, originalSettings);
+ originalSettings = null;
+ }
+ });
+
+ async function overrideSettings(patch: Partial<StorageSettings>) {
+ originalSettings = await getStorageSettings();
+ await setSetting(STORAGE_SETTING_KEY, { ...originalSettings, ...patch });
+ }
+
+ it('stores a new attachment and records the mapping', async () => {
+ const { projectId, columnId, userId } = await makeProject();
+ const issueId = await makeIssue(projectId, columnId);
+ const jobId = await makeImportJob(projectId, userId);
+
+ const attachmentId = await createLocalAttachmentAndRecord(jobId, 'plane-attachment-1', {
+ projectId,
+ issueId,
+ filename: 'notes.txt',
+ contentType: 'text/plain',
+ bytes: Buffer.from('hello from plane'),
+ });
+
+ const [row] = await db
+ .select()
+ .from(issueAttachment)
+ .where(eq(issueAttachment.id, attachmentId));
+ expect(row?.filename).toBe('notes.txt');
+ expect(row?.sizeBytes).toBe(Buffer.byteLength('hello from plane'));
+ expect(await findImportRecord(jobId, 'attachment', 'plane-attachment-1')).toEqual({
+ localId: attachmentId,
+ });
+ const stored = await getObject(row!.s3Key);
+ expect(await new Response(stored.body).text()).toBe('hello from plane');
+ });
+
+ it('reuses an existing attachment on the same issue by filename instead of re-uploading', async () => {
+ const { projectId, columnId, userId } = await makeProject();
+ const issueId = await makeIssue(projectId, columnId);
+ const jobId = await makeImportJob(projectId, userId);
+ const [existing] = await db
+ .insert(issueAttachment)
+ .values({
+ issueId,
+ s3Key: 'projects/x/attachments/existing.txt',
+ filename: 'notes.txt',
+ contentType: 'text/plain',
+ sizeBytes: 5,
+ })
+ .returning({ id: issueAttachment.id });
+
+ const attachmentId = await createLocalAttachmentAndRecord(jobId, 'plane-attachment-2', {
+ projectId,
+ issueId,
+ filename: 'notes.txt',
+ contentType: 'text/plain',
+ bytes: Buffer.from('a different upload'),
+ });
+
+ expect(attachmentId).toBe(existing!.id);
+ const rows = await db
+ .select()
+ .from(issueAttachment)
+ .where(eq(issueAttachment.issueId, issueId));
+ expect(rows).toHaveLength(1);
+ expect(await findImportRecord(jobId, 'attachment', 'plane-attachment-2')).toEqual({
+ localId: existing!.id,
+ });
+ });
+
+ it('rejects an attachment over the configured size limit', async () => {
+ await overrideSettings({ maxAttachmentMb: 0.000001 });
+ const { projectId, columnId, userId } = await makeProject();
+ const issueId = await makeIssue(projectId, columnId);
+ const jobId = await makeImportJob(projectId, userId);
+
+ await expect(
+ createLocalAttachmentAndRecord(jobId, 'plane-attachment-3', {
+ projectId,
+ issueId,
+ filename: 'big.txt',
+ contentType: 'text/plain',
+ bytes: Buffer.from('this file is definitely too big for the limit'),
+ }),
+ ).rejects.toBeInstanceOf(AttachmentRejectedError);
+ const rows = await db
+ .select()
+ .from(issueAttachment)
+ .where(eq(issueAttachment.issueId, issueId));
+ expect(rows).toHaveLength(0);
+ });
+
+ it('rejects an attachment whose mime type is not accepted on this instance', async () => {
+ await overrideSettings({ attachmentMimeTypes: ['application/pdf'] });
+ const { projectId, columnId, userId } = await makeProject();
+ const issueId = await makeIssue(projectId, columnId);
+ const jobId = await makeImportJob(projectId, userId);
+
+ await expect(
+ createLocalAttachmentAndRecord(jobId, 'plane-attachment-4', {
+ projectId,
+ issueId,
+ filename: 'notes.txt',
+ contentType: 'text/plain',
+ bytes: Buffer.from('hello'),
+ }),
+ ).rejects.toBeInstanceOf(AttachmentRejectedError);
+ const rows = await db
+ .select()
+ .from(issueAttachment)
+ .where(eq(issueAttachment.issueId, issueId));
+ expect(rows).toHaveLength(0);
+ });
+
+ it('rejects an attachment that would exceed the project storage quota', async () => {
+ await overrideSettings({ projectQuotaMb: 0.00001 });
+ const { projectId, columnId, userId } = await makeProject();
+ const issueId = await makeIssue(projectId, columnId);
+ const jobId = await makeImportJob(projectId, userId);
+
+ await expect(
+ createLocalAttachmentAndRecord(jobId, 'plane-attachment-5', {
+ projectId,
+ issueId,
+ filename: 'notes.txt',
+ contentType: 'text/plain',
+ bytes: Buffer.from('more bytes than the tiny quota allows'),
+ }),
+ ).rejects.toBeInstanceOf(AttachmentRejectedError);
+ const rows = await db
+ .select()
+ .from(issueAttachment)
+ .where(eq(issueAttachment.issueId, issueId));
+ expect(rows).toHaveLength(0);
+ });
+
+ it('deletes the uploaded object when a concurrent write wins the quota race', async () => {
+ // A quota tight enough that either upload alone fits but both together don't:
+ // the outer, unlocked check on each side sees the project as still empty and
+ // lets both through to the upload; only the one that loses the advisory-lock
+ // race sees the other's committed bytes and is rejected inside the transaction
+ // — after its own upload already ran, which is the case this covers.
+ await overrideSettings({ projectQuotaMb: 1 });
+ const { projectId, columnId, userId } = await makeProject();
+ const issueId = await makeIssue(projectId, columnId);
+ const jobId = await makeImportJob(projectId, userId);
+ const bytes = Buffer.alloc(700_000, 'x');
+
+ const results = await Promise.allSettled([
+ createLocalAttachmentAndRecord(jobId, 'plane-attachment-6a', {
+ projectId,
+ issueId,
+ filename: 'a.bin',
+ contentType: 'text/plain',
+ bytes,
+ }),
+ createLocalAttachmentAndRecord(jobId, 'plane-attachment-6b', {
+ projectId,
+ issueId,
+ filename: 'b.bin',
+ contentType: 'text/plain',
+ bytes,
+ }),
+ ]);
+
+ const [aResult] = results;
+ const fulfilled = results.filter((r) => r.status === 'fulfilled');
+ const rejected = results.filter((r) => r.status === 'rejected');
+ expect(fulfilled).toHaveLength(1);
+ expect(rejected).toHaveLength(1);
+ expect((rejected[0] as PromiseRejectedResult).reason).toBeInstanceOf(AttachmentRejectedError);
+
+ const rows = await db
+ .select()
+ .from(issueAttachment)
+ .where(eq(issueAttachment.issueId, issueId));
+ expect(rows).toHaveLength(1);
+
+ // The winner's import_record points at the one row created; the loser's
+ // rejection rolled back before upsertImportRecordWith ever ran for it, so it
+ // has no import_record at all — which is also true of its uploaded object,
+ // deleted by the same catch block once the transaction rejected it.
+ const [winnerSourceId, loserSourceId] =
+ aResult.status === 'fulfilled'
+ ? ['plane-attachment-6a', 'plane-attachment-6b']
+ : ['plane-attachment-6b', 'plane-attachment-6a'];
+ expect(await findImportRecord(jobId, 'attachment', winnerSourceId)).toEqual({
+ localId: rows[0]!.id,
+ });
+ expect(await findImportRecord(jobId, 'attachment', loserSourceId)).toBeNull();
+ });
+});
diff --git a/apps/worker/src/__tests__/unit/cross-reference.test.ts b/apps/worker/src/__tests__/unit/cross-reference.test.ts
new file mode 100644
index 00000000..056be9c7
--- /dev/null
+++ b/apps/worker/src/__tests__/unit/cross-reference.test.ts
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'bun:test';
+import { extractCrossReferences, applyCrossReferenceReplacements } from '../../cross-reference';
+
+describe('extractCrossReferences', () => {
+ it('finds a plain mention', () => {
+ expect(extractCrossReferences('see ROOMS-524 for details', 'ROOMS')).toEqual([
+ { reference: 'ROOMS-524', sequenceId: '524' },
+ ]);
+ });
+
+ it('finds several distinct mentions, first-seen order', () => {
+ expect(extractCrossReferences('ROOMS-2 blocks ROOMS-1, see also ROOMS-2', 'ROOMS')).toEqual([
+ { reference: 'ROOMS-2', sequenceId: '2' },
+ { reference: 'ROOMS-1', sequenceId: '1' },
+ ]);
+ });
+
+ it('does not match a prefix or suffix that breaks the word boundary', () => {
+ expect(extractCrossReferences('XROOMS-524 and ROOMS-524X', 'ROOMS')).toEqual([]);
+ });
+
+ it('does not match a different project key', () => {
+ expect(extractCrossReferences('see OTHER-524', 'ROOMS')).toEqual([]);
+ });
+
+ it('is case-sensitive, matching Plane identifiers verbatim', () => {
+ expect(extractCrossReferences('see rooms-524', 'ROOMS')).toEqual([]);
+ });
+
+ it('finds nothing in text with no mention', () => {
+ expect(extractCrossReferences('no references here', 'ROOMS')).toEqual([]);
+ });
+});
+
+describe('applyCrossReferenceReplacements', () => {
+ it('substitutes a resolved mention', () => {
+ const replacements = new Map([['ROOMS-524', 'MKT-9']]);
+ expect(applyCrossReferenceReplacements('see ROOMS-524', 'ROOMS', replacements)).toBe(
+ 'see MKT-9',
+ );
+ });
+
+ it('leaves an unresolved mention exactly as-is', () => {
+ const replacements = new Map<string, string>();
+ expect(applyCrossReferenceReplacements('see ROOMS-524', 'ROOMS', replacements)).toBe(
+ 'see ROOMS-524',
+ );
+ });
+
+ it('replaces every occurrence of a repeated mention', () => {
+ const replacements = new Map([['ROOMS-524', 'MKT-9']]);
+ expect(
+ applyCrossReferenceReplacements('ROOMS-524 duplicates ROOMS-524', 'ROOMS', replacements),
+ ).toBe('MKT-9 duplicates MKT-9');
+ });
+
+ it('resolves one mention and leaves another unresolved in the same text', () => {
+ const replacements = new Map([['ROOMS-1', 'MKT-1']]);
+ expect(applyCrossReferenceReplacements('ROOMS-1 and ROOMS-2', 'ROOMS', replacements)).toBe(
+ 'MKT-1 and ROOMS-2',
+ );
+ });
+});
diff --git a/apps/worker/src/__tests__/unit/plane-adapter.test.ts b/apps/worker/src/__tests__/unit/plane-adapter.test.ts
new file mode 100644
index 00000000..f261718b
--- /dev/null
+++ b/apps/worker/src/__tests__/unit/plane-adapter.test.ts
@@ -0,0 +1,139 @@
+import { describe, it, expect } from 'bun:test';
+import {
+ normalizeStateCategory,
+ nextPageCursor,
+ rateLimitBackoffMs,
+ htmlToMarkdown,
+} from '../../plane-adapter';
+
+describe('normalizeStateCategory', () => {
+ it("maps the British-spelled cancelled to itsaplan's canceled", () => {
+ expect(normalizeStateCategory('cancelled')).toBe('canceled');
+ });
+
+ it('falls back triage to backlog, which itsaplan has no equivalent for', () => {
+ expect(normalizeStateCategory('triage')).toBe('backlog');
+ });
+
+ it('passes the shared categories through unchanged', () => {
+ expect(normalizeStateCategory('backlog')).toBe('backlog');
+ expect(normalizeStateCategory('unstarted')).toBe('unstarted');
+ expect(normalizeStateCategory('started')).toBe('started');
+ expect(normalizeStateCategory('completed')).toBe('completed');
+ });
+
+ it('falls back an unknown group to backlog rather than throwing', () => {
+ expect(normalizeStateCategory('something-new')).toBe('backlog');
+ });
+});
+
+describe('nextPageCursor', () => {
+ it('returns null once next_page_results is false, regardless of the cursor string', () => {
+ expect(nextPageCursor('100:4:300', false)).toBeNull();
+ });
+
+ it('returns the exact next_cursor string when another page remains', () => {
+ expect(nextPageCursor('100:3:200', true)).toBe('100:3:200');
+ });
+
+ it('returns null on the first page with no results at all', () => {
+ expect(nextPageCursor(null, false)).toBeNull();
+ });
+});
+
+describe('rateLimitBackoffMs', () => {
+ it('honors Retry-After over everything else', () => {
+ const ms = rateLimitBackoffMs({
+ status: 429,
+ remaining: '5',
+ resetEpochSec: null,
+ retryAfterSec: '30',
+ });
+ expect(ms).toBe(30_000);
+ });
+
+ it('falls back to a minute on a 429 with no Retry-After', () => {
+ const ms = rateLimitBackoffMs({
+ status: 429,
+ remaining: '5',
+ resetEpochSec: null,
+ retryAfterSec: null,
+ });
+ expect(ms).toBe(60_000);
+ });
+
+ it('backs off until x-ratelimit-reset when remaining hits zero', () => {
+ const nowMs = 1_000_000;
+ const resetEpochSec = String(nowMs / 1000 + 45);
+ const ms = rateLimitBackoffMs(
+ { status: 200, remaining: '0', resetEpochSec, retryAfterSec: null },
+ nowMs,
+ );
+ expect(ms).toBe(45_000);
+ });
+
+ it('does not back off on a normal response with remaining hits left', () => {
+ const ms = rateLimitBackoffMs({
+ status: 200,
+ remaining: '59',
+ resetEpochSec: null,
+ retryAfterSec: null,
+ });
+ expect(ms).toBeNull();
+ });
+});
+
+describe('htmlToMarkdown', () => {
+ it('converts a paragraph', () => {
+ expect(htmlToMarkdown('<p>Hello world</p>')).toBe('Hello world');
+ });
+
+ it('converts bold, italic and inline code', () => {
+ expect(htmlToMarkdown('<p><strong>bold</strong> <em>italic</em> <code>x = 1</code></p>')).toBe(
+ '**bold** *italic* `x = 1`',
+ );
+ });
+
+ it('converts a fenced code block without mangling its contents', () => {
+ const html = '<pre><code>const x = 1;\nconst y = 2;</code></pre>';
+ expect(htmlToMarkdown(html)).toBe('```\nconst x = 1;\nconst y = 2;\n```');
+ });
+
+ it('converts a link', () => {
+ expect(htmlToMarkdown('<p><a href="https://example.com">example</a></p>')).toBe(
+ '[example](https://example.com)',
+ );
+ });
+
+ it('converts an unordered list', () => {
+ expect(htmlToMarkdown('<ul><li>one</li><li>two</li></ul>')).toBe('- one\n- two');
+ });
+
+ it('converts a Tiptap task list using data-checked', () => {
+ const html =
+ '<ul data-type="taskList"><li data-checked="true">done</li><li data-checked="false">todo</li></ul>';
+ expect(htmlToMarkdown(html)).toBe('- [x] done\n- [ ] todo');
+ });
+
+ it('converts a heading', () => {
+ expect(htmlToMarkdown('<h2>Section</h2>')).toBe('## Section');
+ });
+
+ it('decodes HTML entities', () => {
+ expect(htmlToMarkdown('<p>Tom &amp; Jerry, a &quot;classic&quot;&nbsp;show</p>')).toBe(
+ 'Tom & Jerry, a "classic" show',
+ );
+ });
+
+ it('strips nested tag fragments', () => {
+ expect(htmlToMarkdown('<p><scr<script>ipt>x</p>')).not.toMatch(/<script/i);
+ });
+
+ it('decodes entities once', () => {
+ expect(htmlToMarkdown('<p>&amp;lt;b&amp;gt;</p>')).toBe('&lt;b&gt;');
+ });
+
+ it('returns an empty string for empty input', () => {
+ expect(htmlToMarkdown('')).toBe('');
+ });
+});
diff --git a/apps/worker/src/canonical.ts b/apps/worker/src/canonical.ts
new file mode 100644
index 00000000..59c96e95
--- /dev/null
+++ b/apps/worker/src/canonical.ts
@@ -0,0 +1,86 @@
+// The canonical intermediate shape a source adapter (SourceReader, see reader.ts)
+// produces. Plain types only, no runtime logic. import-worker.ts converts these
+// into itsaplan's own tables; nothing here depends on @repo/db so a future
+// Linear or Jira adapter can produce the same shape without pulling in the
+// worker's persistence layer.
+
+// itsaplan's own project_column.state_type values (packages/db/src/schema/app.ts).
+export type CanonicalStateCategory = 'backlog' | 'unstarted' | 'started' | 'completed' | 'canceled';
+
+export interface CanonicalState {
+ sourceId: string;
+ name: string;
+ category: CanonicalStateCategory;
+}
+
+export interface CanonicalLabel {
+ sourceId: string;
+ name: string;
+ color?: string;
+}
+
+export interface CanonicalCycle {
+ sourceId: string;
+ name: string;
+ // Date-only ('YYYY-MM-DD'): itsaplan's cycle.startDate/endDate carry no time of day.
+ startDate: string;
+ endDate: string;
+ goal?: string;
+}
+
+export interface CanonicalCustomFieldValue {
+ fieldSourceId: string;
+ value: string | number | boolean | null;
+}
+
+// No URL field: an attachment's download URL is a presigned link that expires
+// (see docs/dev/plane-import-source-notes.md), so it must never be resolved
+// ahead of the phase that actually downloads the bytes. sourceId is what a later
+// phase resolves it from again, on demand. sizeBytes is the source's own claim,
+// used only to skip an obviously-too-large file before downloading it — the
+// size actually stored always comes from the downloaded bytes, never this.
+export interface CanonicalAttachment {
+ sourceId: string;
+ filename: string;
+ contentType: string;
+ sizeBytes: number;
+}
+
+export interface CanonicalComment {
+ sourceId: string;
+ authorEmail: string | null;
+ authorName: string;
+ bodyMarkdown: string;
+ createdAt: string;
+ replyToSourceId: string | null;
+}
+
+export interface CanonicalRelation {
+ kind: 'blocks' | 'relates' | 'duplicates';
+ sourceIssueSourceId: string;
+ targetIssueSourceId: string;
+}
+
+// Comments and attachments are fetched and written per-issue during the Create
+// phase, not nested here: keeping this flat means one issue's payload does not
+// grow with however many comments or attachments it happens to carry.
+export interface CanonicalIssue {
+ sourceId: string;
+ // The source's own human-readable issue number (Plane's sequence_id), used only
+ // to resolve a cross-reference like "ROOMS-524" in another issue's text back to
+ // this one during the Rewrite phase.
+ sequenceId: number;
+ title: string;
+ descriptionMarkdown: string;
+ stateSourceId: string;
+ assigneeEmail: string | null;
+ labelSourceIds: string[];
+ cycleSourceId: string | null;
+ parentSourceId: string | null;
+ priority: string | null;
+ startDate: string | null;
+ dueDate: string | null;
+ customFields: CanonicalCustomFieldValue[];
+ createdAt: string;
+ updatedAt: string;
+}
diff --git a/apps/worker/src/cross-reference.ts b/apps/worker/src/cross-reference.ts
new file mode 100644
index 00000000..e5e3e6ac
--- /dev/null
+++ b/apps/worker/src/cross-reference.ts
@@ -0,0 +1,44 @@
+// Plain-text matching for a "KEY-123"-style cross-reference (Plane's own issue
+// identifier shape). Source-independent and dependency-free like canonical.ts and
+// plane-adapter.ts's pure functions, so this is unit-tested directly, without a
+// database: see import-worker.ts's Rewrite phase for how it resolves what these
+// find into itsaplan's own issue ids.
+
+function escapeRegExp(value: string): string {
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+}
+
+function crossReferencePattern(sourceProjectKey: string): RegExp {
+ return new RegExp(`\\b${escapeRegExp(sourceProjectKey)}-(\\d+)\\b`, 'g');
+}
+
+export interface CrossReferenceMatch {
+ reference: string; // The whole match, e.g. "ROOMS-524".
+ sequenceId: string; // The captured number, e.g. "524".
+}
+
+// Every distinct mention of sourceProjectKey in text, first-seen order. Word
+// boundaries on both ends mean "XROOMS-524" and "ROOMS-524X" do not match.
+export function extractCrossReferences(
+ text: string,
+ sourceProjectKey: string,
+): CrossReferenceMatch[] {
+ const seen = new Map<string, CrossReferenceMatch>();
+ for (const match of text.matchAll(crossReferencePattern(sourceProjectKey))) {
+ if (!seen.has(match[0])) seen.set(match[0], { reference: match[0], sequenceId: match[1]! });
+ }
+ return [...seen.values()];
+}
+
+// Substitutes every mention with its resolved replacement; one with no entry in
+// `replacements` (unresolved - outside the imported set) is left exactly as-is.
+export function applyCrossReferenceReplacements(
+ text: string,
+ sourceProjectKey: string,
+ replacements: Map<string, string>,
+): string {
+ if (replacements.size === 0) return text;
+ return text.replace(crossReferencePattern(sourceProjectKey), (whole) => {
+ return replacements.get(whole) ?? whole;
+ });
+}
diff --git a/apps/worker/src/import-store.ts b/apps/worker/src/import-store.ts
new file mode 100644
index 00000000..f7a26ae0
--- /dev/null
+++ b/apps/worker/src/import-store.ts
@@ -0,0 +1,792 @@
+import {
+ db,
+ project,
+ projectColumn,
+ label,
+ cycle,
+ issue,
+ issueLabel,
+ issueActivity,
+ issueLink,
+ issueAttachment,
+ user,
+ projectMember,
+ importJob,
+ importRecord,
+ getStorageSettings,
+ mimeAllowed,
+ MB,
+ projectStoredBytes,
+ lockAttachmentStorage,
+ type ImportSource,
+} from '@repo/db';
+import { and, eq, gt, isNull, isNotNull, sql } from 'drizzle-orm';
+import { decryptSecret, type EncryptedSecret } from '@repo/crypto';
+import {
+ putObject,
+ deleteObject,
+ safeAttachmentFilename,
+ attachmentObjectKey,
+} from '@repo/storage';
+import type { CanonicalState, CanonicalLabel, CanonicalCycle } from './canonical';
+import type { PlaneCredential } from './plane-adapter';
+
+// All @repo/db access for the Plane import: claiming due import_job rows (the
+// same FOR UPDATE SKIP LOCKED + lease pattern as store.ts uses for
+// webhook_delivery), reading/writing a job's progress, the import_record
+// upsert primitive, and creating the local rows an import produces. The
+// credential decrypt lives here rather than packages/db/src/domains/: that
+// directory is for config more than one process reads, and only the worker
+// ever decrypts an import job's stored credential — the api only sees the raw
+// token once, at creation, before it is encrypted.
+
+const LEASE_SECONDS = 120;
+
+export interface ClaimedImportJob {
+ id: number;
+ projectId: number;
+ source: ImportSource;
+ phase: string;
+ status: string;
+ config: Record<string, unknown>;
+ cursor: Record<string, unknown>;
+ attempts: number;
+ credentialCiphertext: string | null;
+ credentialIv: string | null;
+ credentialAuthTag: string | null;
+}
+
+// Claims up to `limit` due import jobs (default 1: import-worker.ts processes
+// one job per tick). Claiming pushes next_attempt_at forward by the lease and
+// bumps attempts, so a job whose worker crashes mid-tick becomes claimable
+// again once the lease expires — status stays 'pending' throughout, the same
+// as webhook_delivery, so the lease alone drives crash recovery.
+//
+// last_error is cleared here too, the moment a claim starts a new attempt —
+// not only on success. The Settings UI reads a non-null last_error as "waiting
+// out a retry" (see SettingsImportExportJobRow.tsx), computing the countdown
+// from next_attempt_at; without this, a poll landing while the new attempt is
+// still in flight would show the old error next to the lease's own deadline
+// (up to LEASE_SECONDS out) as if it were the retry countdown, even though the
+// job is actively working, not waiting.
+export async function claimDueImportJobs(limit = 1): Promise<ClaimedImportJob[]> {
+ const rows = await db.execute(sql`
+ UPDATE import_job j
+ SET attempts = j.attempts + 1,
+ next_attempt_at = now() + make_interval(secs => ${LEASE_SECONDS}),
+ last_error = NULL
+ WHERE j.id IN (
+ SELECT id FROM import_job
+ WHERE status = 'pending' AND next_attempt_at <= now()
+ ORDER BY next_attempt_at
+ FOR UPDATE SKIP LOCKED
+ LIMIT ${limit}
+ )
+ RETURNING
+ j.id,
+ j.project_id AS "projectId",
+ j.source,
+ j.phase,
+ j.status,
+ j.config,
+ j.cursor,
+ j.attempts,
+ j.credential_ciphertext AS "credentialCiphertext",
+ j.credential_iv AS "credentialIv",
+ j.credential_auth_tag AS "credentialAuthTag"
+ `);
+ return rows as unknown as ClaimedImportJob[];
+}
+
+export function decryptImportCredential(job: ClaimedImportJob): PlaneCredential {
+ if (!job.credentialCiphertext || !job.credentialIv || !job.credentialAuthTag) {
+ throw new Error(`import job ${job.id} has no stored credential`);
+ }
+ const encrypted: EncryptedSecret = {
+ ciphertext: job.credentialCiphertext,
+ iv: job.credentialIv,
+ authTag: job.credentialAuthTag,
+ };
+ return JSON.parse(decryptSecret(encrypted)) as PlaneCredential;
+}
+
+// A successful tick clears the claim lease (nextAttemptAt) and lastError, and
+// resets attempts, so the next tick can claim the job right away instead of
+// waiting out the lease claimDueImportJobs set, and a resolved rate limit or
+// transient failure doesn't linger as if it were still happening. `attempts`
+// counts consecutive claims with no successful tick in between, not ticks
+// claimed overall, so a transient error only fails the job after MAX_ATTEMPTS
+// in a row.
+export async function saveImportJobCursor(jobId: number, cursor: object): Promise<void> {
+ await db
+ .update(importJob)
+ .set({ cursor, attempts: 0, nextAttemptAt: sql`now()`, lastError: null, updatedAt: new Date() })
+ .where(eq(importJob.id, jobId));
+}
+
+export async function advanceImportJobPhase(
+ jobId: number,
+ phase: string,
+ cursor: object,
+): Promise<void> {
+ await db
+ .update(importJob)
+ .set({
+ phase,
+ cursor,
+ attempts: 0,
+ nextAttemptAt: sql`now()`,
+ lastError: null,
+ updatedAt: new Date(),
+ })
+ .where(eq(importJob.id, jobId));
+}
+
+// Terminal states clear the credential columns: nothing needs to read them
+// again once the job can no longer make progress.
+export async function completeImportJob(jobId: number): Promise<void> {
+ await db
+ .update(importJob)
+ .set({
+ status: 'completed',
+ phase: 'done',
+ lastError: null,
+ updatedAt: new Date(),
+ credentialCiphertext: null,
+ credentialIv: null,
+ credentialAuthTag: null,
+ })
+ .where(eq(importJob.id, jobId));
+}
+
+export async function failImportJob(jobId: number, error: string): Promise<void> {
+ await db
+ .update(importJob)
+ .set({
+ status: 'failed',
+ lastError: error.slice(0, 500),
+ updatedAt: new Date(),
+ credentialCiphertext: null,
+ credentialIv: null,
+ credentialAuthTag: null,
+ })
+ .where(eq(importJob.id, jobId));
+}
+
+// A transient failure (rate limited, a network error, an unreachable
+// instance): reschedule rather than fail the job outright.
+export async function retryImportJobLater(
+ jobId: number,
+ delayMs: number,
+ error: string,
+): Promise<void> {
+ const delaySeconds = Math.max(1, Math.ceil(delayMs / 1000));
+ await db
+ .update(importJob)
+ .set({
+ nextAttemptAt: sql`now() + make_interval(secs => ${delaySeconds})`,
+ lastError: error.slice(0, 500),
+ updatedAt: new Date(),
+ })
+ .where(eq(importJob.id, jobId));
+}
+
+export type ImportEntityType = 'issue' | 'comment' | 'label' | 'state' | 'cycle' | 'attachment';
+
+// Bulk id-only snapshot write for the Discover phase: rows start with no local
+// mapping. Idempotent — a source id already recorded (from an earlier attempt
+// at this same phase) is left alone.
+export async function insertDiscoveredIds(
+ jobId: number,
+ entityType: ImportEntityType,
+ sourceIds: string[],
+): Promise<void> {
+ if (sourceIds.length === 0) return;
+ await db
+ .insert(importRecord)
+ .values(
+ sourceIds.map((sourceId) => ({ importJobId: jobId, sourceEntityType: entityType, sourceId })),
+ )
+ .onConflictDoNothing();
+}
+
+// Runs against either the plain db or a transaction, so the local-row insert
+// and the import_record upsert below can share one transaction and commit
+// atomically — see createLocalStateAndRecord/createLocalCycleAndRecord/
+// createLocalIssueAndRecord.
+type ImportDbExecutor = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+// The idempotent-upsert primitive keyed on the unique index
+// (import_job_id, source_entity_type, source_id): inserts a fresh mapping, or
+// overwrites the local mapping of one that already exists (Discover wrote it
+// with no local id, Create is now filling it in).
+async function upsertImportRecordWith(
+ executor: ImportDbExecutor,
+ jobId: number,
+ entityType: ImportEntityType,
+ sourceId: string,
+ localEntityType: ImportEntityType | null,
+ localId: number | null,
+ sourceDisplayId: string | null = null,
+): Promise<void> {
+ await executor
+ .insert(importRecord)
+ .values({
+ importJobId: jobId,
+ sourceEntityType: entityType,
+ sourceId,
+ sourceDisplayId,
+ localEntityType,
+ localId,
+ })
+ .onConflictDoUpdate({
+ target: [importRecord.importJobId, importRecord.sourceEntityType, importRecord.sourceId],
+ set: { localEntityType, localId, sourceDisplayId },
+ });
+}
+
+export async function upsertImportRecord(
+ jobId: number,
+ entityType: ImportEntityType,
+ sourceId: string,
+ localEntityType: ImportEntityType | null,
+ localId: number | null,
+): Promise<void> {
+ await upsertImportRecordWith(db, jobId, entityType, sourceId, localEntityType, localId);
+}
+
+export async function findImportRecord(
+ jobId: number,
+ entityType: ImportEntityType,
+ sourceId: string,
+): Promise<{ localId: number | null } | null> {
+ const rows = await db
+ .select({ localId: importRecord.localId })
+ .from(importRecord)
+ .where(
+ and(
+ eq(importRecord.importJobId, jobId),
+ eq(importRecord.sourceEntityType, entityType),
+ eq(importRecord.sourceId, sourceId),
+ ),
+ )
+ .limit(1);
+ return rows[0] ?? null;
+}
+
+// Resolves a cross-reference like "ROOMS-524" during the Rewrite phase: the
+// captured number is the source's own display id, not its sourceId (a UUID for
+// Plane), so this looks up by the column Create stashed it in instead.
+export async function findImportRecordByDisplayId(
+ jobId: number,
+ entityType: ImportEntityType,
+ sourceDisplayId: string,
+): Promise<{ localId: number | null } | null> {
+ const rows = await db
+ .select({ localId: importRecord.localId })
+ .from(importRecord)
+ .where(
+ and(
+ eq(importRecord.importJobId, jobId),
+ eq(importRecord.sourceEntityType, entityType),
+ eq(importRecord.sourceDisplayId, sourceDisplayId),
+ ),
+ )
+ .limit(1);
+ return rows[0] ?? null;
+}
+
+export interface ImportRecordRow {
+ id: number;
+ sourceId: string;
+}
+
+// The next chunk of this job's snapshot that has not been materialized yet,
+// keyset-paginated on import_record's own id — itsaplan's own position in the
+// snapshot list, not the source's pagination cursor (see the notes file). A
+// retried tick naturally skips rows a crashed earlier attempt already created,
+// since those no longer match "local id still null".
+export async function listUncreatedImportRecords(
+ jobId: number,
+ entityType: ImportEntityType,
+ afterId: number,
+ limit: number,
+): Promise<ImportRecordRow[]> {
+ return db
+ .select({ id: importRecord.id, sourceId: importRecord.sourceId })
+ .from(importRecord)
+ .where(
+ and(
+ eq(importRecord.importJobId, jobId),
+ eq(importRecord.sourceEntityType, entityType),
+ gt(importRecord.id, afterId),
+ isNull(importRecord.localId),
+ ),
+ )
+ .orderBy(importRecord.id)
+ .limit(limit);
+}
+
+export interface CreatedImportRecordRow extends ImportRecordRow {
+ // Guaranteed set by the isNotNull(localId) filter below; the column itself
+ // is nullable so the query builder can't narrow it on its own.
+ localId: number;
+}
+
+// The next chunk of this job's already-created issues, for the Link phase to
+// fetch relations for.
+export async function listCreatedImportRecords(
+ jobId: number,
+ entityType: ImportEntityType,
+ afterId: number,
+ limit: number,
+): Promise<CreatedImportRecordRow[]> {
+ const rows = await db
+ .select({ id: importRecord.id, sourceId: importRecord.sourceId, localId: importRecord.localId })
+ .from(importRecord)
+ .where(
+ and(
+ eq(importRecord.importJobId, jobId),
+ eq(importRecord.sourceEntityType, entityType),
+ gt(importRecord.id, afterId),
+ isNotNull(importRecord.localId),
+ ),
+ )
+ .orderBy(importRecord.id)
+ .limit(limit);
+ return rows as CreatedImportRecordRow[];
+}
+
+export async function firstProjectColumnId(projectId: number): Promise<number | null> {
+ const rows = await db
+ .select({ id: projectColumn.id })
+ .from(projectColumn)
+ .where(eq(projectColumn.projectId, projectId))
+ .orderBy(projectColumn.position)
+ .limit(1);
+ return rows[0]?.id ?? null;
+}
+
+export async function getProjectKey(projectId: number): Promise<string> {
+ const [row] = await db
+ .select({ key: project.key })
+ .from(project)
+ .where(eq(project.id, projectId));
+ if (!row) throw new Error(`project ${projectId} not found`);
+ return row.key;
+}
+
+export async function getIssueSequenceNumber(issueId: number): Promise<number | null> {
+ const [row] = await db
+ .select({ sequenceNumber: issue.sequenceNumber })
+ .from(issue)
+ .where(eq(issue.id, issueId));
+ return row?.sequenceNumber ?? null;
+}
+
+export interface IssueTextForRewrite {
+ description: string;
+ comments: { id: number; body: string }[];
+}
+
+// What the Rewrite phase scans: the issue's own description plus every comment
+// on it, each already local (no more Plane requests needed for this phase).
+export async function getIssueTextForRewrite(issueId: number): Promise<IssueTextForRewrite> {
+ const [issueRow] = await db
+ .select({ description: issue.description })
+ .from(issue)
+ .where(eq(issue.id, issueId));
+ const comments = await db
+ .select({ id: issueActivity.id, body: issueActivity.body })
+ .from(issueActivity)
+ .where(and(eq(issueActivity.issueId, issueId), eq(issueActivity.kind, 'comment')));
+ return {
+ description: issueRow?.description ?? '',
+ comments: comments.map((c) => ({ id: c.id, body: c.body ?? '' })),
+ };
+}
+
+export async function updateIssueDescription(issueId: number, description: string): Promise<void> {
+ await db.update(issue).set({ description }).where(eq(issue.id, issueId));
+}
+
+export async function updateCommentBody(commentId: number, body: string): Promise<void> {
+ await db.update(issueActivity).set({ body }).where(eq(issueActivity.id, commentId));
+}
+
+// project_column has no unique constraint to upsert against like label does,
+// so an exact name match within the project is looked up first and reused —
+// otherwise every project's own default columns (every new project starts
+// with a "Backlog") collide with Plane's own states of the same name and
+// duplicate them. A match reuses the existing column's stateType rather than
+// overwriting it with Plane's category: unlike a label's color, a column's
+// category can move issues between board sections, so an import should not
+// silently change how an existing, possibly hand-configured column behaves.
+// The lookup and the insert-or-reuse share one transaction for the same
+// crash-safety reason as before — a project_column still has nothing to fall
+// back on for a retry once created.
+export async function createLocalStateAndRecord(
+ jobId: number,
+ sourceId: string,
+ projectId: number,
+ state: CanonicalState,
+): Promise<number> {
+ return db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ id: projectColumn.id })
+ .from(projectColumn)
+ .where(and(eq(projectColumn.projectId, projectId), eq(projectColumn.name, state.name)));
+ if (existing) {
+ await upsertImportRecordWith(tx, jobId, 'state', sourceId, 'state', existing.id);
+ return existing.id;
+ }
+ const [posRow] = await tx
+ .select({ pos: sql<number>`COALESCE(MAX(${projectColumn.position}), 0) + 1` })
+ .from(projectColumn)
+ .where(eq(projectColumn.projectId, projectId));
+ const [row] = await tx
+ .insert(projectColumn)
+ .values({
+ projectId,
+ name: state.name,
+ stateType: state.category,
+ position: Number(posRow!.pos),
+ })
+ .returning({ id: projectColumn.id });
+ await upsertImportRecordWith(tx, jobId, 'state', sourceId, 'state', row!.id);
+ return row!.id;
+ });
+}
+
+// A label of the same name already existing (created by hand before the
+// import ran) is reused rather than duplicated, matching label's own
+// unique(project_id, name).
+export async function createLocalLabel(
+ projectId: number,
+ canonicalLabel: CanonicalLabel,
+): Promise<number> {
+ const color = canonicalLabel.color ?? '#6b7280';
+ const [row] = await db
+ .insert(label)
+ .values({ projectId, name: canonicalLabel.name, color })
+ .onConflictDoUpdate({ target: [label.projectId, label.name], set: { color } })
+ .returning({ id: label.id });
+ return row!.id;
+}
+
+// Same name-match-and-reuse reasoning as createLocalStateAndRecord: a cycle
+// has no unique constraint to upsert against, so an existing cycle of the
+// same name is reused rather than duplicated.
+export async function createLocalCycleAndRecord(
+ jobId: number,
+ sourceId: string,
+ projectId: number,
+ canonicalCycle: CanonicalCycle,
+): Promise<number> {
+ return db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ id: cycle.id })
+ .from(cycle)
+ .where(and(eq(cycle.projectId, projectId), eq(cycle.name, canonicalCycle.name)));
+ if (existing) {
+ await upsertImportRecordWith(tx, jobId, 'cycle', sourceId, 'cycle', existing.id);
+ return existing.id;
+ }
+ const [row] = await tx
+ .insert(cycle)
+ .values({
+ projectId,
+ name: canonicalCycle.name,
+ goal: canonicalCycle.goal ?? '',
+ startDate: canonicalCycle.startDate,
+ endDate: canonicalCycle.endDate,
+ })
+ .returning({ id: cycle.id });
+ await upsertImportRecordWith(tx, jobId, 'cycle', sourceId, 'cycle', row!.id);
+ return row!.id;
+ });
+}
+
+export interface NewLocalIssue {
+ projectId: number;
+ columnId: number;
+ cycleId: number | null;
+ parentId: number | null;
+ assigneeUserId: string | null;
+ title: string;
+ description: string;
+ priority: string | null;
+ startDate: string | null;
+ dueDate: string | null;
+}
+
+// An issue whose title matches one already in the project (case- and
+// whitespace-insensitive, the same comparison the file-based importer uses)
+// is reused instead of duplicated — the same protection createLocalLabel and
+// createLocalStateAndRecord give their own entities. Comments and labels the
+// import attaches afterward land on that existing issue rather than being
+// orphaned. Skipped for a blank title: input.title falls back to
+// '(untitled)' below, and matching on that fallback would merge every
+// untitled Plane issue into whichever one happened to import first, which is
+// not a duplicate in any real sense.
+//
+// Sequence numbers ("MKT-42") are issued under a row lock on project, the
+// same pattern apps/api's createIssue uses, so a bulk import never collides
+// with a concurrent interactive create. The import_record mapping is written
+// in the same transaction as the insert: an issue has no unique constraint a
+// retry could fall back on (a fresh sequence number is issued every time),
+// so a crash between the insert and the mapping would otherwise duplicate
+// the issue on the next attempt. sourceDisplayId (the source's own issue
+// number) is stashed on that same mapping either way, for the Rewrite phase.
+export async function createLocalIssueAndRecord(
+ jobId: number,
+ sourceId: string,
+ sourceDisplayId: string,
+ input: NewLocalIssue,
+): Promise<number> {
+ return db.transaction(async (tx) => {
+ if (input.title.trim()) {
+ const [existing] = await tx
+ .select({ id: issue.id })
+ .from(issue)
+ .where(
+ and(
+ eq(issue.projectId, input.projectId),
+ sql`lower(btrim(${issue.title})) = lower(btrim(${input.title}))`,
+ ),
+ );
+ if (existing) {
+ await upsertImportRecordWith(
+ tx,
+ jobId,
+ 'issue',
+ sourceId,
+ 'issue',
+ existing.id,
+ sourceDisplayId,
+ );
+ return existing.id;
+ }
+ }
+ const [seqRow] = await tx
+ .update(project)
+ .set({ nextSequence: sql`next_sequence + 1` })
+ .where(eq(project.id, input.projectId))
+ .returning({ seq: sql<number>`next_sequence - 1` });
+ const [posRow] = await tx
+ .select({ pos: sql<number>`COALESCE(MAX(${issue.position}), 0) + 1000` })
+ .from(issue)
+ .where(eq(issue.columnId, input.columnId));
+ const [row] = await tx
+ .insert(issue)
+ .values({
+ projectId: input.projectId,
+ sequenceNumber: Number(seqRow!.seq),
+ columnId: input.columnId,
+ cycleId: input.cycleId,
+ parentId: input.parentId,
+ assigneeUserId: input.assigneeUserId,
+ title: input.title || '(untitled)',
+ description: input.description,
+ priority: input.priority,
+ startDate: input.startDate,
+ dueDate: input.dueDate,
+ position: Number(posRow!.pos),
+ })
+ .returning({ id: issue.id });
+ await upsertImportRecordWith(tx, jobId, 'issue', sourceId, 'issue', row!.id, sourceDisplayId);
+ return row!.id;
+ });
+}
+
+export async function setIssueLabels(issueId: number, labelIds: number[]): Promise<void> {
+ if (labelIds.length === 0) return;
+ await db
+ .insert(issueLabel)
+ .values(labelIds.map((labelId) => ({ issueId, labelId })))
+ .onConflictDoNothing();
+}
+
+// A comment already on the issue with the same body and createdAt (the two
+// fields Plane's own record carries verbatim) is reused instead of
+// duplicated — the same reuse-by-content protection issues, states, and
+// cycles get, needed here because a second import job resolves the parent
+// issue to the same, already-created row and would otherwise re-post every
+// comment on it.
+export async function createLocalComment(
+ issueId: number,
+ authorUserId: string | null,
+ authorName: string,
+ bodyMarkdown: string,
+ createdAt: Date,
+ replyToId: number | null,
+): Promise<number> {
+ const [existing] = await db
+ .select({ id: issueActivity.id })
+ .from(issueActivity)
+ .where(
+ and(
+ eq(issueActivity.issueId, issueId),
+ eq(issueActivity.kind, 'comment'),
+ eq(issueActivity.body, bodyMarkdown),
+ eq(issueActivity.createdAt, createdAt),
+ ),
+ );
+ if (existing) return existing.id;
+
+ const [row] = await db
+ .insert(issueActivity)
+ .values({
+ issueId,
+ kind: 'comment',
+ body: bodyMarkdown,
+ actorUserId: authorUserId,
+ actorName: authorName,
+ replyToId,
+ createdAt,
+ })
+ .returning({ id: issueActivity.id });
+ return row!.id;
+}
+
+// Sets an issue's parent the first time one resolves. Create sets parentId from
+// whatever import_record knows at that moment, which misses a sub-issue processed
+// before its parent exists; Link revisits every issue a second time (see runLink)
+// and calls this once the parent is resolvable. The parent_id IS NULL guard makes
+// a retry a no-op and never overwrites a parent Create already got right.
+export async function setIssueParentIfUnset(issueId: number, parentId: number): Promise<void> {
+ if (issueId === parentId) return;
+ await db
+ .update(issue)
+ .set({ parentId })
+ .where(and(eq(issue.id, issueId), isNull(issue.parentId)));
+}
+
+// issue_link's unique index is on the unordered pair + kind, so re-running the
+// Link phase for an issue whose relations were already created is a no-op:
+// the duplicate insert is caught and dropped rather than failing the tick.
+export async function createIssueLink(
+ sourceIssueId: number,
+ targetIssueId: number,
+ kind: string,
+): Promise<void> {
+ if (sourceIssueId === targetIssueId) return;
+ try {
+ await db.insert(issueLink).values({ sourceIssueId, targetIssueId, kind });
+ } catch (err) {
+ if (isUniqueViolation(err)) return;
+ throw err;
+ }
+}
+
+function isUniqueViolation(err: unknown): boolean {
+ return typeof err === 'object' && err !== null && (err as { code?: string }).code === '23505';
+}
+
+// Only a user who already belongs to the project is matched: an import never
+// adds someone to the project on its own just because their email matched a
+// Plane assignee or comment author.
+export async function findProjectMemberUserId(
+ projectId: number,
+ email: string,
+): Promise<string | null> {
+ const rows = await db
+ .select({ userId: projectMember.userId })
+ .from(projectMember)
+ .innerJoin(user, eq(user.id, projectMember.userId))
+ .where(and(eq(projectMember.projectId, projectId), sql`lower(${user.email}) = lower(${email})`))
+ .limit(1);
+ return rows[0]?.userId ?? null;
+}
+
+// Thrown for an attachment that simply does not fit this instance's own
+// configured limits (file size, mime type, or project quota) — the Attachments
+// phase catches this specifically and moves on to the next attachment, rather
+// than treating it as a failed tick the way a network or database error is.
+export class AttachmentRejectedError extends Error {}
+
+export interface NewLocalAttachment {
+ projectId: number;
+ issueId: number;
+ filename: string;
+ contentType: string;
+ bytes: Buffer;
+}
+
+// Reuse-before-duplicate, the same shape as the other entities: an attachment
+// already on this issue with the same filename is reused rather than re-uploaded
+// on a second import run. Size, mime type, and project quota are all checked
+// against the instance's own settings before the upload, so a file that cannot
+// be stored never reaches the object store at all; the quota is checked once
+// more inside the lock, right before the insert, the same two-step api's own
+// upload route follows — the first check keeps a doomed-to-reject file off the
+// object store, the second is the one a concurrent write can't slip past.
+export async function createLocalAttachmentAndRecord(
+ jobId: number,
+ sourceId: string,
+ input: NewLocalAttachment,
+): Promise<number> {
+ const filename = safeAttachmentFilename(input.filename);
+ const [existing] = await db
+ .select({ id: issueAttachment.id })
+ .from(issueAttachment)
+ .where(and(eq(issueAttachment.issueId, input.issueId), eq(issueAttachment.filename, filename)));
+ if (existing) {
+ await upsertImportRecordWith(db, jobId, 'attachment', sourceId, 'attachment', existing.id);
+ return existing.id;
+ }
+
+ const limits = await getStorageSettings();
+ if (input.bytes.length > limits.maxAttachmentMb * MB) {
+ throw new AttachmentRejectedError(
+ `"${filename}" is ${Math.ceil(input.bytes.length / MB)} MB, over the ${limits.maxAttachmentMb} MB limit`,
+ );
+ }
+ if (!mimeAllowed(input.contentType, limits.attachmentMimeTypes)) {
+ throw new AttachmentRejectedError(
+ `"${filename}" is type "${input.contentType}", not accepted on this instance`,
+ );
+ }
+ if (limits.projectQuotaMb > 0) {
+ const used = await projectStoredBytes(input.projectId);
+ if (used + input.bytes.length > limits.projectQuotaMb * MB) {
+ throw new AttachmentRejectedError(
+ `the project has used its ${limits.projectQuotaMb} MB storage quota`,
+ );
+ }
+ }
+
+ const key = attachmentObjectKey(input.projectId, 'attachments', input.issueId, filename);
+ await putObject(key, input.bytes, input.contentType);
+
+ try {
+ return await db.transaction(async (tx) => {
+ await lockAttachmentStorage(tx, input.projectId);
+ if (limits.projectQuotaMb > 0) {
+ // Re-checked against the lock: the check above ran before the upload,
+ // outside any lock, so a concurrent write could have landed since.
+ const used = await projectStoredBytes(input.projectId, tx);
+ if (used + input.bytes.length > limits.projectQuotaMb * MB) {
+ throw new AttachmentRejectedError(
+ `the project has used its ${limits.projectQuotaMb} MB storage quota`,
+ );
+ }
+ }
+ const [row] = await tx
+ .insert(issueAttachment)
+ .values({
+ issueId: input.issueId,
+ s3Key: key,
+ filename,
+ contentType: input.contentType,
+ sizeBytes: input.bytes.length,
+ })
+ .returning({ id: issueAttachment.id });
+ await upsertImportRecordWith(tx, jobId, 'attachment', sourceId, 'attachment', row!.id);
+ return row!.id;
+ });
+ } catch (error) {
+ await deleteObject(key).catch(() => {});
+ throw error;
+ }
+}
diff --git a/apps/worker/src/import-worker.ts b/apps/worker/src/import-worker.ts
new file mode 100644
index 00000000..1b97db24
--- /dev/null
+++ b/apps/worker/src/import-worker.ts
@@ -0,0 +1,506 @@
+import { pinnedFetch } from '@repo/net';
+import { getStorageSettings, mimeAllowed, MB } from '@repo/db';
+import { startPollLoop, type WorkerHandle } from './poll-loop';
+import { intEnv } from './env';
+import { equalJitterBackoffMs } from './backoff';
+import { PlaneReader, PlaneRateLimitedError } from './plane-adapter';
+import type { SourceReader } from './reader';
+import type { CanonicalComment, CanonicalStateCategory } from './canonical';
+import { extractCrossReferences, applyCrossReferenceReplacements } from './cross-reference';
+import {
+ claimDueImportJobs,
+ decryptImportCredential,
+ saveImportJobCursor,
+ advanceImportJobPhase,
+ completeImportJob,
+ failImportJob,
+ retryImportJobLater,
+ insertDiscoveredIds,
+ upsertImportRecord,
+ findImportRecord,
+ findImportRecordByDisplayId,
+ listUncreatedImportRecords,
+ listCreatedImportRecords,
+ firstProjectColumnId,
+ getProjectKey,
+ getIssueSequenceNumber,
+ getIssueTextForRewrite,
+ updateIssueDescription,
+ updateCommentBody,
+ createLocalStateAndRecord,
+ createLocalLabel,
+ createLocalCycleAndRecord,
+ createLocalIssueAndRecord,
+ setIssueLabels,
+ setIssueParentIfUnset,
+ createLocalComment,
+ createIssueLink,
+ findProjectMemberUserId,
+ createLocalAttachmentAndRecord,
+ AttachmentRejectedError,
+ type ClaimedImportJob,
+} from './import-store';
+
+// The poll loop that drives a Plane import through its phases: discover ->
+// create -> link -> rewrite -> attachments -> done. Follows the same claim-a-lease,
+// bounded-chunk-per-tick shape as worker.ts and agent-worker.ts. Each tick
+// claims at most one due import_job and advances it by one bounded unit of
+// work, then reschedules — a large import interleaves across many ticks
+// rather than running to completion in one.
+export function startImportWorker(): WorkerHandle {
+ return startPollLoop('import-worker', tick, () => intEnv('IMPORT_POLL_INTERVAL_MS', 3000));
+}
+
+// How many issues Create/Link process per tick. Each issue costs several
+// additional Plane requests (comments, attachments, relations) against a
+// ~60 requests/minute budget, so this stays well under the discover page size.
+const ISSUES_PER_TICK = 15;
+// import_store.ts resets job.attempts to 0 on every tick that makes progress
+// (saveImportJobCursor/advanceImportJobPhase), so this counts consecutive
+// failed ticks, not total ticks claimed over the job's life — a multi-tick
+// import doesn't fail itself out just by running long.
+const MAX_ATTEMPTS = 10;
+
+async function tick(): Promise<void> {
+ const [job] = await claimDueImportJobs();
+ if (!job) return;
+ try {
+ const reader = buildReader(job);
+ switch (job.phase) {
+ case 'discover':
+ await runDiscover(job, reader);
+ break;
+ case 'create':
+ await runCreate(job, reader);
+ break;
+ case 'link':
+ await runLink(job, reader);
+ break;
+ case 'rewrite':
+ await runRewrite(job);
+ break;
+ case 'attachments':
+ await runAttachments(job, reader);
+ break;
+ default:
+ await completeImportJob(job.id);
+ }
+ } catch (error) {
+ await handleTickError(job, error);
+ }
+}
+
+async function handleTickError(job: ClaimedImportJob, error: unknown): Promise<void> {
+ if (error instanceof PlaneRateLimitedError) {
+ await retryImportJobLater(job.id, error.retryAfterMs, 'rate limited');
+ return;
+ }
+ const message = error instanceof Error ? error.message : String(error);
+ if (job.attempts >= MAX_ATTEMPTS) {
+ await failImportJob(job.id, message);
+ return;
+ }
+ await retryImportJobLater(job.id, equalJitterBackoffMs(job.attempts), message);
+}
+
+interface PlaneImportConfig {
+ planeProjectId: string;
+ // The source project's own short identifier (Plane's "identifier", e.g. "ROOMS"),
+ // stored at job creation for the Rewrite phase to build "ROOMS-524"-style
+ // cross-reference patterns from. Optional: a job created before this existed has
+ // none, and Rewrite is a no-op for it rather than a failure.
+ planeProjectKey?: string;
+ // Set from the mapping review step at job creation. Both are optional and default
+ // to itsaplan's automatic mapping when absent.
+ unmatchedUserPolicy?: 'unassigned' | 'skip';
+ stateOverrides?: Record<string, CanonicalStateCategory>;
+}
+
+function buildReader(job: ClaimedImportJob): SourceReader {
+ const credential = decryptImportCredential(job);
+ const config = job.config as Partial<PlaneImportConfig>;
+ if (!config.planeProjectId)
+ throw new Error(`import job ${job.id} has no source project configured`);
+ return new PlaneReader(credential, config.planeProjectId);
+}
+
+// --- Discover: snapshot every source id up front, writing import_record rows
+// with no local mapping yet. Plane's own pagination cursor is not a safe
+// resumability anchor across a job that can span many ticks (see "Pagination"
+// in docs/dev/plane-import-source-notes.md) — Create resumes from this
+// snapshot instead, keyed on import_record's own id.
+
+interface DiscoverCursor {
+ subphase: 'meta' | 'issues';
+ planeCursor: string | null;
+}
+
+async function runDiscover(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ const cursor = job.cursor as Partial<DiscoverCursor>;
+ if (cursor.subphase !== 'issues') {
+ const [states, labels, cycles] = await Promise.all([
+ reader.listStates(),
+ reader.listLabels(),
+ reader.listCycles(),
+ ]);
+ await insertDiscoveredIds(
+ job.id,
+ 'state',
+ states.map((s) => s.sourceId),
+ );
+ await insertDiscoveredIds(
+ job.id,
+ 'label',
+ labels.map((l) => l.sourceId),
+ );
+ await insertDiscoveredIds(
+ job.id,
+ 'cycle',
+ cycles.map((c) => c.sourceId),
+ );
+ const next: DiscoverCursor = { subphase: 'issues', planeCursor: null };
+ await saveImportJobCursor(job.id, next);
+ return;
+ }
+
+ const page = await reader.listIssues(cursor.planeCursor ?? null);
+ await insertDiscoveredIds(
+ job.id,
+ 'issue',
+ page.items.map((i) => i.sourceId),
+ );
+ if (page.cursor === null) {
+ await advanceImportJobPhase(job.id, 'create', {});
+ return;
+ }
+ const next: DiscoverCursor = { subphase: 'issues', planeCursor: page.cursor };
+ await saveImportJobCursor(job.id, next);
+}
+
+// --- Create: materialize states/labels/cycles once (cheap, unpaginated),
+// then create one chunk of not-yet-created issues per tick, with their
+// comments and their attachment metadata (byte download is a later phase).
+
+interface RecordCursor {
+ lastRecordId: number;
+}
+
+async function runCreate(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ await materializeStates(job, reader);
+ await materializeLabels(job, reader);
+ await materializeCycles(job, reader);
+
+ const cursor = job.cursor as Partial<RecordCursor>;
+ const afterId = cursor.lastRecordId ?? 0;
+ const pending = await listUncreatedImportRecords(job.id, 'issue', afterId, ISSUES_PER_TICK);
+ if (pending.length === 0) {
+ await advanceImportJobPhase(job.id, 'link', {});
+ return;
+ }
+ for (const record of pending) {
+ await createOneIssue(job, reader, record.sourceId);
+ }
+ const next: RecordCursor = { lastRecordId: pending[pending.length - 1]!.id };
+ await saveImportJobCursor(job.id, next);
+}
+
+// stateOverrides (Plane state id -> itsaplan category) comes from the mapping review
+// step at job creation; only newly-created columns are affected, never a dedup-matched
+// existing one - createLocalStateAndRecord already never touches an existing match's
+// stateType.
+async function materializeStates(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ const pending = await listUncreatedImportRecords(job.id, 'state', 0, 1000);
+ if (pending.length === 0) return;
+ const overrides = (job.config as Partial<PlaneImportConfig>).stateOverrides ?? {};
+ const states = new Map((await reader.listStates()).map((s) => [s.sourceId, s]));
+ for (const record of pending) {
+ const state = states.get(record.sourceId);
+ if (!state) continue;
+ const category = overrides[record.sourceId] ?? state.category;
+ await createLocalStateAndRecord(job.id, record.sourceId, job.projectId, {
+ ...state,
+ category,
+ });
+ }
+}
+
+async function materializeLabels(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ const pending = await listUncreatedImportRecords(job.id, 'label', 0, 1000);
+ if (pending.length === 0) return;
+ const labels = new Map((await reader.listLabels()).map((l) => [l.sourceId, l]));
+ for (const record of pending) {
+ const label = labels.get(record.sourceId);
+ if (!label) continue;
+ const localId = await createLocalLabel(job.projectId, label);
+ await upsertImportRecord(job.id, 'label', record.sourceId, 'label', localId);
+ }
+}
+
+async function materializeCycles(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ const pending = await listUncreatedImportRecords(job.id, 'cycle', 0, 1000);
+ if (pending.length === 0) return;
+ const cycles = new Map((await reader.listCycles()).map((c) => [c.sourceId, c]));
+ for (const record of pending) {
+ const cycle = cycles.get(record.sourceId);
+ if (!cycle) continue;
+ await createLocalCycleAndRecord(job.id, record.sourceId, job.projectId, cycle);
+ }
+}
+
+async function createOneIssue(
+ job: ClaimedImportJob,
+ reader: SourceReader,
+ sourceId: string,
+): Promise<void> {
+ const canonical = await reader.getIssue(sourceId);
+
+ const stateRecord = await findImportRecord(job.id, 'state', canonical.stateSourceId);
+ const columnId = stateRecord?.localId ?? (await firstProjectColumnId(job.projectId));
+ if (columnId == null)
+ throw new Error(`project ${job.projectId} has no workflow column to import into`);
+
+ const cycleRecord = canonical.cycleSourceId
+ ? await findImportRecord(job.id, 'cycle', canonical.cycleSourceId)
+ : null;
+ const parentRecord = canonical.parentSourceId
+ ? await findImportRecord(job.id, 'issue', canonical.parentSourceId)
+ : null;
+ const assigneeUserId = canonical.assigneeEmail
+ ? await findProjectMemberUserId(job.projectId, canonical.assigneeEmail)
+ : null;
+
+ const labelIds: number[] = [];
+ for (const labelSourceId of canonical.labelSourceIds) {
+ const record = await findImportRecord(job.id, 'label', labelSourceId);
+ if (record?.localId != null) labelIds.push(record.localId);
+ }
+
+ const localId = await createLocalIssueAndRecord(job.id, sourceId, String(canonical.sequenceId), {
+ projectId: job.projectId,
+ columnId,
+ cycleId: cycleRecord?.localId ?? null,
+ parentId: parentRecord?.localId ?? null,
+ assigneeUserId,
+ title: canonical.title,
+ description: canonical.descriptionMarkdown,
+ priority: canonical.priority,
+ startDate: canonical.startDate,
+ dueDate: canonical.dueDate,
+ });
+ if (labelIds.length) await setIssueLabels(localId, labelIds);
+
+ await createComments(job, localId, await reader.listIssueComments(sourceId));
+
+ const attachments = await reader.listIssueAttachments(sourceId);
+ if (attachments.length) {
+ await insertDiscoveredIds(
+ job.id,
+ 'attachment',
+ attachments.map((a) => a.sourceId),
+ );
+ }
+}
+
+// Comments are recorded in import_record too (entity type 'comment'), so a
+// crashed-and-retried tick does not insert the same comment twice — issue_
+// activity carries no unique constraint of its own to fall back on.
+// Processed in the order Plane returned them, which is assumed chronological,
+// so a reply's parent is created before the reply itself.
+async function createComments(
+ job: ClaimedImportJob,
+ issueLocalId: number,
+ comments: CanonicalComment[],
+): Promise<void> {
+ const unmatchedUserPolicy = (job.config as Partial<PlaneImportConfig>).unmatchedUserPolicy;
+ const localIdBySourceId = new Map<string, number>();
+ for (const comment of comments) {
+ const existing = await findImportRecord(job.id, 'comment', comment.sourceId);
+ if (existing?.localId != null) {
+ localIdBySourceId.set(comment.sourceId, existing.localId);
+ continue;
+ }
+ const authorUserId = comment.authorEmail
+ ? await findProjectMemberUserId(job.projectId, comment.authorEmail)
+ : null;
+ // 'skip' drops a comment whose author matched no project member, rather than
+ // creating it unattributed. A comment with no authorEmail at all (Plane gave no
+ // address to match) is unaffected - there was never a member to match against.
+ if (comment.authorEmail && !authorUserId && unmatchedUserPolicy === 'skip') continue;
+ const replyToId = comment.replyToSourceId
+ ? (localIdBySourceId.get(comment.replyToSourceId) ?? null)
+ : null;
+ const localId = await createLocalComment(
+ issueLocalId,
+ authorUserId,
+ comment.authorName,
+ comment.bodyMarkdown,
+ new Date(comment.createdAt),
+ replyToId,
+ );
+ await upsertImportRecord(job.id, 'comment', comment.sourceId, 'comment', localId);
+ localIdBySourceId.set(comment.sourceId, localId);
+ }
+}
+
+// --- Link: for each created issue, fetch its relations and create the ones
+// with a destination in itsaplan's issue_link.kind (see "Relations vs.
+// dependencies" in the notes file). Also gives every issue's parent link a
+// second chance to resolve: Create only knew what import_record held at the
+// moment it ran, so a sub-issue processed before its parent existed was left
+// with no parent — by Link, every issue in the job has been created.
+
+async function runLink(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ const cursor = job.cursor as Partial<RecordCursor>;
+ const afterId = cursor.lastRecordId ?? 0;
+ const pending = await listCreatedImportRecords(job.id, 'issue', afterId, ISSUES_PER_TICK);
+ if (pending.length === 0) {
+ await advanceImportJobPhase(job.id, 'rewrite', {});
+ return;
+ }
+ for (const record of pending) {
+ const canonical = await reader.getIssue(record.sourceId);
+ if (canonical.parentSourceId) {
+ const parentRecord = await findImportRecord(job.id, 'issue', canonical.parentSourceId);
+ if (parentRecord?.localId != null) {
+ await setIssueParentIfUnset(record.localId, parentRecord.localId);
+ }
+ }
+ const relations = await reader.listIssueRelations(record.sourceId);
+ for (const relation of relations) {
+ const targetRecord = await findImportRecord(job.id, 'issue', relation.targetIssueSourceId);
+ if (targetRecord?.localId == null) continue;
+ await createIssueLink(record.localId, targetRecord.localId, relation.kind);
+ }
+ }
+ const next: RecordCursor = { lastRecordId: pending[pending.length - 1]!.id };
+ await saveImportJobCursor(job.id, next);
+}
+
+// --- Rewrite: a description or comment that mentions the source's own issue
+// number ("ROOMS-524") still says that after Create — this phase resolves any
+// such mention that lands inside the imported set and rewrites it to this
+// project's own identifier. Purely local: everything it needs was captured
+// during Create/Link, so it makes no further Plane requests.
+
+async function rewriteCrossReferences(
+ jobId: number,
+ sourceProjectKey: string,
+ localProjectKey: string,
+ text: string,
+): Promise<string> {
+ const references = extractCrossReferences(text, sourceProjectKey);
+ if (references.length === 0) return text;
+
+ const replacements = new Map<string, string>();
+ for (const { reference, sequenceId } of references) {
+ const record = await findImportRecordByDisplayId(jobId, 'issue', sequenceId);
+ if (record?.localId == null) continue;
+ const targetSequence = await getIssueSequenceNumber(record.localId);
+ if (targetSequence == null) continue;
+ replacements.set(reference, `${localProjectKey}-${targetSequence}`);
+ }
+ return applyCrossReferenceReplacements(text, sourceProjectKey, replacements);
+}
+
+async function runRewrite(job: ClaimedImportJob): Promise<void> {
+ const cursor = job.cursor as Partial<RecordCursor>;
+ const afterId = cursor.lastRecordId ?? 0;
+ const pending = await listCreatedImportRecords(job.id, 'issue', afterId, ISSUES_PER_TICK);
+ if (pending.length === 0) {
+ await advanceImportJobPhase(job.id, 'attachments', {});
+ return;
+ }
+
+ // A job created before this phase existed has no planeProjectKey — its
+ // description/comment text is left exactly as Create wrote it.
+ const sourceProjectKey = (job.config as Partial<PlaneImportConfig>).planeProjectKey;
+ if (sourceProjectKey) {
+ const localProjectKey = await getProjectKey(job.projectId);
+ for (const record of pending) {
+ const { description, comments } = await getIssueTextForRewrite(record.localId);
+ const nextDescription = await rewriteCrossReferences(
+ job.id,
+ sourceProjectKey,
+ localProjectKey,
+ description,
+ );
+ if (nextDescription !== description) {
+ await updateIssueDescription(record.localId, nextDescription);
+ }
+ for (const comment of comments) {
+ const nextBody = await rewriteCrossReferences(
+ job.id,
+ sourceProjectKey,
+ localProjectKey,
+ comment.body,
+ );
+ if (nextBody !== comment.body) await updateCommentBody(comment.id, nextBody);
+ }
+ }
+ }
+
+ const next: RecordCursor = { lastRecordId: pending[pending.length - 1]!.id };
+ await saveImportJobCursor(job.id, next);
+}
+
+// --- Attachments: metadata (filename, content type, size) was already listed
+// per-issue during Create, but never the bytes — those need a fresh
+// resolve-then-fetch of the two-hop, hour-lived S3 redirect right before each
+// download (see "Attachments" in the notes file), so this phase re-lists each
+// issue's attachments rather than reusing anything captured earlier.
+
+async function runAttachments(job: ClaimedImportJob, reader: SourceReader): Promise<void> {
+ const cursor = job.cursor as Partial<RecordCursor>;
+ const afterId = cursor.lastRecordId ?? 0;
+ const pending = await listCreatedImportRecords(job.id, 'issue', afterId, ISSUES_PER_TICK);
+ if (pending.length === 0) {
+ await completeImportJob(job.id);
+ return;
+ }
+ const limits = await getStorageSettings();
+ for (const record of pending) {
+ const attachments = await reader.listIssueAttachments(record.sourceId);
+ for (const attachment of attachments) {
+ if ((await findImportRecord(job.id, 'attachment', attachment.sourceId))?.localId != null) {
+ continue;
+ }
+ try {
+ // Plane's own advertised size/type skip an obviously-too-large or
+ // disallowed file before spending a download on it; the authoritative
+ // check is still the real downloaded byte count, in
+ // createLocalAttachmentAndRecord.
+ if (attachment.sizeBytes > limits.maxAttachmentMb * MB) {
+ throw new AttachmentRejectedError(
+ `"${attachment.filename}" is ${Math.ceil(attachment.sizeBytes / MB)} MB, over the ${limits.maxAttachmentMb} MB limit`,
+ );
+ }
+ if (!mimeAllowed(attachment.contentType, limits.attachmentMimeTypes)) {
+ throw new AttachmentRejectedError(
+ `"${attachment.filename}" is type "${attachment.contentType}", not accepted on this instance`,
+ );
+ }
+ const url = await reader.resolveAttachmentDownloadUrl(record.sourceId, attachment.sourceId);
+ const res = await pinnedFetch(url, {
+ timeoutMs: 30_000,
+ maxBytes: limits.maxAttachmentMb * MB,
+ });
+ const bytes = Buffer.from(await res.arrayBuffer());
+ await createLocalAttachmentAndRecord(job.id, attachment.sourceId, {
+ projectId: job.projectId,
+ issueId: record.localId,
+ filename: attachment.filename,
+ contentType: attachment.contentType,
+ bytes,
+ });
+ } catch (error) {
+ if (!(error instanceof AttachmentRejectedError)) throw error;
+ console.error(
+ `[import ${job.id}] attachment ${attachment.sourceId} rejected:`,
+ error.message,
+ );
+ }
+ }
+ }
+ const next: RecordCursor = { lastRecordId: pending[pending.length - 1]!.id };
+ await saveImportJobCursor(job.id, next);
+}
diff --git a/apps/worker/src/index.ts b/apps/worker/src/index.ts
index d6522318..60274c4b 100644
--- a/apps/worker/src/index.ts
+++ b/apps/worker/src/index.ts
@@ -1,16 +1,19 @@
import { startWorker } from './worker';
import { startAgentWorker } from './agent-worker';
+import { startImportWorker } from './import-worker';
-// Entry point for webhook delivery, agent scheduling, and autonomous agent runs.
-// The api applies database migrations on startup.
+// Entry point for webhook delivery, agent scheduling, autonomous agent runs,
+// and source imports. The api applies database migrations on startup.
console.log('[worker] worker starting');
const worker = startWorker();
const agentWorker = startAgentWorker();
+const importWorker = startImportWorker();
function shutdown(signal: string): void {
console.log(`[worker] ${signal} received, stopping`);
worker.stop();
agentWorker.stop();
+ importWorker.stop();
process.exit(0);
}
diff --git a/apps/worker/src/plane-adapter.ts b/apps/worker/src/plane-adapter.ts
new file mode 100644
index 00000000..68426785
--- /dev/null
+++ b/apps/worker/src/plane-adapter.ts
@@ -0,0 +1,456 @@
+import { pinnedFetch } from '@repo/net';
+import type { Page, SourceReader } from './reader';
+import type {
+ CanonicalState,
+ CanonicalStateCategory,
+ CanonicalLabel,
+ CanonicalCycle,
+ CanonicalIssue,
+ CanonicalRelation,
+ CanonicalComment,
+ CanonicalAttachment,
+} from './canonical';
+
+// The concrete SourceReader for Plane (docs/dev/plane-import-source-notes.md is
+// the spec this file follows). Base URL, workspace slug and API key come from
+// the operator's own decrypted credential (import-store.ts), never from env —
+// this has to work against any self-hosted instance, not one fixed one.
+
+export interface PlaneCredential {
+ baseUrl: string;
+ workspaceSlug: string;
+ apiKey: string;
+}
+
+const PER_PAGE = 100;
+
+// Thrown when Plane's rate limit is hit (or about to be): x-ratelimit-remaining
+// reaches 0, or a 429 arrives. The worker catches this and reschedules the job
+// instead of treating it as a failed attempt.
+export class PlaneRateLimitedError extends Error {
+ constructor(public readonly retryAfterMs: number) {
+ super('Plane rate limit reached');
+ }
+}
+
+// A 404 confirmed live to mean "this Plane version doesn't have this
+// endpoint" (custom properties, work item types, ...) rather than a broken
+// import, when it happens on one of those. Nothing catches it specially yet —
+// it currently propagates like any other failure — because this milestone
+// doesn't call those version-dependent endpoints (custom fields are not
+// imported yet).
+export class PlaneNotFoundError extends Error {}
+
+// Plane's GroupEnum uses British spelling ('cancelled') and adds 'triage',
+// which itsaplan's project_column.state_type has no equivalent for.
+const STATE_CATEGORY_MAP: Record<string, CanonicalStateCategory> = {
+ backlog: 'backlog',
+ unstarted: 'unstarted',
+ started: 'started',
+ completed: 'completed',
+ cancelled: 'canceled',
+ triage: 'backlog',
+};
+
+export function normalizeStateCategory(planeGroup: string): CanonicalStateCategory {
+ return STATE_CATEGORY_MAP[planeGroup] ?? 'backlog';
+}
+
+// Plane's WorkItemRelationTypeEnum. start_before/after and finish_before/after
+// are Gantt-style scheduling dependencies with no destination in itsaplan's
+// schema at all, so they are dropped rather than mapped.
+const RELATION_KIND_MAP: Record<string, CanonicalRelation['kind']> = {
+ blocking: 'blocks',
+ blocked_by: 'blocks',
+ duplicate: 'duplicates',
+ relates_to: 'relates',
+};
+
+// Whether next_page_results says there is another page to fetch — the only
+// correct loop-termination signal (not "fewer than per_page came back", not
+// "cursor unchanged"). Isolated as a pure function because getting this wrong
+// silently drops results with no error (confirmed live, see the notes file).
+export function nextPageCursor(nextCursor: string | null, hasNextPage: boolean): string | null {
+ return hasNextPage ? nextCursor : null;
+}
+
+// x-ratelimit-remaining / x-ratelimit-reset are on every response; a 429 was
+// never observed live, so Retry-After on it is handled but unconfirmed. Pure
+// so the three trigger conditions (Retry-After, 429, remaining-hits-zero) are
+// each unit-testable without a network call.
+export function rateLimitBackoffMs(
+ headers: {
+ status: number;
+ remaining: string | null;
+ resetEpochSec: string | null;
+ retryAfterSec: string | null;
+ },
+ nowMs = Date.now(),
+): number | null {
+ if (headers.retryAfterSec) return Math.max(1, Number(headers.retryAfterSec)) * 1000;
+ if (headers.status === 429) return 60_000;
+ if (headers.remaining === '0') {
+ if (headers.resetEpochSec) {
+ return Math.max(1000, Number(headers.resetEpochSec) * 1000 - nowMs);
+ }
+ return 60_000;
+ }
+ return null;
+}
+
+// Minimal HTML-to-markdown conversion for description_html (Tiptap-flavored
+// markup, confirmed live — see "Descriptions" in the notes file). No
+// HTML-to-markdown library is already a dependency anywhere in the monorepo
+// (marked is markdown-to-HTML; tiptap-markdown needs a browser editor
+// instance), so this is a small tag-by-tag pass rather than a new dependency
+// for one conversion. Best-effort: nested structures beyond one level (a list
+// inside a blockquote, say) are not guaranteed to round-trip perfectly.
+export function htmlToMarkdown(html: string): string {
+ if (!html) return '';
+ let out = html;
+
+ // Fenced code blocks first, so their content is not touched by the inline
+ // and entity passes below.
+ out = out.replace(
+ /<pre[^>]*><code[^>]*>([\s\S]*?)<\/code><\/pre>/gi,
+ (_m, body: string) => `\n\`\`\`\n${decodeEntities(stripTags(body))}\n\`\`\`\n`,
+ );
+ out = out.replace(
+ /<code[^>]*>([\s\S]*?)<\/code>/gi,
+ (_m, body: string) => `\`${stripTags(body)}\``,
+ );
+
+ out = out.replace(
+ /<img[^>]*\balt="([^"]*)"[^>]*\bsrc="([^"]*)"[^>]*>/gi,
+ (_m, alt: string, src: string) => `![${alt}](${src})`,
+ );
+ out = out.replace(
+ /<img[^>]*\bsrc="([^"]*)"[^>]*\balt="([^"]*)"[^>]*>/gi,
+ (_m, src: string, alt: string) => `![${alt}](${src})`,
+ );
+ out = out.replace(/<img[^>]*\bsrc="([^"]*)"[^>]*>/gi, (_m, src: string) => `![](${src})`);
+ out = out.replace(
+ /<a[^>]*\bhref="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,
+ (_m, href: string, text: string) => `[${stripTags(text)}](${href})`,
+ );
+
+ out = out.replace(
+ /<(strong|b)[^>]*>([\s\S]*?)<\/\1>/gi,
+ (_m, _tag, text: string) => `**${text}**`,
+ );
+ out = out.replace(/<(em|i)[^>]*>([\s\S]*?)<\/\1>/gi, (_m, _tag, text: string) => `*${text}*`);
+
+ // Task-list items (Tiptap: <li data-checked="true|false">) before plain
+ // list items, so the checkbox marker is not lost to the generic <li> rule.
+ out = out.replace(
+ /<li[^>]*\bdata-checked="(true|false)"[^>]*>([\s\S]*?)<\/li>/gi,
+ (_m, checked: string, text: string) =>
+ `\n- [${checked === 'true' ? 'x' : ' '}] ${stripTags(text).trim()}`,
+ );
+ out = out.replace(
+ /<li[^>]*>([\s\S]*?)<\/li>/gi,
+ (_m, text: string) => `\n- ${stripTags(text).trim()}`,
+ );
+ out = out.replace(/<\/?(ul|ol)[^>]*>/gi, '\n');
+
+ for (let level = 6; level >= 1; level--) {
+ const tag = `h${level}`;
+ out = out.replace(
+ new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, 'gi'),
+ (_m, text: string) => `\n${'#'.repeat(level)} ${stripTags(text).trim()}\n`,
+ );
+ }
+
+ out = out.replace(/<blockquote[^>]*>([\s\S]*?)<\/blockquote>/gi, (_m, text: string) => {
+ const lines = stripTags(text).trim().split('\n');
+ return `\n${lines.map((line) => `> ${line}`).join('\n')}\n`;
+ });
+
+ out = out.replace(/<p[^>]*>([\s\S]*?)<\/p>/gi, (_m, text: string) => `\n${text.trim()}\n`);
+ out = out.replace(/<br\s*\/?>/gi, '\n');
+ out = out.replace(/<hr\s*\/?>/gi, '\n---\n');
+
+ out = decodeEntities(stripTags(out));
+ return out.replace(/\n{3,}/g, '\n\n').trim();
+}
+
+function stripTags(html: string): string {
+ let out = html;
+ let prev: string;
+ do {
+ prev = out;
+ out = out.replace(/<[^>]*>/g, '');
+ } while (out !== prev);
+ return out;
+}
+
+const ENTITIES: Record<string, string> = {
+ nbsp: ' ',
+ amp: '&',
+ lt: '<',
+ gt: '>',
+ quot: '"',
+ '#39': "'",
+};
+
+function decodeEntities(text: string): string {
+ return text.replace(/&(nbsp|amp|lt|gt|quot|#39);/g, (_m, name: string) => ENTITIES[name]!);
+}
+
+interface PlaneMember {
+ id: string;
+ email: string;
+ display_name?: string;
+ first_name?: string;
+ last_name?: string;
+}
+
+interface PlaneListEnvelope<T> {
+ results: T[];
+ next_cursor: string | null;
+ next_page_results: boolean;
+}
+
+export class PlaneReader implements SourceReader {
+ private membersPromise: Promise<Map<string, PlaneMember>> | null = null;
+
+ constructor(
+ private readonly credential: PlaneCredential,
+ private readonly projectId: string,
+ ) {}
+
+ async listStates(): Promise<CanonicalState[]> {
+ const rows = await this.getResults<{ id: string; name: string; group: string }>('/states/');
+ return rows.map((s) => ({
+ sourceId: s.id,
+ name: s.name,
+ category: normalizeStateCategory(s.group),
+ }));
+ }
+
+ async listLabels(): Promise<CanonicalLabel[]> {
+ const rows = await this.getResults<{ id: string; name: string; color?: string }>('/labels/');
+ return rows.map((l) => ({ sourceId: l.id, name: l.name, color: l.color }));
+ }
+
+ async listCycles(): Promise<CanonicalCycle[]> {
+ const rows = await this.getResults<{
+ id: string;
+ name: string;
+ start_date: string | null;
+ end_date: string | null;
+ description?: string;
+ }>('/cycles/');
+ // Cycles carry full timestamps, not dates; itsaplan's cycle.startDate/
+ // endDate are date-only so the time of day is dropped here.
+ return rows
+ .filter((c) => c.start_date && c.end_date)
+ .map((c) => ({
+ sourceId: c.id,
+ name: c.name,
+ startDate: dateOnly(c.start_date!),
+ endDate: dateOnly(c.end_date!),
+ goal: c.description || undefined,
+ }));
+ }
+
+ async listIssues(cursor: string | null): Promise<Page<CanonicalIssue>> {
+ const query = `per_page=${PER_PAGE}&expand=assignees,labels,state${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`;
+ const envelope = await this.getJson<PlaneListEnvelope<PlaneWorkItem>>(`/work-items/?${query}`);
+ return {
+ items: envelope.results.map(mapWorkItem),
+ cursor: nextPageCursor(envelope.next_cursor, envelope.next_page_results),
+ };
+ }
+
+ async getIssue(sourceId: string): Promise<CanonicalIssue> {
+ const raw = await this.getJson<PlaneWorkItem>(
+ `/work-items/${sourceId}/?expand=assignees,labels,state`,
+ );
+ return mapWorkItem(raw);
+ }
+
+ async listIssueRelations(issueSourceId: string): Promise<CanonicalRelation[]> {
+ // Not a list: one array per relation kind, each holding the related issue's
+ // id directly (confirmed live) — {blocking: [...], blocked_by: [...], ...},
+ // not {relation_type, related_work_item}[].
+ const grouped = await this.getJson<Record<string, string[]>>(
+ `/work-items/${issueSourceId}/relations/`,
+ );
+ return Object.entries(grouped).flatMap(([planeKind, targetIds]) => {
+ const kind = RELATION_KIND_MAP[planeKind];
+ if (!kind) return [];
+ return targetIds.map((targetIssueSourceId) => ({
+ kind,
+ sourceIssueSourceId: issueSourceId,
+ targetIssueSourceId,
+ }));
+ });
+ }
+
+ async listIssueComments(issueSourceId: string): Promise<CanonicalComment[]> {
+ const rows = await this.getResults<{
+ id: string;
+ comment_html: string;
+ created_by: string;
+ created_at: string;
+ reply_to_comment?: string | null;
+ }>(`/work-items/${issueSourceId}/comments/`);
+ if (rows.length === 0) return [];
+ const members = await this.members();
+ return rows.map((c) => {
+ const author = members.get(c.created_by);
+ return {
+ sourceId: c.id,
+ authorEmail: author?.email ?? null,
+ authorName: author ? memberName(author) : 'Unknown',
+ bodyMarkdown: htmlToMarkdown(c.comment_html),
+ createdAt: c.created_at,
+ replyToSourceId: c.reply_to_comment ?? null,
+ };
+ });
+ }
+
+ async listIssueAttachments(issueSourceId: string): Promise<CanonicalAttachment[]> {
+ const rows = await this.getJson<
+ { id: string; attributes: { name: string; type: string; size: number } }[]
+ >(`/work-items/${issueSourceId}/attachments/`);
+ return rows.map((a) => ({
+ sourceId: a.id,
+ filename: a.attributes.name,
+ contentType: a.attributes.type,
+ sizeBytes: a.attributes.size,
+ }));
+ }
+
+ // Two-hop resolve, confirmed live (see "Attachments" in the notes file): this
+ // call itself 302s to an S3 URL valid for exactly an hour, needing no Plane
+ // auth — never resolved ahead of the moment it's actually downloaded.
+ async resolveAttachmentDownloadUrl(
+ issueSourceId: string,
+ attachmentSourceId: string,
+ ): Promise<string> {
+ const path = `/work-items/${issueSourceId}/attachments/${attachmentSourceId}/`;
+ const res = await this.requestRaw(path);
+ const location = res.headers.get('location');
+ if (res.status < 300 || res.status >= 400 || !location) {
+ throw new Error(
+ `Plane attachment resolve did not redirect: GET ${path} -> HTTP ${res.status}`,
+ );
+ }
+ return location;
+ }
+
+ // members/ is flat, unpaginated, and carries email directly — exactly what
+ // comment authors (bare user ids, since expand does not reach the comments
+ // endpoint) need to be matched against. Fetched once per job run and cached.
+ private members(): Promise<Map<string, PlaneMember>> {
+ if (!this.membersPromise) {
+ this.membersPromise = this.getJson<PlaneMember[]>('/members/').then(
+ (rows) => new Map(rows.map((m) => [m.id, m])),
+ );
+ }
+ return this.membersPromise;
+ }
+
+ private async getJson<T>(path: string): Promise<T> {
+ const res = await this.request(path);
+ return (await res.json()) as T;
+ }
+
+ // states/, labels/ and cycles/ are the same paginated envelope as work-items,
+ // confirmed live — not the bare array members/ returns. Small enough lists
+ // that the default per_page covers them in one page.
+ private async getResults<T>(path: string): Promise<T[]> {
+ return (await this.getJson<PlaneListEnvelope<T>>(path)).results;
+ }
+
+ private async request(path: string): Promise<Response> {
+ const res = await this.requestRaw(path);
+ if (!res.ok) throw new Error(`Plane request failed: GET ${path} -> HTTP ${res.status}`);
+ return res;
+ }
+
+ // The rate-limit and 404 checks every Plane call needs, without requiring a
+ // 2xx status — resolveAttachmentDownloadUrl's whole point is a 3xx response.
+ private async requestRaw(path: string): Promise<Response> {
+ const base = this.credential.baseUrl.replace(/\/$/, '');
+ const url = `${base}/api/v1/workspaces/${this.credential.workspaceSlug}/projects/${this.projectId}${path}`;
+ const res = await pinnedFetch(url, {
+ headers: { 'X-Api-Key': this.credential.apiKey },
+ timeoutMs: 15_000,
+ });
+ const backoff = rateLimitBackoffMs({
+ status: res.status,
+ remaining: res.headers.get('x-ratelimit-remaining'),
+ resetEpochSec: res.headers.get('x-ratelimit-reset'),
+ retryAfterSec: res.headers.get('retry-after'),
+ });
+ if (backoff !== null) throw new PlaneRateLimitedError(backoff);
+ if (res.status === 404) throw new PlaneNotFoundError(path);
+ return res;
+ }
+}
+
+function memberName(m: PlaneMember): string {
+ return m.display_name || [m.first_name, m.last_name].filter(Boolean).join(' ') || m.email;
+}
+
+function dateOnly(isoTimestamp: string): string {
+ return isoTimestamp.slice(0, 10);
+}
+
+// Plane's work-item shape. title/cycle/parent/due-date field names below are a
+// best-effort reading (name / cycle_id / parent_id / target_date) — the notes
+// file confirms description_html, state, assignees and labels live but does
+// not pin these down; verify against a live response if issues import with an
+// empty title, or a missing cycle/parent/due date.
+interface PlaneWorkItem {
+ id: string;
+ name?: string;
+ title?: string;
+ sequence_id: number;
+ description_html: string;
+ state?: { id: string } | string;
+ assignees?: ({ email: string } | string)[];
+ labels?: ({ id: string } | string)[];
+ cycle_id?: string | null;
+ cycle?: string | null;
+ parent_id?: string | null;
+ parent?: string | null;
+ priority?: string | null;
+ start_date?: string | null;
+ target_date?: string | null;
+ due_date?: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+function mapWorkItem(raw: PlaneWorkItem): CanonicalIssue {
+ return {
+ sourceId: raw.id,
+ sequenceId: raw.sequence_id,
+ title: raw.name ?? raw.title ?? '',
+ descriptionMarkdown: htmlToMarkdown(raw.description_html),
+ stateSourceId: typeof raw.state === 'string' ? raw.state : (raw.state?.id ?? ''),
+ assigneeEmail: firstAssigneeEmail(raw.assignees),
+ labelSourceIds: (raw.labels ?? []).map((l) => (typeof l === 'string' ? l : l.id)),
+ cycleSourceId: raw.cycle_id ?? raw.cycle ?? null,
+ parentSourceId: raw.parent_id ?? raw.parent ?? null,
+ priority: raw.priority ?? null,
+ startDate: raw.start_date ?? null,
+ dueDate: raw.target_date ?? raw.due_date ?? null,
+ // Custom fields are not read by this adapter: Plane scopes them to a work
+ // item type with no project-wide list endpoint, and 404s outright on a
+ // real self-hosted instance (see "Custom properties" in the notes file).
+ customFields: [],
+ createdAt: raw.created_at,
+ updatedAt: raw.updated_at,
+ };
+}
+
+function firstAssigneeEmail(assignees: PlaneWorkItem['assignees']): string | null {
+ const first = assignees?.[0];
+ if (!first) return null;
+ return typeof first === 'string' ? null : first.email;
+}
diff --git a/apps/worker/src/reader.ts b/apps/worker/src/reader.ts
new file mode 100644
index 00000000..279b0f5f
--- /dev/null
+++ b/apps/worker/src/reader.ts
@@ -0,0 +1,48 @@
+import type {
+ CanonicalState,
+ CanonicalLabel,
+ CanonicalCycle,
+ CanonicalIssue,
+ CanonicalRelation,
+ CanonicalComment,
+ CanonicalAttachment,
+} from './canonical';
+
+// One page of a cursor-paginated list. cursor is the exact, opaque value the
+// source API returned for the next page, or null when there is no next page.
+// It must be passed back to the source verbatim — never reconstructed — and a
+// caller must stop on cursor === null rather than inferring completion from
+// the page size (see docs/dev/plane-import-source-notes.md).
+export interface Page<T> {
+ items: T[];
+ cursor: string | null;
+}
+
+// The port a source-specific adapter implements (plane-adapter.ts is the only
+// implementation today). Shaped from what import-worker.ts actually needs to
+// drive the Discover/Create/Link phases, not speculatively:
+//
+// - states/labels/cycles are small, unpaginated project-level lists.
+// - listIssues walks the source's own pagination for the Discover snapshot.
+// - getIssue re-fetches one issue by id: Create resumes from itsaplan's own
+// import_record snapshot, not from the source's pagination position, so it
+// needs a single-item fetch rather than a page walk (see the notes file's
+// "Design consequence" under Pagination).
+// - relations, comments and attachments are not part of the main issue
+// payload for Plane, and are unpaginated per-issue lists there too, so they
+// are fetched one issue at a time rather than walked as their own pages.
+export interface SourceReader {
+ listStates(): Promise<CanonicalState[]>;
+ listLabels(): Promise<CanonicalLabel[]>;
+ listCycles(): Promise<CanonicalCycle[]>;
+ listIssues(cursor: string | null): Promise<Page<CanonicalIssue>>;
+ getIssue(sourceId: string): Promise<CanonicalIssue>;
+ listIssueRelations(issueSourceId: string): Promise<CanonicalRelation[]>;
+ listIssueComments(issueSourceId: string): Promise<CanonicalComment[]>;
+ listIssueAttachments(issueSourceId: string): Promise<CanonicalAttachment[]>;
+ // Resolves one attachment's download URL, fresh each call: the source's own
+ // resolved URL is a presigned link that expires (Plane's lasts exactly an
+ // hour), so this is called at the moment of download, never cached or
+ // resolved ahead of time.
+ resolveAttachmentDownloadUrl(issueSourceId: string, attachmentSourceId: string): Promise<string>;
+}
diff --git a/bun.lock b/bun.lock
index e92c7374..f1b9a897 100644
--- a/bun.lock
+++ b/bun.lock
@@ -35,6 +35,7 @@
"@repo/db": "workspace:*",
"@repo/mailer": "workspace:*",
"@repo/net": "workspace:*",
+ "@repo/storage": "workspace:*",
"@tiptap/pm": "3.30.5",
"croner": "^10.0.1",
"decode-named-character-reference": "^1.3.0",
@@ -157,9 +158,11 @@
"name": "worker",
"version": "1.0.0",
"dependencies": {
+ "@repo/crypto": "workspace:*",
"@repo/db": "workspace:*",
"@repo/mailer": "workspace:*",
"@repo/net": "workspace:*",
+ "@repo/storage": "workspace:*",
"croner": "^10.0.1",
"drizzle-orm": "^0.45.2",
},
@@ -286,6 +289,19 @@
"typescript": "^6.0.3",
},
},
+ "packages/storage": {
+ "name": "@repo/storage",
+ "version": "0.0.0",
+ "dependencies": {
+ "@aws-sdk/client-s3": "^3.1109.0",
+ },
+ "devDependencies": {
+ "@repo/eslint-config": "workspace:*",
+ "@types/bun": "latest",
+ "eslint": "^9.39.0",
+ "typescript": "^6.0.3",
+ },
+ },
},
"overrides": {
"@scalar/themes": "0.16.2",
@@ -940,6 +956,8 @@
"@repo/net": ["@repo/net@workspace:packages/net"],
+ "@repo/storage": ["@repo/storage@workspace:packages/storage"],
+
"@scalar/agent-chat": ["@scalar/[email protected]", "", { "dependencies": { "@ai-sdk/vue": "3.0.33", "@scalar/api-client": "3.15.0", "@scalar/components": "0.27.11", "@scalar/helpers": "0.10.0", "@scalar/icons": "0.7.5", "@scalar/json-magic": "0.12.20", "@scalar/openapi-types": "0.9.4", "@scalar/schemas": "0.8.1", "@scalar/themes": "0.17.2", "@scalar/types": "0.17.1", "@scalar/use-toasts": "0.10.4", "@scalar/validation": "0.6.2", "@scalar/workspace-store": "0.56.1", "@vueuse/core": "13.9.0", "ai": "6.0.33", "js-base64": "^3.7.8", "neverpanic": "0.0.8", "truncate-json": "3.0.1", "vue": "^3.5.40" } }, "sha512-wIDE//zXOIto05DJlTGLOdXiuRzSCMT+DOzLhLTWmRFaR8WeTMSneiNppQ7kQGMtukD6hpz/awQRRx+PY8XIYw=="],
"@scalar/api-client": ["@scalar/[email protected]", "", { "dependencies": { "@headlessui/tailwindcss": "^0.2.2", "@headlessui/vue": "1.7.23", "@scalar/blocks": "0.1.10", "@scalar/components": "0.27.11", "@scalar/helpers": "0.10.0", "@scalar/icons": "0.7.5", "@scalar/oas-utils": "0.19.10", "@scalar/openapi-types": "0.9.4", "@scalar/sidebar": "0.9.35", "@scalar/snippetz": "0.9.25", "@scalar/themes": "0.17.2", "@scalar/typebox": "^0.1.3", "@scalar/types": "0.17.1", "@scalar/use-codemirror": "0.14.14", "@scalar/use-hooks": "0.4.9", "@scalar/use-toasts": "0.10.4", "@scalar/workspace-store": "0.56.1", "@vueuse/core": "13.9.0", "@vueuse/integrations": "13.9.0", "focus-trap": "^7.8.0", "fuse.js": "^7.5.0", "js-base64": "^3.7.8", "jsonc-parser": "3.3.1", "nanoid": "^5.1.6", "pretty-ms": "^9.3.0", "radix-vue": "^1.9.17", "set-cookie-parser": "3.1.0", "vue": "^3.5.40", "yaml": "^2.9.0", "zod": "^4.3.5" } }, "sha512-xWxb2JvIMKP7LoSJOfXiqyjdPy/C0FQd/nPOrt483gC/D/2TVtmyxtbVIF6huhOHzsR17Aeh0Awfghsj7tp7/A=="],
diff --git a/docker-compose.coolify-images.yml b/docker-compose.coolify-images.yml
index ba3b5b4e..ddf0b3c8 100644
--- a/docker-compose.coolify-images.yml
+++ b/docker-compose.coolify-images.yml
@@ -154,6 +154,14 @@ services:
TELEMETRY_DEBUG: ${TELEMETRY_DEBUG:-}
# The same list the api reads. This process delivers webhooks to those hosts.
SSRF_ALLOWED_HOSTS: ${SSRF_ALLOWED_HOSTS:-}
+ # A downloaded Plane import attachment is stored here, the same bucket the
+ # api's own uploads use.
+ S3_ENDPOINT: http://minio:9000
+ S3_BUCKET: ${S3_BUCKET:-planner-attachments}
+ S3_ACCESS_KEY_ID: ${SERVICE_USER_MINIO}
+ S3_SECRET_ACCESS_KEY: ${SERVICE_PASSWORD_MINIO}
+ S3_REGION: ${S3_REGION:-us-east-1}
+ S3_FORCE_PATH_STYLE: ${S3_FORCE_PATH_STYLE:-}
# Optional tuning — defaults live in apps/worker/src/config.ts:
# WEBHOOK_POLL_INTERVAL_MS, WEBHOOK_BATCH_SIZE, WEBHOOK_TIMEOUT_MS,
# WEBHOOK_MAX_ATTEMPTS, WEBHOOK_DISABLE_THRESHOLD, WEBHOOK_LEASE_SECONDS,
diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.yml
index b65a5a0c..5dbc235e 100644
--- a/docker-compose.coolify.yml
+++ b/docker-compose.coolify.yml
@@ -154,6 +154,14 @@ services:
TELEMETRY_DEBUG: ${TELEMETRY_DEBUG:-}
# The same list the api reads. This process delivers webhooks to those hosts.
SSRF_ALLOWED_HOSTS: ${SSRF_ALLOWED_HOSTS:-}
+ # A downloaded Plane import attachment is stored here, the same bucket the
+ # api's own uploads use.
+ S3_ENDPOINT: http://minio:9000
+ S3_BUCKET: ${S3_BUCKET:-planner-attachments}
+ S3_ACCESS_KEY_ID: ${SERVICE_USER_MINIO}
+ S3_SECRET_ACCESS_KEY: ${SERVICE_PASSWORD_MINIO}
+ S3_REGION: ${S3_REGION:-us-east-1}
+ S3_FORCE_PATH_STYLE: ${S3_FORCE_PATH_STYLE:-}
# Optional tuning — defaults live in apps/worker/src/config.ts:
# WEBHOOK_POLL_INTERVAL_MS, WEBHOOK_BATCH_SIZE, WEBHOOK_TIMEOUT_MS,
# WEBHOOK_MAX_ATTEMPTS, WEBHOOK_DISABLE_THRESHOLD, WEBHOOK_LEASE_SECONDS,
diff --git a/docker-compose.yml b/docker-compose.yml
index 151e90c3..523d12d3 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -154,6 +154,14 @@ services:
TELEMETRY_DEBUG: ${TELEMETRY_DEBUG:-}
# The same list the api reads. This process delivers webhooks to those hosts.
SSRF_ALLOWED_HOSTS: ${SSRF_ALLOWED_HOSTS:-}
+ # A downloaded Plane import attachment is stored here, the same bucket the
+ # api's own uploads use.
+ S3_ENDPOINT: http://minio:9000
+ S3_BUCKET: ${S3_BUCKET:-planner-attachments}
+ S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}
+ S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY}
+ S3_REGION: ${S3_REGION:-us-east-1}
+ S3_FORCE_PATH_STYLE: ${S3_FORCE_PATH_STYLE:-}
# Optional tuning lives in apps/worker/src/config.ts.
# Telegram bot: long polling for the instance bot, completing the account links
diff --git a/docs/dev/plane-import-source-notes.md b/docs/dev/plane-import-source-notes.md
new file mode 100644
index 00000000..fb8dae57
--- /dev/null
+++ b/docs/dev/plane-import-source-notes.md
@@ -0,0 +1,365 @@
+# Plane as an import source
+
+Ground-truth notes for the Plane `SourceReader` adapter (see issue #253). Every fact below
+either comes from reading the Plane Python SDK's own source (the wire contract, not its docs)
+or from a real authenticated call against a live self-hosted instance (one real workspace, one
+real project — "Rooms" / `ROOMS`, 488 work items, 66 labels, 30 modules, 3 cycles, 16 members).
+Facts still resting on the SDK read alone, not yet confirmed against a live response, are marked
+**unverified**.
+
+Where this came from: the `plane` MCP server (`plane-mcp-server`, run via `uvx`) depends on a
+`plane` PyPI package that is a thin REST client. Both are cached locally after `uvx` installs
+them (paths below) — this is not a project dependency, just where the source was read.
+
+| What | Where |
+| ------------------------------ | ------------------------------------------------------------------------------------------ |
+| MCP server (`plane_mcp`) | `~/.cache/uv/archive-v0/LcFRqvyWGcEPmXRW/plane_mcp/` (`plane-mcp-server` 0.3.1) |
+| REST client (`plane`) | `~/.cache/uv/archive-v0/PeLyjVcN9KmZTRLB/plane/` |
+| Base HTTP plumbing | `plane/api/base_resource.py`, `plane/config.py` |
+| Work item endpoints | `plane/api/work_items/base.py`, `.../attachments.py`, `.../relations.py` |
+| Response/request shapes | `plane/models/work_items.py`, `.../pagination.py`, `.../query_params.py`, `.../enums.py` |
+
+## Base URL and auth
+
+`{base_url}/api/v1/workspaces/{slug}/...`. `PLANE_BASE_URL` defaults to `https://api.plane.so`
+for the SaaS product; a self-hosted instance sets it to its own origin. Auth is `X-Api-Key:
+<token>` (a workspace/personal API key, not OAuth) — confirmed both in the SDK's header-building
+code and live. No workspace-slug header is needed once it's in the path.
+
+## Pagination — cursor is position-based, not a keyset
+
+Confirmed live on `GET /workspaces/{slug}/projects/`:
+
+```json
+{ "total_count": 6, "next_cursor": "10:1:0", "prev_cursor": "10:-1:1",
+ "next_page_results": false, "count": 6, "total_pages": 1, "results": [...] }
+```
+
+The cursor is a literal `"{per_page}:{page}:{offset}"` string (the SDK's own docstring says so
+verbatim), not an opaque keyset token. This means resuming an import from a stored cursor is
+**not safe** if the underlying result set shifted between the crash and the resume — an issue
+edited, created, or moved mid-migration can shift every subsequent page by one, silently
+skipping or duplicating rows on resume.
+
+**Design consequence:** the Discover phase should do a full, fast pass that snapshots the
+complete list of source ids up front (write them to `import_record` immediately), rather than
+treating Plane's pagination cursor as the resumability anchor for the slower Create phase.
+`import_job.cursor` should track *our own* position in that snapshot list, not Plane's cursor.
+
+**Confirmed the hard way**: reconstructing the cursor yourself (e.g. a loop counter formatted
+as `"{per_page}:{page}:{offset}"`) instead of passing back the exact `next_cursor` string the
+server returned silently drops results — a real attempt at this fetched 388 of 488 real work
+items with **no error of any kind**, because the server's own page-numbering convention doesn't
+match a naive incrementing counter. Refetching correctly (chaining the literal `next_cursor`
+value each time, stopping only when `next_page_results` is `false`) got all 488, no gaps, no
+duplicates. **The adapter must treat the cursor as fully opaque** — store and pass back exactly
+what the server returned, never construct or predict one, even though its format happens to be
+readable.
+
+`next_page_results: false` is the correct loop-termination signal (not "cursor equals the
+previous one" or "fewer than `per_page` results came back" — page 4 above returned 88 items
+with `next_page_results: false` and page 3 returned exactly 100 with `next_page_results: true`,
+so result count alone doesn't tell you whether you're done).
+
+## Rate limiting — and what it actually costs
+
+Confirmed live — every response, including plain reads, carries real headers:
+
+```
+x-ratelimit-remaining: 59
+x-ratelimit-reset: 1788234260
+```
+
+`x-ratelimit-remaining` visibly ticks down one per request, two consecutive calls a second
+apart showed resets 95 seconds apart — consistent with roughly **60 requests/minute**, not a
+generous ceiling. So self-hosted Plane does enforce and report a rate limit, not just the SaaS
+product. The SDK's `RetryConfig` retries `429, 500, 502, 503, 504` (`total=3,
+backoff_factor=0.3`) and sets `respect_retry_after_header=True` on the underlying
+`urllib3.Retry`. **Still unverified**: no 429 was actually triggered during exploration, so
+whether a real `Retry-After` header shows up on the throttled response itself (as opposed to
+just the two headers above on a normal 200) is still open — the adapter should handle both:
+back off on `x-ratelimit-remaining: 0`, and respect `Retry-After` if a 429 ever carries one.
+
+**This is the actual constraint on the whole design, not a background concern.** `relations`,
+`comments`, and `attachments` are each a separate per-work-item endpoint — confirmed below,
+`expand` does not fold them into the list page. For this one project: 488 work items × 3 calls
+≈ 1,460 requests, plus ~5 list pages, at ~60/min — **roughly 25 minutes of pure API waiting for
+one medium-sized project**, before a single byte of an actual attachment downloads. A
+Jira-scale migration is hours, not minutes. Consequences:
+
+- This closes the case against a synchronous or chat-turn import even more directly than the
+ credential argument already did — there is no way to do this within one request/response
+ cycle for a project of any real size.
+- The progress view needs to communicate pace honestly (e.g. "1,204 of 1,460 API calls made,
+ ~4 min remaining at current rate"), not just a raw item count — a bar sitting at 40/488 for
+ ten minutes reads as hung, when it's actually on schedule.
+- It makes `expand` (below) worth checking for every entity, since folding N calls into 1
+ wherever it works is the single highest-leverage optimization available.
+
+## `expand` — folds in relational fields, not related collections
+
+Confirmed live: `GET .../work-items/?expand=assignees,labels,state` returns `assignees` and
+`labels` as full objects (name, email, color, etc.) instead of bare UUIDs, and `state` as
+`{id, name, color, group}` instead of a bare UUID — collapsing what would otherwise be separate
+member/label/state lookups per issue into the one list call already being made.
+
+**Confirmed it does NOT extend to relations, comments, or attachments**: requesting
+`expand=relations,attachments,comments` on the list endpoint returns the exact same key set as
+no `expand` at all — those three stay separate per-work-item endpoints with no bulk variant.
+`expand` folds in *fields on the work item itself*, not *related collections*. So the
+1,460-call estimate above is not avoidable by a smarter query — those calls are real.
+
+## Descriptions
+
+A work item carries three description representations at once:
+
+- `description_html` — HTML. This is the one to convert to markdown for the canonical format.
+ Confirmed live: real content uses Tiptap-flavored markup, e.g.
+ `<p class="editor-paragraph-block" data-id="...">`, not plain semantic HTML. A markdown
+ converter needs testing against real checklist/code/mention blocks, not just paragraphs —
+ none of those appeared in the one issue pulled so far.
+- `description_stripped` — declared in the model, but **confirmed absent as a key** on both the
+ list and the retrieve response for a real issue. Not null — genuinely not sent. Don't rely on
+ it; derive plain text from `description_html` instead if it's ever needed.
+- `description_binary` — present as a key, looks like a CRDT snapshot (Yjs/Automerge) for
+ collaborative editing, not a document format; ignore it for import.
+- `description` (raw, richer) only appears on the `?expand=` variant (`WorkItemExpand`) per the
+ model; not tried live.
+
+`description_html` is confirmed populated on both `list` and `retrieve` (3291 chars on a real
+issue via `retrieve`; list results also carried non-empty `description_html`) — no need for an
+extra per-issue call just to get the body, the list page already has it.
+
+## Attachments — two-hop, and the URL expires in exactly an hour
+
+`WorkItemAttachment.asset` is an id-like string, not a URL, but the list response already
+carries `attributes: {name, size, type}` and a duplicate `storage_metadata` block — enough to
+render the review/preview step without ever resolving a download URL. Getting actual bytes is
+two requests:
+
+1. `GET .../work-items/{id}/attachments/{attachment_id}/` with the Plane auth header, **not
+ following redirects**.
+2. Confirmed live: a `302` whose `Location` is an S3 URL with `X-Amz-Expires=3600` — exactly one
+ hour, not "typically" — needing no Plane auth at all.
+
+**Design consequence:** `CanonicalAttachment` must carry a stable reference (attachment id +
+parent work item id), never a resolved URL — the Attachments phase runs after Create/Link and
+may execute long after Discover, well past an hour later. The adapter re-resolves the redirect
+at the moment it actually downloads, not before.
+
+**Inline images in descriptions are a second, separate attachment path.** Tiptap editors can
+embed an image directly in the body (an `<img>` pointing at a Plane asset URL), not just as a
+separate attachment row. Checked live across 50 real issues: **zero** had an inline `<img>` in
+`description_html` — this team attaches screenshots as separate files rather than pasting them
+inline. That is this workspace's habit, not proof Plane's editor can't do it. If a source
+project does embed images inline, they'd render as broken images pointing at a host the new
+instance can't necessarily reach, unless the Attachments phase also parses description HTML for
+embedded asset references, downloads and re-uploads those too, and rewrites the HTML before
+conversion to markdown. That means description handling can't be a pure function that finishes
+during Create — it may need a pass revisited during Attachments. Not yet designed; flagged here
+so it isn't discovered mid-implementation.
+
+## Comments — not yet placed in the phase design
+
+`GET .../work-items/{id}/comments/` is a real, working, unpaginated array endpoint
+(`comment_html`, `comment_stripped`, `created_by`, `created_at`, ...) — the one work item
+checked here had zero comments, so its shape wasn't fully exercised, but the endpoint itself is
+confirmed live. **The phase list posted to #253 (Discover → Create → Link → Attachments → Done)
+has nowhere for comments to go.** They need either their own phase (most likely between Create
+and Link, since a comment can itself contain a cross-reference needing the same second-pass
+resolution as description text) or an explicit decision that comments don't migrate in v1 — but
+right now the design implies neither, silently. Comments also carry `created_by`, which needs
+the same unmatched-user policy as `assignees` do. On a 488-issue project, comments plausibly
+outnumber issues — this isn't a minor omission to patch in later.
+
+## Idempotency vs. re-run — resume and re-run are different problems
+
+`import_record` (source id → local id, keyed per job) solves *resume*: a crashed job picks up
+where it left off without duplicating. It does not solve *re-run*: if someone imports, doesn't
+like the state/user mapping, and runs a fresh import against the same source project, nothing
+currently stops that from creating 976 issues instead of updating the original 488. Plane's own
+`external_id`/`external_source` fields — present on `WorkItem`, `WorkItemComment`, and
+`WorkItemAttachment` already, confirmed in the models — exist for exactly this kind of
+cross-system dedup. Whether itsaplan's own tables need an equivalent persisted reference (a
+migration, not just the job-scoped `import_record`) is an open product/schema decision, not
+something to default silently — the maintainer should weigh in given it's a real schema change
+beyond what's already proposed.
+
+## Version skew is broader than one endpoint
+
+The work-item-types 404 already noted below is not an isolated quirk. On this same instance,
+also confirmed 404: `archived-work-items/` (the exact path `list_archived` in the SDK uses) and
+`work-items/count/` (workspace-level). And confirmed absent everywhere: no export-shaped
+endpoint at all (see below). Three-for-three 404s on endpoints the SDK's source code documents
+as real is enough to treat this as a general fact about self-hosted deployments, not a fluke:
+**a meaningful fraction of the officially-documented API surface may not exist on any given
+self-hosted instance**, likely because the operator is running an older release.
+
+**Design consequence:** the Connect step should do more than validate a token. After "Test
+connection" succeeds, probe the optional endpoints (work item types, custom properties,
+archived items, modules, count) and report back what this instance can actually supply —
+"Connected. Issues, states, labels, members, cycles available. Work item types and custom
+properties not supported by this instance." — before the user ever reaches the mapping step.
+That turns version skew into a fact stated up front, not a surprise discovered mid-import.
+
+## Does Plane have its own whole-project export? No, confirmed closed
+
+Worth checking before building a REST-walking adapter from scratch — if Plane can hand back a
+full-fidelity dump of a project in one shot, that beats 1,460 individual calls. Checked two
+ways:
+
+- Grepped the entire SDK (`api/` and `models/`) for anything export-shaped — zero matches. The
+ only "export"-adjacent thing in the SDK is `import-work-item-types` (a POST endpoint for
+ importing *type definitions*, the reverse direction, not a project dump).
+- Probed `export/`, `exports/`, `work-items/export/`, and a workspace-level `exports/` directly
+ against the live instance — all four `404`.
+
+Closed: no bulk export exists to lean on, at least not one the official SDK or this instance
+exposes. Plane's own UI reportedly offers CSV/XLSX export for work items, which would be a
+spreadsheet of rows losing relations, comments, attachments, and cycle membership — the same
+shape (and the same limitations) as this app's own file importer (#228) already handles, not a
+shortcut past it. The REST-walking approach isn't a fallback; it's the only path, and it's the
+same machinery Linear and Jira will need anyway.
+
+## Modules — 30 of them, real usage, a concrete answer rather than more investigation
+
+Confirmed live: this project reports `total_modules: 30`. Itsaplan has no module-equivalent
+table. Rather than treat this as an open question needing more API exploration, the workspace's
+own data already implies the answer: this team already models secondary grouping through
+prefixed labels (`"Page: API / Backend"`, `"Suggestion: Must Have"`). A `"Module: <name>"`
+label is the same shape. Proposed: map each of a project's modules to a label named
+`Module: <name>`, applied to every work item that belonged to that module, shown as its own row
+in the mapping-review step (so it's a visible, opt-out-able choice, not a silent one) rather
+than folded wordlessly into the does-not-migrate list.
+
+## Relations vs. dependencies — two different concepts
+
+`WorkItemRelationTypeEnum`: `blocking, blocked_by, duplicate, relates_to, start_before,
+start_after, finish_before, finish_after`. Three map cleanly onto itsaplan's `issue_link.kind`:
+
+| Plane | itsaplan `issue_link.kind` |
+| ------------------------- | --------------------------- |
+| `blocking` / `blocked_by` | `blocks` (one row, direction read both ways) |
+| `duplicate` | `duplicates` |
+| `relates_to` | `relates` |
+
+The other four (`start_before/after`, `finish_before/after`) are Gantt-style scheduling
+dependencies with no destination in itsaplan's schema at all — not a translation problem, an
+absent concept. Add to the does-not-migrate list, or collapse to `relates` as a lossy
+best-effort (undecided — see open questions).
+
+There is also a separate **custom relation definitions** system
+(`work_item_relation_definitions.py`, `CreateWorkItemCustomRelation`) — workspaces can define
+their own named relation types beyond the eight built-in ones. **Unverified** whether this
+workspace actually uses any; if it does, those have no destination in itsaplan either.
+
+## Custom properties (`work_item_property`) vs itsaplan's `custom_field`
+
+**Structural difference, confirmed live, bigger than the type-mapping table below**: Plane
+scopes custom properties to a *work item type*, not to the project directly —
+`.../projects/{id}/work-item-types/{type_id}/work-item-properties/`. There is no
+"list every custom field in this project" endpoint; discovering them means first listing the
+project's work item types, then listing properties per type. That's an N+1 fan-out the Discover
+phase needs to account for, not a single call like states/labels/cycles.
+
+**Also confirmed live**: on this self-hosted instance (this Plane version, this project, despite
+`is_issue_type_enabled: true`), `GET .../work-item-types/` returns a real `404`, not an empty
+list. The endpoint the SDK targets doesn't exist here — version/feature skew between the SDK
+and a given self-hosted deployment is real, not hypothetical. **Design consequence:** custom
+field and work-item-type discovery must be optional and degrade quietly (zero custom fields
+found, not a failed import) when the source instance doesn't have the endpoint, rather than
+treating a 404 here the same as a 404 on, say, work-items list.
+
+`PropertyTypeEnum`: `TEXT, DATETIME, DECIMAL, BOOLEAN, OPTION, RELATION, URL, EMAIL, FILE,
+FORMULA`.
+
+| Plane | itsaplan `custom_field.field_type` | Notes |
+| ------------- | ------------------------------------ | ----- |
+| `TEXT` | `text` | direct |
+| `DATETIME` | `datetime` | direct (Plane has no separate plain `date`) |
+| `DECIMAL` | `number` | direct |
+| `BOOLEAN` | `boolean` | direct |
+| `URL` | `url` | direct |
+| `OPTION` | `select` or `multi_select` | depends on a multiple-values flag — **unverified**, need a real property definition |
+| `RELATION`→USER | `member` | direct, if the relation target is a user |
+| `RELATION`→ISSUE/RELEASE | — | no destination; drop or flatten to text |
+| `EMAIL` | — | no destination; flatten to `text` (value survives, validation semantics don't) |
+| `FILE` | — | no destination as a *field* (itsaplan attachments aren't field values); best-effort: store the file's name/URL as text, or drop |
+| `FORMULA` | — | computed at Plane's layer; the formula itself can't migrate, only its last computed value could be snapshotted as read-only text |
+
+## State categories — the category can't be trusted, confirmed on real data
+
+`GroupEnum`: `backlog, unstarted, started, completed, cancelled, triage`. itsaplan's
+`project_column.state_type`: `backlog, unstarted, started, completed, canceled`.
+
+- Spelling: Plane uses `cancelled` (double L), itsaplan uses `canceled` (single L). A
+ category-fallback mapping that does a naive string match will silently fail on every
+ cancelled-category state unless this is normalized explicitly.
+- `triage` has no itsaplan equivalent (itsaplan has no intake/triage concept at all). Falls
+ back to `backlog`.
+- **The real data makes the case for a mandatory review step, not just politeness.** This
+ workspace's actual states include one named "In Progress" whose `group` is `backlog`, and one
+ named "Cancled" (a typo in the display name) whose `group` is `completed`, not `cancelled`.
+ Name-match-then-category-fallback, applied automatically with no review, would silently
+ place both in the wrong local state. The mapping step in the UI design (states shown with an
+ editable target, not auto-applied) exists because of exactly this — confirmed on a real
+ workspace, not a hypothetical.
+
+## Other real shapes worth knowing
+
+- **Response envelope is not consistent across endpoints, and pattern-matching from a couple
+ of confirmed cases is not a substitute for checking each one.** Only `members/` and a work
+ item's `attachments/` are bare arrays. `labels/`, `states/`, `cycles/`, and a work item's
+ `comments/` are the same `{total_count, next_cursor, ..., results: [...]}` envelope as
+ `projects/`/`work-items/` — confirmed live after a real import failed immediately on
+ `cycles/` assuming otherwise. A work item's `relations/` isn't a list at all: it's one array
+ per relation kind, `{blocking: [...], blocked_by: [...], duplicate: [...], relates_to:
+ [...], start_after: [...], ...}`, each holding the related work item's id directly, not
+ `{relation_type, related_work_item}` rows. Every endpoint needs its own live check against a
+ real response before an adapter relies on its shape.
+- **Labels have a `parent` field** (nullable, self-referential UUID) — Plane supports real
+ label hierarchies natively. Unused in this workspace (66 labels, all `parent: null`, using a
+ `"Suggestion: X"` / `"Page: Y"` naming convention instead of the real hierarchy) but a source
+ workspace that *does* use `parent` would need it mapped onto itsaplan's separate
+ `label_group` table.
+- **Members** (`GET .../members/`) return `{id, first_name, last_name, email, display_name,
+ avatar, avatar_url}` directly, flat list, no pagination — exactly the shape needed for
+ email-based user matching, no extra lookup required.
+- **Cycles carry full timestamps, not dates** — `start_date`/`end_date` are
+ `2026-08-20T13:19:13.714493+05:00`, not a plain date. itsaplan's `cycle.startDate`/`endDate`
+ are date-only columns, so the time-of-day is dropped on import — lossy but harmless, worth
+ one line in the PR description rather than a silent truncation nobody documented.
+
+## What this workspace's real data shows
+
+The one real project here (`Rooms`, identifier `ROOMS`, id `db95831f-b1ff-49e1-91c1-df28cd99bc41`)
+reports `total_modules: 30` and `total_cycles: 3` (2 actual cycles returned) in its project
+listing, plus 488 work items, 66 labels, 16 members. Modules are not a theoretical edge case for
+this data — they're heavily used, more than cycles. Confirms modules need an explicit answer
+(map to nothing, or best-effort as extra labels?) rather than a passing mention in the
+does-not-migrate list.
+
+## Archived and draft items — not proven absent, just not visible through this path
+
+All 488 work items fetched via the default (correctly-paginated) list have `is_draft: false`
+and `archived_at: null` — no drafts or archived items showed up. But `archived-work-items/`
+404s on this instance (see version skew above), so there's no way, on this instance, to check
+whether archived items exist but are simply invisible to the default list (which is exactly
+what a separate `list_archived` method existing in the SDK implies should happen — archived
+items are normally excluded from the default listing, not merged in with a flag). **Not
+resolved**: whether a source project with real archived issues would have them silently
+excluded from an import unless the adapter has some working way to reach them — worth checking
+against a different Plane instance (or version) where the endpoint actually responds.
+
+## Still open (not yet pulled)
+
+- Whether `OPTION`-type custom properties distinguish single- vs multi-select, and what a real
+ property/option definition looks like — blocked on the work-item-types 404 above; would need
+ a different project or a newer instance to check.
+- Whether this workspace uses Plane's custom relation-definitions system beyond the eight
+ built-in relation types.
+- A real 429 response's exact headers (only ever saw a normal 200 with remaining/reset).
+- Milestones' actual field shape — not pulled (modules already resolved above).
+- Linear (GraphQL cursor shape, attachment auth) and Jira (REST pagination token, ADF shape) —
+ not started; same source-code-first approach applies once there's an SDK or OpenAPI spec to
+ read for each.
diff --git a/docs/dev/plane-import.md b/docs/dev/plane-import.md
new file mode 100644
index 00000000..7a1678be
--- /dev/null
+++ b/docs/dev/plane-import.md
@@ -0,0 +1,186 @@
+# The Plane import feature
+
+What actually shipped for issue #253, and exactly where it falls short of the design that
+was posted there. `docs/dev/plane-import-source-notes.md` covers Plane's own API wire
+format; this file covers the feature built on top of it. Read both before extending this —
+this one for what the code does and does not do, that one for what Plane's API actually
+returns.
+
+## Shape
+
+- `packages/db/src/schema/app.ts` — `import_job` (one row per run, `status`/`attempts`/
+ `next_attempt_at`/`last_error` the same shape as `webhook_delivery`, credential columns
+ encrypted the same way as `integration_credential`) and `import_record` (source id →
+ local id mapping, the idempotency and resume primitive).
+- `apps/worker/src/{canonical,reader,plane-adapter,import-store,import-worker}.ts` — the
+ `SourceReader` port, the only implementation (Plane), and the phase state machine
+ (discover → create → link → rewrite → attachments → done) that drives a job one bounded chunk per
+ tick.
+- `packages/storage` and `packages/db/src/domains/storage.ts` — object storage and upload
+ limits, shared with `apps/api` so an imported attachment is held to the same rules an
+ interactive upload is.
+- `apps/api/src/modules/import-export/` — create/test-connection/plane-preview/export/status/
+ pause/resume/cancel routes.
+- `apps/web/src/features/settings/components/import-export/` — the Settings page.
+
+## Export: a JSON snapshot, not a live sync
+
+`apps/api/src/modules/import-export/export.ts` (`GET /projects/:projectKey/import-jobs/export`,
+gated the same as starting an import) reads a project's states, labels, cycles, and issues
+(with their comments and relations) directly via `@repo/db` and shapes them into a
+self-contained, human-readable JSON document — issues, parents, and relation targets are
+referenced by their own identifier (`"MKT-42"`), not a database id, so the file reads
+sensibly opened on its own. `SettingsImportExportDownloadButton.tsx` fetches it and saves it
+client-side with the same blob + `createObjectURL` pattern `DocumentExportDialog` already
+uses for documents.
+
+This is deliberately a download, not a live write-back into Plane or anywhere else: there is
+no write-capable adapter, no export job phase, and no target-specific format. Building a
+live sync into a specific target (starting with Plane, since that is the one adapter that
+exists) is a separate, much larger piece of work — a `PlaneWriter` mirroring `PlaneReader`,
+handling Plane's own id assignment and rate limits on the way out — deferred, not started.
+
+## Mapping review, parent links, and cross-references
+
+Originally all missing against the design posted to #253; now built:
+
+- **Mapping review.** Picking a source project (`SettingsImportExportProjectPicker.tsx`) no
+ longer starts the job directly — `SettingsImportExportMappingReview.tsx` fetches the
+ source project's states from the new `POST /projects/:projectKey/import-jobs/plane-preview`
+ route (`testPlaneStatesPreview`, `apps/api/src/modules/import-export/service.ts`) and shows
+ each one with the category itsaplan would automatically map it to, editable before the job
+ is created. Only a row the user actually changes is sent as a `stateOverrides` entry;
+ `materializeStates` (`import-worker.ts`) resolves `overrides[state.sourceId] ?? state.
+ category` before calling `createLocalStateAndRecord`, so an override only ever affects a
+ newly-created column, never a dedup-matched existing one. `unmatchedUserPolicy: 'skip'`
+ drops a comment whose author matched no project member instead of creating it
+ unattributed; an issue's own assignee is unaffected either way, since an unmatched
+ assignee already left the field empty by default.
+
+Parent links and cross-references each get the same second-pass treatment relations
+already had via `runLink`:
+
+- **Parent/sub-issue links.** `createOneIssue` still sets `parentId` from whatever
+ `import_record` says at that moment, which misses a sub-issue processed before its
+ parent exists. `runLink` (`import-worker.ts`) now re-fetches every created issue a
+ second time (it already does this for relations) and calls
+ `setIssueParentIfUnset` (`import-store.ts`) once the parent resolves. Idempotent: the
+ `parent_id IS NULL` guard makes a retry a no-op and never overwrites a parent Create
+ already set correctly.
+- **Cross-references in text.** A new `rewrite` phase runs between Link and Attachments.
+ `import_record.source_display_id` carries Plane's own `sequence_id` for every imported
+ issue (stashed at Create time, from `CanonicalIssue.sequenceId`); the job's `config.
+ planeProjectKey` (the source project's Plane identifier, e.g. `"ROOMS"`, stored at job
+ creation) is what a mention has to start with. For every created issue, its description
+ and every comment on it are scanned for `<planeProjectKey>-<number>` and rewritten to
+ this project's own identifier when the referenced number was itself imported into this
+ job; an unresolvable mention (outside the imported set) is left exactly as it was. The
+ matching and substitution logic is pure and unit-tested in `cross-reference.ts`
+ (`extractCrossReferences`/`applyCrossReferenceReplacements`) — no database, no network.
+ A job created before this phase existed has no `planeProjectKey`, and Rewrite is a
+ no-op for it rather than a failure.
+
+## Attachments are downloaded and attached to their issue
+
+Originally missing (bytes were never fetched, only a source id recorded for the discovered
+count); now built. `runAttachments` (`import-worker.ts`) re-lists each created issue's
+attachments — the metadata captured during Create is not reused, since a download needs a
+fresh resolve of the two-hop, hour-lived URL right before it happens, not before — and
+downloads the ones it hasn't already created a local row for. Plane's own advertised size
+and mime type are checked against the instance's own upload settings (`getStorageSettings`/
+`mimeAllowed`, `@repo/db`) before the request is even made; the project's storage quota is
+checked once before the upload (so an already-over-quota file is never written to the
+object store at all) and once more inside the same advisory lock
+(`lockAttachmentStorage`) an interactive upload takes, immediately before the insert — the
+two never both pass a check the project can only actually fit one of. A rejected attachment
+(`AttachmentRejectedError`, `import-store.ts`) is logged and skipped, not treated as a
+failed tick that retries. Re-running an import reuses an existing attachment by exact
+filename on the same issue, the same reuse-by-content-match philosophy every other entity
+here already has.
+
+The bytes are stored the same way an interactive attachment upload is: `putObject`/
+`attachmentObjectKey`/`safeAttachmentFilename` now live in `@repo/storage`, and
+`getStorageSettings`/`mimeAllowed`/`projectStoredBytes`/`lockAttachmentStorage` in
+`packages/db/src/domains/storage.ts` — both extracted from `apps/api` (which used to be
+their only reader) specifically so the worker could reuse them rather than duplicate
+quota/mime enforcement and risk it drifting out of sync with an instance's own configured
+limits. The worker does **not** enforce the team-wide storage ceiling
+(`getLimits`/`maxStorageBytes`) — that is a hosted-cloud concept that resolves to
+"unlimited" on every self-hosted instance this feature targets, via a provider only the api
+process registers; replicating that plugin wiring for a limit that is always zero here
+was not worth it. Only the project quota, a real always-on instance setting, is enforced.
+
+Inline images embedded directly in description/comment HTML (not listed as a separate
+attachment) are a distinct path, not covered by this — see "Inline images" in
+`docs/dev/plane-import-source-notes.md`.
+
+## Other real limitations, by design or by scope, not oversights
+
+- **Custom fields, modules, milestones, work item types**: not read from Plane at all.
+ `CanonicalIssue.customFields` exists as a type but `plane-adapter.ts` hardcodes it to `[]`
+ (see the source notes file's "Custom properties" section for why — no project-wide list
+ endpoint, and the endpoint 404s on some self-hosted versions).
+- **Four of Plane's eight relation kinds are dropped intentionally**: `RELATION_KIND_MAP`
+ (`plane-adapter.ts`) has no entry for `start_before`/`start_after`/`finish_before`/
+ `finish_after` — itsaplan's `issue_link.kind` has no scheduling-dependency concept, so
+ these are filtered out, not a bug.
+- **Re-running an import against the same source project reuses what a previous run already
+ created, by name/content match, not by any record of which import created what.**
+ `import_record` makes one job's own retries and resumes safe; across two separate jobs
+ (a fresh job started after a cancel, or a second job against the same Plane project) it
+ offers nothing, since each job starts its own `import_record` set. Instead,
+ `createLocalStateAndRecord`/`createLocalCycleAndRecord`/`createLocalIssueAndRecord`/
+ `createLocalComment` (`import-store.ts`) each look up existing content in the destination
+ project first — a `project_column`/`cycle` by exact name, an `issue` by case- and
+ whitespace-insensitive title, a comment by exact body and `createdAt` on the resolved
+ issue — and reuse it instead of inserting a duplicate; `createLocalLabel` already did this
+ via its own `(project_id, name)` unique constraint. A match is reused, never overwritten:
+ an existing column's `stateType` is left as Plane's category disagrees with it, for
+ instance. This is a content match, not provenance tracking, so it also matches content a
+ user created by hand before importing, not only a previous import's output. `issue_link`
+ needs no equivalent logic — its `(pair, kind)` unique index rejects the duplicate insert
+ outright, caught by `isUniqueViolation` in `createIssueLink`.
+ State/cycle name matching is exact (case-sensitive); issue title matching is not. Nothing
+ currently makes the two consistent — worth revisiting if a Plane workspace turns out to
+ use different casing than itsaplan's own default column names.
+ Concurrent ticks racing this lookup-then-insert (two import jobs targeting the same
+ project, processed by two different worker replicas at once) could still both miss the
+ same not-yet-created match and insert twice — not addressed, since a self-hosted worker
+ normally runs as one replica.
+- **Whether archived Plane issues are silently excluded is unverified** — the default
+ `work-items/` listing this adapter uses returned zero archived items in the one workspace
+ checked during development, and the separate archived-items endpoint 404s on that same
+ instance, so this could not be confirmed either way. See the source notes file.
+
+## Rate limiting and resumability, working as designed
+
+`rateLimitBackoffMs` (`plane-adapter.ts`) reads `x-ratelimit-remaining`/`x-ratelimit-reset`/
+a 429 off every response; hitting the limit throws `PlaneRateLimitedError`, and
+`handleTickError` (`import-worker.ts`) reschedules via `retryImportJobLater` rather than
+counting it as a failed attempt. `import_job.last_error` is cleared the moment a claim starts
+a new attempt, as well as on success and on completion (`import-store.ts`'s
+`claimDueImportJobs`/`saveImportJobCursor`/`advanceImportJobPhase`/`completeImportJob`), so a
+non-null `lastError` on a still-`pending` job reliably means "currently waiting out a retry,"
+never "an attempt is in flight" — which is what the Settings page's warning banner reads.
+Clearing it at claim time (not only on success) matters: without it, a poll landing while the
+new attempt is still running would show the *previous* error next to the claim lease's own
+deadline (up to `LEASE_SECONDS` out) as if that were the retry countdown — a real bug this
+session found live, from a workspace large enough to retry several times in a row (the
+countdown jumped from a real ~15s to a bogus ~118s). Verified live against a real workspace
+during development: Create's per-issue
+cost (`getIssue` + `listIssueComments` + `listIssueAttachments`, three requests) times
+`ISSUES_PER_TICK = 15` fires 45 requests in one tick with no pacing between them, which
+reliably exhausts Plane's ~60 req/min budget within the first tick or two of Create on any
+project of real size. Safe (never exceeds the limit, always resumes), not throughput-optimal
+— worth pacing requests within a tick rather than bursting, if import speed matters later.
+
+Pausing and resuming while a job is mid-retry does not bypass the wait: pausing touches
+neither `last_error` nor `next_attempt_at`, so `resumeImportJob` (`service.ts`) sees the same
+values a live rate-limited job has and keeps the stored `next_attempt_at` rather than
+resetting it to now — the external rate limit did not clear just because the job was paused,
+so resuming into "now" regardless would have sent an immediate, still-doomed request and come
+back rate-limited again right away with a new, unrelated countdown. Only a job paused for no
+real reason (`last_error` null, or a stored deadline that already elapsed by itself) resumes
+immediately. The Settings page's countdown also now ticks every second on its own
+(`SettingsImportExportJobRow.tsx`) instead of only moving in the 2s jumps of the job list's
+own poll.
diff --git a/docs/importing-from-plane.md b/docs/importing-from-plane.md
new file mode 100644
index 00000000..72f519a7
--- /dev/null
+++ b/docs/importing-from-plane.md
@@ -0,0 +1,120 @@
+# Importing from Plane
+
+Project Settings → Import/Export connects a project to a self-hosted (or cloud) Plane
+instance, pulls one Plane project's issues into it, and shows the job's progress while it
+runs. This page describes exactly what it brings over, what it does not, and what to expect
+while it runs. Read the limitations section before importing anything you care about — some
+of them affect data you may not notice is missing until later.
+
+## What you need
+
+- The URL of the Plane instance (e.g. `https://plane.example.com`).
+- The workspace slug.
+- An API token (workspace or personal) with read access to that workspace's projects,
+ issues, and members. The token is stored encrypted and is only ever used by the import
+ itself — it is never shown again after you submit it, and it is deleted once the job
+ finishes or is canceled.
+
+## Steps
+
+1. Open the project's **Settings → Import/Export**.
+2. Enter the Plane URL, workspace slug, and API token, then **Test connection**. This
+ checks the token live against Plane and lists that workspace's projects — nothing is
+ saved yet at this point.
+3. Pick the Plane project to import from. Its states appear for review (see below), with a
+ choice for how to handle an unmatched assignee or comment author.
+4. **Start import.** The job appears in the list below, in the background. You can leave the
+ page and come back — it keeps running, and pause, resume, or cancel it from the same list
+ at any time.
+
+## What is imported
+
+- **Issues** — title, description (converted from Plane's rich text to Markdown), state,
+ labels, cycle, priority, start date, due date, and the parent issue if it is a sub-issue.
+- **Assignees and comment authors** — matched to an existing project member by email. It is
+ never assigned to the wrong person, and no placeholder account is created; what happens
+ when no member has that email is a choice you make in the mapping review step below.
+- **Comments** — body (converted to Markdown) and reply threading.
+- **Labels, workflow states, and cycles** — created if they do not already exist by that
+ name.
+- **Issue relations** — "blocks", "relates to", and "duplicates" only.
+- **Cross-references inside text, when both sides were imported.** A description or
+ comment that says "see ROOMS-524" is rewritten to point at this project's own
+ identifier for that issue, once it has been imported too. A mention of an issue
+ outside the imported set is left exactly as Plane wrote it.
+- **Attachment files**, downloaded and attached to the same issue they were on in Plane.
+ A file is skipped, not imported, when it is larger than this instance's own upload
+ limit or of a file type this instance doesn't accept — the same limits an ordinary
+ attachment upload on this instance is held to. A skipped file is only noted in the
+ server log, not shown anywhere in this screen today. Re-running an import reuses a
+ file already attached with the same name on the same issue, rather than attaching it
+ a second time.
+
+## What is not imported
+
+- **A mention of an attachment inside a description or comment's own text** (an image
+ pasted directly into the rich text, not listed as a separate attached file) comes
+ across as plain text with nothing behind it — only attachments listed as their own
+ files are downloaded.
+- **Custom fields**, whatever they are named in the source project.
+- **Modules and milestones.**
+- **Work item types** (Epic and any custom type) — every imported item becomes a plain
+ issue, with no record of what type it was in Plane.
+- **Time logs, reactions, watchers, and edit/activity history.**
+- **Four of Plane's eight relation kinds** — the scheduling-dependency ones (starts
+ before/after, finishes before/after) have no equivalent here and are dropped.
+
+## Reviewing the mapping before you import
+
+After you pick the source project, its states are shown with the category itsaplan would
+automatically map each one to (matched by name, falling back to Plane's own backlog/
+unstarted/started/completed group when no name matches). This matters because Plane's own
+state categories are not always accurate: a real workspace checked during development had a
+state named "Cancled" (misspelled) that Plane itself grouped as "completed" internally, not
+"canceled". Change any row that reads wrong before starting the import — a state you don't
+change keeps the automatic mapping.
+
+The same screen has one more choice: what happens to an assignee or comment author whose
+email matches no member of this project. "Leave unassigned" (the default) imports the issue
+or comment anyway, with that field empty. "Skip the assignment or comment" leaves an issue's
+assignee empty the same way, but drops a comment entirely rather than importing it with no
+attributed author.
+
+## Rate limits are real, and the import waits them out
+
+Plane limits how many requests it will answer per minute. A project of any real size will
+run into that limit, and the job pauses to wait it out — you will see "Plane's rate limit
+was reached, retrying in Ns" in the job list when this happens. This is normal, not a
+failure; the import resumes on its own once the wait is over. A large project can take a
+long time to finish for this reason alone.
+
+## Pausing, resuming, canceling, and running it again
+
+Pausing and resuming continues from where the job left off. Canceling stops it where it
+stands — issues already created stay created, nothing is rolled back.
+
+Starting a *new* import against the same Plane project (after a cancel, or any other time)
+reuses what a previous run already created instead of duplicating it: a state, cycle, or
+issue is matched by name (issue titles case- and whitespace-insensitively) against what is
+already in the project, and a comment is matched by its exact body and timestamp on the
+matched issue. Labels always dedupe this way too. Nothing about an existing match is
+overwritten — an existing state's category, for instance, is left as it is even if Plane
+categorizes it differently.
+
+This is a name/content match, not a record of which import created what, so it also means
+an issue you created by hand before importing — one that happens to share an exact title
+with something in Plane — is treated as the same issue and gets Plane's labels, comments,
+and other fields attached to it rather than getting a second copy.
+
+## Exporting your project's data
+
+The **Export** section at the bottom of the page downloads a JSON file with the project's
+states, labels, cycles, and issues (with their comments and relations) — a self-contained
+snapshot, readable on its own, using this project's own identifiers rather than database
+ids. This is a download, not a live sync: it does not write anywhere, including back into
+Plane, and nothing is scheduled or kept running.
+
+## Only Plane, only import
+
+Plane is the only supported source to import from today — Linear and Jira are not
+available.
diff --git a/packages/db/AGENTS.md b/packages/db/AGENTS.md
index f113ac7d..67045254 100644
--- a/packages/db/AGENTS.md
+++ b/packages/db/AGENTS.md
@@ -22,7 +22,9 @@ See root `AGENTS.md` for monorepo-wide rules.
caller stay with that caller — the api's settings routes, or god mode in
`@repo/auth`. A config only one process reads does not belong here at all.
Currently: the instance Telegram bot (api, bot, worker), the instance mail provider
- (`@repo/auth`, api, worker), and a team's notification providers (api, worker).
+ (`@repo/auth`, api, worker), a team's notification providers (api, worker), and the
+ instance's upload limits and project-storage-quota accounting (api, worker — an
+ imported attachment is checked against the same limits an interactive upload is).
- `src/migrate.ts` — programmatic migrator run on api container startup (no drizzle-kit in prod).
- `drizzle/` — generated SQL migrations (committed).
diff --git a/packages/db/drizzle/0130_aspiring_naoko.sql b/packages/db/drizzle/0130_aspiring_naoko.sql
new file mode 100644
index 00000000..351baad2
--- /dev/null
+++ b/packages/db/drizzle/0130_aspiring_naoko.sql
@@ -0,0 +1,43 @@
+CREATE TABLE "import_job" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "project_id" integer NOT NULL,
+ "created_by_user_id" text NOT NULL,
+ "source" text NOT NULL,
+ "phase" text DEFAULT 'discover' NOT NULL,
+ "status" text DEFAULT 'pending' NOT NULL,
+ "config" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "cursor" jsonb DEFAULT '{}'::jsonb NOT NULL,
+ "credential_ciphertext" text,
+ "credential_iv" text,
+ "credential_auth_tag" text,
+ "attempts" integer DEFAULT 0 NOT NULL,
+ "next_attempt_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "last_error" text,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "import_job_source_check" CHECK ("import_job"."source" IN ('plane')),
+ CONSTRAINT "import_job_phase_check" CHECK ("import_job"."phase" IN ('discover', 'create', 'link', 'rewrite', 'attachments', 'done')),
+ CONSTRAINT "import_job_status_check" CHECK ("import_job"."status" IN ('pending', 'running', 'paused', 'completed', 'failed'))
+);
+--> statement-breakpoint
+CREATE TABLE "import_record" (
+ "id" serial PRIMARY KEY NOT NULL,
+ "import_job_id" integer NOT NULL,
+ "source_entity_type" text NOT NULL,
+ "source_id" text NOT NULL,
+ "source_display_id" text,
+ "local_entity_type" text,
+ "local_id" integer,
+ "created_at" timestamp with time zone DEFAULT now() NOT NULL,
+ CONSTRAINT "import_record_source_entity_type_check" CHECK ("import_record"."source_entity_type" IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')),
+ CONSTRAINT "import_record_local_entity_type_check" CHECK ("import_record"."local_entity_type" IS NULL OR "import_record"."local_entity_type" IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment'))
+);
+--> statement-breakpoint
+ALTER TABLE "import_job" ADD CONSTRAINT "import_job_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "import_job" ADD CONSTRAINT "import_job_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+ALTER TABLE "import_record" ADD CONSTRAINT "import_record_import_job_id_import_job_id_fk" FOREIGN KEY ("import_job_id") REFERENCES "public"."import_job"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+CREATE INDEX "import_job_project_idx" ON "import_job" USING btree ("project_id");--> statement-breakpoint
+CREATE INDEX "import_job_due_idx" ON "import_job" USING btree ("next_attempt_at") WHERE "import_job"."status" = 'pending';--> statement-breakpoint
+CREATE UNIQUE INDEX "import_record_job_source_uq" ON "import_record" USING btree ("import_job_id","source_entity_type","source_id");--> statement-breakpoint
+CREATE INDEX "import_record_job_local_idx" ON "import_record" USING btree ("import_job_id","local_entity_type","local_id");--> statement-breakpoint
+CREATE INDEX "import_record_job_display_idx" ON "import_record" USING btree ("import_job_id","source_entity_type","source_display_id");
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0130_snapshot.json b/packages/db/drizzle/meta/0130_snapshot.json
new file mode 100644
index 00000000..f843fdb5
--- /dev/null
+++ b/packages/db/drizzle/meta/0130_snapshot.json
@@ -0,0 +1,10950 @@
+{
+ "id": "119aa919-9472-49b6-9b15-d9964a32f00d",
+ "prevId": "b73ebb20-d26f-45bd-87b6-5e47f13a8c7c",
+ "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.oauth_access_token": {
+ "name": "oauth_access_token",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_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
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "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
+ }
+ },
+ "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_userId_idx": {
+ "name": "oauthAccessToken_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauth_access_token_client_id_oauth_application_client_id_fk": {
+ "name": "oauth_access_token_client_id_oauth_application_client_id_fk",
+ "tableFrom": "oauth_access_token",
+ "tableTo": "oauth_application",
+ "columnsFrom": [
+ "client_id"
+ ],
+ "columnsTo": [
+ "client_id"
+ ],
+ "onDelete": "cascade",
+ "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"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_access_token_access_token_unique": {
+ "name": "oauth_access_token_access_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "access_token"
+ ]
+ },
+ "oauth_access_token_refresh_token_unique": {
+ "name": "oauth_access_token_refresh_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refresh_token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_application": {
+ "name": "oauth_application",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "client_secret": {
+ "name": "client_secret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirect_urls": {
+ "name": "redirect_urls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "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
+ }
+ },
+ "indexes": {
+ "oauthApplication_userId_idx": {
+ "name": "oauthApplication_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauth_application_user_id_user_id_fk": {
+ "name": "oauth_application_user_id_user_id_fk",
+ "tableFrom": "oauth_application",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_application_client_id_unique": {
+ "name": "oauth_application_client_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "client_id"
+ ]
+ }
+ },
+ "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": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "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
+ },
+ "consent_given": {
+ "name": "consent_given",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "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_application_client_id_fk": {
+ "name": "oauth_consent_client_id_oauth_application_client_id_fk",
+ "tableFrom": "oauth_consent",
+ "tableTo": "oauth_application",
+ "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.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
+ },
+ "scim_external_id": {
+ "name": "scim_external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "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
+ },
+ "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
+ },
+ "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"
+ }
+ },
+ "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')"
+ }
+ },
+ "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
+ },
+ "cron": {
+ "name": "cron",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "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": true
+ },
+ "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": {}
+ }
+ },
+ "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"
+ }
+ },
+ "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')"
+ }
+ },
+ "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": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "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
+ },
+ "max_steps": {
+ "name": "max_steps",
+ "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
+ },
+ "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_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
+ },
+ "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_connection_idx": {
+ "name": "git_managed_repository_connection_idx",
+ "columns": [
+ {
+ "expression": "connection_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "full_name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "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_connection_external_unique": {
+ "name": "git_managed_repository_connection_external_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "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
+ },
+ "project_id": {
+ "name": "project_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_project_idx": {
+ "name": "git_provider_connection_project_idx",
+ "columns": [
+ {
+ "expression": "project_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "git_provider_connection_project_id_project_id_fk": {
+ "name": "git_provider_connection_project_id_project_id_fk",
+ "tableFrom": "git_provider_connection",
+ "tableTo": "project",
+ "columnsFrom": [
+ "project_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "git_provider_connection_project_provider_url_account_unique": {
+ "name": "git_provider_connection_project_provider_url_account_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "project_id",
+ "provider",
+ "base_url",
+ "account_login"
+ ]
+ }
+ },
+ "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')"
+ },
+ "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_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.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": true
+ },
+ "source_activity_id": {
+ "name": "source_activity_id",
+ "type": "integer",
+ "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_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')"
+ }
+ },
+ "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
+ },
+ "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_key_unique": {
+ "name": "project_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "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
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mcp_enabled": {
+ "name": "mcp_enabled",
+ "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": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "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.scim_group": {
+ "name": "scim_group",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "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": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "scim_group_display_name_unique": {
+ "name": "scim_group_display_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "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
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index 881cbf3b..21416b3f 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -911,6 +911,13 @@
"when": 1789549970943,
"tag": "0129_round_morlocks",
"breakpoints": true
+ },
+ {
+ "idx": 130,
+ "version": "7",
+ "when": 1789555189795,
+ "tag": "0130_aspiring_naoko",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts
index b5e240c3..657f96dc 100644
--- a/packages/db/src/client.ts
+++ b/packages/db/src/client.ts
@@ -14,3 +14,8 @@ if (!connectionString) {
const queryClient = postgres(connectionString, { prepare: false });
export const db = drizzle(queryClient, { schema });
+
+// Either the plain db or a transaction, for a function whose caller may need to
+// share one transaction across several reads/writes that must observe the same
+// snapshot (a lock taken, then a read, then a write, all inside one db.transaction).
+export type DbExecutor = typeof db | Parameters<Parameters<typeof db.transaction>[0]>[0];
diff --git a/packages/db/src/domains/storage.ts b/packages/db/src/domains/storage.ts
new file mode 100644
index 00000000..e3bd0afe
--- /dev/null
+++ b/packages/db/src/domains/storage.ts
@@ -0,0 +1,188 @@
+import { eq, sql } from 'drizzle-orm';
+import { db, type DbExecutor } from '../client';
+import { getSetting } from '../settings';
+import {
+ chatAttachment,
+ documentAsset,
+ initiative,
+ initiativeAttachment,
+ issue,
+ issueAttachment,
+ project,
+ projectDocument,
+} from '../schema';
+
+// Instance-wide upload limits (app_setting key 'storage'). Read by the api (every
+// upload path, and the settings/god UI) and by the worker (an imported Plane
+// attachment is checked against the same limits an interactive upload would be).
+// The api owns the write (modules/settings/service.ts's setStorageSettings).
+//
+// The row is seeded by migration 0046, so the limits are set in the database and
+// edited in god mode — there is no env var for them. defaultStorageSettings() is
+// the fallback for a missing row and the source of the seeded values; keep the two
+// in sync.
+
+export const STORAGE_SETTING_KEY = 'storage';
+
+export const MB = 1024 * 1024;
+
+export interface StorageSettings {
+ // Upper bound on a single attachment. The multipart body is buffered in memory,
+ // so this also bounds per-upload memory.
+ maxAttachmentMb: number;
+ // Upper bound on a single avatar image.
+ maxAvatarMb: number;
+ // Accepted attachment content types. An entry is a full type ('application/pdf')
+ // or a wildcard ('image/*'). An empty list accepts any type.
+ attachmentMimeTypes: string[];
+ // Total stored attachment bytes allowed per project, in MB. 0 means unlimited.
+ projectQuotaMb: number;
+}
+
+// Images, video, PDF, office documents and plain text formats. Executables,
+// archives and anything else are refused until an admin adds them.
+export const DEFAULT_ATTACHMENT_MIME_TYPES = [
+ 'image/*',
+ 'video/*',
+ 'application/pdf',
+ 'text/plain',
+ 'text/csv',
+ 'text/markdown',
+ 'application/msword',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'application/vnd.oasis.opendocument.text',
+ 'application/vnd.ms-excel',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.oasis.opendocument.spreadsheet',
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.oasis.opendocument.presentation',
+];
+
+export function defaultStorageSettings(): StorageSettings {
+ return {
+ maxAttachmentMb: 25,
+ maxAvatarMb: 5,
+ attachmentMimeTypes: DEFAULT_ATTACHMENT_MIME_TYPES,
+ projectQuotaMb: 50 * 1024,
+ };
+}
+
+export async function getStorageSettings(): Promise<StorageSettings> {
+ const stored = await getSetting<Partial<StorageSettings>>(STORAGE_SETTING_KEY);
+ // Merge over the default so a value written before a field was added stays valid.
+ return { ...defaultStorageSettings(), ...(stored ?? {}) };
+}
+
+// Whether a content type passes the allowlist. An empty list accepts anything.
+// Entries are matched case-insensitively; setStorageSettings normalizes what it stores.
+export function mimeAllowed(contentType: string, allowed: string[]): boolean {
+ if (allowed.length === 0) return true;
+ const ct = contentType.split(';')[0]?.trim().toLowerCase() ?? '';
+ return allowed.some((pattern) =>
+ pattern.endsWith('/*') ? ct.startsWith(pattern.slice(0, -1)) : ct === pattern,
+ );
+}
+
+function num(value: unknown): number {
+ return Number(value ?? 0);
+}
+
+const ATTACHMENT_QUOTA_LOCK_NAMESPACE = 1_145_390_932;
+
+// Serializes a project's quota check against a concurrent one — two uploads (or
+// an upload and an import) racing the same read-then-insert could otherwise
+// both pass the check and land over quota together. Held for the rest of the
+// caller's transaction (pg_advisory_xact_lock), so it must be called inside one.
+export async function lockAttachmentStorage(
+ executor: DbExecutor,
+ projectId: number,
+): Promise<void> {
+ await executor.execute(
+ sql`select pg_advisory_xact_lock(${ATTACHMENT_QUOTA_LOCK_NAMESPACE}, ${projectId})`,
+ );
+}
+
+// Total attachment bytes a project has stored, across every kind that counts
+// against its quota (issue, chat, document, initiative attachments) — what a new
+// upload's size is checked against before it is allowed, and what a worker
+// importing issue attachments checks against too. Runs against either the plain
+// db or a transaction: a caller commonly checks capacity and inserts in the same
+// transaction, so both must observe the same snapshot.
+export async function projectStoredBytes(
+ projectId: number,
+ executor: DbExecutor = db,
+): Promise<number> {
+ const issues = await executor
+ .select({ total: sql<string>`coalesce(sum(${issueAttachment.sizeBytes}), 0)` })
+ .from(issueAttachment)
+ .innerJoin(issue, eq(issue.id, issueAttachment.issueId))
+ .where(eq(issue.projectId, projectId));
+ const chats = await executor
+ .select({ total: sql<string>`coalesce(sum(${chatAttachment.sizeBytes}), 0)` })
+ .from(chatAttachment)
+ .where(eq(chatAttachment.projectId, projectId));
+ const documents = await executor
+ .select({ total: sql<string>`coalesce(sum(${documentAsset.sizeBytes}), 0)` })
+ .from(documentAsset)
+ .innerJoin(projectDocument, eq(projectDocument.id, documentAsset.documentId))
+ .where(eq(projectDocument.projectId, projectId));
+ const initiatives = await executor
+ .select({ total: sql<string>`coalesce(sum(${initiativeAttachment.sizeBytes}), 0)` })
+ .from(initiativeAttachment)
+ .innerJoin(initiative, eq(initiative.id, initiativeAttachment.initiativeId))
+ .where(eq(initiative.projectId, projectId));
+ return (
+ num(issues[0]?.total) +
+ num(chats[0]?.total) +
+ num(documents[0]?.total) +
+ num(initiatives[0]?.total)
+ );
+}
+
+// The project's team, read through the same executor a quota check runs on — a
+// copy checks the quota of a project its own transaction has not committed yet.
+export async function projectTeamId(
+ projectId: number,
+ executor: DbExecutor = db,
+): Promise<number | null> {
+ const [owner] = await executor
+ .select({ teamId: project.teamId })
+ .from(project)
+ .where(eq(project.id, projectId));
+ return owner?.teamId ?? null;
+}
+
+// The same total as projectStoredBytes, summed across every project of one team —
+// what a team-wide storage ceiling is checked against.
+export async function teamStoredBytes(teamId: number, executor: DbExecutor = db): Promise<number> {
+ const issues = await executor
+ .select({ total: sql<string>`coalesce(sum(${issueAttachment.sizeBytes}), 0)` })
+ .from(issueAttachment)
+ .innerJoin(issue, eq(issue.id, issueAttachment.issueId))
+ .innerJoin(project, eq(project.id, issue.projectId))
+ .where(eq(project.teamId, teamId));
+ const chats = await executor
+ .select({ total: sql<string>`coalesce(sum(${chatAttachment.sizeBytes}), 0)` })
+ .from(chatAttachment)
+ .innerJoin(project, eq(project.id, chatAttachment.projectId))
+ .where(eq(project.teamId, teamId));
+ const documents = await executor
+ .select({ total: sql<string>`coalesce(sum(${documentAsset.sizeBytes}), 0)` })
+ .from(documentAsset)
+ .innerJoin(projectDocument, eq(projectDocument.id, documentAsset.documentId))
+ .innerJoin(project, eq(project.id, projectDocument.projectId))
+ .where(eq(project.teamId, teamId));
+ const initiatives = await executor
+ .select({ total: sql<string>`coalesce(sum(${initiativeAttachment.sizeBytes}), 0)` })
+ .from(initiativeAttachment)
+ .innerJoin(initiative, eq(initiative.id, initiativeAttachment.initiativeId))
+ .innerJoin(project, eq(project.id, initiative.projectId))
+ .where(eq(project.teamId, teamId));
+ return (
+ num(issues[0]?.total) +
+ num(chats[0]?.total) +
+ num(documents[0]?.total) +
+ num(initiatives[0]?.total)
+ );
+}
diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts
index 74621f61..db75a541 100644
--- a/packages/db/src/index.ts
+++ b/packages/db/src/index.ts
@@ -1,4 +1,4 @@
-export { db } from './client';
+export { db, type DbExecutor } from './client';
export * from './schema';
export * from './permissions';
export { getSetting, getOrCreateSetting, setSetting } from './settings';
@@ -24,3 +24,16 @@ export {
readNotificationConfig,
type NotificationConfig,
} from './domains/notification-settings';
+export {
+ STORAGE_SETTING_KEY,
+ MB,
+ DEFAULT_ATTACHMENT_MIME_TYPES,
+ defaultStorageSettings,
+ getStorageSettings,
+ mimeAllowed,
+ projectStoredBytes,
+ projectTeamId,
+ teamStoredBytes,
+ lockAttachmentStorage,
+ type StorageSettings,
+} from './domains/storage';
diff --git a/packages/db/src/permissions.ts b/packages/db/src/permissions.ts
index ffa1a001..e8cf5093 100644
--- a/packages/db/src/permissions.ts
+++ b/packages/db/src/permissions.ts
@@ -26,6 +26,7 @@ export const PERMISSION_RESOURCES = [
'actions',
'webhooks',
'note_boards',
+ 'import_export',
'danger_zone',
] as const;
export type PermissionResource = (typeof PERMISSION_RESOURCES)[number];
diff --git a/packages/db/src/schema/app.ts b/packages/db/src/schema/app.ts
index 68ec7322..dfcd1b23 100644
--- a/packages/db/src/schema/app.ts
+++ b/packages/db/src/schema/app.ts
@@ -2142,6 +2142,93 @@ export const webhookDelivery = pgTable(
],
);
+// Background job that imports issues from an external tracker into a project. The
+// worker claims due rows the same way as webhook_delivery, and cursor is the
+// job's own per-phase resumability checkpoint, not the source API's pagination
+// cursor. The credential columns are cleared once the job reaches a terminal
+// status; only 'plane' is supported as a source today.
+export type ImportSource = 'plane';
+
+export const importJob = pgTable(
+ 'import_job',
+ {
+ id: serial('id').primaryKey(),
+ projectId: integer('project_id')
+ .notNull()
+ .references(() => project.id, { onDelete: 'cascade' }),
+ createdByUserId: text('created_by_user_id')
+ .notNull()
+ .references(() => user.id, { onDelete: 'cascade' }),
+ source: text('source').notNull(),
+ phase: text('phase').notNull().default('discover'),
+ status: text('status').notNull().default('pending'),
+ config: jsonb('config').notNull().default({}),
+ cursor: jsonb('cursor').notNull().default({}),
+ credentialCiphertext: text('credential_ciphertext'),
+ credentialIv: text('credential_iv'),
+ credentialAuthTag: text('credential_auth_tag'),
+ attempts: integer('attempts').notNull().default(0),
+ nextAttemptAt: timestamp('next_attempt_at', { withTimezone: true }).notNull().defaultNow(),
+ lastError: text('last_error'),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ check('import_job_source_check', sql`${t.source} IN ('plane')`),
+ check(
+ 'import_job_phase_check',
+ sql`${t.phase} IN ('discover', 'create', 'link', 'rewrite', 'attachments', 'done')`,
+ ),
+ check(
+ 'import_job_status_check',
+ sql`${t.status} IN ('pending', 'running', 'paused', 'completed', 'failed')`,
+ ),
+ index('import_job_project_idx').on(t.projectId),
+ // Backs the worker's claim query: due pending rows ordered by next_attempt_at.
+ index('import_job_due_idx')
+ .on(t.nextAttemptAt)
+ .where(sql`${t.status} = 'pending'`),
+ ],
+);
+
+// Source-id-to-local-id mapping for one import job. The unique index on
+// (import_job_id, source_entity_type, source_id) makes the upsert idempotent, so
+// a re-run of a phase finds the existing row instead of creating another. No
+// foreign key on local_id: it spans every table an import can create, not one.
+export const importRecord = pgTable(
+ 'import_record',
+ {
+ id: serial('id').primaryKey(),
+ importJobId: integer('import_job_id')
+ .notNull()
+ .references(() => importJob.id, { onDelete: 'cascade' }),
+ sourceEntityType: text('source_entity_type').notNull(),
+ sourceId: text('source_id').notNull(),
+ // The source's own human-readable number for the entity (Plane's work item
+ // sequence_id, as a string) — only set for 'issue' rows, at Create time. Lets
+ // the Rewrite phase resolve a cross-reference like "ROOMS-524" back to this
+ // job's mapping without re-fetching every issue a second time to learn it.
+ sourceDisplayId: text('source_display_id'),
+ localEntityType: text('local_entity_type'),
+ localId: integer('local_id'),
+ createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
+ },
+ (t) => [
+ check(
+ 'import_record_source_entity_type_check',
+ sql`${t.sourceEntityType} IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')`,
+ ),
+ check(
+ 'import_record_local_entity_type_check',
+ sql`${t.localEntityType} IS NULL OR ${t.localEntityType} IN ('issue', 'comment', 'label', 'state', 'cycle', 'attachment')`,
+ ),
+ uniqueIndex('import_record_job_source_uq').on(t.importJobId, t.sourceEntityType, t.sourceId),
+ index('import_record_job_local_idx').on(t.importJobId, t.localEntityType, t.localId),
+ // Backs the Rewrite phase's cross-reference lookup (job, entity type, display id).
+ index('import_record_job_display_idx').on(t.importJobId, t.sourceEntityType, t.sourceDisplayId),
+ ],
+);
+
// 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.
diff --git a/packages/storage/eslint.config.mjs b/packages/storage/eslint.config.mjs
new file mode 100644
index 00000000..f9b96942
--- /dev/null
+++ b/packages/storage/eslint.config.mjs
@@ -0,0 +1,4 @@
+import { config } from '@repo/eslint-config/base';
+
+/** @type {import("eslint").Linter.Config[]} */
+export default config;
diff --git a/packages/storage/package.json b/packages/storage/package.json
new file mode 100644
index 00000000..a446c3f1
--- /dev/null
+++ b/packages/storage/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@repo/storage",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "scripts": {
+ "lint": "eslint .",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@aws-sdk/client-s3": "^3.1109.0"
+ },
+ "devDependencies": {
+ "@repo/eslint-config": "workspace:*",
+ "@types/bun": "latest",
+ "eslint": "^9.39.0",
+ "typescript": "^6.0.3"
+ }
+}
diff --git a/apps/api/src/shared/s3.ts b/packages/storage/src/index.ts
similarity index 64%
rename from apps/api/src/shared/s3.ts
rename to packages/storage/src/index.ts
index 58a551fe..a9bda38e 100644
--- a/apps/api/src/shared/s3.ts
+++ b/packages/storage/src/index.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from 'node:crypto';
import {
S3Client,
PutObjectCommand,
@@ -5,9 +6,10 @@ import {
DeleteObjectCommand,
} from '@aws-sdk/client-s3';
-// S3-compatible object store (MinIO) for issue attachments. Only the file
-// bytes live here; the metadata and object key are rows in issue_attachment
-// (see modules/attachments/service.ts).
+// S3-compatible object store (MinIO) for attachments — api's issue/chat/document/
+// initiative attachments and the worker's imported issue attachments alike. Only
+// the file bytes live here; the metadata and object key are rows in whichever
+// table owns them (issue_attachment, chat_attachment, ...).
//
// Config comes from env. forcePathStyle is required for MinIO (and most
// self-hosted S3 gateways) because they do not serve virtual-host-style buckets;
@@ -80,8 +82,40 @@ export async function deleteObjects(keys: string[]): Promise<void> {
await Promise.all(
keys.map((key) =>
deleteObject(key).catch((err) => {
- console.error(`[planner] failed to delete object ${key}:`, err);
+ console.error(`[storage] failed to delete object ${key}:`, err);
}),
),
);
}
+
+// Keeps a filename usable as a path segment and free of control characters,
+// falling back to a plain default when nothing usable is left.
+export function safeAttachmentFilename(input: string, fallback = 'file'): string {
+ const basename = input.split(/[\\/]/).pop() ?? '';
+ const printable = [...basename]
+ .map((character) => {
+ const code = character.charCodeAt(0);
+ return code < 32 || code === 127 ? '_' : character;
+ })
+ .join('')
+ .trim();
+ const filename = printable.slice(-255);
+ return filename && filename !== '.' && filename !== '..' ? filename : fallback;
+}
+
+// The object key an attachment is stored under: scoped by project and namespace,
+// optionally by an owner within it (an issue id, say), and made unique with a
+// uuid so re-uploading the same filename never collides with or overwrites
+// an earlier version.
+export function attachmentObjectKey(
+ projectId: number,
+ namespace: 'attachments' | 'chat' | 'documents' | 'initiatives',
+ ownerId: number | null,
+ filename: string,
+): string {
+ const safeName = safeAttachmentFilename(filename)
+ .replace(/[^\w.-]+/g, '_')
+ .slice(-100);
+ const ownerPath = ownerId === null ? '' : `${ownerId}/`;
+ return `projects/${projectId}/${namespace}/${ownerPath}${randomUUID()}-${safeName}`;
+}
diff --git a/packages/storage/tsconfig.json b/packages/storage/tsconfig.json
new file mode 100644
index 00000000..12ec9a86
--- /dev/null
+++ b/packages/storage/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "types": ["bun"]
+ },
+ "include": ["src"]
+}